views:

39

answers:

1

Hello everyone,

I have a code snipet like this:


var nbrPrevArt = $("#accordion > div .accordionPanel").size();
var processing = false;

if (nbrPrevArt == 0) {
    processing = true;
    getArticlesPreview();//Fetches articles first
}

//loop that makes the browser to wait  until finishes "getArticlesPreview()" 
while(!processing)
{
}

//getArticlesPreview() is finished now we can safely execute this step
$.ajax({
    type: "GET",
    url: "http://mydomain.com/somepage.htl",
    success: function(data) { alert(data);}
});


//-----------------------------------

function getArticlesPreview()
{
    //lenghty operation
    processing = false;
}

don't look much practical because i am using a loop to make it wait until the function is competely executed to perform next step.

Is there a way to define a callback message to be called when the first operation is done and the have my second step ( the $.ajax call) inside it to run properly?

Thank you in advance! Teixeira

+3  A: 

You could create your callback yourself, by using the apply function. You juste have to add a callback parameter to getArticlesPreview, and put the function inside this callback.

This could look like this :

function makeAjax()
{
    $.ajax({
       type: "GET",
       url: "http://mydomain.com/somepage.htl",
      success: function(data) { alert(data);}
    });
}

function getArticlesPreview(callback)
{
    //lenghty operation

    callback.apply(this)
}

var nbrPrevArt = $("#accordion > div .accordionPanel").size();

if (nbrPrevArt == 0) {
    getArticlesPreview(makeAjax);
}
Valentin Rocher
In this case you do not need apply, you just can execute callback as anonymous function. "callback()". But still +1.
nemisj
Great guys! Thank you very much for the great input!
byte_slave