Search code examples
javascriptbackbone.jsbackbone-views

One-line callbacks in Backbone.js events object


In my Backbone view I have an events handler and a callback:

events: {
    "click .update": "update"
},

update: function() {
    this.model.fetch();
},

However this seems a bit excessive, it'd be much easier if I could just do something like this:

events: {
    "click .update": this.model.fetch
}

Is there any way to formulate the events object so that I can call the fetch() function without creating another wrapper function for it?


Solution

  • From the fine manual:

    If an events hash is not passed directly, uses this.events as the source. [...] The callback may be either the name of a method on the view, or a direct function body.

    So you can use anonymous functions in events:

    events: {
        "click .update": function() { this.model.fetch() }
    }
    

    Also, Backbone will use the view as the this when calling the function so this.model will be the right thing.

    Demo: http://jsfiddle.net/ambiguous/svVsu/