发布订阅模式

const corp = {
  list: [],
  on(eventName, fn) {
    if (!this.list[eventName]) {
      this.list[eventName] = []
    }
    this.list[eventName].push(fn);
  },
  emit() {
    const fns = this.list[arguments[0]]
    if (!fns || !fns.length) {
      return null;
    }
    fns.forEach(fn => {
      fn.apply(this, [...arguments].slice(1))
    })
  }
}

// 测试用例
corp.on('job', function (position) {
  console.log('你的职位是:' + position);
});
corp.on('job', function (position) {
  console.log('你的薪资是:10000');
});
corp.on('skill', function (skill) {
  console.log('你的技能有: ' + skill);
});

corp.emit('job', '前端');
corp.emit('job', '后端');
corp.emit('skill', 'javascript');

// 打印
你的职位是:前端
你的薪资是:10000
你的职位是:后端
你的薪资是:10000
你的技能有: javascript
原文地址:https://www.cnblogs.com/liea/p/13231393.html