簡體   English   中英

如何從以當前模型為參數的模型方法中觸發集合的方法

[英]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() {}
);

並已方法changeIndexes與模型,並引發increase=true每當modelFromCollection.increse()被觸發,並有increase=false每當modelFromCollection.decrease()被觸發?

我的第一個猜測是使用在集合內傳播的自定義事件。 這是要走的路,還是有更好的方法?

要從模型的函數調用changeIndexes,可以直接引用該集合。

var Chapter  = Backbone.Model.extend({
    increase: function(){
        this.collection.changeIndexes(this, true);
    },
    decrease: function(){
        this.collection.changeIndexes(this, false);
    },
});

或者,集合可以偵聽模型上的change事件。

var Chapters = Backbone.Collection.extend({
  initialize: function(){
      this.on('change:index', this.changeIndexes_2);
  },
  changeIndexes_2: function(model, attrValue) {
      // do something
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM