Kri-ban
Kri-ban

Reputation: 546

Wrong event executes in CoffeeScript

This works:

$("#add").click( -> stack.op "add" )
$("#sub").click( -> stack.op "sub" )

but this doesn't:

for op in ['add','sub']  
  $('#' + op).click( -> stack.op op)

Both buttons executes the last operation, "sub".

Class Stack
  add: ...
  sub: ...
  op: (name) ->
    eval "this.#{name}()"

Upvotes: 0

Views: 53

Answers (1)

cji
cji

Reputation: 6705

Use do construct:

for op in ['add', 'sub']
    do (op) ->
        $('#' + op).click( -> stack.op op)

It's because for loop does not create a closure.

Upvotes: 3

Related Questions