美文网首页
Subscribe-Publisher

Subscribe-Publisher

作者: 田帅奇 | 来源:发表于2018-08-21 14:12 被阅读0次
          class Event {
              constructor(){
                    this.handlers = {};
                }
                on(eventType, handler){
                    if(!(eventType in this.handlers)){
                        this.handlers[eventType] = [];
                    }
                    this.handlers[eventType].push(handler);
                }
                emit(eventType){
                    let handlerArgs = Array.prototype.slice.call(arguments, 1);
                    this.handlers[eventType] && this.handlers[eventType].forEach(handler => {
                        handler.apply(this, handlerArgs);
                    });
                }
                off(eventType, handler){
                    delete this.handlers[eventType];
                }
            };
            let event = new Event();
            event.on('A', (parmas) => {
                console.log('First on');
            });
            event.on('A', (parmas) => {
                console.log('Second on');
            });
            event.on('B', (parmas) => {
                console.log(parmas);
            });
            event.emit('A', 'xxx');
            event.emit('B', 'xxx');
            event.off('B');
            event.emit('B', 'xxx');
    

    相关文章

      网友评论

          本文标题:Subscribe-Publisher

          本文链接:https://www.haomeiwen.com/subject/grtjiftx.html