我很好奇为什么重置主干集合不会触发模型事件。然而,只有当模型被物理地从集合中移除时,才会触发模型事件。
这是故意的,还是我漏掉了什么?如果backbone不做这类事情,那么像这样委托事件的好做法是什么呢?
为什么backbone在采集重置时没有触发模型事件?
var TicketModel = Backbone.Model.extend({
defaults: {
name: 'crafty',
email: 'dwq@dwqcqw.com'
},
initialize: function(){
this.on("all", function(event){
console.log(event)
});
}
});
var TicketCollection = Backbone.Collection.extend({
model: TicketModel,
});
var tickets = new TicketCollection([
{
name: 'halldwq'
},
{
name: 'dascwq'
},
{
name: 'dsacwqe'
}
]);
tickets.reset();发布于 2013-02-09 01:19:28
当更新到另一个版本时,覆盖Backbone方法可能会导致痛苦。
Backbone在options.previousModels中存储了重置之前的模型数组,所以只需监听重置事件,并在那些以前的模型上触发一个'remove‘事件:
collection.on('reset', function(col, opts){
_.each(opts.previousModels, function(model){
model.trigger('remove');
});
});这样就行了。
发布于 2012-08-02 17:59:36
这是主干复位功能:
reset: function(models, options) {
models || (models = []);
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},我们可以忽略最后3行,因为您没有为reset-function提供任何模型。另外,让我们也忽略前两行。因此,首先我们遍历这个集合中的模型并调用集合的_removeReference(model)方法,它看起来像这样:
_removeReference: function(model) {
if (this == model.collection) {
delete model.collection;
}
model.off('all', this._onModelEvent, this);
},这里发生的事情是,我们从模型对象中完全删除了集合属性,还删除了到此模型事件的绑定。下一步我们调用集合的_reset()-function,看起来像这样:
_reset: function(options) {
this.length = 0;
this.models = [];
this._byId = {};
this._byCid = {};
}, 它只是直接删除了对集合中曾经拥有的任何模型的引用。
我们能从中得到什么呢?Backbone中的收集reset -function基本上只是绕过了所有移除模型的官方渠道,并且都是在保密的情况下进行的,除了reset之外,不会导致其他事件被触发。因此,您想为重置过程中从集合中删除的每个模型触发模型的remove事件?简单!只需覆盖Backbone.Collection的重置函数,如下所示:
var Collection = Backbone.Collection.extend({
reset: function(models, options) {
models || (models = []);
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
// trigger the remove event for the model manually
this.models[i].trigger('remove', this.models[i], this);
}
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
}
});希望这能有所帮助!
https://stackoverflow.com/questions/11774738
复制相似问题