我想要一个集合的分页 View 。我尝试使用 Backbone.Paginator,但我无法让它工作。
我想我会自己做分页,我认为拥有我的完整收藏是个好主意,然后将 View 发送到大收藏的一小部分,每次有人点击“下一步”时都这样做'.
我尝试这样做,但它不起作用:
var purchaseCollection = new purchaseItemCollection({url:endpoints.purchases});
purchaseCollection.fetch();
var purchaseRangeCollection = new Backbone.Collection(purchaseCollection.models),
purchaseView = new purchaseItemCollectionView({collection:purchaseRangeCollection});
我的第二个系列本应有多个模型,但只包含一个模型。
我想知道这是否是最好的方法。
如有任何关于如何将一个集合拆分为多个集合或如何以另一种方式拆分的建议,我们将不胜感激!
最佳答案
您可以使用自定义对象来控制表示当前所选模型列表的集合。
例如,
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);
}
});
然后您将创建该 Controller 的一个实例并监听自定义事件 sliced
在这个对象上或在 reset
上sliced
上的事件集合以更新您的 View :
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/
请注意,您还必须考虑 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);
});
关于javascript - Backbone : Make collection from slice of another collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24664510/