与此类似:Issue with Coffeescript comprehensions and closures
我知道我必须以某种方式使用闭包,但我无法弄清楚究竟是怎样的。我想添加事件处理程序,它使用字符串附加参数并使用类方法作为处理程序方法。
# 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
提前致谢。
答案 0 :(得分:0)
您想要创建一个函数,该函数返回一个函数,关闭变量:
# 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