這是一個5部分backbone.js你好世界教程/應用程序。 http://arturadib.com/hello-backbonejs/docs/3.html在第3部分中,作者闡釋瞭如何使用集合和模型來存儲數據以及如何將更改與視圖綁定。骨幹:收集活動活頁夾
我瞭解大部分,除了這行
this.collection.bind('add', this.appendItem); // collection event binder
這是「捆綁」只是結合上下文,或者它作爲一個「事件」這樣的appendItem功能是隨時隨地,一個模型已添加叫什麼名字?
我問,因爲在ListView的渲染方法,它的顯式調用appendItem方法,所以爲什麼它必然要「添加」
_(this.collection.models).each(function(item){ // in case collection is not empty
self.appendItem(item);
}, this);
可有人請解釋一下這些代碼是如何工作的。我查看了文檔,但無法找到以這種方式使用的綁定的解釋。
的完整代碼
(function($){
¶
Item class: The atomic part of our Model. A model is basically a Javascript object, i.e. key-value pairs, with some helper functions to handle event triggering, persistence, etc.
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
}
});
¶
List class: A collection of Items. Basically an array of Model objects with some helper functions.
var List = Backbone.Collection.extend({
model: Item
});
var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem'
},
¶
initialize() now instantiates a Collection, and binds its add event to own method appendItem. (Recall that Backbone doesn't offer a separate Controller for bindings...).
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;
this.render();
},
render: function(){
¶
Save reference to this so it can be accessed from within the scope of the callback below
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() now deals solely with models/collections. View updates are delegated to the add event listener appendItem() below.
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() is triggered by the collection event add, and handles the visual update.
appendItem: function(item){
$('ul', this.el).append("<li>"+item.get('part1')+" "+item.get('part2')+"</li>");
}
});
var listView = new ListView();
})(jQuery);
幾件事情使教程更新:** 1。**使用'this。$ el'而不是'$(this.el)'** 2。**'_(this.collection.models ).each(...)'應該是'this.collection.each(...)'** 3。**'$('ul',this.el)'應該是'this。$('ul 「)'。有關詳細信息,請參見[documentation](http://backbonejs.org/)。 –