监听集合添加/更改作为视图的模型属性

时间:2014-07-17 19:04:45

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

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

我知道如果你正在听change事件,那么当添加某些内容时,该集合不会响应。你应该使用bind。文档并不是最好的。因此,如果子表示视图看起来像这样:

here is a visual

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视图中,当任何兄弟视图点击“添加节拍”时,我们如何让表示视图重新渲染

1 个答案:

答案 0 :(得分:3)

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

技巧在于表示。查看替换

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