Last active
March 6, 2016 14:54
-
-
Save vendethiel/5541389 to your computer and use it in GitHub Desktop.
Coffee Arrows
This file contains 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 SomeAjaxCallback | |
constructor: (@value) -> | |
throw "Bad value" unless value? | |
setTimeout @process, 5000 | |
# setTimeout doesn't give us a "new context" | |
# so we'd get our "global context" : window. | |
# let's avoid that using the fat arrow. | |
process: => | |
throw "Wrong context" unless @value? | |
class SomeElement | |
constructor: (@value, sel) -> | |
# now, we have another problem. | |
# We need to keep our `this`, but | |
# jQuery gives us a new one through the event. | |
# Thankfully, we can use the parameter (ev) | |
# to get the target, and still use the fat arrow. | |
$(sel).click @onclick | |
onclick: (ev) => | |
$(ev.target).html @value | |
class NotNiceApi | |
constructor: (@value) -> | |
# now, the third case : | |
# the library doesn't pass the new `this` | |
# as an argument. We have to bind | |
# the function by ourselves. | |
self = this | |
onmsg = -> | |
@dispatch 'new value', self.value | |
SomeApi.on 'message', onmsg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment