Skip to content

Instantly share code, notes, and snippets.

@lmartins
Created May 19, 2014 13:52
Show Gist options
  • Select an option

  • Save lmartins/7b95f116220df5ea8935 to your computer and use it in GitHub Desktop.

Select an option

Save lmartins/7b95f116220df5ea8935 to your computer and use it in GitHub Desktop.
Passing objects to addEventListener. Here’s a super awesome trick I had no idea about until someone pointed out you could do this. addEventListener can take an object as a second argument that will look for a method called handleEvent and call it! No need for binding “this” so it will pass around the context correctly, the context is the object …
object =
init: ->
btnEl = document.querySelector 'button'
btnEl.addEventListener 'click', this
btnEl.addEventListener 'touchstart', this
handleEvent: (e) ->
switch e.type
when 'click'
@action(e.type)
when 'touchstart'
@action(e.type)
action: (type) ->
console.log "This is action #{type}"
object.init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment