将事件处理程序上的闭包与coffeescript一起使用

将事件处理程序上的闭包与coffeescript一起使用,coffeescript,closures,Coffeescript,Closures,与此类似: 我知道我必须以某种方式使用闭包,但我不知道具体如何使用。我想添加事件处理程序,它使用一个字符串附加参数,并使用类方法作为处理程序方法 # Load all transport layers @_transportLayers = {} for protocolName, protocol of transportLayerProtocols @_transportLayers[protocolName] = new protocol(config) @_transport

与此类似:

我知道我必须以某种方式使用闭包,但我不知道具体如何使用。我想添加事件处理程序,它使用一个字符串附加参数,并使用类方法作为处理程序方法

# Load all transport layers
@_transportLayers = {}
for protocolName, protocol of transportLayerProtocols
   @_transportLayers[protocolName] = new protocol(config)
   @_transportLayers[protocolName].on 'data', (e, protocolName) =>

        # HERE IS THE PROBLEM: 

        # This generic event handler should get the protocolName as argument
        # But the protocolName is always the last one.
        @eventHandler(e, protocolName)
        return

提前感谢。

您想创建一个返回函数的函数,关闭变量:

# Load all transport layers
@_transportLayers = {}

handlerCreater = (protocolName) =>
  (e) => @eventHandler(e, protocolName) 

for protocolName, protocol of transportLayerProtocols
  @_transportLayers[protocolName] = new protocol(config)
  @_transportLayers[protocolName].on 'data', handlerCreater protocolName