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 :)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With