原生JS实现发布-订阅模式

根据vue的发布-监听原理,原生JS手写发布-监听模式。

  function eventBus(){
     
    this._events = {
     }
  }
  eventBus.prototype.on = function(eventName,callback){
     
    if(this._events[eventName]){
     
      this._events[eventName].push(callback);
    }else{
     
      this._events[eventName] = [callback];
    }
  }
  eventBus.prototype.emit = function(eventName,...args){
     
    if(this._events[eventName]){
     
      this._events[eventName].forEach(cb=>cb(args));
      console.log(args);
    }
  }
  var p = new eventBus();
  p.on("ha",function(data){
     
    console.log("ha的p.on接收到p.emit值为:" + data)
  });
  p.emit("ha","这是emit要传递的值","emit值1");

你可能感兴趣的:(js)