1

I have multiple on change events.

$('#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

Tom Maeckelberghe
  • 1,969
  • 3
  • 21
  • 24

3 Answers3

3

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.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

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).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

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).

Community
  • 1
  • 1
Shadikka
  • 4,116
  • 2
  • 16
  • 19