【问题标题】:listen to a collection add/change as a model attribute of a view监听集合添加/更改作为视图的模型属性
【发布时间】:2014-07-17 19:04:44
【问题描述】:

我有一个 Measure View,它有一个关联的 Measure Model,它有两个集合,RepresentationsCollection 和 BeatsCollection。 Measure View 具有嵌套的子 Representation 视图,每个视图都有自己的表示模型,并且所有表示模型共享对 Measure View 的 BeatsCollection 的引用的相同属性。

我知道,如果您正在收听 change 事件,则在添加某些内容时集合不会响应。你应该使用绑定。文档不是最好的。所以如果子表示视图看起来像这样:

representation.View = Backbone.View.extend({
  initialize: function(options) {
    // this.beatsCollection is a reference to the Parent Measure View attribute beatsCollection which is a collection
    this.model.listenTo(this, 'change:beatsCollection', this.render);
    this.model.on('change:beatsCollection', this.render, this);
    this.bind.listenTo(this, 'change:beatsCollection', this.render);
  },

这是模型:

representation.Model = Backbone.Model.extend({
  initialize: function(options) {
    console.log(options); 
    this.idAttribute = options.idAttribute;
    this.type = options.type;
    this.beatsCollection = options.beatsCollection;
 } 

如何侦听此视图关联模型上的属性,该模型具有链接到另一个模型上的集合的属性?

这是Plnkr: http://plnkr.co/edit/z4mWqo1v0nDe13TiB9r3?p=preview
首先点击“添加代表”。
其次,单击“添加节拍”并注意节拍数不会更新。 第三,如果您再次单击“添加表示”,它将添加另一个具有正确节拍数的表示。 在 Representation.js 视图中,当任何同级视图单击“添加节拍”时,我们如何让表示视图重新渲染

【问题讨论】:

    标签: backbone.js backbone-events backbone.js-collections backbone-model


    【解决方案1】:

    更新的 Plnkr:http://plnkr.co/edit/JtyxnhaGlPVijhbRPt5v?p=preview

    trick is here in representation.View 替换

    initialize: function(options) {
      if(options.model){this.model=options.model;}
      this.model.listenTo(this, 'change:beatsCollection', this.render);
      this.model.on('change:beatsCollection', this.render, this);
      this.model.on('change:beatsCollection', this.render, this);
      //this.model.on('destroy', this.remove, this);
    },
    

    initialize: function(options) {
      if(options.model){this.model=options.model;}
      this.listenTo(this.model.beatsCollection,  'add remove reset', this.render);
    },
    

    【讨论】:

    • 这个只听添加。我应该链接removechange 还是应该使用bindbindAll。如果有,怎么做?
    • 还要注意 beatsCollection 不是模型的属性,所以 change:beatsCollection 永远不会被触发。即使您将其设为属性,因为它们是通过引用传递的 change:beatsCollection 永远不会被触发。
    • 所以即使它被存储为一个属性,我还是应该把它当作一个集合来对待?
    • 我建议继续使用 model.beatsCollection 并像收藏一样继续收听它。这使代码更具可读性,并消除了触发更改事件的混乱。
    • 请注意,在初始化函数中设置this.model 是不必要的,因为 Backbone 会为您完成。
    猜你喜欢
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多