unblevable
unblevable

Reputation: 1316

How does one define a Backbone View events hash as a function?

The Backbone documentation says

Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime.

I have yet to see examples that make use of this feature. Can someone show me how it can be implemented?

Upvotes: 1

Views: 2288

Answers (1)

jevakallio
jevakallio

Reputation: 35940

In its simplest form, you just return a events hash object from a function:

View = Backbone.View.extend({
  events: function() {
    return {
      "click #save" : "save"
    };
  }
});

Of course, this doesn't make so much sense. This feature can be useful if you need to bind events conditionally or use some information, which is only available at runtime:

View = Backbone.View.extend({
  events: function() {
    return {
      "click #save" : this.model.isNew() ? "create" : "update"
    };
  }
});  

Upvotes: 5

Related Questions