Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent backbone model to collection event propagation?

How do I prevent Backbone Model events from propagating to Backbone Collections?

Edit:

Let's say I have something like the following, where CollectionView contains a collection of MyModels...

var CollectionView = Backbone.Collection.Extend({
    initialize: function() {
        this.collection.on("change", doStuff);
    }
});

var ModelView = Backbone.View.Extend({ 
    initialize: function() {
        this.model = new MyModel();
        this.model.on( "change", doStuff );
        this.model.fetch();
    }
});

If in a special case I did not want the "change" event to propagate up to the collection after fetch completes, I am wondering if there is any way to stop it.

Thanks

like image 838
user1031947 Avatar asked Feb 15 '13 18:02

user1031947


1 Answers

To prevent a model from firing a change event:

model.set(attrs, {silent: true});

This may not be what you want, though, because this will also prevent the model's change event from firing.

Collections pass through all model events, but what you can do is pass extra options which will also get passed through:

model.set(attrs, {dontBubble: true});

And in your CollectionView:

var CollectionView = Backbone.View.extend({
  this.initialize = function() {
    this.collection.on('change', doStuff, this);
  },
  this.doStuff = function(model, collection, options) {
    if (options.dontBubble) {
      return;
    }
    // Do some stuff.
  }
});

Granted, it's a little ugly, but it's one way to go about it.

like image 124
satchmorun Avatar answered Sep 23 '22 00:09

satchmorun