Search code examples
backbone.jsmarionette

How can i be sure a marionette view has been totally destroyed?


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.


Solution

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

    1. 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).

    2. 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.