如果我将一个项目添加到集合中,我如何找到它被添加的位置? Underscore.js documentation for add建议实现这一点的唯一方法是绑定(bind)到 add 事件。
还有其他方法吗?
如果没有,那么我如何从回调中获取索引?我尝试提供以下回调:
foo:function(model, options) {
console.log("foo: " + options.index);
},
但 options.index 是
undefined
.我使用以下代码绑定(bind)到事件:this.collection.bind('add', this.foo);
并使用此代码添加一个项目:
this.collection.add(myNewItem);
集合中的模型是:
MyModel = Backbone.Model.extend({
defaults : {
key:undefined,
myObj:undefined,
},
该系列是:
MyModel List = Backbone.Collection.extend({
model: MyModel,
initialize: function() {
this.comparator = function(aModel) {
return aModel.get('key');
};
}});
我将模型添加到集合中:
var key = "always_the_same";
var mm = new MyModel({key:key});
this.collection.add(mm);
var index = this.collection.sortedIndex(mm , this.collection.comparator));
更新
问题是(我认为),比较器函数用于 indexOf 和 sortedIndexOf,因此就比较器函数而言,具有相同键的两个对象实际上是同一个对象。
我曾希望* CID 将用于确保对象实际上是我在已经排序的集合中寻找的对象。然而似乎不是。我想一种可能的解决方案是更改我的比较器函数以包含 CID:
initialize: function() {
this.comparator = function(aModel) {
return aModel.get('key') + aModel.cid;
};
},
模型仍根据其
key
排序值,但以下代码返回正确的索引位置:this.collection.sortedIndex(myModel, this.collection.comparator);
感觉很老套:(
任何人都可以对此发表意见吗?
最佳答案
如果您正在处理使用 add
将模型添加到集合的简单场景方法,那么您只需要调用 indexOf
添加后使用该模型的方法。
var myModel = new MyModel({some: "data"});
var myCollection = new MyCollection();
myCollection.add(myModel);
var index = myCollection.indexOf(myModel);
关于backbone.js - 检索添加到 Backbone.js 集合的项目的索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161164/