Skip to content
js
// 一个订阅器
class EventEmitter {
  constructor() {
    this.events = {};
  }
  on(event, callback) {
    //如果有该事件
    if (this.events[event]) {
      this.events[event].push(callback);
    } else {
      //如果没有
      this.events[event] = [callback];
    }
  }
  emit(event, ...payload) {
    const callbacks = this.events[event];
    if (callbacks) {
      callbacks.forEach((callback) => callback.apply(this, payload));
    }
  }
  off(event, callback) {
    console.log("---删除订阅---");
    //如果event为undefined
    if (event == null) {
    } else if (typeof callback === "function") {
      //删除指定事件的回调
      this.events[event] = this.events[event].filter((e) => e !== callback);
    } else {
      //删除事件
      delete this.events[event];
    }
  }
  // 只进行一次的订阅
  once(event, callback) {
    const proxy = (...payload) => {
      callback.apply(this, payload);
      this.off(event, proxy);
    };
    this.on(event, proxy);
  }
}

const changePrice = (price, N) => {
  console.log(`当前总价格+${price}`);
};
const e = new EventEmitter();
e.on("addToCart", changePrice);

e.on("addToCart", (price, N) => {
  console.log(`当前商品总数+${N}`);
});

e.emit("addToCart", 50, 6);

e.off("addToCart", changePrice);
e.emit("addToCart", 50, 6);

e.once('pay', () => {
    console.log('付款了...')
})

e.emit('pay', ()=>{
    console.log('发送商品id=1...')
})
e.emit('pay', ()=>{
    console.log('发送商品id=2...')
})