We all know doing something like this is bad:
<ul>
<li>Item</li>
<li>Item</li>
... 500 more list items
</ul>
and then…
$("ul li").bind("click", function() { ... });
I’ve been looking through a lot of Backbone examples / guides and the following seems to be a standard approach to rendering a list with items, based from a collection of models.
var ListView = Backbone.View.extend() {
tagName: 'ul',
render: function() {
this.collection.each(function(item) {
var view = new ListItemView({model: item});
$(this.el).append(view.render().el);
});
return this;
}
});
A list item view:
var ListItemView = Backbone.View.extend() {
tagName: 'li',
events: {
'click' : 'log'
}
log : function() {
console.log(this.model.get("title"));
}
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
If I’m not mistaken, instantiating the listView with a collection with 500 models, gives me 500 click events, one for each row. This is bad right?
I know Backbone has built in event delegation for namespaced events:
events : {
'click li' : 'log'
}
I suppose I could put this in my ListView, and it would only create one click event for the entire list, but then I wouldn’t be able access to model data corresponding to the clicked list item.
What patterns do backbone developers use to solve this typical problem?
Derick Bailey wrote a detailed blog post about this dilemma, you can check it out here: http://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/