Property Accessible In Initialize Not Accessible In Template?
Solution 1:
You're passing a function to this.$el.html
:
this.$el.html(self.template);
That's the same as saying:
var f = this.template;
this.$el.html(f);
So what does html
do when you pass it a function? Well, from the fine manual:
.html( function )
A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function,
this
refers to the current element in the set.
When you pass html
a function, it will call that function but this
won't be what you think it is, this
inside the function will be the DOM element that is having its HTML set.
I think you want to call this.template
yourself and hand its return value to html
:
this.$el.html(this.template());
// ------------------------^^
That way template
will have the view as its this
as you expect it to.
Solution 2:
Best guess would be this no longer refers to the context of the view. if you log this within the function what does it show.
EDIT- Actually not sure if this will give the expected results, i normally use handlebars but i think the setup for _.template and hanblebars is pretty similar. Your template template normally wants a plain java object passed to it other wise you would have to access the variables you want in yours like post.attributes.name, however if you just pass the toJSON version of your model you can access the attributes without the need for post.attributes.
Also you can compile your template once then just refer to it, no need place it as a function and have it grab from the DOM every time (assuming it never changes). Below is an example of what i mean. In your template you would then have <%= name %> etc to grab you model attributes. var postView = Backbone.View.extend({
initialize : function() {
// returns model
console.log('the model we are interested in',this.model);
this.render();
},
el : "#blog-post",
template : _.template($('#postview').html()),
render : function() {
this.$el.html(this.template(this.model.toJSON()));
returnthis;
}
});
Oh also the convention normally is that render returns 'this' so if you want to call it from some where else and attach it to a new part of the page you can do it calling postView.render().el
Solution 3:
You may be passing the model, but you're not receiving it in your view. Try:
initialize: function(model) { ...
Post a Comment for "Property Accessible In Initialize Not Accessible In Template?"