【问题标题】:Backbone js: Only render when specific attributes have changed?Backbone js:仅在特定属性发生更改时渲染?
【发布时间】:2014-11-07 11:33:16
【问题描述】:

我知道在主干视图中,您可以绑定到更改事件以像这样重新呈现:

initialize: function() {
  this.model.bind('change', this.render, this);
},

但是有没有办法只在特定属性发生变化时才进行渲染? IE。指定应该或不应触发重新渲染的属性的白名单(或黑名单)?

【问题讨论】:

    标签: javascript backbone.js backbone-events


    【解决方案1】:

    如果您有属性白名单,您可以执行以下操作

    var whitelist = ['att1', 'attr2'];
    this.model('change', function(model){
        var hasChanged = function(attr) { //check if attr has changed
                return model.hasChanged(attr);
            };
        if(whitelist.some(hasChanged)) { //some attr has changed
           this.render();
        }
    }, this);
    

    【讨论】:

      【解决方案2】:

      Backbone 也会在每个属性发生变化时触发一个 change 事件,格式为 change:attributeName,所以下面就是你想要的:

      initialize: function() {
        this.model.bind('change:attributeName', this.render, this);
      },
      

      来自the docs:

      "change:[attribute]" (model, value, options) — 当特定属性被更新时。

      【讨论】:

        【解决方案3】:

        你只能像这样指定一个属性

        change:attributeNmae
        

        例子:

        this.model.bind('change:name', this.render, this);
        

        仅当名称更改时才会调用render

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-21
          • 1970-01-01
          相关资源
          最近更新 更多