How to pass a parameter to a function without starting it immediately?

I have a weird problem trying to combine a somewhat dynamic Google Maps display. I have overlays on the map that I would call a function when clicked. At first I had everything hardcoded, so I had a function for each overlay, for example:

google.maps.event.addListener(southEast, 'click', showSouth); function showSouth() { // do stuff } 

This worked without problems, but then I made the whole page more dynamic, so I decided to make one function that will pass an identifier, and then display based on this, which, in my opinion, should have been configured initially anyway, I changed code to look more like this:

 google.maps.event.addListener(southEast, 'click', showArea(1)); function showArea(id) { // do stuff based on that id } 

The function worked, but the problem is that it is invoked when the page loads. After studying, I found out that when you call a function with parentheses, this function is called immediately and then refers to the return value. a source

So, now I'm a little fixated on how to pass this identifier to a function without calling the function immediately. I found some hacker ways to do this that might work, but I feel that this should not be something that I have to crack together ...

+15
source share
3 answers

Have showArea return a function that works with the identifier.

 function showArea(id) { return function() { // do stuff with id }; } 

The returned function is closed above id , so it continues to refer to it and is passed to addListener for use as a handler.


Alternatively, you can simply embed a function that calls showArea(1) ...

 google.maps.event.addListener(southEast, 'click', function() { showArea(1); }); function showArea(id) { // do stuff based on that id } 

This will work because you hardcode 1 . If it were a variable that could change, as in a loop, you would use the first example.

+19
source

Try using bind() .

You can also use bind() which binds this function and allows you to pass parameters to this method without starting the method during initialization.

 google.maps.event.addListener( southEast, 'click', showArea.bind( this, 1 ) ); 

With bind() first parameter is always the context (for example, this ), and any other parameters will be passed to the method itself. So,

  • your first method parameter is passed as the second parameter to bind ,
  • your second method parameter is passed as the third parameter in bind ,
  • etc.

Notice I'm not a Javascript expert, so I'm not sure if there are any implications for this strategy that I am missing.

0
source
 myFunction(msg) {console.log(msg)} // example function myFunction('hello world') // myFunction called "immediately" () => myFunction('hello world') // myFunction not called here; returns myFunction function() { return myFunction('hello world') } // myFunction not called here; returns myFunction 
0
source

All Articles