1. // 题目描述:实现一个发布订阅模式拥有 on emit once off 方法
    2. class EventEmitter {
    3. constructor() {
    4. // 存储事件
    5. this.events = {};
    6. }
    7. // 订阅
    8. on(type, callback) {
    9. if (Reflect.has(this.events, type)) {
    10. this.events[type].push(callback)
    11. } else {
    12. this.events[type] = [callback]
    13. }
    14. }
    15. // 删除订阅
    16. off(type, callback) {
    17. if (!Reflect.has(this.events, type)) return
    18. this.events[type] = this.events[type].filter((item) => item !== callback)
    19. }
    20. // 只执行一次订阅事件
    21. once(type, callback) {
    22. function fn() {
    23. // 执行一次订阅事件
    24. callback()
    25. this.off(type, fn)
    26. }
    27. // 注意传入的 callback 是 fn 函数
    28. this.on(type, fn)
    29. }
    30. // 触发
    31. emit(type, ...rest) {
    32. this.events[type] && this.events[type].forEach((fn) => fn.apply(this, rest))
    33. }
    34. }
    35. // 使用如下
    36. let event = new EventEmitter();
    37. let handle = (...rest) => {
    38. console.log(rest);
    39. };
    40. event.on("click", handle);
    41. // event.emit("click", 1, 2, 3, 4);
    42. // event.off("click", handle);
    43. // event.emit("click", 1, 2);
    44. event.once("dbClick", () => {
    45. console.log(123456);
    46. });
    47. event.emit("dbClick");
    48. event.emit("dbClick");