检索添加到Backbone.js Collection的项目的索引位置

Jac*_*ack 10 backbone.js underscore.js backbone.js-collections

如果我将一个项目添加到Collection中,如何找到添加它的位置?用于添加Underscore.js文档表明,实现此目的的唯一方法是绑定到add事件.

还有其他方法吗?如果没有,那我怎样才能从我的回调中重新索引索引?我尝试提供回调:

foo:function(model, options) {
  console.log("foo: " + options.index);
},
Run Code Online (Sandbox Code Playgroud)

但是options.index是undefined.我用这段代码绑定到事件:

this.collection.bind('add', this.foo);
Run Code Online (Sandbox Code Playgroud)

并使用以下代码添加项目:

this.collection.add(myNewItem);
Run Code Online (Sandbox Code Playgroud)

该系列中的模型是:

MyModel = Backbone.Model.extend({
defaults : {
   key:undefined,
   myObj:undefined,
},
Run Code Online (Sandbox Code Playgroud)

该系列是:

MyModel List = Backbone.Collection.extend({
      model: MyModel,

initialize: function() {
   this.comparator = function(aModel) {
   return aModel.get('key'); 
  };
 }});
Run Code Online (Sandbox Code Playgroud)

我将模型添加到集合中:

 var key = "always_the_same";
var mm = new MyModel({key:key});
this.collection.add(mm);
var index = this.collection.sortedIndex(mm , this.collection.comparator));
Run Code Online (Sandbox Code Playgroud)

更新

问题是(我认为),比较器函数用于indexOf和sortedIndexOf,因此,就比较器函数而言,具有相同键的两个对象实际上是相同的对象.

我曾希望*CID将用于确保对象实际上是我在已经排序的集合中寻找的对象.但似乎没有.我想一个可能的解决方案是更改我的比较器功能以包含CID:

initialize: function() {
        this.comparator = function(aModel) {
          return aModel.get('key') + aModel.cid; 
        };
      },
Run Code Online (Sandbox Code Playgroud)

模型根据其key值保持排序,但以下代码返回正确的索引位置:

this.collection.sortedIndex(myModel, this.collection.comparator);
Run Code Online (Sandbox Code Playgroud)

感觉hacky :(任何人都能提出他们的意见吗?

Der*_*ley 18

如果您正在处理使用该add方法将模型添加到集合的简单方案,那么您只需indexOf在添加该模型后调用该模型.

var myModel = new MyModel({some: "data"});

var myCollection = new MyCollection();
myCollection.add(myModel);

var index = myCollection.indexOf(myModel);
Run Code Online (Sandbox Code Playgroud)


txo*_*elu 1

更新

如果您想知道带有下划线的集合中元素的“索引”,您可以使用indexOf.

您能否在小提琴中添加更大的代码示例,以便我可以更好地理解您想要做什么?因为例如,如果集合中的元素不是原始类型(没有整数或字符串,而是 javascript 对象)indexOf可能会出现问题,因为不同引用的具有相同值的对象不会被视为相等indexOf

更新2

你可以尝试这样做:

var cids = this.collection.map(function(elem){ return elem.cid; });
var index = _(cids).indexOf(myModel.cid);
Run Code Online (Sandbox Code Playgroud)