If I have a code like this:
class SomeClass
constructor: ->
@someAttr = false
someFunction: ->
process.nextTick ->
@someAttr = true
obj = new SomeClass
obj.someFunction()
obj.someAttr # Would still be false, because the @ (this) is in the process context
it won't work, because process.nextTick brings us into a different context, in which @someAttr isn't defined. How can I work around this (also when I want to call methods of SomeClass)?
The usual way around this is to store a reference to this in a local variable which will be available within the anonymous function. In JavaScript:
function someFunction() {
var self = this;
process.nextTick(function() {
self.someAttr = true;
});
}
CoffeeScript has a special syntax to help with this; the "fat arrow":
class SomeClass:
someFunction: ->
process.nextTick =>
@someAttr = true
Use => instead of -> to preserve this variable.
class SomeClass
constructor: =>
@someAttr = false
someFunction: ->
process.nextTick =>
@someAttr = true