如何从以当前模型作为参数的模型方法触发集合的方法

How to trigger collection's method from a model method with a current model as a parameter

我有以下设置:

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"}));

根据要求,我需要更改章节索引。我有什么办法可以使用以下语法在 Chapters 集合上实现方法 changeIndexes

var Chapters = Backbone.Collection.extend({
  changeIndexes: function(model, bool: increase) {
    // change indexes of the model and sibling models here
  }
});

和方法 increasedecrease 来自集合的模型:

var Chapter = Backbone.Model.extend({
   increase: function() {},
   decrease: function() {}
);

并在触发 modelFromCollection.increse() 时使用模型和 increase=true 触发方法 changeIndexes,并在触发 modelFromCollection.decrease() 时使用 increase=false

我的第一个猜测是使用在集合中传播的自定义事件。这是可行的方法还是有更好的方法?

要从模型的函数中调用 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
  }
});