views:

54

answers:

1

Hello,

I am trying to pass in a function as a parameter:

GEvent.addListener(marker_1, "click", populateMarkerWindow(0, marker_1) );

the addListener function takes an inline function as a parameter, and it works fine, but I want to call this function from other places as well, so I made it into a defined function:

var populateMarkerWindow = function(id, marker) {
  //...
}

This, however, only means that my function gets called when I try to register it.

Is there a way to tell JS that I want to pass in the function itself, not the result of the call to the function?

Thank you,

+9  A: 

Just pass the function's name. If you need to arrange for the function to be invoked with a particular set of parameters, well, there are fancy ways to do that, but the simplest thing is to just wrap a call to your function in another function.

GEvent.addListener(marker_1, "click", function() {
  populateMarkerWindow(0, marker_1);
});

You might want to look for Douglas Crockford's various lectures on YouTube, as well as his website (crockford.com I think). In addition to that there are approx. a zillion other Javascript introductions out there.

Pointy
+1. In fact, that is exactly what the Google Maps API Docs suggest: http://code.google.com/apis/maps/documentation/events.html#Event_Listeners
Daniel Vassallo
You should remove one of the ")" at line 2.
xavierm02
Thanks @Xavier, done!
Pointy
+1 for currying without headaches ;)
Agos
@Agos check out functional.js for its argument-populating tricks! http://osteele.com/sources/javascript/functional/
Pointy
@Pointy thanks a lot! It looks tremendously useful :)
Agos