3

I'm dynamically binding event to a text element. This is my code:

<input type="text" id="myTxt" />

<script type="text/javascript">
    function attachEvent1(element){
        element.keyup(function(){
            console.log("Event:"+event.keyCode);
        });
    }
    function attachEvent2(element){
        element.keyup(function(){
            console.log("Value:"+this.value);
        });
    }   
    attachEvent1($('#myTxt'));
    attachEvent2($('#myTxt'));      
</script>

What I need it, I want the second event handler (attched by attachEvent2) to get called first, even if it is binded after attachEvent1. Is it possible in jQuery?

Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • Not out of the box, no. You would need to digg into the `jQuery._data` object expandos, where event handlers are stored and re-order functions. – jAndy Dec 04 '12 at 11:53
  • At the end of the handler that you want to execute first you could fire an event and have the second handler bound to this event. – Toni Toni Chopper Dec 04 '12 at 11:54
  • 2
    jQuery deliberately guarantees that event handlers will be called in the order they are bound. You could bind a proxy function that knows what order to call the other functions. – nnnnnn Dec 04 '12 at 12:05
  • I answered this a while back. You can get around by messing around with internal APIs. But unfortunately they changed since version 1.8+ so I've updated my answer. That is also the reason why instead of hacking around with jQuery APIs, you should create your own API layer on top of jQuery where you control the order. http://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-t – Anurag Dec 06 '12 at 04:28
  • @Anurag. Thanks. Can you move your comment to an answer, so that I can accept as answer. – Akhil Sekharan Dec 06 '12 at 04:35
  • There's no point duplicating the answer here. I'll mark this question as a duplicate since they cover exactly the same grounds. – Anurag Dec 06 '12 at 04:38
  • I mean just point the link in answer – Akhil Sekharan Dec 06 '12 at 04:41

1 Answers1

0

What about something like this:

function handler1()
{
  console.log("Event:"+event.keyCode);
}

function handler2()
{
  console.log("Value:"+this.value);
}

function attachEvent1(element)
{
  element.keyup(handler1);
}

function attachEvent2(element)
{
  element.unbind('keyup', handler1);
  element.keyup(handler2);
  element.bind('keyup', handler1);
}   

attachEvent1($('#myTxt'));
attachEvent2($('#myTxt'));

If you want something fancier, you could keep a list of the handlers, and do the rebinding in a loop, etc. but this basic idea of re-binding the events, has the desired effect.

Cesar Varela
  • 5,004
  • 2
  • 16
  • 17