[英]Getting the next and previous elements in backbone.js
假設我在 backbone 中有一個集合,我希望能夠找到給定元素的上一個和下一個元素。 請假設可以動態刪除和添加元素。
var MyModel=Backbone.Model.extend({
nextElement: function(){
//????
},
previousElement:function(){
//?????
}
});
var MyCollectionType=Backbone.Collection.extend({
model:MyModel;
});
var collection=new MyCollectionType
將 model 添加到集合時, collection
屬性將添加到引用它所在集合的 model。您可以在 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);
}
}
但是,似乎nextElement
和previousElement
是集合應該關注的問題,而不是 model。您是否考慮過將這些功能放在集合而不是 model 上?
它被討論為一個骨干問題
https://github.com/jashkenas/backbone/issues/136
林森
它可以是這樣的你總是可以使用新的 model 方法來解決這個問題:
getRelative: function(direction) {
return this.collection.at(this.collection.indexOf(this) + direction);
}
因此,如果您傳遞 -1,它將獲得前一個,而 1 將獲得下一個。 如果沒有找到任何東西,它將返回 -1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.