shortcut-key-js
Version:
js按键,组合键监听
52 lines (48 loc) • 2.16 kB
JavaScript
/**
* @description 按键监听
*/
import defaultOptions from '../config/options';
import { beforeBind, formatKey2Unit, keyItemize } from '../helper';
import { emitError } from '../utils';
import listenerMaps from '../helper/listener-maps';
class PressKey {
constructor() {
}
eventListener(evt, itemize, callback, options) {
// 检查修饰键是否全部命中
if (itemize[0].reduce((total, key) => evt[`${key}Key`] ? ++total : total, 0) === itemize[0].length) {
// 检查所有被排除的修饰键是否全部未命中
if (itemize[1].reduce((total, key) => !evt[`${key}Key`] ? ++total : total, 0) === itemize[1].length) {
// 检查非修饰键是否命中
if (evt.key.toLowerCase() === itemize[2]) {
callback(evt);
options.preventDefault && evt.preventDefault();
options.stopPropagation && evt.stopPropagation();
}
}
}
}
/**
* 注册一组按键监听, 组合按键使用key+key的方式输入
* @param {string} keyCombination 监听的按键组合
* @param {function} callback 组合键触发时的回调函数
* @param {object} params 额外的配置参数,默认参数为PressKey.options
*/
on(keyCombination, callback, params = {}) {
const options = { ...defaultOptions, ...params }, error = beforeBind(keyCombination, options, callback);
// 存在异常信息时直接退出程序
if (error.length === 2) return emitError(error[0], error[1]);
const key2Units = formatKey2Unit(keyCombination, options.separator), eventListener = evt => {
this.eventListener(evt, keyItemize(key2Units), callback, options);
};
listenerMaps.setItem(key2Units.join(options.separator), callback, { eventListener, options });
options.target.addEventListener(options.type, eventListener);
}
// 移除一组按键绑定
off(keyCombination, callback) {
const listener = listenerMaps.removeItem(keyCombination, callback);
// 监听器存在时移除绑定在元素上的事件
listener.length === 2 && listener[1].options.target.removeEventListener(listener[1].options.type, listener[1].eventListener);
}
}
export default new PressKey();