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
1 | $('textarea').on('click', function(){ |
Then you manipulate the element by removing the click handlers
1 | //This could be a very dangerous thing to do |
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
1 | //Each of the click handler has now suffix |
Remove only the second click handler as to preserve the first
1 | $('textarea').off('click.second'); |
Your first click handler should still be attached.