Last Updated: February 25, 2016
· iilei

Don't forget to unbind event handlers

Fix your Specs and allow multiple instantiation of your JS modules

Experiencing inconsistent results in your Jasmine test suite can be quite painful – as I have just learned the hard way.

Imagine the following situation:

When running your Jasmine suite one spec for myFunkyModule results in a failure. Running the test standalone however passes nicely.
You check for global variable leaks, ensure your fixtures look good and everything seems to be ok. Still, the test suite as a whole does not pass.

Namespaces and detaching event handlers as a remedy

When writing a JS module that uses delegated event handlers, put the events into a namespace. Ensure to unbind all event handlers of your module which might accidently have been initiated more than once.

Using jQuery, this can be easily achieved like this:

         .on("click.myFunkyModule", ".funky", yourClickHandler)
         .on("mousedown.myFunkyModule", ".funky", yourMousedownHandler);
         // etc ...

This little call of off() at the start ensures event hanlders within the given namespace myFunkyModule are not bound more than once.