发布订阅工具函数

发布订阅作为一种设计模式,在前端领域中使用场景也非常多,这里分享一下使用ES6编写的发布订阅工具函数。

1. 工具函数

/** * @file 发布订阅 * @module event * @author yueluo <yueluo.yang@qq.com> * @version 0.1.0 * @time 2020-06-23 */ function event () { // 订阅事件集合 let callbacks = new Map(); /** * @description 订阅事件 * @param {string} key - 名称 * @param {function} callback - 回调函数 * @return {void} */ const on = (key, callback) => { callbacks.set(key, callback); } /** * @description 订阅单次事件 * @param {string} key - 事件名称 * @param {function} callback - 回调函数 * @return {void} */ const once = (key, callback) => { const fn = (...args) => { callback.apply(null, args); off(key); }; on(key, fn); } /** * @description 发布事件 * @param {object} sender - 当前上下文环境 * @param {string} key - 事件名称 * @param {any} args - 传递参数 * @return {void} */ const emit = (sender, key, args) => { callbacks.get(key) && callbacks.get(key)(sender, args); } /** * @description 移除事件 * @param {string} key - 事件名称 * @return {void} */ const off = (key) => { callbacks.delete(key); } return { on, once, emit, off } } // 导出发布订阅函数 module.exports = event;

2. 使用方式

/** * @file 测试发布订阅函数 * @module test * @version 0.1.0 * @author yueluo <yueluo.yang@qq.com> * @time 2020-06-23 */ /** * @requires event/event 发布订阅函数 */ const event = require('./event')(); // 订阅on事件 event.on('on', () => { console.log('订阅的on事件被触发'); }); // 订阅once事件 event.once('once', () => { console.log('订阅的once事件被触发'); }); event.emit(this, 'on'); event.emit(this, 'on'); event.off('on'); event.emit(this, 'on'); // 订阅的on事件被触发 // 订阅的on事件被触发 event.emit(this, 'once'); event.emit(this, 'once'); event.emit(this, 'once'); // 订阅的once事件被触发