开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜