Wrong event executes in CoffeeScript
This works:
$("#add").click( -> stack.op "add" )
$("#sub").开发者_StackOverflow社区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}()"
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.
精彩评论