• 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
5 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

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Waiting for an Element to Exist With JavaScript
  • Thoughts on the Flipper Zero
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • How To Paginate An Array In Javascript
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Reliably waiting for network responses in Playwright
  • How To Mock uuid In Jest
  • Wild Natural Deodorant Review

Recent Comments

  • Dwayne on Is Asking Developers How to Write FizzBuzz Outdated?
  • kevmeister68 on Is Asking Developers How to Write FizzBuzz Outdated?
  • Kevmeister68 on Start-Ups and Companies That Embrace Work From Anywhere Will Be More Likely to Survive the Coming Recession in 2023
  • kevmeister68 on What Would Get People Back Into the Office?
  • Dwayne on PHP Will Not Die

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz