gpt4 book ai didi

backbone.js - 从集合中获取下一个和上一个模型

转载 作者:行者123 更新时间:2023-12-03 15:19:21 25 4
gpt4 key购买 nike

我已经看到了从集合中获取下一个或上一个模型的几种不同方法,但想知道是否有人可以就我决定实现它的方式提供一些建议。我的收藏是有序的,但我排序的 id 不能保证是连续的。它只能保证是唯一的。假设较小的 id 是集合的“旧”条目,而较大的 id 是"new"条目。

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("next") 和 getElement("prev") 之类的操作来请求我的集合中的下一个或上一个模型。从 getElement 返回的是实际模型,而不是索引。我知道 collection.indexOf,但我想要一种方法来循环遍历集合,而无需先从模型开始。这个实现是否比它需要的更难?

最佳答案

我会做这样的事情。请记住,当前没有任何错误处理,因此如果您当前处于集合中的第一个模型并尝试获取前一个模型,则可能会出现错误。

MyCollection = Backbone.Collection.extend({
model: MyModel,
initialize:function (){
this.bindAll(this);
this.setElement(this.at(0));
},
comparator: function(model) {
return model.get("id");
},
getElement: function() {
return this.currentElement;
},
setElement: function(model) {
this.currentElement = model;
},
next: function (){
this.setElement(this.at(this.indexOf(this.getElement()) + 1));
return this;
},
prev: function() {
this.setElement(this.at(this.indexOf(this.getElement()) - 1));
return this;
}
});

进入下一个模型 collection.next() .进入下一个模型并返回 var m = collection.next().getElement();
更好地解释下一个/上一个是如何工作的。
// The current model
this.getElement();
// Index of the current model in the collection
this.indexOf(this.getElement())
// Get the model either one before or one after where the current model is in the collection
this.at(this.indexOf(this.getElement()) + 1)
// Set the new model as the current model
this.setElement(this.at(this.indexOf(this.getElement()) + 1));

关于backbone.js - 从集合中获取下一个和上一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com