2011-08-18 65 views
4

好像我尝试这种方式的每种方式都会引发某种错误。以下是我的代码现在的样子: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); 

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

+0

使用setTimeout中的字符串在幕后调用eval。我会强烈考虑将其改为该函数的参考。例如t = setTimeout(this.runShow,2000); http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea – Gazler

+0

够公平的@Gazler,我已经从代码中删除它。 user576875解决方案也将其删除。 – thatmiddleway

回答

8

您可以使用setTimeout函数来评估"this.runShow()",setTimeout将在window的上下文中执行此操作。这意味着this是评估此代码时的window对象。

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

在咖啡脚本,您可以用=>做到这一点:

func = => 
    this.runShow() 

setTimeout(func, 2000) 

或者在同一行:

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

how can I reference t from another function?

t你的对象的属性:

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

辉煌的解决方案@ user576875。感谢您的回复如此之快!我甚至没有想过要用=> – thatmiddleway

+0

我更喜欢你编辑前的东西!我的骨干视图更简洁,看起来更干净。 – thatmiddleway

+1

你的意思是这个语法:'setTimeout((=> this.runShow()),2000)'? – arnaud576875