Search code examples
backbone.js

Backbone: Does Collection#get return a copy of the model or the model object itself?


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.


Solution

  • 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:

    1. Yes. When you 'get' the model, what you 'get' from backbone is a pointer to the place in memory where the object is stored. Now you have two pointers (one in the collection and one in your variable), and you can perform operations on either of them and either will perform that operation on the same piece of data in memory.
    2. Kind of. Each collection has, again, a pointer to the same object/model. When you remove that pointer from a collection, the other pointers remain pointing to the same piece of memory, and that memory is not erased, because it's still being pointed at from other collections. 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.