Reputation: 1449
Im having trouble rendering a view in Backbone, and I can't figure out where my snag is. My log error reads Uncaught TypeError: Cannot read property '$el' of undefined
and the collection render that produces the error is as follows:
render: function(){
this.$el = $('#list_entries');
console.log(this.$el);
var self = this;
self.$el.html('');
_.each(this.model.toArray(), function(list, i){
self.$el.append(new ListView({model: list}).render().$el);
});
return this;
}
This is the single entry view that the collection render
calls
var ListView = Backbone.View.extend({
model: new List(),
tagName: 'div',
className: 'singleList',
initialize: function(){
this.template = _.template($('#list_template').html());
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
The odd thing is that I am using the exact same method to render another view and dont have this issue.
Upvotes: 0
Views: 305
Reputation: 8961
Your render
is missing return this;
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
Also,
You can pass in this into _.each
_.each(this.model.toArray(), function(list, i){
this.$el.append(new ListView({model: list}).render().$el);
}, this);
Then you won't need var self = this;
at all
Upvotes: 2
Reputation: 15673
I believe the issue is the context of this in the _.each
function call back is not the view that you think it is. Try using self.$el.append
instead.
Upvotes: 0
Reputation: 1901
You should use self
in the _.each
callback to have the correct scope.
_.each(this.model.toArray(), function(list, i){
self.$el.append(new ListView({model: list}).render().$el);
});
Upvotes: 0