Backbone.js setTimeout () loop in CoffeeScript

It seems that every way I try to do this causes some kind of error. This is what my code looks like:

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 a function in my events. I have inc = 1 and pre = 0 defined outside of Backbone.View. My current error is: "Unsigned TypeError: Object [object DOMWindow] does not have a runShow method"
BONUS POINTS: how can I refer to another function (to run clearTimeout (t))?

+4
source share
1 answer

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

To avoid this, you can create a function and bind it to the current context, so that every time the function is called, this is the same as the function was created.

In a coffee script, you can do this with => :

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

Or in one line:

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

how can i reference t to another function?

Make the t property of your object:

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

All Articles