0

Possible Duplicate:
How to order events bound with jQuery

I have bound two event for the same element.Let's say Button:

<button>Click</button>

<script>
/*First Event*/
 $('button').click(function(){
   /***Have some piece of code which gets the data that is used for next event***/
 });

/*Second Event*/
 $('button').click(function(){
   /***do some operations with the data that has been fetched from the previous event***/
 });
</script>

Now, whenever click is triggered on the button, two events are called simultaneously..So I cannot acheive my goal as what I guess.

Can we restrict the event should be calle onced the first event has finished its job....

Note: Above code is psuedo code to explain my issue..

Community
  • 1
  • 1
Rama Rao M
  • 2,961
  • 11
  • 44
  • 64
  • Why two event handlers? Can't you create a function and call it within first one? – Ram Dec 26 '12 at 11:58
  • This question should not have been closed. I believe the "Possible Duplicate:" question addresses a similar point but not exactly the same. – Beetroot-Beetroot Dec 28 '12 at 08:56

2 Answers2

1

The two handlers are actually called sequentially. However, we must assume that the first involves an asynchronous task (probably ajax), and that the second handler requires the data obtained by the first.

The secret is to perform both tasks in one handler, like this :

$('button').click(function(){
    $.ajax({
        //options
    }).then(function(data) {
        //do some operations with the data that has been fetched
    });
});
Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44
0

AFAIK you cant define order for jQuery events but you can achieve same using manual call or callbacks.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161