Skip to content

Instantly share code, notes, and snippets.

@changtimwu
Created November 9, 2012 02:09
Show Gist options
  • Select an option

  • Save changtimwu/4043276 to your computer and use it in GitHub Desktop.

Select an option

Save changtimwu/4043276 to your computer and use it in GitHub Desktop.
How to keep context(aka this) for a setInterval callback in a coffeescript class
class ggp
constructor: (@nm)->
self = this
setInterval (->
self.shownm()
),1000
shownm: ->
console.log 'my name is ', @nm
g1 = new ggp( 'qq')
#the other way: define a special setInterval() which can accept context
setInterval_withctx = (t, ctx, func)->
setInterval (->
func.call ctx
),t
class yyp
constructor: (@nm)->
setInterval_withctx 1000, @, @shownm
shownm:->
console.log 'my name is ', @nm
g2 = new yyp( 'jj')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment