Jquery: trigger one handler of the same event
I have multiple on change events.
$('开发者_如何学C#parent').change(function(){ console.log("first"); });
$('#parent').change(function(){ console.log("second"); });
It triggers both handlers when I trigger "change"
$('#parent').trigger('change')
OUTPUT:
"first"
"second"
What I want to do (pseudo code)
$('#parent').trigger('change:first')
or
$('#parent').trigger('<handler_id>')
OUTPUT
"first"
How do I do this? And, yes I need 2 handlers.
Thanks
You can use namespaces when you assign events.
$('#parent').bind('change.first',function(){ console.log("first"); });
$('#parent').bind('change.second',function(){ console.log("second"); });
This way you can trigger them with
('#parent').trigger('change.first');
or
('#parent').trigger('change.second');
But when you fire the event through normal user interaction (and not manually triggering it) it will fire both.
What comes to my mind is that you could alternatively use event.stopImmediatePropagation() in the first handler if there is a clear condition when the second handler shouldn't fire, or fetch the element's handlers and just fire the first one of them manually (see jQuery find events handlers registered with an object).
You can use namespaced events:
$('#parent').bind('change.a', function(){ console.log("first"); });
$('#parent').bind('change.b', function(){ console.log("second"); });
$('#parent').trigger('change.a');
The pattern is event.namespace
. $('#parent').trigger('change')
will still trigger both (so you are not loosing anything).
精彩评论