CoffeeScript 中的 Backbone.js setTimeout() 循环
似乎我尝试的每一种方法都会引发某种错误。我的代码现在如下所示:
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 = 1
和 pre = 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要求 setTimeout 函数计算
"this.runShow()"
,setTimeout 将在window
上下文中执行此操作。这意味着在计算此代码时,this
是window
对象。为了避免这种情况,您可以创建一个函数并将其绑定到当前上下文,以便每次调用该函数时,
this
与创建该函数时相同。在咖啡脚本中,您可以使用
=>
:或者在一行上:
使
t
成为对象的属性:You ask the setTimeout function to evaluate
"this.runShow()"
, and setTimeout will do that in the context ofwindow
. This means thatthis
is thewindow
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
=>
:Or on a single line:
Make
t
a property of your object: