You're saying something like this:
var PersonView = Backbone.View.extend({
//...
template: _.templateFromUrl("templatefile1.html", this.model.toJSON()),
//...
});
What do you think this
is in that context? It certainly won't be an instance of your view since no instances have been made yet. this
is going to be window
at the level and window
won't have a useful model
property. You need to defer that call until you have an instance of your view created with a model
property.
You could make template
a method:
template: function() {
return _.templateFromUrl('templatefile1.html', this.model.toJSON());
}
and then call it at the appropriate time:
render: function(){
this.$el.html(this.template());
return this; // <----- Standard practise so you can x.append(v.render().el)
}
I'd recommend against using async:false
with $.ajax
though, that's a nasty thing to do to people. Instead, you should hand templateFromUrl
a callback function that it can call when the template has come in from the server.
If you're going to be doing this sort of thing a lot then you could add a template
function to a base view:
var BaseView = Backbone.View.extend({
template: function() {
// This assumes that you have exactly one of `this.model` and
// `this.collection`, you can do other things here if that doesn't
// work in your world.
var data_source = this.model || this.collection;
return _.templateFromUrl(this.template_name, data_source.toJSON());
}
});
and then use it your PersonView
:
var PersonView = BaseView.extend({
template_name: 'templatefile1.html',
render: function() {
this.$el.html(this.template());
return this;
},
//...
});