Passing a parameter in onClick callback function

I have to pass a name to a onClick callback function.  As the function is called asynchronously, how can I pass the name to the callback function.

function createEntry(name) {
       .....
       runIcon.onclick = (function(event) {
           runCommand(name);  // is name valid in async call here?
        });
       .....
}

Open in new window

ambuliAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Technology SpecialistCommented:
Yes, this will work.
It doesn't really matter if the main function is called asynchronously.

Here's a demo: http://jsfiddle.net/AlexCode/ev4dvd5j/
ambuliAuthor Commented:
Thanks, but can you explain why it would work even in async call.  For example, if name is out of scope( we already exited the createEntry function), how it would work.  Again thanks for the response.
Alexandre SimõesManager / Technology SpecialistCommented:
That's how javascript works.
Your event handler will always execute within the scope of the createEntry function (where it was declared).
Even if in theory it already exited, JavaScript "remembers" the context of the function call and can still access the variables within that scope.

If you think about it, even in my example you already exited the function, and it still works! :)

This "feature" is called Closures, and you should really read about it.
Closures and scope, are probably the most misunderstood features in JavaScript.

I would recommend this book to everyone:
http://www.manning.com/resig/

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ambuliAuthor Commented:
Thank you!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.