モデルがコレクションに追加された場合、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);
}
}
しかし、nextElement
とpreviousElement
コレクションがモデルを持っているべきではない懸念しているようです。これらの機能をモデルではなくコレクションに入れることを検討しましたか?
モデルイテレータのようですか? – DashK
あなたは情報の収集を求めてはいけませんか? –
それをコレクションに置く方がいいでしょう。しかし、もしあなたが何か小さなものを書いているのであれば、いずれにしても行くことができます。 – Joe