我已经看到了几种不同的方式从集合中获取下一个或以前的模型,但想知道是否有人可以提供一些建议,以便我决定实施它。我的收藏是有序的,但我排序的ID不保证是连续的。它只保证是唯一的。假设较小的ID是集合的“较旧”条目,较大的ID是“较新”。从集合中获取下一个和以前的模型
MyCollection = Backbone.Collection.extend({
model: MyModel,
initialize:function(){
this.getElement = this._getElement(0);
},
comparator: function(model) {
return model.get("id");
},
_getElement: function (index){
var self = this;
return function (what){
if (what === "next"){
if (index+1 >= self.length) return null;
return self.at(++index);
}
if (what === "prev"){
if (index-1 < 0) return null;
return self.at(--index);
}
// what doesn't equal anything useful
return null;
};
}
});
当使用getElement,我不喜欢的东西getElement(“下一步”)而getElement(“上一页”),要求我的集合中的一个或下一个模型。从getElement返回的是实际模型,而不是索引。我知道关于collection.indexOf,但我想要一种方式来循环一个集合,而不需要先创建一个模型。这个实现比它需要的更难吗?
我喜欢你的一些想法,特别是在初始化方法中使用this.at()。虽然你的代码虽然很长。如果没有其他人提出任何更好和/或更简洁的建议,您将得到绿色检查:-)我的方法更短,并且在到达任何一端时通过返回null来防止脱落到集合的末尾。 – 2012-04-18 16:52:42
您可以通过抛弃'set/getElement'函数并直接访问'currentElement'值来缩短它。 – abraham 2012-04-20 03:03:59
如果使用v0.9 +,你需要有this.setElement(this.at(0));目前在创建集合之后调用的初始化函数中。这是因为在Collection创建模型之前调用initialize。例如:var myCollection = new MyCollection(data); myCollection.setElement(this.at(0)); – 2012-07-17 01:43:00