【发布时间】:2014-11-07 15:00:03
【问题描述】:
在 Backbone.js 中,我想在集合上引发自定义事件,但在将 id(或任何任意数据)从原始更改模型传递到事件侦听器时遇到困难.
简单地说,每次我的模型上的属性“速度”发生变化时,以下示例都会启动一个事件:
var CarCollection = Backbone.Collection.extend({
model: Car,
url: '/api/cars/',
parse: function (response, options) {
return response;
},
initialize: function () {
// if the car's 'Speed' changes, trigger the event
this.on('change:Speed', this.onSpeedChanged, this);
},
onSpeedChanged: function(car_id) {
// QUESTION: how to get 'car_id' here?
this.trigger('SpeedChanged', car_id);
}
});
现在这让我可以做这样的事情:
var cars = new CarCollection();
cars.on("SpeedChanged", function (car_id) {
console.log("This also works!");
// QUESTION: how to get 'car_id' here (= undefined, of course)?
});
请注意,这一切都有效,但问题是:如何从更改的模型中获取 car_id 并将其传递给调用者/侦听器?
【问题讨论】:
-
在您的示例中,
car_id不是未定义的,而是更改来自的模型:jsfiddle.net/nikoshr/d2La14g7
标签: javascript events backbone.js backbone-events