Coffeescript setInterval in class

I started writing coffeescript last week since I am programming a new Play20 site where coffeescript is standard. I want to update the 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 available, since the setUpdateInterval () function is called from the constructor.

But after the first call, setInterval no longer has any connection with the Widget instance and does not know what this.getData () function is (and how to achieve it).

Does anyone know how to do this?

Here is my code:

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

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

  setUpdateInterval: (widget) ->
    setInterval( this.getData(), 3000000 )
+3
source share
3 answers

Javascript. Reference

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

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

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

(, ), -. :

callback = => @getData
+5

, .

, , . do => .

 setUpdateInterval: (widget) ->
    setInterval (do =>
      @getData), 3000000
    true

Widget.prototype.setUpdateInterval = function(widget) {
      var _this = this;
      setInterval((function() {
        return _this.getData;
      })(), 3000000);
      return true;
    };

, self-invoking, , this, ( _this)

, ( ), , . , . .

, coffeescript , true, .

+3

It is also convenient in node. This is the defendant Tass.

class Widget
  constructor: (@options = {}) ->
    @options.interval ?= 1000
    @setInterval()

  timer: ->
    console.log 'do something'

  setInterval: ->
    cb = @timer.bind @
    setInterval cb, @options.interval

w = new Widget()
0
source

All Articles