2013-03-30 140 views
0

我想向Google地图事件添加侦听器,但 不使用匿名函数但命名为外部函数 ,因为这发生在循环内部,我不想定义一个匿名函数在那里,而是使用了一个名为,外部函数:如何通过map.event.addListener将参数传递给外部函数

不:

for (...) { 
    googleMap.event.addListener(instance, eventName, function() {...}); 
} 

反倒是某事。像:

doSomething = function(parameter1, parameter2...) { 
    ... 
} 

for (...) { 
    googleMap.event.addListener(instance, eventName, params, doSomething); 
} 

当“实例”是一个谷歌地图标记,我可以使用marker.set(paramName, paramValue)添加参数(一个或多个),以该标记,然后通过this.paramName访问事件处理函数内部的参数,但没有任何当我不想使用匿名函数时,将值传递给事件处理函数的其他方法是什么?

任何意见欢迎,罗马。

回答

3

我有同样的问题。这是一个解决方案。它真正避免了创建函数在一个循环问题,通过这里所描述

In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?

我称之为“功能工厂”模式的模式。

其他成分是在函数“this”中引用了引发函数的对象(被点击的地图上的东西或其他),并且因为JavaScript是完全动态的,所以可以将附加属性附加到将到被点击的东西,并通过调用this.blah功能

function doSomethingHandlerFactory(){ 
var f = function(event){ 
    //do something, for example call a method on a property we attached to the object which raised the event 
    this.blah.clicked(event); 
}; 
return f; 
} 

//add a property to the google overlay object (for example a polyline which we've already set up) 
thePolyline.blah = ...; 

//get a handle for a function, attach the event (in this case to a polyline), and keep 
//a reference to the event (in case we want to call removeListener later). The latter 
//is optional. 
var f = doSomethingHandlerFactory(); 
var ev = google.maps.event.addListener(thePolyline, 'click', f); 

我希望这可以帮助别人了内对它们进行查询。

1

如何包装你的命名函数匿名函数:

google.maps.event.addListener(instance, eventName, function() { doSomething(parameter1, parameter2,...) }); 
+0

不错,geocodezip。这样我可以传递我的参数,并仍然使用命名函数。但说实话,这个想法并不是在这个地方定义一个函数,因为addListener发生在一个循环中,我认为在一个循环中定义一个函数是一种糟糕的风格......我将把它添加到原始问题 - 对不起,应该早些提到这一点。 – RSeidelsohn

相关问题