Search code examples
backbone.js

How does model event binding work in backbone.js?


I got a line in the codebase that I inherited and it goes like this:

App.Models.Configuration   = Backbone.Model.extend({
  initialize: function(){
    this.bind('change', function(config, options){
      this.save_previous_state();
      // ---- 8< ---- snip
    })
  },

  // ---- 8< ---- snip
})

My question is, the anonymous function that gets called: function(config, options){} - what are the objects being passed to it, the config and options?


Solution

  • In the Backbone docs, at the bottom is the catalog of events.

    The Model's change event is passed the model, and a hash of options:

    So, in your case, config = the changed model = itself.

    Inside that event handler, you can access a few fun things like the attributes that changed:

    http://backbonejs.org/#Model-changedAttributes

    The previous state of the attributes before the change:

    http://backbonejs.org/#Model-previousAttributes