我想了解這個tutorial這個樣本骨幹代碼,但我無法理解我們爲什麼需要這個dummy function
- 任何想法它是什麼?骨幹教程:model.destroy +刪除和不提示功能
Backbone.sync = function(method, model, success, error){
success();
}
然後,remove
和unrender
功能似乎是相同的 - 爲什麼我們需要他們兩個?
什麼是這行,
this.model.bind('remove', this.unrender);
,而我們已綁定了remove
功能和click事件到DOM?
也,我們已經在這條線綁定的所有功能(包括unrender
),
_.bindAll(this, 'render', 'unrender', 'swap', 'remove');
所以爲什麼我們需要下面這條線?
this.model.bind('remove', this.unrender);
你可以閱讀從上面的教程整個代碼,這裏是它的一些,
// `Backbone.sync`: Overrides persistence storage with dummy function. This enables use of `Model.destroy()` without raising an error.
Backbone.sync = function(method, model, success, error){
success();
}
var Item = Backbone.Model.extend({
defaults: {
part1: 'hello',
part2: 'world'
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li', // name of tag to be created
// `ItemView`s now respond to two clickable actions for each `Item`: swap and delete.
events: {
'click span.swap': 'swap',
'click span.delete': 'remove'
},
// `initialize()` now binds model change/removal to the corresponding handlers below.
initialize: function(){
_.bindAll(this, 'render', 'unrender', 'swap', 'remove'); // every function that uses 'this' as the current object should be in here
this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);
},
// `render()` now includes two extra `span`s corresponding to the actions swap and delete.
render: function(){
$(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
return this; // for chainable calls, like .render().el
},
// `unrender()`: Makes Model remove itself from the DOM.
unrender: function(){
$(this.el).remove();
},
// `swap()` will interchange an `Item`'s attributes. When the `.set()` model function is called, the event `change` will be triggered.
swap: function(){
var swapped = {
part1: this.model.get('part2'),
part2: this.model.get('part1')
};
this.model.set(swapped);
},
// `remove()`: We use the method `destroy()` to remove a model from its collection. Normally this would also delete the record from its persistent storage, but we have overridden that (see above).
remove: function(){
this.model.destroy();
}
});
awww感謝您解釋'虛擬功能'。現在我明白它的意義了! :D – laukok