2012-04-09 25 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

+3

あなたは情報の収集を求めてはいけませんか? –

+0

それをコレクションに置く方がいいでしょう。しかし、もしあなたが何か小さなものを書いているのであれば、いずれにしても行くことができます。 – Joe

答えて

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はコレクションではなく、モデルではないはずですか? –

+1

@LarryBattleまさに私の回答を編集し、同じ提案 – Paul

0

それは

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

linssen

は、それはあなたが常に新しいモデルを用いる方法この問題を回避することができ、この ようなものになることができますバックボーンの問題として議論されました:

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

-1を渡すと前の値が得られ、1なら次の値が得られます。何も見つからない場合は-1を返します。

関連する問題