Skip to content

Commit

Permalink
Merge pull request #51 from smerickson/development
Browse files Browse the repository at this point in the history
add "destroy" method
  • Loading branch information
dmauro committed Nov 9, 2014
2 parents 09d38c3 + 6d2b12c commit a7b474c
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions keypress.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -98,28 +98,43 @@ class keypress.Listener
@_defaults[property] = @_defaults[property] or value

# Attach handlers to element
element = element or document.body
@element = element or document.body

attach_handler = (target, event, handler) ->
if target.addEventListener
target.addEventListener event, handler
else if target.attachEvent
target.attachEvent "on#{event}", handler

attach_handler element, "keydown", (e) =>
handler

@keydown_event = attach_handler @element, "keydown", (e) =>
e = e or window.event
@_receive_input e, true
@_bug_catcher e
attach_handler element, "keyup", (e) =>

@keyup_event = attach_handler @element, "keyup", (e) =>
e = e or window.event
@_receive_input e, false
attach_handler window, "blur", =>

@blur_event = attach_handler window, "blur", =>
# Assume all keys are released when we can't catch key events
# This prevents alt+tab conflicts
for key in @_keys_down
@_key_up key, {}
@_keys_down = []

destroy: () ->
remove_handler = (target, event, handler) ->
if target.removeEventListener
target.removeEventListener event, handler
else if target.removeEvent
target.removeEvent "on#{event}", handler

remove_handler @element, "keydown", @keydown_event
remove_handler @element, "keyup", @keyup_event
remove_handler window, "blur", @blur_event

# Helper Methods

_bug_catcher: (e) ->
Expand Down

0 comments on commit a7b474c

Please sign in to comment.