feat: add capture option (#368)

pull/369/head
Ilya Suhodolskiy 3 years ago committed by GitHub
parent 18f2526115
commit 56af32dccb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -158,6 +158,7 @@ hotkeys('*','wcj', function(event){
- `keyup<Boolean>`
- `keydown<Boolean>`
- `splitKey<string>` (default is `+`)
- `capture<Boolean>`
```js
hotkeys('o, enter', {

1
index.d.ts vendored

@ -15,6 +15,7 @@ type Options = {
element?: HTMLElement | null;
keyup?: boolean | null;
keydown?: boolean | null;
capture?: boolean
splitKey?: string;
}

@ -325,6 +325,7 @@ function hotkeys(key, option, method) {
let keyup = false;
let keydown = true;
let splitKey = '+';
let capture = false;
// 对为设定范围的判断
if (method === undefined && typeof option === 'function') {
@ -336,6 +337,7 @@ function hotkeys(key, option, method) {
if (option.element) element = option.element; // eslint-disable-line
if (option.keyup) keyup = option.keyup; // eslint-disable-line
if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line
if (option.capture !== undefined) capture = option.capture; // eslint-disable-line
if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line
}
@ -372,17 +374,17 @@ function hotkeys(key, option, method) {
elementHasBindEvent.push(element);
addEvent(element, 'keydown', (e) => {
dispatch(e, element);
});
}, capture);
if (!winListendFocus) {
winListendFocus = true;
addEvent(window, 'focus', () => {
_downKeys = [];
});
}, capture);
}
addEvent(element, 'keyup', (e) => {
dispatch(e, element);
clearModifier(e);
});
}, capture);
}
}

@ -1,9 +1,9 @@
const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false;
// 绑定事件
function addEvent(object, event, method) {
function addEvent(object, event, method, useCapture) {
if (object.addEventListener) {
object.addEventListener(event, method, false);
object.addEventListener(event, method, useCapture);
} else if (object.attachEvent) {
object.attachEvent(`on${event}`, () => { method(window.event); });
}

@ -646,6 +646,23 @@ describe('\n Hotkeys.js Test Case222.\n', () => {
});
});
test('Hotkey modifier capture', async () => {
let isExecuteFunction = false;
const el = document.createElement('div');
el.addEventListener('keydown', () => {
isExecuteFunction = true;
});
await hotkeys('a', { capture: true, element: el }, (event) => {
event.stopImmediatePropagation();
});
__triggerKeyboardEvent(el, 65);
expect(isExecuteFunction).toBeFalsy();
await hotkeys.unbind('a');
});
afterAll(async () => {
await browser.close();
});

Loading…
Cancel
Save