Search code examples
backbone.js

Do not trigger add event on adding a model to a collection


Is there a way not to trigger add event when i am adding a new model to a collection by collection method add or push Example:

collection.add({name: 'any name'})

I tried like giving

collection.add({name: 'xyz'}, {add: false})

but it is not working


Solution

  • @idbehold has perfectly answered this. You can pass {silent: true} in the options to suppress the add event. I just want to add some information from the documentation. Read what it says

    Generally speaking, when calling a function that emits an event (model.set, collection.add, and so on...), if you'd like to prevent the event from being triggered, you may pass {silent: true} as an option.

    Note that this is rarely, perhaps even never, a good idea.

    Passing through a specific flag in the options for your event callback to look at, and choose to ignore, will usually work out better.

    So, consider passing an additional flag in the options and check that flag in your event listener to ignore what you do not need.

    Check this Jsbin Example

    var M = Backbone.Model.extend({ defaults: { a: 5 } });
    var C = Backbone.Collection.extend({ model: M });
    
    var c = new C();
    var m = new M({a:1});
    
    c.on('add', function(model, collection, options) { 
      console.log(options); 
      if (!options.flag) { return; }
    });
    
    c.add(m, {flag: false});