I'm binding a handler to the keyup event of all input,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.
My question really is, 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. Like:
$(document).on('keyup','input,textarea,not([data-nokeyup]',$.debounce(600, editor.handleGlobalChange));
Appreciate your thoughts.
//Edit
Sorry I didn't make it clear, I have to use a delegated event handler because my inputs & 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])– Flambino Oct 13 '12 at 5:33input:not([data-nokeyup]), textarea:not([data-nokeyup]):) – Flambino Oct 14 '12 at 11:51