JS 事件发布订阅

21 阅读1分钟

常用在类框架库中,在最底层,支持整个库的消息通知

什么是发布订阅模式?

发布订阅模式是一种消息范式,消息的发送者(发布者)不会直接将消息发送给特定的接收者(订阅者),而是通过消息通道(事件中心)进行广播,订阅者可以接收到自己感兴趣的消息。

核心概念:

发布者(Publisher):发出事件/消息的对象

订阅者(Subscriber):监听特定事件/消息的对象

事件中心(Event Channel):管理事件与订阅者之间的关系

class Emitter {
	_listeners: Record<string, Function[]>;
    constructor() {
        this._listeners = {};
    }
	addEventListener( type: string, listener: Function ) {
		const listeners = this._listeners;
		if ( listeners[ type ] === undefined ) {
			listeners[ type ] = [];
		}
		if ( listeners[ type ].indexOf( listener ) === - 1 ) {
			listeners[ type ].push( listener );
		}
	}
	removeEventListener( type: string, listener: Function ) {
		const listeners = this._listeners;
		const listenerArray = listeners[ type ];
		if ( listenerArray !== undefined ) {
			const index = listenerArray.indexOf( listener );
			if ( index !== - 1 ) {
				listenerArray.splice( index, 1 );
			}
		}
	}
	emit( event: Record<string, any> ) {
		const listeners = this._listeners;
		const listenerArray = listeners[ event.type ];
		if ( listenerArray !== undefined ) {
			event.target = this;
			const array = listenerArray.slice( 0 );
			for ( let i = 0, l = array.length; i < l; i ++ ) {
				const listener = array[ i ];
				if ( listener !== undefined ) {
					listener.call( this, event );
				}
			}
			event.target = null;
		}
	}
}


export { Emitter };