Creating (binding) a specific event and removing (unbinding) it only

less than 1 minute read

Say you want to add some specific event and want to specifically unbind just it (and not others) later.

As an example, consider the binding of the ESC key to close a modal of yours:

and, later on:

The problem here is just that the .off() snippet may remove some other bindings as well - not just the ones you made. Any keyup binding before will be removed. This may not seem troublesome now, but may bring some unpredictable behavior in the future, the kind of trouble that makes the developer shout: “WTF!?” - and we don’t want that karma.

The solution is simple: jQuery allows the attachment of “namespaces” to the events - just like a label - so you can refer specifically to it later.

The format is: event.[namespace]. Our code above could then do the binding just like:

And the removal:

All clean. Awesome.

Check out a working JSFiddle demo. More on event.namespace.

Leave a Comment