Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow other bound element events to trigger first?

Is there a way to allow other bound events to the same object(ex. textbox) to fire/trigger first?

Say 2 events got bound to the same textbox. Both keyup events. In my case there is a plugin binding its own events, but the way the code is written, mine get bound first. I do not want mine to fire first.

$("#firstname").keyup(function() {
    // ...is there anyway to allow the other keyup event to fire first, from here?
    // do my work here...
}

$("#firstname").keyup(function() {
    // the plugin work.
}

I need to use keyup, there is already key down events.

like image 206
Yogurt The Wise Avatar asked Nov 13 '22 16:11

Yogurt The Wise


1 Answers

You should really rewrite your code to only have one keyup binding to that event but if that isn't feasible, you could do it dirty with semaphores and separate your functionality from the binding so it can be called from either bind...

var semaphore = 0; // on init

$("#firstname").keyup(function () { // this one should run first
 semaphore++;

 if (semaphore === 0) {
    first_action();
 }
}

$("#firstname").keyup(function () { // this one should run second
 if (semaphore > 1) { // you know the first event fired
   second_action();
 }
 else if (semaphore < 1) {
   first_action();
   second_action();
   semaphore++; 
 }
}
like image 102
mattacular Avatar answered Nov 17 '22 05:11

mattacular