I've been having some difficulty understanding exactly what happens when a model is manipulated in Backbone.
1) When calling #get on a Collection to "grab" a model, is the model the same model as the Collection's model? (e.g., updating the model will update the Collection's model)
2) If a model is added to various collections, do all of those collections contain the actual model (or a "copy" of the model)? It seems to me that it's the "copy" because when I try to destroy a model that has been added to various collections, not all the models in the various collections are destroyed.
Thanks! Appreciate any insights.
Like every other object in Javascript, Backbone objects are 'passed by a copy of the reference'. The best way to think about this is that javascript has a piece of data in memory, and variables are nothing more than pointers to those bits of data. When you set one variable equal to another, what you really get is two copies of the pointer, both pointing at the same piece of data in memory. So, applying this to your question:
model.destroy()
will trigger a destroy event on both
the model and the collection it is holding a pointer to in it's
collection attribute. However, the model can not hold pointers
to multiple collections if it is a part of more than one collection.
So on your destroy
event, it is removed only from the collection it was last assigned to - the one it holds in the model.collection attribute. Ordinarily, when no variables are holding pointers to the piece of data in memory, that memory will be erased, however, in this case, because your other collections have pointers to the model, the model remains in memory as a part of those collections.