Whilst working with Ember one of the habits that it’s taken me a little while to get used to has been making sure that once components are removed everything gets garbage collected along with them.

The lifecycle hooks are perfect for this, but there are still a few caveats I’ve encountered which I thought I’d explain to help anyone else that may find themselves in the same situation.

Here are a couple of ways I’ve found to help reduce the chances of some unexpected behaviour left behind after components have been removed.

Ensure any attached event handlers, e.g. jQuery’s on() or bind(), are removed

Problem

Sometimes it’s necessary to attach event handlers to elements using something like jQuery’s on() method outside of the scope of the component.

Doing this means that after the component has been destroyed the event handlers will still persist.

you can still see that the logging still happens after the component is removed

JSBin example

This is a very basic example and is only used to illustrate the problem as simply as possible.

Solution

First, a simple solution that works in some cases but has a big gotcha which means it is often the wrong approach is to simply add jQuery’s off() method to the component’s WillDestroyElement hook.

this removes all instances of click handlers on $(window) when the component is removed

JSBin example

But this approach introduces a new issue in our code. As it removes all instances of the window .on(‘click’) event handlers you can see in this JSBin example that the click handlers are removed from two different components.

By including the component’s elementId in the handler by using a namespace it can be specifically removed in the willDestroyElement hook.

with the element namespaced only the component’s specific handler is removed

JSBin example

You can see from the example that this removes only the event handler added by that component now.