将模型添加到集合中,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 2012-04-09 21:01:48
你不应该问收集的信息? – 2012-04-09 21:07:59
它可能会更好地把它放在集合上。但是,如果你写的东西很小,它可以用任何方式。 – Joe 2012-04-10 03:55:20