首页 > 其他分享 >eventBus的手写实现on、emit、once、off

eventBus的手写实现on、emit、once、off

时间:2022-12-23 15:25:12浏览次数:43  
标签:off key1 events foo1 eventBus type emit fn

事件总线

事件总线使用方法

const events = new EventBus();
function foo1() {
  console.log('foo1');
}

function foo2() {
  console.log('foo2');
}

function foo3() {
  console.log('foo3')
}

events.on('key1', foo1);
events.on('key1', foo2); // 在key1上绑定两个回调函数
events.emit('key1'); // 触发函数,输出foo1、foo2,此时可以在后面添参数
events.off('key1', foo1); // 移除key1上的foo1函数
events.emit('key1');  // 输出foo2
events.once('key2', foo3) // 在key2上绑定foo3,但是只会响应一次
events.emit('key2') // foo3
events.emit('key2) // 没有反应

实现

首先用类来实现eventBus

class EventBus {
  constructor() {
    this.events = {};  // 记录
  }

  on(type, fn, isOnce=false) {
     const events = this.events;
     if(events[type] === null) {
       events[type] = []; // 初始化
     }
      events[type].push({fn, isOnce});
  }

  off(type, fn) {
    const events = this.events;
    if(events[type] === null) return;
    if(!fn) { // 如果没有特定的,就将所有事件都清空
      events[type] = [];
      return;
    }
    return events[type].filter(item => item.fn !== fn);
  }

  emit(type, ...argus) {
    const events = this.events;
    if(events[type] === null) return;
    this.events = events[type].filter(item => {
      item.fn(...argus);
      return !item.isOnce;
    })
  }

  once(type, fn) {
    this.on(type, fn, true);
  }
}

标签:off,key1,events,foo1,eventBus,type,emit,fn
From: https://www.cnblogs.com/taosifan/p/17000714.html

相关文章