views:

246

answers:

4

I have this javascript:

triggerAnimation(listItem,toggleToggleRadioListItem(listItem));


function triggerAnimation(listItem,passThruFunction){
    listItem.find(".inlineLoading").show();
// pause and then call the toggle function
    $("body").animate({opacity: 1}, 1000, 
    function(){
        alert("a");
 passThruFunction;
    }
    );  
}

function toggleToggleRadioListItem(listItem) {
    alert("b");
};

What is supposed to happen:

  • triggerAnimation is called passing an object and a function
  • triggerAnimation does a dummy animation (to create a pause) then raises an alert and triggers a callback function which executes the function that was passed through.
  • the function that was passed through is called raising an alert.

Based on the above, I'd expect the alert A to appear before alert B but that is not the case. What happens is that (it seems) alert B is called as soon as triggerAnimation() is called. Why is that? How can I achieve that behavior?

+1  A: 

Because you call the toggleToggleRadioListItem(listItem) when you call triggerAnimation(listItem,toggleToggleRadioListItem(listItem));, then executes toggleToggleRadioListItem(listItem) first.

Cesar
+2  A: 

Well, you could pass the function reference and an array of parameters to trigger animation instead, which is then passed to passThruFunction on execution. In Javascript, what you pass to a function will always be evaluated before the function code is actually executed, thats why you get your alert("b") first. Thats called busy evaluation [of function parameters], btw.

x3ro
+4  A: 

You can delay the execution by passing in a function and calling it later.

triggerAnimation(listItem, function () {
   toggleToggleRadioListItem(listItem)
});


function triggerAnimation(listItem,passThruFunction){
    listItem.find(".inlineLoading").show();
// pause and then call the toggle function
    $("body").animate({opacity: 1}, 1000, 
    function(){
        alert("a");
        passThruFunction();
    }
    );  
}

function toggleToggleRadioListItem(listItem) {
    alert("b");
};
eduffy
That's a nice solution, I admit.
x3ro
that was exactly my intention! Thanks! It was a syntax error on my part by not passing it as a function in the first call (as Cesar states, it appears I was calling it, rather than passing it)
DA
A: 

eduffy's answer is the simplest possible thing that could work, and will work a treat. If you want something more hardcore, a quiet read of partial application might give you another technique to add to your toolbelt.

Dan F