user1615817
user1615817

Reputation: 1

Backbone events hash with collections

Im trying to utilize Backbone's view events hash to bind a change event to the current view's collection:

events: {
    'this.collection change': 'render'
}

as opposed to my current method:

initialize: function() {
    this.collection.on('change', this.render, this);
}

but this does not seem to fire the event. Are their limitations on binding events to collections using the events hash?

Upvotes: 0

Views: 975

Answers (2)

Jon Onstott
Jon Onstott

Reputation: 13727

If you were using Marionette views, you can use collectionEvents in the way you mentioned. See http://marionettejs.com/docs/marionette.view.html#viewmodelevents-and-viewcollectionevents.

collectionEvents: {
    'change': 'render'
}

If you're using plain Backbone, orangewarp's suggestion of listening to the collection's change event using this.collection.on is the way to go.

Upvotes: 0

jmk2142
jmk2142

Reputation: 8581

events: {
    // hash
}

Is for hooking up your DOM events to your view functions.

this.collection.on('change', this.render, this);  // Except change is for models

in the initialization function is the way to do it, except the change event is for models and not collections, unless you have designated a custom change event for the collection that is properly triggered.

What you might be looking for is to bind an add remove or reset event to your collection.

Upvotes: 3

Related Questions