Reputation: 18351
I'm working on an app that has an ItemListView
that contains a number of ItemView
elements. In my ItemListView
, I'm using the jQuery .each()
method to loop through the collection of items and render them as list elements.
I've got all the pieces in place except for the actual attaching of the li
elements to the containing ul
. The sticking point is getting access to the ItemListView.appendItem
method from inside of my .each()
loop. I've tried using this.appendItem
and self.appendItem
, but inside the loop this
is the item
and self
is the window
object.
Here's what I have right now:
ItemListView = Backbone.View.extend({
el: '#item-rows',
initialize: function () {
this.collection = new Items();
this.render();
},
render: function () {
$.each(this.collection.models, function (i, item) {
var itemview = new ItemView( { model: item });
this.appendItem(itemview); // this refers to the item, so appendItem is undefined
});
},
appendItem: function (itemView) {
$(this.el).append(itemView.render().el);
}
});
var itemlistview = new ItemListView;
I'm pretty sure that the context issue is the only problem, as I've examined the other pieces of the this by outputting them to the console and they look fine.
What am I missing?
Upvotes: 2
Views: 1690
Reputation: 30432
A more Backbone-y way to do this would be to use the collection's each
, provided by underscore.js:
render: function() {
this.collection.each( function( item, index ) {
var itemView = new ItemView( { model:item } );
this.appendItem( itemView );
}, this );
return this;
}
Notes:
each
which take a reference to bind the function toeach
takes the element first and the index secondrender
should generally return this
for chaining purposes (as mentioned in the docs), I don't think your appendItem
function will work as you expect without this partUpvotes: 3
Reputation: 7141
Yeah, it's a pretty simple fix. You just gotta refer to the this
in the outer context.
render: function () {
var somereftothis = this;
$.each(this.collection.models, function (i, item) {
var itemview = new ItemView( { model: item });
somereftothis.appendItem(itemview); // this refers to the item, so appendItem is undefined
});
},
Upvotes: 2