Key Bindings Attaching keyboard events to components command Guide

Key Bindings

Keybindings can be attached to any component by passing in keys to defineComponent

defineComponent({
keys: {
'ctrl + f'({ self }) {
self.focusSearch()
},
'up'({ self }) {
self.selectPreviousResult();
},
'down'({ self }) {
self.selectNextResult();
},
'esc'({ self }) {
self.blurSearch();
},
}
});

Types of Bindings

Single keys

Key bindings can be bound to any key by their common name. Multiple key bindings can be bound to the same event using , separation.

const keys = {
't' () => {
// handle "t" key
}
}

Special keys are mapped to their common names like ctrl, alt, meta shift

const keys = {
'meta' () => {
// handle mac/win key
}
};

Multiple Keys

Multiple keys can be bound to the same event using a comma separated list.

const keys = {
'up, down, left, right' () => {
// handle all keyboard events together
}
}

Key Combinations

Key combinations can be used by including a + between keys. Spacing is ignored.

const keys = {
'ctrl + o' () => {
// handle ctrl+o pressed together
}
'ctrl+s' () => {
// handle ctrl+s pressed together
}
};

Key Sequences

Key sequences can be used by leaving a space between each key. Keys will need to be pressed within a 500ms interval to be part of the same sequence.

const keys = {
'up up down down' () => {
// 4 keys pressed in sequence
}
};

Basic Keybinding Example

Callback Data

In addition to the standard callback data found in lifecycle guide keyboard bindings have access to a couple extra values.

parameteruse
inputFocusedwhether any input/contenteditable is focused
repeatedKeywhether the key is held down

Dynamic Keybinding

All lifecycle callbacks receive as a parameter two methods bindKey and unbindKey which can be used to dynamically add and remove keybindings as necessary.

This is often used with componet reactivity to adjust key bindings when something significant has changed with a component.

const createComponent = ({ reaction, bindKey, unbindKey }) => ({
initialize() {
reaction(() => {
if(self.isSomeCondition()) {
bindKey('enter', self.submitForm());
}
else {
unbindKey('enter');
}
})
}
});