これは、バックボーン・リセット機能である:あなたがリセット機能に任意のモデルを供給していないため
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行を無視することができます。また、最初の2行も無視してみましょう。このコレクションのモデルを通してだから、まずはループとコレクションの_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 = {};
},
それはちょうどあからさまなコレクションが今まで持っていた任意のモデルへの参照を削除します。
私たちはこれで何ができますか?まあ、バックボーンのコレクションreset
は、基本的にはモデルを削除する公式チャンネルをすべて迂回し、それはすべてハッシュ秘密で行い、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;
}
});
それがもっと分かりやすい場合は、感謝リーマン – nimrod