Pergunta

Similar to this: Issue with Coffeescript comprehensions and closures

I know I have to use closures somehow, but I can't figure out how exactly. I want to add event handlers, that use an string additional argument and use class method as handler-method.

# 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

Thanks in advance.

Foi útil?

Solução

You want to create a function that returns a function, closing over the variable:

# 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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top