lmartins
5/19/2014 - 1:52 PM

Passing objects to addEventListener. Here’s a super awesome trick I had no idea about until someone pointed out you could do this. addEvent

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 you’ve just set as the event listener callback.

Reference: http://www.thecssninja.com/javascript/handleevent

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()