CoffeeScript中的Backbone.js setTimeout()循环

tha*_*way 4 javascript jquery coffeescript backbone.js

似乎我尝试这种方式,它会引发某种错误.这是我的代码现在的样子:

runShow: ->
  moments = @model.get('moment_stack_items')
  if inc == moments.length
    inc = 1
    pre = 0
  $("#" + moments[pre].uid).hide("slide", { direction: "left" }, 1000)
  $("#" + moments[inc].uid).show("slide", { direction: "right" }, 1000)

  inc += 1
  pre += 1

  console.log "looping" + inc
  t = setTimeout(this.runShow(),2000);
Run Code Online (Sandbox Code Playgroud)

我在我的活动中调用了这个函数.我已经inc = 1pre = 0所述Backbone.View之外定义..我的电流误差是"未捕获类型错误:对象[对象DOMWindow]无方法'runShow’"
积分:我怎样才能引用吨从另一个功能(运行我clearTimeout(t)的)?

Arn*_*anc 8

您要求setTimeout函数进行求值"this.runShow()",并且setTimeout将在上下文中执行此操作window.这意味着这是评估此代码时thiswindow对象.

为了避免这种情况,您可以创建一个函数并将其绑定到当前上下文,以便每次调用该函数时,this都与创建函数时相同.

在咖啡脚本中,您可以使用=>:

func = =>
    this.runShow()

setTimeout(func, 2000)
Run Code Online (Sandbox Code Playgroud)

或者在一行上:

setTimeout((=> this.runShow()), 2000)
Run Code Online (Sandbox Code Playgroud)

我怎样才能从另一个函数中引用t?

t你的对象的属性:

class Something
    t: null
    runShow: ->
       ...
       this.t = ...
    otherFunction: ->
       t = this.t
Run Code Online (Sandbox Code Playgroud)