-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
42 lines (41 loc) · 1.23 KB
/
index.js
File metadata and controls
42 lines (41 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Mousetrap from "mousetrap";
/**
* Bind mousetrap event to a vue component instance
* @param {HTMLElement} el - HTMLElement of the vue component
* @param {String|String[]} value - Keyboard shortcuts mousetrap should listen to
* @param {Vue.VNode} vnode - VNode of the vue component
* @returns {void}
*/
const bindMousetrap = (el, value, vnode, preventDefault) => {
Mousetrap.bind(value, (ev, combo) => {
if (preventDefault) {
ev.preventDefault();
}
if (vnode.component) {
// When on a Vue component
vnode.component.emit("mousetrap", ev, combo);
} else {
// When on a native HTMLElement
const evx = new CustomEvent("mousetrap", { detail: { original: ev, combo} } );
el.dispatchEvent(evx);
}
});
};
const MousetrapDirective = {
beforeMount(el, { value, modifiers }, vnode) {
bindMousetrap(el, value, vnode, modifiers.prevent === true);
},
updated(el, { value, oldValue, modifiers }, vnode) {
Mousetrap.unbind(oldValue);
bindMousetrap(el, value, vnode, modifiers.prevent === true);
},
unmounted(el, { value }) {
Mousetrap.unbind(value);
}
};
export default {
install(app) {
app.directive("mousetrap", MousetrapDirective);
}
};
export { MousetrapDirective };