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

时间:2014-11-07 15:00:03

标签: javascript events backbone.js javascript-events

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

1 个答案:

答案 0 :(得分:1)

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

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