Search code examples
javascripteventsbackbone.jsbackbone-events

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


In Backbone.js I want to raise a custom event on a collection but am having difficulty passing along the id (or any arbitrary data) from the originating, changed model to the listener of the event.

Simply put, the following sample initiates an event each time the property 'Speed' changes on my model:

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);
    }
});

Now this lets me do something like this:

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)?
});

Note that this all works, but the questions is: how to get get the car_id from the model that changed and pass it along to the caller/listener?


Solution

  • AFAIU, you want to pass car_id attribute of changed model to custom event. You can use get method to get the current value of needed attribute:

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