1

With reference to the code from here

With reference to the addListener(instance:Object, eventName:string, handler:Function) function. Here we pass in a handler. So toggleBounce is called when you click it.

I could also change it to var toggleFn = function toggleBounce() {....) and pass in toggleFn

My question is, can I pass in a function which takes parameters, for example if I wanted the handler to be a zoom(mapOptions.zoom -5) or similar function.

I know this is essentially a 'how do you pass functions as parameters' question but I just can't get it to work with different combinations.

function initialize() {
  var mapOptions = {zoom: 13, center: stockholm };
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  marker = new google.maps.Marker({map:map,position: parliament });
  google.maps.event.addListener(marker, 'click', toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() != null) { marker.setAnimation(null);} 
  else {marker.setAnimation(google.maps.Animation.BOUNCE);}
}

1 Answer 1

3

You can pass a anonymous function:

functionToPassTo(function(){ zoom(mapOptions.zoom -5) });

You can also pass variables:

var options = "something";
functionToPassTo(function(){ zoom(options) });

The only other way would be to store the function in a variable:

var options = "something",
func=function(){ zoom(options) });
functionToPassTo(func);
Sign up to request clarification or add additional context in comments.

7 Comments

Cheers. Is this the only way to do it? Can I not pass in a reference?
@Tim you can pass a function reference, but that just gets you to the function itself and doesn't handle your parameters. What you want is a reference to a function that calls the function you really want to call, passing the parameters too.
Ok but say I wanted to pass in a local variable, such as the mapOptions as one of the parameters? The toggleBounce() method still can't access it
@JCOC611 thank you for that. I can get what I want to do using anonymous functions now. However, I'd still like to know if its possible any other way. I personally hate the mess of anonymous functions bring to code but if its the only way to do this so be it.
@Tim: Edited again, you can store the new function in a variable...although that really is just wasting more code...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.