Can one instance of the Backbone Model be in two collections at once?

I understand that this value of this this.collection will only display the first collection, but is it compatible with Backbone? Or is it automatically deleted 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 am breaking something (especially related to events) by doing this.

+6
source share
1 answer

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

If you look at the installation method , then the part where the model changes 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); }, 

Thus, the collection of models will not be installed on a new one if it already exists, but all events will still be transmitted correctly from all collections added to it.

The reverse is also true, any collection events are triggered by iterating over the models in the collection,

  for (i = 0, l = models.length; i < l; i++) { ... if (!options.silent) { model.trigger('remove', model, this, options); } ... } 
+8
source

All Articles