Search code examples
javascriptbackbone.jsbackbone.js-collections

Backbone: pass or retrieve details on a Collection update


I think this gets my question across.

var coll = myBackboneCollection();
coll.on('update', this.collUpdated, this);
coll.create({ id: 1 });

collUpdated: function (collection, options) {
    var newId = ???;
}

I want to know that newId is 1 in the callback function. Is this possible? I'd prefer not to use a state variable on the Collection if possible.


Solution

  • From what I can see in the docs, create only triggers the following directly:

    Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model

    judging by that, you should be listening to the add event.

    Also note that the signature of create method is collection.create(attributes, [options]).

    So if you are trying to set the actual id property of the model, you should be passing it in the options as the second argument:

    var coll = myBackboneCollection();
    coll.on('add', this.collUpdated, this);
    coll.create({},{ id: 1 });
    collUpdated: function (model, collection, options) {
      if(model.id === 1){
      }
    }