Namespacing Event Handlers

Conflicting Events Handlers

Use event namespacing when attaching or detaching event listeners. This reduces the possibility of you accidentally removing event listeners that was not intended to be removed. This is especially important if you plan to use someone else’s JQuery plugin that interacts with an element which you are also manipulating through your own event handler attachment or detachment. There could also be the opposite problem where someone else’s JQuery plugin removes your attached listeners. This is why namespacing events is a good practice.

Not only can namespacing reduce conflicts of interest with other plugins, namespacing also allows for selective removal of your own event listeners.

Supposedly two click handlers are attached to a textarea element

Two Click Handlers With No Namespacing
1
2
3
4
5
$('textarea').on('click', function(){
alert('Making a racket here.');
}).on('click', function(){
alert('Just to annoy you.');
});

Then you manipulate the element by removing the click handlers

No Control Event Handler Removal
1
2
3
//This could be a very dangerous thing to do
//because all click handlers are indiscriminately taken out
$('textarea').off('click');

However, sometimes you do not wish to remove all click listeners for a certain element. Let say that you would only like to remove the last one. You can accomplish this when a namespace is provided

Gave each Click Handler a Namespace
1
2
3
4
5
6
7
//Each of the click handler has now suffix
//serving as a namespace
$('textarea').on('click.first', function(){
alert('Making a racket here.');
}).on('click.second', function(){
alert('Just to annoy you.');
});

Remove only the second click handler as to preserve the first

Remove Event Handler Selectively
1
$('textarea').off('click.second');

Your first click handler should still be attached.

Demo