您可以使用自定義對象來控制代表當前所選模型列表的集合。
例如,
var Slicer = function(opts) {
opts || (opts = {});
// your big collection
this.collection = opts.collection || new Backbone.Collection();
// a collection filled with the currently selected models
this.sliced = new Backbone.Collection();
};
_.extend(Slicer.prototype, Backbone.Events, {
// a method to slice the original collection and fill the container
slice: function(begin, end) {
var models = this.collection.models.slice(begin, end);
this.sliced.reset(models);
// triggers a custom event for convenience
this.trigger('sliced', this.sliced);
}
});
你會再創建該控制器的一個實例,要麼聽取他們對這個對象上或在sliced
收集reset
事件自定義事件sliced
更新您的看法:
var controller = new Slicer({
collection: purchaseCollection
});
controller.on('sliced', function(c) {
console.log('sliced', c.pluck('id'));
});
controller.sliced.on('reset', function(c) {
console.log('reset', c.pluck('id'));
});
並演示與http://jsfiddle.net/nikoshr/zjgkF/
注意THA玩你也必須考慮到fetch
的異步性質,你不能立即在模型上工作。在這個設置中,你會做類似
var purchaseCollection = new purchaseItemCollection(
[], // you have to pass an array
{url:endpoints.purchases} // and then your options
);
purchaseCollection.fetch().then(function() {
// do what you want
// for example
controller.slice(0, 10);
});