且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建jquery可拖动“停止”回调在for循环

更新时间:2023-10-30 22:47:46

问题是你的回调:

stop: =>
  alert "x === #{_x}"

全部结束引用 _x ,但他们不评估 _x ,直到它们被调用。 _x 的值为 total + 1 ,这是CoffeeScript具有 do 关键字来帮助:

all end up referencing _x but they don't evaluate _x until they get called. By the time that happens, _x has the value total + 1. This is such a common issue that CoffeeScript has the do keyword to help:


当使用JavaScript循环生成函数时,通常插入一个闭包,以确保循环变量被关闭,所有生成的函数不仅仅共享最终值。CoffeeScript提供 do 关键字,它立即调用传递的函数,转发任何参数。

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.


$ b b

所以你可以这样说:

So you can say this instead:

for _x in [0..total]
  do (_x) ->
    $(window).ready $(".draggable-#{_x}").draggable
      #... as before