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.
Awesome useful content, as always. I just wish you’d respond to my multiweek old comment about Vue.js 🙂
how can I test this class?
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.. ‘);
}