Google Maps - Load Window On Marker Click
Solution 1:
In your addListener
invocation, you're actually calling loadInfo
instead of passing a reference to it. Try the following instead:
GEvent.addListener( marker1, "click", function() {
loadInfo(1);
});
This will create an anonymous function which wraps your loadInfo
method, calling the method when the anonymous function is executed.
Alternatively, if you weren't using any parameters in loadInfo
, simply removing the parentheses would work too:
GEvent.addListener( marker1, "click", loadInfo);
Something worth keeping in mind when using such function references is the scope in which it will be called. If you were to use the 'this'
reference, you'll run into the situation where 'this'
within the callback function will in fact not refer to the scope in which it was created, but to the scope within which it's being executed which most likely will not contain the fields or methods you're expecting to call, resulting in errors stating Undefined
instead. As Jonathan points out, you'll have to use the call()
and apply()
methods to bind explicitly to ensure your function executes within the correct scope.
Solution 2:
You're calling loadInfo in the .addListener, not providing a refernce to it.
GEvent.addListener( marker1, "click", loadInfo(1) );
try:
functionwrap(method) {
var args = Array.prototype.slice.apply(arguments,1);
returnfunction () {
return method.apply(this,args);
}
}
GEvent.addListener( marker1, "click", wrap(loadInfo,1) );
see http://www.alistapart.com/articles/getoutbindingsituations for more information on binding arguments to functions. also see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply for more information on the very useful apply() (also recommended you look at call() as well)
Solution 3:
loadInfo(1)
means execute this function immediately, but you need to pass a callback function to the GEvent.addListener() method. For that, you can use anonymous function:
GEvent.addListener( marker1, "click", function() { loadInfo(1) });
Post a Comment for "Google Maps - Load Window On Marker Click"