最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone.js setTimeout() loop in CoffeeScript - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Aug 18, 2011 at 16:57 pizza247 asked Aug 18, 2011 at 16:17 pizza247pizza247 3,8977 gold badges35 silver badges47 bronze badges 2
  • Using strings in your setTimeout is calling eval behind the scenes. I would strongly consider changing this to a reference of the function. e.g. t = setTimeout(this.runShow ,2000); stackoverflow./questions/86513/… – Gazler Commented Aug 18, 2011 at 16:43
  • fair enough @Gazler, I've removed it from the code. The solution by user576875 also has it removed. – pizza247 Commented Aug 18, 2011 at 16:59
Add a ment  | 

1 Answer 1

Reset to default 8

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
发布评论

评论列表(0)

  1. 暂无评论