views:

106

answers:

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?

+2  A: 

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) }
}
Guffa
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)?
Luk