Created
November 9, 2012 02:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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