jQuery: Unbinding specific event with namespace
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.
Things will get more clear with example below:
[js]
$("#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");
});
[/js]
$("#updateStatus").off("hover.myNamespace") // unbind only single event(hover) bound by namespace
$("#updateStatus").off(".myNamespace2") // unbind all events bound by namespace2
[/js]
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! 🙂