From fe2dd3c6fe083ab93668bdfc001303e26eaf0d19 Mon Sep 17 00:00:00 2001 From: jaywcjlove <398188662@qq.com> Date: Wed, 21 Nov 2018 14:42:34 +0800 Subject: [PATCH] feat: Unbind events through functions. #44 --- README-zh.md | 21 +++++++++++++++++++++ README.md | 11 +++++++++++ src/main.js | 10 +++++++++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/README-zh.md b/README-zh.md index 63f3fbc3..6ca01564 100644 --- a/README-zh.md +++ b/README-zh.md @@ -263,6 +263,27 @@ hotkeys.setScope('scope1'); `hotkeys.unbind("ctrl+o, ctrl+alt+enter")` 解除绑定两组快捷键 `hotkeys.unbind("ctrl+o","files")` 解除绑定名字叫files钟的一组快捷键 +```js +// 解除绑定 'a' 程序函数 +hotkeys.unbind('a'); + +// 仅针对单个范围解除绑定快捷键 +// 如果未指定范围,则默认为当前范围(hotkeys.getScope()) +hotkeys.unbind('o, enter', 'issues'); +hotkeys.unbind('o, enter', 'files'); +``` + +通过函数来解除绑定 + +```js +function example(){} +hotkeys('a', example); +hotkeys.unbind('a', example); + +hotkeys('a', 'issues', example); +hotkeys.unbind('a', 'issues', example); +``` + ## 键判断 判断摁下的键是否为某个键 diff --git a/README.md b/README.md index e1c24668..958fddd6 100644 --- a/README.md +++ b/README.md @@ -240,6 +240,17 @@ hotkeys.unbind('o, enter', 'issues'); hotkeys.unbind('o, enter', 'files'); ``` +Unbind events through functions. + +```js +function example(){} +hotkeys('a', example); +hotkeys.unbind('a', example); + +hotkeys('a', 'issues', example); +hotkeys.unbind('a', 'issues', example); +``` + ### isPressed Other key queries. For example, `hotkeys.isPressed(77)` is true if the `M` key is currently pressed. diff --git a/src/main.js b/src/main.js index bd1b7f13..ddac821d 100644 --- a/src/main.js +++ b/src/main.js @@ -73,11 +73,17 @@ function clearModifier(event) { } // 解除绑定某个范围的快捷键 -function unbind(key, scope) { +function unbind(key, scope, method) { const multipleKeys = getKeys(key); let keys; let mods = []; let obj; + // 通过函数判断,是否解除绑定 + // https://github.com/jaywcjlove/hotkeys/issues/44 + if (typeof scope === 'function') { + method = scope; + scope = 'all'; + } for (let i = 0; i < multipleKeys.length; i++) { // 将组合快捷键拆分为数组 @@ -100,6 +106,8 @@ function unbind(key, scope) { // 让触发快捷键键之后没有事件执行到达解除快捷键绑定的目的 for (let r = 0; r < _handlers[key].length; r++) { obj = _handlers[key][r]; + // 通过函数判断,是否解除绑定,函数相等直接返回 + if (method && obj.method !== method) return; // 判断是否在范围内并且键值相同 if ( obj.scope === scope &&