在Backbone.js集合上引发自定义事件并传递数据

Raising custom event on Backbone.js collection and pass along data

本文关键字:事件 数据 自定义 js Backbone 集合      更新时间:2023-09-26

在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,并将其传递给调用者/监听器?

AFAIU,您希望将更改后的模型的car_id属性传递给自定义事件。您可以使用get方法来获得所需属性的当前值:

var CarCollection = Backbone.Collection.extend({
    ...
    onSpeedChanged: function(model) {
        // model - changed model
        this.trigger('SpeedChanged', model.get('car_id'));
    }
});