Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js - Custom collection events

I'm trying to implement custom collection events for view binding.

In my view I want to do something like:

this.collection.on('available', this.available);

And somehow trigger this in method within my collection.

So say I have a method in my collection which sets a particular models attribute (available), how could I then trigger all views that are bound to this method?

Is this possible, and able to pass the model in question to the view for updating.

Thanks for any help in advance, much appreciated :)

like image 719
jahilldev Avatar asked Sep 19 '12 10:09

jahilldev


1 Answers

It's very simple to add new events to Backbone. You just need to call the trigger method on the object that you want to trigger the event on.

For example, assuming you're in a method of the collection, and have a model (called model):

this.trigger('available', model);

The code to bind to the available event would just be as you described in your question.

EDIT: These days Backbone provides a listenTo method that you should usually use when binding to collection events from your views. Views will automatically unbind from this event when their remove function is called, which stops old views from continuing to receive collection events after they have been removed. From your view, this can be used like this:

this.listenTo(this.collection, 'available', this. available);
like image 104
obmarg Avatar answered Sep 28 '22 13:09

obmarg