Reputation: 546
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
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