5

使用 .on() 将多个事件绑定到 Backbone 集合时,我如何知道在 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();
4

2 回答 2

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);
}
于 2012-07-03T16:03:40.853 回答
0

您需要覆盖trigger这样做的方法,看看代码:

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

于 2012-07-03T08:22:12.327 回答