Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I know what event is triggered on a Backbone collection when binding multiple events to it using .on()? See the following example for clarification. (Also see the 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();
like image 550
Benny Johansson Avatar asked Nov 13 '22 02:11

Benny Johansson


1 Answers

If we want specific actions per event the most ordered way is to listen every one, also if you want to have an overall change listener when anything change call it inside your listeners and specify the event name at yourself.

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);
}
like image 119
Daniel Aranda Avatar answered Apr 30 '23 03:04

Daniel Aranda