From d5f93601a930c600dfadbf27d6510086edf67e71 Mon Sep 17 00:00:00 2001 From: Spencer P Date: Mon, 11 Feb 2019 12:36:05 -0500 Subject: [PATCH] Fix unbind with Method (#54) * add failing test to address #53 * add fix for #53 --- src/main.js | 4 +++- test/run.test.js | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/main.js b/src/main.js index ddac821..485820d 100644 --- a/src/main.js +++ b/src/main.js @@ -107,9 +107,11 @@ function unbind(key, scope, method) { for (let r = 0; r < _handlers[key].length; r++) { obj = _handlers[key][r]; // 通过函数判断,是否解除绑定,函数相等直接返回 - if (method && obj.method !== method) return; + const isMatchingMethod = method ? obj.method === method : true; + // 判断是否在范围内并且键值相同 if ( + isMatchingMethod && obj.scope === scope && compareArray(obj.mods, mods) ) { diff --git a/test/run.test.js b/test/run.test.js index f932ab3..743911b 100644 --- a/test/run.test.js +++ b/test/run.test.js @@ -315,6 +315,43 @@ describe('\n Hotkeys.js Test Case.\n', () => { hotkeys.unbind('a'); }); + test('unbind with method test', async () => { + const callbackA = jest.fn(); + const callbackB = jest.fn(); + + hotkeys('shift+a', callbackA); + + await __triggerKeyboardEvent(document.body, 65, { + shiftKey: true, + }); + + expect(callbackA.mock.calls.length).toBe(1); + + hotkeys.unbind('shift+a', callbackA); + + await __triggerKeyboardEvent(document.body, 65, { + shiftKey: true, + }); + + expect(callbackA.mock.calls.length).toBe(1); + + hotkeys('shift+a', callbackB); + + await __triggerKeyboardEvent(document.body, 65, { + shiftKey: true, + }); + + expect(callbackB.mock.calls.length).toBe(1); + + hotkeys.unbind('shift+a', callbackB); + + await __triggerKeyboardEvent(document.body, 65, { + shiftKey: true, + }); + + expect(callbackB.mock.calls.length).toBe(1); + }); + test('HotKeys Key combination Test Case', async () => { hotkeys('⌘+d', (e) => { expect(e.keyCode).toBe(82);