diff --git a/addon/create-mixin.js b/addon/create-mixin.js index bd9f949..a0836cb 100644 --- a/addon/create-mixin.js +++ b/addon/create-mixin.js @@ -7,38 +7,38 @@ export default function(bindEvent, unbindEvent) { return Ember.Mixin.create({ mousetraps:[], bindShortcuts: Ember.on(bindEvent, function() { - var self = this; - var shortcuts = this.get('keyboardShortcuts'); - + const shortcuts = this.get('keyboardShortcuts'); + const self = this; if (Ember.typeOf(shortcuts) !== 'object') { return; } this.mousetraps = []; Object.keys(shortcuts).forEach(function(shortcut) { - var actionObject = shortcuts[shortcut]; - var mousetrap = new Mousetrap(document.body); - var preventDefault = true; + const actionObject = shortcuts[shortcut]; + let mousetrap; + let preventDefault = true; function invokeAction(action, eventType) { var type = Ember.typeOf(action); - + var callback; if (type === 'string') { - mousetrap.bind(shortcut, function(){ + callback = function(){ self.send(action); return preventDefault !== true; - }, eventType); + } } else if (type === 'function') { - mousetrap.bind(shortcut, action.bind(self), eventType); + callback = action.bind(self) } else { throw new Error('Invalid value for keyboard shortcut: ' + action); } + mousetrap.bind(shortcut, callback, eventType); } if (Ember.typeOf(actionObject) === 'object') { if (actionObject.global === false) { - mousetrap = new Mousetrap(document); + mousetrap = new Mousetrap(document.body); } else if (actionObject.scoped) { if (Ember.typeOf(actionObject.scoped) === 'boolean') { mousetrap = new Mousetrap(self.get('element')); @@ -48,26 +48,37 @@ export default function(bindEvent, unbindEvent) { } else if (actionObject.targetElement) { mousetrap = new Mousetrap(actionObject.targetElement); } - if (actionObject.preventDefault === false) { preventDefault = false; } - invokeAction(actionObject.action, actionObject.eventType); } else { + mousetrap = new Mousetrap(document.body); invokeAction(actionObject); } - self.mousetraps.push(mousetrap); - }); }), unbindShortcuts: Ember.on(unbindEvent, function() { + const _removeEvent = (object, type, callback) => { + if (object.removeEventListener) { + object.removeEventListener(type, callback, false); + return; + } + object.detachEvent('on' + type, callback); + } this.mousetraps.forEach( - (mousetrap) => mousetrap.reset() + (mousetrap) => { + // manually unbind JS event + _removeEvent(mousetrap.target, 'keypress', mousetrap._handleKeyEvent); + _removeEvent(mousetrap.target, 'keydown', mousetrap._handleKeyEvent); + _removeEvent(mousetrap.target, 'keyup', mousetrap._handleKeyEvent); + mousetrap.reset() + } ); + this.mousetraps = [] }) });