javascript 自定义发布与订阅

//声明一个类,与普通的类的声明不一样,
function Girl() {
    //将类的事件声明成一个私有的属性,里面是一个对象
    this._events = {}
}

/*
  {
    "失恋":["哭","吃","购物"]
  }
*/

Girl.prototype.on = function (eventName,callback) {
    if (this._events[eventName]){
        //如果已经在里面了,说明不是第一次失恋了
        this._events[eventName].push(callback);
    } else{
        this._events[eventName] = [callback,];
    }
};

Girl.prototype.emit = function (eventName,...args) {
    if (this._events[eventName]){
        this._events[eventName].forEach(cb=>cb(...args));
    }
};

// 声明一个实例
let  girl = new Girl();
let  cry = (who)=>{console.log(who+"哭")};
let  eat = (who)=>{console.log(who+"吃")};
let  shoping  = (who)=>{console.log(who+"购物")};

//监听
girl.on("失恋",cry); 
girl.on("失恋",eat);
girl.on("失恋",shoping);

//触发的时候传入应的数据,后面的多个参数就是数据
girl.emit("失恋","殷超");

/*
    监听一个"失恋"的这样一个事件,但是这个事件里面包含多个操作。 
    是一个数组 ["哭","吃","购物"] 
*/

  

原文地址:https://www.cnblogs.com/leigepython/p/9156710.html