Skip to content Skip to sidebar Skip to footer

Binding Events To Dynamic Objects In Underscore/backbone

I'm trying to figure out how to listen for custom events on objects which have not been prototyped or are not dom objects in underscore.js/backbone.js. for example: //this is insid

Solution 1:

if you want to bind to an object, you will need to make it extend from the Backbone.Events object.

lets say you create a new object

var o = {};

you can't bind to it, o.bind() does not exist

unless you extend from backbone.Events.

var o = _.extend({}, Backbone.Events);

o.bind('myCustomEvent', function(){
    alert('triggered!');
});

o.trigger('myCustomEvent');

i'm not sure what this means on performance if you want to start binding to hundreds of objects. so you should test around with this before just using it.

this is also the technique used to create a global event Aggregator in your app, as described by Derick Bailey in his post (http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js)

Post a Comment for "Binding Events To Dynamic Objects In Underscore/backbone"