In JavaScript, how do you pass explicit arguments to a function from a function expression callback?
-
When I have a function that needs to wait, and not be executed during scanning, but has arguments that need to be specified beforehand, I run into this problem: <button id="myButton">Hello</button> function show(msg) { return alert(msg); } $('myButton').addEventListener('click', show('How are you?')); The above is a basic example of what I'm talking about. The show(); function executes beforehand without me having to click on the button. Inline works fine but I do not want to go that road. How to I make the function wait until I have clicked the button but still have the specified arguments?
-
Answer:
All you have to do is wrap the function you want to call in a function expression (callback): <button id="myButton">Hello</button> function show(msg) { return alert(msg); } $('myButton').addEventListener('click', function() { show('How are you?'); });
Rick Waldron at Quora Visit the source
Other answers
You can use `Function.prototype.bind` in order to burn in those arguments without invoking the function immediately. function show (msg) { return function (event) { // you can also use this.id if you really want to. return alert(msg + event.target.id) } } document.getElementById('myButton') .addEventListener('click', show('You have clicked: ')) SEE: http://jsfiddle.net/wilmoore/ovpm556b/
Wil Moore III
Related Q & A:
- What Is The Geometric Meaning Of Third Derivative Of A Function At A Point?Best solution by Mathematics
- How to pass a parameter to a function that is called on an event?Best solution by Stack Overflow
- How can I pass global variables into a function?Best solution by Stack Overflow
- Should I handle unexpected arguments of a function?Best solution by mathworks.com
- How do you find the derivative of a function?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.