在Backbone集合上使用.on()获取多个事件时获取事件名称。

时间:2012-07-03 08:19:14

标签: backbone.js backbone-events

如何使用.on()将多个事件绑定到Backbone集合时触发什么事件?有关说明,请参阅以下示例。 (另见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();

2 个答案:

答案 0 :(得分:1)

如果我们想要针对每个事件采取特定的操作,那么最有序的方法就是监听每个事件,如果你想要有一个整体更改监听器,当你在监听器内调用它时自己指定事件名称时也是如此。

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 :(得分:0)

您需要覆盖trigger方法,看一下代码:

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