user2309394
user2309394

Reputation: 53

How do you listen on change events in the model from a view using the shorthand 'events' object?

I've got the following BackboneJS view, which has a model:

view = Backbone.View.extend({
   events: {
       // This will fire btnClicked() when the button is clicked
       "click .btn": "btnClicked",

       // Will this fire when the "data" property of my model changes?
       "change:data": "render"
   },
   btnClicked: function() {},
   render: function() {}
});

Any idea if it is possible to use this shortcut?

If not, the extended form would be:

this.model.bind("change:data", render);

Upvotes: 1

Views: 266

Answers (2)

Andrew Hubbs
Andrew Hubbs

Reputation: 9426

As Kyle said, the events hash is for delegating DOM events to the view object.

Something worth adding, you should usually use the listenTo form instead of the bind approach as this will handle the event cleanup for you (one of the main upsides of using the events hash for DOM events).

this.listenTo(this.model, "change:data", render);

Upvotes: 1

Kyle Burton
Kyle Burton

Reputation: 27528

That events map is for views to listen to UI events, not for wiring up data events.

The Documentation on Views states

Uses jQuery's on function to provide declarative callbacks for DOM events within a view.

So the View's event map can't be used for model events.

Upvotes: 1

Related Questions