2011-08-18 63 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