CoffeeScript 中的 Backbone.js setTimeout() 循环

发布于 2024-11-30 09:56:15 字数 625 浏览 0 评论 0原文

似乎我尝试的每一种方法都会引发某种错误。我的代码现在如下所示:

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 。我当前的错误是“Uncaught TypeError: Object [object DOMWindow] has no method 'runShow' ”
奖励积分:如何从另一个函数引用 t (以运行我的clearTimeout(t))?

Seems like every way I try this, it throws some sort of error. Here's what my code looks like now:

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

I call the function in my events.
I have inc = 1 and pre = 0 defined outside the Backbone.View.. My current error is "Uncaught TypeError: Object [object DOMWindow] has no method 'runShow'"
BONUS POINTS: how can I reference t from another function (to run my clearTimeout(t))?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒儿 2024-12-07 09:56:15

您要求 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

You ask the setTimeout function to evaluate "this.runShow()", and setTimeout will do that in the context of window. This means that this is the window object when this code is evaluated.

To avoid this you can create a function and bind it to a the current context, so that everytime the function is called, this is the same as when the function has been created.

In coffee script you can do this with the =>:

func = =>
    this.runShow()

setTimeout(func, 2000)

Or on a single line:

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

how can I reference t from another function?

Make t a property of your object:

class Something
    t: null
    runShow: ->
       ...
       this.t = ...
    otherFunction: ->
       t = this.t
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文