I'm binding a handler to the keyup event of all input and textareas in a document:
$(document).on('keyup','input,textarea',$.debounce(600, editor.handleGlobalChange));
I don't want the handler to fire on a specific input field. So I want to unbind the keyup event:
$('#afield').off('keyup');
However this does not unbind the keyup event, the handler is still called. I assume this is because there is no keyup event bound to the $('#afield')
element, the event is just bubbling up to the $(document)
where the actual handler is bound.
So to stop it triggering I can do the following:
$('#afield').on('keyup',function(e) {
e.stopImmediatePropagation();
});
This works, but it feels grim, setting a handler to stop another.
Is this acceptable or should I just no bind the event in the first place?
I could ignore certain classes or a custom data-nokeyup attribute:
$(document).on('keyup','input,textarea,not([data-nokeyup]',$.debounce(600, editor.handleGlobalChange));
I have to use a delegated event handler because my inputs and textareas are created after the initialisation code is run. $('input,textarea').keyup(...)
would return no elements. $(document).on('keyup','input,textarea',...)
catches all keyup events and inspects the event's target element.
input:not([data-keyup]), textarea:not([data-keyup])
\$\endgroup\$input:not([data-nokeyup]), textarea:not([data-nokeyup])
:) \$\endgroup\$