1

I am using jQuery 1.9.1.

Suppose i have a button with id="clickMe" My jQuery code is:

$('#clickMe').click(function(event)
{
    eventHandler1();//do something
    eventHandler2();//use output from eventHandler1() and do something
}

Now, i want "eventHandler2" to be executed at last so that i could use the output of "eventHandler1". Is there any way to do this manually and not just the way i have put the handlers inside the click event? One more thing, "eventHandler1()" and "eventHandler2()" are present in different .js files and thus the requirement.

3
  • does you eventHandler1() uses any async request to server? Commented Apr 17, 2013 at 6:30
  • i can tell you that all these handlers work without page reload Commented Apr 17, 2013 at 6:33
  • Does this answer your question? How to order events bound with jQuery Commented Jan 23, 2024 at 0:10

2 Answers 2

4

jQuery.when() provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

For example, when the Deferreds are jQuery.ajax() requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.

$.when(eventHandler1).then(eventHandler2).done(function(){
 alert('done.');
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks mate! even though i found another way of dealing with my not-so-complex problem, this approach surely works :)
Oh Great and glad this helped.
1

So can even use GLOBAL variable to store eventHandler1 output and access that inside eventHandler2

Example

var someVar;

function eventHandler1()
{
   // process
   someVar = some value from process
   return someVar;
}

function eventHandler2()
{
   alert(someVar);
}

Response to OP comment

as you have asked about execute handler in queue you can use Jai answer.

you can use .when .then and .done as below.

$.when(eventHandler1).then(eventHandler2).done(function(){
  //process code
});

3 Comments

eventHandler1() dynamically filters the data.it is a long plug-in.i would rather not make any changes there...just want to make eventHandler2() the last to execute
@spyder so you can use jQuery.done() handler to make sure that eventHandler 1 is finished.
@spyder see Jai answer that what i mean/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.