モデルがコレクションに追加されると、その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
。これらの関数をモデルではなくコレクションに配置することを検討しましたか?