From fcb3c1dd6b5cb0d8dbb45cfeff056c5ed66d42ea Mon Sep 17 00:00:00 2001 From: cptran777 Date: Fri, 7 Sep 2018 11:27:54 -0700 Subject: [PATCH] Cleanup event listener --- .../app/components/hotkeys/global-hotkeys.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/wherehows-web/app/components/hotkeys/global-hotkeys.ts b/wherehows-web/app/components/hotkeys/global-hotkeys.ts index 48787ec000..7bce35cc9d 100644 --- a/wherehows-web/app/components/hotkeys/global-hotkeys.ts +++ b/wherehows-web/app/components/hotkeys/global-hotkeys.ts @@ -1,5 +1,5 @@ import Component from '@ember/component'; -import { get, set } from '@ember/object'; +import { get } from '@ember/object'; import { service } from '@ember-decorators/service'; import ComputedProperty from '@ember/object/computed'; import HotKeys from 'wherehows-web/services/hot-keys'; @@ -39,11 +39,6 @@ export default class GlobalHotkeys extends Component { @service hotKeys: ComputedProperty; - /** - * The event listener function created for the body - */ - bodyEventListener: (e: KeyboardEvent) => void; - /** * Returns true if target exists, is not an input, and is not an editable div * @param {HTMLElement} target - target element @@ -61,19 +56,21 @@ export default class GlobalHotkeys extends Component { * Method for handling the global keyup. * @param {KeyboardEvent} e - KeyboardEvent triggered by user input */ - onKeyUp(e: KeyboardEvent) { + // Note: Important to define this as an arrow function in order to maintain this context when + // attaching to event listener below + onKeyUp = (e: KeyboardEvent) => { const target = e.target; if (this.isEligibleTarget(target)) { get(this, 'hotKeys').applyKeyMapping(e.keyCode); } - } + }; didInsertElement() { const body = document.querySelector('.ember-application'); if (body) { - body.addEventListener('keyup', set(this, 'bodyEventListener', this.onKeyUp.bind(this))); + body.addEventListener('keyup', this.onKeyUp); } } @@ -81,7 +78,7 @@ export default class GlobalHotkeys extends Component { const body = document.querySelector('.ember-application'); if (body) { - body.removeEventListener('keyup', this.bodyEventListener); + body.removeEventListener('keyup', this.onKeyUp); } } }