Reputation: 473
I've searched existing questions, and haven't found one that I understand to be applicable to my scenario.
I'm coding a jQuery plugin that must handle document-level events. The plugin will be executed on multiple input[type=text] elements in the same form, and it's possible that document-level event listeners are registered in other open source plugins that I'm using. I suspect there will be conflicts.
Following is an example of the kind of listener I need. It collapses a custom coded combo box when a click, focus or blur event is triggered on any element besides its own components. It's currently written in jQuery, but I'm certainly open to rewriting in JavaScript.
$(document).on('click focus blur',function(e)
{
switch (e.target)
{
case $(comboBox)[0]:
case $(settings.dropdownContainer)[0]:
break;
default:
$(settings.dropdownContainer).addClass('hide');
$(settings.dropdownContainer + ' ul li').remove();
break;
}
})
JavaScript .addEventListener is advertised as follows on developer.mozilla.org: "It allows adding more than one handler for an event. This is particularly useful for libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries or extensions." But I'm not sure how to use .addEventListener to solve my problem.
As I look at the code above, it occurs to me that looping through multiple instances of $(comboBox) might be part of the solution. But I don't know how to code it.
So, what is the best way to avoid event listener problems given my requirements? Or, if my general approach is wrong, is there a better way to get each instance of comboBox to collapse if a click is detected on an element other than a combo box?
Upvotes: 2
Views: 1199
Reputation: 2936
You can use .off()
. Events will fire the normally. myNamespace is whatever you want to call it. Namespacing will prevent the duplicate listener.
$(document).off('.myNamespace'); //Thanks to venimus
$(document).on('click.myNamespace focus.myNamespace blur.myNamespace',function(e)
{
switch (e.target)
{
case $(comboBox)[0]:
case $(settings.dropdownContainer)[0]:
break;
default:
$(settings.dropdownContainer).addClass('hide');
$(settings.dropdownContainer + ' ul li').remove();
break;
}
})
You may find the following usefull:
https://api.jquery.com/event.namespace/
and
https://css-tricks.com/namespaced-events-jquery/
Thanks to Venimus for the abreviated .off() code!
Upvotes: 1