我有以下设置:
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.add(new Chapter({index: 9, title: "The End"}));
chapters.add(new Chapter({index: 5, title: "The Middle"}));
chapters.add(new Chapter({index: 1, title: "The Beginning"}));
根据要求,我需要更改章节索引。有没有办法让我使用以下语法在changeIndexes
集合上实现方法Chapters
:
var Chapters = Backbone.Collection.extend({
changeIndexes: function(model, bool: increase) {
// change indexes of the model and sibling models here
}
});
来自集合的模型上的和方法increase
和decrease
:
var Chapter = Backbone.Model.extend({
increase: function() {},
decrease: function() {}
);
每当触发changeIndexes
时,触发模型increase=true
,modelFromCollection.increse()
触发increase=false
?{/ p} >
我的第一个猜测是使用在集合中传播的自定义事件。这是一种方法还是可能有更好的方法?
答案 0 :(得分:1)
要从模型的函数中调用changeIndexes,可以直接引用该集合。
var Chapter = Backbone.Model.extend({
increase: function(){
this.collection.changeIndexes(this, true);
},
decrease: function(){
this.collection.changeIndexes(this, false);
},
});
或者,集合可以在模型上收听更改事件。
var Chapters = Backbone.Collection.extend({
initialize: function(){
this.on('change:index', this.changeIndexes_2);
},
changeIndexes_2: function(model, attrValue) {
// do something
}
});