Skip to content

Instantly share code, notes, and snippets.

@vendethiel
Last active March 6, 2016 14:54
Show Gist options
  • Save vendethiel/5541389 to your computer and use it in GitHub Desktop.
Save vendethiel/5541389 to your computer and use it in GitHub Desktop.
Coffee Arrows
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