I got a problem with backbone.js collection.add used in a view initialize(); in my app when you change sections I remove my views but I dot not remove my collections used in that section (collections are initialized empty on app load).
If someone come back in my section I use the same collection, and initialize a this.collection.add() on it. However as a side effect the collection add 2 times the model in my new view now, is there a way to prevent that behavior?
Event stranger it only happen in Firefox.. Also, this double collection.add make no sense, since I clearly see that its not the same view number (even is it comes from the same variable.)
You have to manually unbind the event listeners when you change views – otherwise the event listeners will keep references to the removed views in the memory and they will never be garbage collected. In long term it can cause massive memory leaks and whole system slow downs as your app starts eating resources.
Currently there is no built in solution for that in Backbone so you have to handle it yourself .
pro tip 🙂
you can for example listen to route change from the view and if route changes then call a “onDestroy” method which could clean up all the references
other option is – instead of removing views – use jquery
detachmethod which doesn’t clean up all the jquery dom/custom events and reuse same view multiple times