Wednesday 15 September 2010

jquery - Call a custom function when a third party javascript async function completes its execution -


I have a scenario where I want my function after the completion of the implementation of a particular third party JS function Execute.

I can not edit the source of loadOne , but as a click lister, I can add / override my newLoadOne I am That's why I can execute loadOne on my behalf and execute my code with that data.

Now, my newLoadOne print console loadOne before the async callback return of the method .log

HTML

  & lt; Select id = "option1" & gt; & Lt; Options & gt; 1 & lt; / Options & gt; & Lt; Options & gt; 2 & lt; / Options & gt; & Lt; Options & gt; 3 & lt; / Options & gt; & Lt; / Select & gt; & Lt; Select ID = "Option 2" & gt; & Lt; Options & gt; A & lt; / Options & gt; & Lt; Options & gt; Two & lt; / Options & gt; & Lt; Options & gt; Three & lt; / Options & gt; & Lt; / Select & gt; & Lt; Input id = "submit" type = "button" value = "submit" />   

javascript

  function loadOne () {someAsyncXhrMethod (with_its_own_parameters); // AINC callback} with its own xhr method} newLoadOne () function () {LoadOne (); Console.log ('done');} ()); } Functionschangchanged () {console.log ('option changes'); } Function bEvents () {$ ('# option1'). Changes (optionschanged); . $ ('# OPTION2') (optionschanged); $ ('# Submit') Bind ('click', new load-on); // This is where I change the call to load with my new loading $ $ (document) .ready (function () {console.log ('ready'); bEvents ();});   

is here - Note: The source code for the $ .ajax call is to explain some async callback in loadOne then $ (Document) .ajaxComplete no answer.

You have it to see if the asynchronous method has been completed, poll < There is no real liking for / strong> Maybe something that changes a state that is visible to you which you can vote on (we will call that routine check_some_async_xhr_method_completed ), At some reasonable frequency

  function newLoadOne () {loadOne (); Check_completion (function (full) {console.log (done? Done ':' never finished ');}); } Function check_completion (callback) {var number_of_tries = 20; Var timer = setInterval (function (if (check_some_async_xhr_method_completed ()) {clear interval (timer); callback (true);} and if (! Number_of_tries--) {clear interval (timer); callback (wrong);}} , 500);}   

Or, if you would like to use the promises:

  function newLoadOne () {loadOne (); Check_completion () Then (function () {console.log ('done'), function () {console.log ('never ending'))}} Function check_completion () {var promo = Promise.new (); var number_of_tries = 20 ; Var timer = setInterval (function () (if (check_some_async_xhr_method_completed ()) {clear interval (timer); p.fulfill ();} else if (! Number_of_tries--) {clear Interval (timer); p.reject ();}}, 500); return promise;}   

or, when is already a regular in the library Which is handled by voting.

No comments:

Post a Comment