Subscribe-Publisher

      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)