2

I need to tell if model inside add event was retrieved with collection.fetch or created by collection.create. Is it possible?

collection.on('add', onModelAdded)
collection.fetch()
collection.create({})

function onModelAdded(model, collection, options) {
   // created or fetched?
}
Andrey Kuzmin
  • 4,479
  • 2
  • 23
  • 28

2 Answers2

2

I'd guess that something like this create override would work:

create: function(attributes, options) {
    options = options || { };
    options.came_from_create = true;
    return Backbone.Collection.prototype.create.call(this, attributes, options);
}

Then you could look for came_from_create in your callback:

function onModelAdded(model, collection, options) {
    if(options && options.came_from_create) {
        // We started in a create call on the collection.
    }
    else {
        // We came from somewhere else.
    }
}

You can usually use the options argument to piggy back bits of data around if you're careful not to use any option names that Backbone wants to use.

Andrey Kuzmin
  • 4,479
  • 2
  • 23
  • 28
mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

from Backbone Docs

isNew

Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.

Backbone source :

isNew: function() {
   return this.id == null;
},

When creating model not setting id then it's a new model (model without id considered as new), and therefore model.isNew() returns true

function onModelAdded(model, collection, options) {
   if(model.isNew()){
       // It's created
   }else{
       // It's fetched!
   }
}
KiT O
  • 867
  • 6
  • 21
  • Unfortunately I cannot rely on this, because I might have `{wait: true}`. – Andrey Kuzmin Oct 15 '13 at 20:51
  • Another idea is to set a flag (by overriding backbone create method) and after model save complete unset the flag, `create: function(model,collection){ ... if (options.wait) { model.createdNew = true; model.once('sync',function(){delete this.createdNew}; } ... }` Can't test this solution, but hope it works! – KiT O Oct 15 '13 at 21:06