观察者模式是一种软件设计模式,观察者定义了一种一对多的关系,观察者监听被观察者,等待通知,一旦被观察者发出通知,所有观察者均会接收到通知,并做出一些具体业务。
实现on、emit、off、once。
class EventEmitter {constructor() {this._events = {}}on(event, cb) {if (!this._events[event]) {this._events[event] = [];}this._events[event].push(cb);return this;}emit(event, ...args) {let arr = this._events[event];for (let cb of arr) {cb(...args);}return this;}off(event, cb) {if (!cb) {return;}if (this._events[event]) {this._events[event] = this._events[event].filter((cbitem) => {return cb !== cbitem;})}return this;}once(event, cb) {let fn = function(...args) {cb.apply(this,...args);this.off(event,fn);}fn = fn.bind(this)this.on(event,fn);return this;}
}