• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

Working With Keypress Events in Aurelia

Aurelia 1 · January 25, 2016

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.

Dwayne

Leave a Reply Cancel reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Charles
Charles
7 years ago

Awesome useful content, as always. I just wish you’d respond to my multiweek old comment about Vue.js 🙂

0
René
René
6 years ago

how can I test this class?

-1
Bjørn Øyvind Halvorsen
Bjørn Øyvind Halvorsen
6 years ago

You can use the built-in functionality for this:

HTML:

TypeScript:
ignoreEnter(event: KeyboardEvent) {
let key = event.which || event.keyCode;
if (key === 13) {
console.log(‘You pressed the enter key! Don’t!’);
event.preventDefault();
}
else
console.log(‘All good.. ‘);
}

0

Primary Sidebar

Popular

  • How To Get The Hash of A File In Node.js
  • Handling Errors with the Fetch API
  • Testing Event Listeners In Jest (Without Using A Library)
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz