When i call destroy on a marionette view and later try to use it throws an error saying it has been destroyed. Also when i remove the view from the DOM directly it also throws the same error. So i need to know how i can certain that the view is destroyed.
You can check whether a view has been destroyed or not using the view's isDestroyed property.
// Example
if (view.isDestroyed) {
view = new View({});
}
view.doSomething();
So #JonathanMiles is correct but I think some elaboration may help you and our Googlers.
You aptly mentioned two ways in which you may destroy a view.
Call this.destroy() on your view. The .destroy() method does several crucial things: 1. sets the view.isDestroyed bit so that Marionette can know that your view has been removed from the DOM; removes the view from the DOM and most bindings attached to it by calling view.remove() which eventually calls view.$el.remove(), and removes other bindings that view.$el.remove() does not (like Marionette ui elements and behaviors).
Simpy do this.$el.remove() on your view. This removes the HTML associated with the view from the DOM as well as events bound to that HTML, but not events that are created on cached HTML elements.
Now, with the first mentioned, it's obvious that Marionette will know that the view is destroyed. If you need to know whether the view is destroyed, like #JonathanMiles pointed out, simply obtain a reference to your view and check the value of view.isDestroyed.
But, if you decide to remove the view HTML from the DOM yourself, Marionette will not know if the view is not in the DOM. You may get errors, specifically since you may still have events bound to a view without HTML associated with it (although most of these situations would probably just pass silently unnoticed), but not from Marionette. Even worse, you may decide that to replace the rejected view, you'll spawn new views. The old view instance however will still live. While you won't have zombie events, this is a potential memory leak.
The moral of the story is don't simply do view.$el.remove(). Use Marionette's view.destroy() to completely free the view object for garbage collection, and reap the advantage of knowing if the view .isDestroyed.
Related
What are the advantages and disadvantages of the following 2 lines of code? I don't understand why there are 2 different ways to do the same thing.
this.listenTo(app.Todos, 'change:completed', this.filterOne);
app.Todos.on('change:completed', this.filterOne);
Also when using .on, how do I determine is the default context?
listenTo is the newer and better option because these listeners will be automatically removed for you during stopListening which is called when a view gets removed (via remove()). Prior to listenTo there was a really insidious problem with phantom views hanging around forever (leaking memory and causing misbehavior) because view methods were referenced as event listeners on models even though the view instances themselves were long gone and no longer in the DOM.
If you want to read the back story for listenTo, search the backbone github repository for listenTo and read through some of the longer issue discussions.
As to the default context, several things can end up bound to this:
if you do the binding via this.listenTo, it will always be the view instance (pointed out by Wim Leers in the comments)
without this.listenTo, the story gets complicated
For misc events, it will be the global object (best to avoid this)
for DOM events, it will be the source element just like in regular DOM event binding
If you provide an explicit context (the 3rd argument to foo.on), backbone will use that (thus this is a more robust approach)
If you use the ECMA standard function () {//your event handler}.bind(this), you can also manually control the context (also recommended)
As #mu pointed out, _.bind or $.proxy are available alternatives to ECMA function.bind
For backbone views, doing this.bindAll('onClick', ...) will ensure the view instance is the this context when any view methods are used as event handlers
any events wired up by using the view's standard events property will get bound for you automatically to the view instance by backbone (this is belt & suspenders with bindAll)
So to summarize into some guidelines:
use the events property whenever possible as it is concise and correct
use this.listenTo for all bindings to models and collections
any additional bindings remember to bind the context reliably using your preferred method. I usually use ECMA Function.bind because hey, standards, but there are several good options here.
With listenTo, the object whose events you want to listen to is passed as the first argument. In the case of on, it is actually a method on that object.
The advantages of listenTo over on are:
The listener keeps track of all the event handlers, making it easier to remove them all at once when needed.
The callback’s context is always set to the listener itself.
I'm currently working with a CompositeView. The problem is, when I call destroy() on one of the child views from the CollectionView part, it still remains in the this.children._view obejct, even do it disappears from the screen.
If I try to do anything with it (let's say call destroy() again) than it says, it has already been destroyed, but than why doesn't it get deleted from the object?
Thanks in advance.
Child views are not parent aware
This may sound annoying, but it's set up like that by design, since a CollectionView child may also exists on its own. As far as I can't tell children of a Collection View are not aware that they are children (except for the case that the model is destroyed [and thus removed from permanent storage]).
CollectionView.removeChildView can help
However, Marionette does expose a CollectionView method that is made exactly for what you want to do, CollectionView.removeChildView(view).
CollectionView.removeChildView will remove the view from the DOM, destroy the view (remove any listeners on the view) and remove it from the children container. Just pass in one of your views.
If you need some tips on how to trigger CollectionView.removeChildView on an event on your child view, drop me a comment.
I am building a SPA and am trying to figure out a safe and clean way to delete all backbone entities when navigating away from one section of the application. I am aware of the Model.destroy(), View.remove() and Collection.reset() methods. My main concerns are:
Model.destroy() takes care of destroying the model on the server. Does one still need to manually delete the Javascript model?
Similariy, I realize that View.remove() will remove the view from the DOM. How should one safely get rid of the view object?
Collection.reset() clears the models in the collection. Will this also delete the underlying Javascript model objects or do they need to be explicitly deleted?
How would one get rid of the collection object itself?
My questions may seem simple to some but they have been confusing me for a while. I have not found any useful information regarding this exact problem which is why I decided to post here. I am also a relatively new to Javascript and am unaware of Javascript's garbage collection scheme. Does Javascript have a garbage collector and will it take care of deleting all such objects?
I am also looking into understanding the best way to remove Views.
View.remove() only removes the view from the DOM. My guess is that one still needs to take care of removing/destroying the underlying Model and unbinding all event listeners. Is that correct?
I often use _.bindAll to change the context of a function call. I have not come across a way to unbind this binding. My understanding says that this is unnecessary. Am I right?
Here is a good resource for learning about garbage collection in javascript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
To summarize, the only thing you need to worry about with Backbone is removing custom event handlers in your view, and a common way to do this is to override remove and remove the handlers before calling Backbone.View.prototype.remove. You don't need to manually remove events that you declared in the events property of the view, if you are using that.
To be a little more specific, lets consider the three types of objects you are asking about in turn. If you are using the backbone router, then you are probably creating a view object in a router method, maybe assigning it to a var, and then setting the html somewhere on the page. When the user navigates away, a different router method is invoked, and the reference you created to this view is unreachable. It will get garbage collected assuming you didn't create it as a property on window or your root level object or something like that.
The remove method is about removing the view from the DOM. The garbage collector takes care of removing the view from memory. The remove method is a convenient place to put any cleanup code that you need to run before taking the view off the page, so unhook your custom event handlers here.
Likewise, model.destroy is not about destroying the model object stored in memory, its about sending an AJAX DELETE request to the server. Model objects are garbage collected like everything else, and will go away once they are unreachable. If the only references to a model are contained within a view, then removing that view will cause the model to be garbage collected. Same goes for collections.
And for your last point, the underscore bind will not be an issue. Its about binding context (the value of this that a function is invoked with), not about binding event handlers. Remove those event handlers as usual.
Model.destroy() takes care of destroying the model on the server. Does one still need to manually delete the Javascript model?
Yes, you still need to manually delete the model. Model.destroy() does not delete it.
Similariy, I realize that View.remove() will remove the view from the DOM. How should one safely get rid of the view object?
Remove all references to it. If nothing is pointing at your object it will get garbage collected. Generally speaking, unless you go out of your way to make sure references to an object stay alive (such as global variables) or get careless with .on() you should be ok.
Note that using .listenTo() on your views instead of .on() makes your life easier. Memory leaks with views used to be a big problem when we just had .on()(See here for more).
Collection.reset() clears the models in the collection. Will this also delete the underlying Javascript model objects or do they need to be explicitly deleted?
How would one get rid of the collection object itself?
Does Javascript have a garbage collector and will it take care of deleting all such objects?
As long as there's no remaining reference to your objects they will get garbage collected.
I already described the birds-eye view of this (make sure you're no longer referencing your objects!), but here is a pretty good article about garbage collection in the context of Backbone.
View.remove() only removes the view from the DOM. My guess is that one still needs to take care of removing/destroying the underlying Model and unbinding all event listeners. Is that correct?
Note that it also calls .stopListening(), which unbinds your listeners if you used .listenTo() in your views. You do not need to remove/destroy the underlying model to let it get GC'd, again as long as there are no remaining references to it. Using .listenTo() with a model is a reference to it, but if you .remove() your view that will remove that reference.
I often use _.bindAll to change the context of a function call. I have not come across a way to unbind this binding. My understanding says that this is unnecessary. Am I right?
It's not clear to me what you would be trying to achieve by "unbinding," so I would say that it isn't necessary.
I have a main section of code that initialises of all my views. How should I handle / listen / bind events from the main sections (probably will turn this into a main app view eventually) with elements of these initialised views? I could pass a reference of a view into another view and do something from inside that view but I'd rather have all this logic in the main / parent. Is this possible or good practice?
If they are all DOM events. No, each view should handle it's own DOM events.
If one view needs to know if something is happening in another view...well, there're lots of ways to do it. I'd usually prefer the subscriber/publisher pattern.
See my answer to another question for code examples:
Call a function in another Marionette.ItemView
You do not need Marionette for that.
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 detach method which doesn't clean up all the jquery dom/custom events and reuse same view multiple times