Search code examples
javascriptbackbone.jsbackbone-events

Backbone js: Only render when specific attributes have changed?


I know that in a backbone view you can bind to the change event to rerender like this:

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

However is there a way to only render when specific attributes change? I.e. specify a whitelist (or blacklist) of attributes that should or shouldn't trigger a re-render?


Solution

  • If you have a whitelist of attributes you can do the following

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