> From: weepy
>
> I have variables in the scope that i'm calling jQuery
>
> - won't they be lost inside the anonymous function ?
No, they won't be lost. I think that's the key point you're missing that's
causing so much worry.
When you nest functions inside each other, JavaScript code always has full
access not only to the variables of the innermost function, but also the
variables of every outer function.
When the interpreter looks up a variable name, it first looks in the
innermost function. If the variable isn't found there, it then looks at the
function that contains that inner function. If not there, it looks at the
next outer function, and so on until it runs out of functions and looks at
the global object. These variable lookups work even in callback functions
where the original outer function may have already returned.
This chain of nested functions is called the "scope chain". If you read up
on closures, this is what they are talking about.
It's also why global variables work. They aren't magic, and they aren't a
special case. The global object simply appears at the end of the scope chain
as if it were one last function to search.
Because of this, you never need a special way to pass arguments into a
function like you're looking for. You can simply use a nested function
instead.
This is why many JavaScript APIs don't bother with providing a special way
to pass arguments into deferred callback functions. It's never necessary.
Instead of having to find (or implement) this capability in every single API
that uses a callback, there is one general purpose solution that always
works in any JavaScript code.
> E.g. how do I do this :
>
> var my_z_index = 10
>
> $(el).animate( css, speed, function(){
> $(el).css(zIndex: my_z_index)
> });
Simply wrap the code in a function:
function myAnimate( el, css, speed, myZ ) {
$(el).animate( css, speed, function(){
$(el).css( zIndex: myZ );
});
}
myAnimate( something, something, something, 10 );
Now, when you call myAnimate, it captures that value of 10 in the myZ
variable. That variable remains valid and accessible inside the animate
callback function.
It's really that simple.
-Mike
p.s. A note about setTimeout: I don't think all browsers support the extra
arguments to setTimeout. (Maybe they do and I'm just being cautious.) But in
any case, you never have to use them, because the same technique above will
work for setTimeout as well.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"jQuery Development" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/jquery-dev?hl=en
-~----------~----~----~----~------~----~------~--~---