UNPKG

crootfast

Version:

大前端工程化命令行脚手架

49 lines (41 loc) 1.06 kB
import Mousetrap from "mousetrap"; export const MousetrapEvents = {}; // 快捷键事件订阅 export function mtSubscribe(key, fn = () => {}, manual = true) { if (!MousetrapEvents[key]) { MousetrapEvents[key] = []; } MousetrapEvents[key].push(fn); if (manual) { onKeyEmit(key); } } // 取消订阅 export function mtUnsubscribe(key, fn = () => {}) { if (MousetrapEvents[key]) { MousetrapEvents[key] = MousetrapEvents[key].filter((cb) => cb !== fn); } } // 执行事件 export function onKeyEmit(key, ...data) { Mousetrap.bind(key, function (e) { e.preventDefault(); // 防止默认行为 e.stopPropagation(); // 防止事件传递行为 emit(key, ...data); }); } // 发布事件 export function emit(key, ...data) { if (!MousetrapEvents[key] || !MousetrapEvents[key]?.length) { return; } MousetrapEvents[key]?.map((cb) => { if (typeof cb === "function") { cb(...data); } }); } // // 注册事件到订阅集合中 // export function mtListeners() { // mtSubscribe("mod+b"); // }