2012-04-09 138 views
1

假设我有一个骨干集合,我希望能够找到给定元素的上一个元素和下一个元素。请假定可以动态删除和添加元素。获取backbone.js中的下一个元素和上一个元素

var MyModel=Backbone.Model.extend({ 
nextElement: function(){ 
//???? 
}, 
previousElement:function(){ 
//????? 
} 
}); 

var MyCollectionType=Backbone.Collection.extend({ 
model:MyModel; 
}); 
var collection=new MyCollectionType 
+0

像模型迭代器? – DashK 2012-04-09 21:01:48

+3

你不应该问收集的信息? – 2012-04-09 21:07:59

+0

它可能会更好地把它放在集合上。但是,如果你写的东西很小,它可以用任何方式。 – Joe 2012-04-10 03:55:20

回答

13

将模型添加到集合中,collection属性添加到它引用的集合是在模型中,您可以在nextElement和previousElement方法使用该属性。

var MyModel = Backbone.Model.extend({ 
    initialize: function() { 
    _.bindAll(this, 'nextElement', 'previousElement'); 
    }, 

    nextElement: function() { 
    var index = this.collection.indexOf(this); 
    if ((index + 1) === this.collection.length) { 
     //It's the last model in the collection so return null 
     return null; 
    } 
    return this.collection.at(index + 1); 
    }, 

    previousElement: function() { 
    var index = this.collection.indexOf(this); 
    if (index === 0) { 
     //It's the first element in the collection so return null 
     return null; 
    } 
    return this.collection.at(index - 1); 
    } 
} 

然而,似乎nextElementpreviousElement担心的收集应该有,而不是模型。你有没有考虑过将这些功能放在集合而不是模型上?

+3

不错的代码,但不应该nextElement和previousElement是集合的一部分,而不是模型? – 2012-04-09 21:29:15

+1

@LarryBattle准确地说,这就是为什么我编辑了我的回复并提供了相同的建议 – Paul 2012-04-09 21:32:13

0

它被讨论为骨干的问题

https://github.com/jashkenas/backbone/issues/136

林森

它可以是这样的 可以解决这个使用新的模型的方法总是得到:

getRelative: function(direction) { 
    return this.collection.at(this.collection.indexOf(this) + direction); 
} 

所以如果你通过-1它会得到前一个和1会让你下一个。如果它没有找到任何东西,它会返回-1。