使用CoffeeScript的类和jquery.transit创建一个回调循环

时间:2013-12-15 17:05:45

标签: javascript jquery animation coffeescript transition

使用jquery.transit我想使用jquery.transit的回调参数构建一个循环。我不想使用setTimeout()来避免可能的竞争条件。

以下代码有效:http://jsfiddle.net/2errn/

$ ->
  animate = () ->
    console.log "animate()"
    $(".rect").transition({x: 10}, animate)
  animate()

矩形只移动一次,但在控制台中很明显该方法被多次输入。这样可行!为了让它更频繁地移动,我需要在x坐标上添加一个增量计数器,但这不是问题所在。

我想在一个类中封装功能,但在这里它失败了:http://jsfiddle.net/6A97m/1/

$ ->
  class Animator
    animate: ->
      console.log "animate()"
      $(".rect").transition({x: 10}, @animate)

    new Animator().animate()

在记录语句的输出停止之前,该函数仅输入两次。这是为什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

这只是一个未绑定的函数引用:

@animate

该引用没有绑定到它的特定@,因此在调用它时将选择@。特别是,@不会是您的Animator个实例,因此第二次访问时@animate将是undefined

如果您将console.log更改为:

console.log @, "animate()"

第一次调用@时,您会看到Animatoranimate个实例,但第二次是其他内容。

有各种解决方案:

  1. 使用bound method

    animate: =>
      console.log "animate()"
      $(".rect").transition({x: 10}, @animate)
    

    演示:http://jsfiddle.net/ambiguous/3puUe/

  2. 使用bind传递时animate绑定:

    animate: ->
      console.log "animate()"
      $(".rect").transition({x: 10}, @animate.bind(@))
    

    演示:http://jsfiddle.net/ambiguous/BPSa9/

  3. 使用旧的@技巧手动设置相应的_this = this

    animate: ->
      console.log "animate()"
      _this = @
      $(".rect").transition({x: 10}, -> _this.animate())
    

    演示:http://jsfiddle.net/ambiguous/p4z8x/

  4. 大多数工具包库都有自己的绑定方法,以防您无法保证Function.bind可用:_.bind$.proxy,...