我正在經歷學習骨幹的過程,並不理解所有的語法。下面我加入一些我一直在努力學習的骨幹代碼,所以我可以在這個問題中引用它。儘管我掌握了大多數骨幹的工作原理,但我並不完全理解某些代碼中的一些標記背後的一些含義。 BackBone的文檔來源很少。我得到了90%,但是我沒有得到的語法是下劃線'_'真正提供了什麼以及何時使用它。例如下面的代碼在「.bindAll(...」中使用了下劃線。當然,我確實理解綁定是什麼,只是不確定何時使用下劃線和標記起什麼作用。當下劃線顯示在'(this.collection.models).each(function(item)...'代碼之前時,我知道代碼正在做一個循環,但爲什麼它們使用下劃線標記。謝謝你的幫助。下劃線標記在骨幹中做什麼以及我們何時使用它?
(function($){
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem'); // remember: every function that uses 'this' as the current object should be in here
this.collection = new List();
this.collection.bind('add', this.appendItem); // collection event binder
this.counter = 0;
//once the object is initialized, render the page.
this.render();
},
render: function(){
var self = this;
$(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
self.appendItem(item);
}, this);
},
addItem: function(){
this.counter++;
var item = new Item();
item.set({
part2: item.get('part2') + this.counter // modify item defaults
});
this.collection.add(item); // add item to collection; view is updated via event 'add'
},
appendItem: function(item){
$('ul', this.el).append("<li>"+item.get('part1')+" "+item.get('part2')+"</li>");
}
});
var listView = new ListView();
})(jQuery);
參見:http://underscorejs.org/ – tgriesser