Getting event names when using .on () for multiple events in the Backbone collection.

How do I know which event is fired in the Backbone collection when multiple events are bound to it using .on ()? See the following example for an explanation. (Also see JsFiddle: http://jsfiddle.net/PURAU/3/ )

var Car = Backbone.Model.extend({
    nrOfWheels: 4,
    color: 'red',
    speed: 'slow'
});

var Garage = Backbone.Collection.extend({
    model: Car
});

var myGarage = new Garage(),
    myCar = new Car();

myGarage.on('add change reset', function() {
    // How do I know what event was triggered?
    console.log('add change reset', arguments);
});

myGarage.on("all", function() {
    // In here, the name of the event is the first argument.
    console.log('all', arguments);
});

// Trigger add
myGarage.add(myCar);

// Trigger change
myCar.set('speed', 'fast');

// Trigger reset
myGarage.reset();
+5
source share
2 answers

To do this, you need to override the method trigger, see the code:

https://github.com/documentcloud/backbone/blob/master/backbone.js#L148

0
source

, , , - , .

myGarage.on('add', function() {
     yourGlobalFunction(arguments, 'add');
     //specific actions for add
});
myGarage.on('change', function() {
     yourGlobalFunction(arguments, 'change');
     //specific actions for change
});
myGarage.on('reset', function() {
     yourGlobalFunction(arguments, 'reset');
     //specific actions for reset
});

function yourGlobalFunction(prevArguments, eventName){
   log(prevArguments, eventName);
}
+1

All Articles