其他分享
首页 > 其他分享> > 设计模式-发布订阅模式(typescript版本)

设计模式-发布订阅模式(typescript版本)

作者:互联网

实际操作:


/**
 * example:
 * 订阅:
 * ObserveEvent.on(EventName,this.userInfo,this);
 * 发布:
 * ObserveEvent.emit(EventName,{userName:"小明",age:18,sex:"man"});
 * 取消订阅:
 * ObserveEvent.on(EventName,this.userInfo);
 */
// call is faster than apply, optimize less than 3 argu
// http://blog.csdn.net/zhengyinhui100/article/details/7837127
 function emitEvents(
    events: EventCallback[],
    args: any[],
    context?: any
): void {
        if(args.length === 0){
            events.forEach(event=>{
                event.callback.call(context || event.context);
            })
        }else if(args.length <=3){
            events.forEach(event=>{
                event.callback.call(context || event.context, ...args);
            })
        }else{
            events.forEach(event=>{
                event.callback.apply(context || event.context, args);
            })
        }
}
interface EventCallback {
    context?: any;
    callback: (...args: any[]) => any;
    force?: boolean; //是否强制推送
}
export default class ObserveEvent {
    private static _eventMap: Map<string, EventCallback[]> = new Map<
        string,
        EventCallback[]
    >();
    public static on(
        eventName: string,
        callback: (...args: any[]) => any,
        context?: any,
        force?: boolean 
    ): Event {
        if (!this._eventMap.has(eventName)) this._eventMap.set(eventName, []);
        this._eventMap.get(eventName)?.push({
            callback,
            context,
            force,
        });
        return this;
    }
    public static off( eventName: string,callback?: (...args: any[])=>void): Event {
        if (!this._eventMap.has(eventName)) return this;
        if(!callback){
            delete this._eventMap[eventName];
            return;
        }
        const events = this._eventMap.get(eventName);
        const index = events.findIndex(event=> event.callback === callback );
        if(events[index]){
            events.splice(index,1);
        }
        if(0 === events.length)delete this._eventMap[eventName];
        return this;
    }
    public  static emit(eventName: string,...args:any): boolean {
        if (!this._eventMap.has(eventName)) return false;
        const events = this._eventMap.get(eventName);
        emitEvents(events,args)
    }
    public static clear():void{
        this._eventMap.clear();
    }
}

export interface Event {
    on( eventName: string,
        callback: (...args: any[]) => any,
        context?: any,
        force?: boolean 
        ): Event;
    off(
        eventName: string,
        callback?: (...args: any[]) => any
    ): Event;
    clear():void;
    
    emit(eventName: string, data: any): boolean;
}

标签:订阅,typescript,args,eventName,callback,eventMap,context,设计模式,any
来源: https://blog.csdn.net/z1067832450_/article/details/123633939