Working With Keypress Events in Aurelia

Recently in my Aurelia application I needed to handle some keypress events when the user hit the enter and escape keys. Fortunately Aurelia doesn’t abstract Javascript too much, so adding in keypress support is easy. You don’t really see things like this documented anywhere, so this is for my reference just as much as it is yours.

export class SomeClass {
    constructor() {
        this.myKeypressCallback = this.keypressInput.bind(this);
    }

    activate() {
        window.addEventListener('keypress', this.myKeypressCallback, false);
    }

    deactivate() {
        window.removeEventListener('keypress', this.myKeypressCallback);
    }

    // This function is called by the aliased method
    keypressInput(e) {
        console.log(e);
    }
}

The best practice here is to ensure that the ViewModel has instantiated itself so we can register our event listener, then make sure in our deactivate method we remove the event listener to clean up memory usage.