jQuery: Unbinding specific event with namespace

27 / Aug / 2013 by Shreyance Jain 0 comments
If we follow the normal jQuery practices for binding and unbinding multiple jQuery events, it involves writing code again and again for each of the binding and unbinding which makes it very repetitive, specially when unbinding.

Joint unbinding is also seen when you have same event bound to the same DOM element multiple times. Lets consider an example: You bind a click event on a button and your team mate also does the same. In this scenario if you unbind your click event using the jQuery .off method on the element, it will also unbind the event that your team mate bounded for some other purpose/s. Same can be the case when you are using any jQuery plugin.

To tackle this situation more cleanly and in an efficient manner,  jQuery provides us a concept of namespaces while binding or unbinding events to any DOM element.

Things will get more clear with example below:

$("#updateStatus").on('click.myNamespace', function () {
  console.log("this click is initiated by myNamespace");
});

$("#updateStatus").on('hover.myNamespace', function () {
  console.log("this hover is initiated by myNamespace");
});

$("#updateStatus").on('click.myNamespace2', function () {
  console.log("this click is initiated by myNamespace2");
});

$("#updateStatus").on('hover.myNamespace2', function () {
  console.log("this hover is initiated by myNamespace2");
});
$("#updateStatus").off("hover.myNamespace") // unbind only single event(hover) bound by namespace

$("#updateStatus").off(".myNamespace2") // unbind all events bound by namespace2

This allow us to unbind all of the events, previously bound under a single namespace. At the same time it also facilitates us to unbind specific events using same namespace pattern. This makes the code more clean, less repetitive and also solves the problem described in the example above.

Hope it helps you! Cheers! :)

FOUND THIS USEFUL? SHARE IT

Leave a comment -