Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a single Backbone Model Instance be in two collections at once?

Tags:

backbone.js

I understand that it's "this.collection" value will only show the first collection, but is this otherwise compatible with Backbone? Or will it automatically get removed from the previous collection?

var MyModel = Backbone.Model.extend({defaults: {test: '123'}});
var MyCollection1 = Backbone.Collection.extend({model: MyModel});
var MyCollection2 = Backbone.Collection.extend({model: MyModel});

var instance = new MyModel({
    test: '456'
});
MyCollection1.add(instance);
MyCollection2.add(instance);

console.log(instance.collection); //Returns "MyCollection1" only, not an array of all collections of which this model is a member

The above code works, I'm just wondering if I'm breaking anything (particularly related to events) by doing this.

like image 879
AlexZ Avatar asked Apr 03 '14 12:04

AlexZ


1 Answers

TL;DR Nothing will break, you can verify this by looking at the source, add is a shorthand method for, set(model, {add: true, remove: false, merge: false})

If you look at the set method the part where it modifies the model is here,

 _addReference: function(model, options) {
  this._byId[model.cid] = model;
  if (model.id != null) this._byId[model.id] = model;
  if (!model.collection) model.collection = this;
  model.on('all', this._onModelEvent, this);
},

So the models' collection will not be set to the new one if it already has one, but all events will still be passed through correctly from all collections it is added to.

The reverse is also true, any collection events are called by iterating on the models in the collection,

 for (i = 0, l = models.length; i < l; i++) {
    ...
    if (!options.silent) {
      model.trigger('remove', model, this, options);
    }
    ...
  }
like image 195
Andrew Avatar answered Nov 10 '22 07:11

Andrew