【问题标题】:Backbone.js setTimeout() loop in CoffeeScriptCoffeeScript 中的 Backbone.js setTimeout() 循环
【发布时间】:2011-08-19 00:57:36
【问题描述】:

似乎我尝试的每一种方式都会引发某种错误。这是我的代码现在的样子:

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);

我在我的事件中调用该函数。 我在 Backbone.View 之外定义了 inc = 1pre = 0。我当前的错误是“未捕获的 TypeError:对象 [object DOMWindow] 没有方法 'runShow'”
奖励积分:如何从另一个函数引用 t(运行我的 clearTimeout(t))?

【问题讨论】:

  • 在 setTimeout 中使用字符串是在后台调用 eval。我会强烈考虑将其更改为函数的引用。例如t = setTimeout(this.runShow ,2000); stackoverflow.com/questions/86513/…
  • 很公平@Gazler,我已经从代码中删除了它。 user576875 的解决方案也将其删除。

标签: javascript jquery backbone.js coffeescript


【解决方案1】:

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

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

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

func = =>
    this.runShow()

setTimeout(func, 2000)

或单行:

setTimeout((=> this.runShow()), 2000)

如何从另一个函数中引用 t?

t 设为对象的属性:

class Something
    t: null
    runShow: ->
       ...
       this.t = ...
    otherFunction: ->
       t = this.t

【讨论】:

  • 出色的解决方案@user576875。感谢您这么快回复!我什至没有想过要使用 =>
  • 我实际上更喜欢您在编辑之前的内容!在我的主干视图中更简洁,看起来更干净。
  • 你的意思是这个语法:setTimeout((=> this.runShow()), 2000)?
  • 是的,它对我来说看起来更干净。
猜你喜欢
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2013-03-18
  • 2011-12-20
  • 2012-12-08
  • 1970-01-01
相关资源
最近更新 更多