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();
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);
}
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