发布订阅事件

Posted xiaozhumaopao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发布订阅事件相关的知识,希望对你有一定的参考价值。

监听触发事件:

class EventEmeitter {
    constructor(){
        this._events = this._events || new Map();
        this._maxLength = this._maxLength || 10;
    }
}

EventEmeitter.prototype.$on = function(type,fn){
    const handle = this._events.get(type);
    if(handle){
        handle.push(fn);
    }else{
        this._events.set(type,[fn])
    }
}
EventEmeitter.prototype.$emit = function(type,...args){
    const handle = this._events.get(type);
    for(let i=0;i<handle.length;i++){
        handle[i].apply(this,args);
    }
}

const emitter = new EventEmeitter()
emitter.$on(‘arson‘, man => {
  console.log(`expel ${man}`);
});
emitter.$on(‘arson‘, man => {
  console.log(`save ${man}`);
});

emitter.$on(‘arson‘, man => {
  console.log(`kill ${man}`);
});
// 触发事件
emitter.$emit(‘arson‘, ‘low-end‘);

以上是关于发布订阅事件的主要内容,如果未能解决你的问题,请参考以下文章