Created
May 19, 2014 13:52
-
-
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 …
This file contains hidden or 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
| 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