// 题目描述:实现一个发布订阅模式拥有 on emit once off 方法class EventEmitter { constructor() { // 存储事件 this.events = {}; } // 订阅 on(type, callback) { if (Reflect.has(this.events, type)) { this.events[type].push(callback) } else { this.events[type] = [callback] } } // 删除订阅 off(type, callback) { if (!Reflect.has(this.events, type)) return this.events[type] = this.events[type].filter((item) => item !== callback) } // 只执行一次订阅事件 once(type, callback) { function fn() { // 执行一次订阅事件 callback() this.off(type, fn) } // 注意传入的 callback 是 fn 函数 this.on(type, fn) } // 触发 emit(type, ...rest) { this.events[type] && this.events[type].forEach((fn) => fn.apply(this, rest)) }}// 使用如下let event = new EventEmitter();let handle = (...rest) => { console.log(rest);};event.on("click", handle);// event.emit("click", 1, 2, 3, 4);// event.off("click", handle);// event.emit("click", 1, 2);event.once("dbClick", () => { console.log(123456);});event.emit("dbClick");event.emit("dbClick");