【问题标题】:Backbone view not listeningTo a model change主干视图不听模型更改
【发布时间】:2013-09-11 12:26:29
【问题描述】:

数据结构:

- Measure (collection)
  - Measure (model)
     - beats (c)
       - beat (m)
         - on/off (attribute)
     - representations (c)
       - representation (m)
         - currentType (attribute)
         - previousType (a)

通过转换函数调用表示模型,我通过控制台打印输出注意到更改,但是,视图根本没有注册更改。我可以访问点击事件,所以我知道视图的el 是正确的。为什么 listenTo 在视图中不起作用?

表示模型:

define([
  'underscore',
  'backbone'
], function(_, Backbone) {
  var RepresentationModel = Backbone.Model.extend({
    initialize: function(options){
      this.representationType = options.representationType;
      this.previousRepresentationType = undefined;
    },
    transition: function(newRep){
      this.previousRepresentationType = this.representationType;
      this.representationType = newRep;
      console.error('model change : ' + this.previousRepresentationType + ' ' + this.representationType);
    }
  });
  return RepresentationModel;
});

测量表示视图:

define([…], function(…){
  return Backbone.View.extend({
    initialize: function(options){
      if (options) {
        for (var key in options) {
          this[key] = options[key];
        }
      }
      //Dispatch listeners
      …
      //Binding
      //this was the old way, so I changed to the new listenTo to take advantage of when the view is destroyed.
      //this.model.bind('change', _.bind(this.transition, this));
      this.listenTo(this.model, 'change', _.bind(this.transition, this));

      this.render();
    },

    render: function(){
      // compile the template for a representation
      var measureRepTemplateParamaters = {…};
      var compiledTemplate = _.template( MeasureRepTemplate, measureRepTemplateParamaters );
      // put in the rendered template in the measure-rep-container of the measure
      $(this.repContainerEl).append( compiledTemplate );
      this.setElement($('#measure-rep-'+this.measureRepModel.cid));

      // for each beat in this measure
      _.each(this.parentMeasureModel.get('beats').models, function(beat, index) {
          measurePassingToBeatViewParamaters = {…};
        };
        new BeatView(measurePassingToBeatViewParamaters);
      }, this);

      return this;
    },

    transition: function(){
      console.warn('getting in here'); //NEVER GET HERE
      console.log(this.model.get('previousRepresentationType') + '|' + this.model.get('representationType'));
    }
  });
});

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    仅当您使用model.set 进行更改时才会触发更改事件。您不能只分配新属性。 Backbone 没有使用 defineProperty 样式,它是一种更明确的样式。

    this.set({
      previousRepresentationType: this.representationType,
      representationType: newRep
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 2014-05-24
      • 2014-10-06
      • 1970-01-01
      • 2023-03-13
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多