BackboneJs tutorial question
I am following a tutorial I found on BackboneJs located here.
About halfway down in the render
method he does the following:
events: { 'click button#add': 'addItem' },
initialize: function () {
this.collection = new List();
// Collection event binder
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function () {
this.el.append("<button id='add'> Add List Item</button>");
this.el.append("<ul></ul>");
_(this.collection.models).each(function(item){
// in case collection is not empty
appendItem(item);
}, this);
},
addItem: function () {
var item = new Item();
this.counter++;
item.set({
part2: item.get('part2') + " " + this.count开发者_JS百科er
});
this.collection.add(item);
},
appendItem: function (item) {
$('ul').append('<li>' + item.get('part1') + " " + item.get('part2') + '</li>');
}
I have a couple of questions about the line below.
_(this.collection.models).each(function(item){
// in case collection is not empty
appendItem(item);
}, this);
What does the underscore _
do in this context?
Why is this even needed?
The comment says in case the collection is not empty. However without that line it works just fine. And the bind
override in the initialize
function tells Backbone to run this.appendItem
when the add
event is triggered on the collection, or so I thought and confirmed by removing the line in question.
i think this method typically wraps an array in an "underscore" helper class, to give it access to all of the underscore.js helper methods. in this case, the .each method is coming from the underscore helper class.
like you said, though, this should work fine without it. it may be that the version of backbone on which this tutorial was written (v0.3.3) requires the _ method for the array of models to be iterated like this.
the documentation for underscore.js ( http://documentcloud.github.com/underscore/ ) talks about using _() as a method call, instead of using the library in an object-oriented mannter.
精彩评论