1
jQuery.fn.testeee = function(_msg)
{
    alert(_msg);
    $(this[0]).overlay({ 
        onBeforeLoad: function() 
        {
            alert(_msg);
        }
    }).load();
};
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');

This displays:

  • test
  • test
  • another_test
  • test

The alert() inside de anonymous function asigned to onBeforeLoad keeps showing "test". I try this:

jQuery.fn.testeee = function(_msg)
{
    alert(_msg);
    $(this[0]).overlay({ 
        onBeforeLoad: static_func(_msg)
    }).load();
};
function static_func(_msg) 
{
    alert(_msg);
}
$("#popup").testeee ('test');
$("#popup").testeee ('another_test');

And it works just fine. It displays:

  • test
  • test
  • test
  • test

Anybody knows why can be happening this?

1
  • What happens when you call testeee on different elements? Perhaps overlay doesn't create a new one if there's already one on the element? Commented Sep 9, 2009 at 5:24

1 Answer 1

2

If you create an object like this:

{
   onBeforeLoad: static_func(_msg)
}

It doesn't specify a function to call, instead it calls the function immediately and stores the return value in the object.

To specify a function to call you only use the function name:

{
   onBeforeLoad: static_func
}

If you want to call the function with a parameter that you specify yourself, you have to create a closure that contains the variable by wrapping it in an anonymous function:

{
   onBeforeLoad: function() { static_func(_msg) }
}
Sign up to request clarification or add additional context in comments.

1 Comment

So, why in the first example the function alert() (which is called by an anonymous function) keeps showing the first value of _msg test instead of showing the value that you are actually passing in the next callings (another_test in this case)?

Your Answer

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