Coffeescript setInterval in class

coffeescript, setinterval

Solution

Now here some Javascript magic is required. Reference

class Widget
  constructor: (@name) ->
    this.setUpdateInterval()

  getData: ->
    console.log "get Data by Ajax"

  setUpdateInterval: (widget) ->
    callback = @getData.bind(this)
    setInterval( callback, 3000000 )

This will work in almost all browsers (guess which one not), so the function will have to be bound differently. Some coffeescript magic:

callback = => @getData

Problem

I started writing coffeescript last week, as I am programming a new Play20 site where coffeescript is the standard. I want to update a getData function in my class every 5 minutes, but the setInterval function does not bind to my class. Only the first time it calls getData, because the 'this' object is still reachable, as the setUpdateInterval() function is called from within the constructor. But after the first call, the setInterval does not have any connection anymore with the Widget instance, and does not know what the this.getData() function is (and how to reach it). Does someone know how to do it? Here is my code: ``` class Widget constructor: (@name) -> this.setUpdateInterval() getData: -> console.log "get Data by Ajax" setUpdateInterval: (widget) -> setInterval( this.getData(), 3000000 ) ```

Original source