Modify EventEmitter to class style

This commit is contained in:
ben.qin 2021-12-30 16:14:21 +08:00
parent c3773a3c71
commit 14b03af584
5 changed files with 128 additions and 156 deletions

View File

@ -1,13 +1,23 @@
import { IAppAPIParam } from "./core/Api";
import { Logger } from "./core/Logger"; import { Logger } from "./core/Logger";
import { LevelLogLabel, LifeCycleLogLabel } from "./core/PresetLogLabel"; import { LevelLogLabel, LifeCycleLogLabel } from "./core/PresetLogLabel";
App({ App<IAppAPIParam>({
/**
* API
* "/core/Api"
*/
api: {
nextId: 1,
pool: []
},
/** /**
* *
*/ */
storageCache: new Set<string>(), // storageCache: new Set<string>(),
/** /**
* *

View File

@ -1,8 +1,23 @@
import mitt, { Emitter } from "./EventEmitter"; import { EventEmitter } from "./EventEmitter";
import { LogLabel } from "./LogLabel"; import { LogLabel } from "./LogLabel";
import { Logger } from "./Logger"; import { Logger } from "./Logger";
import { LevelLogLabel, colorRadio } from "./PresetLogLabel"; import { LevelLogLabel, colorRadio } from "./PresetLogLabel";
interface IAppAPIParam {
api: {
/**
* API
*/
nextId: number;
/**
*
*/
pool: API<IAnyData, IAnyData>[];
}
}
interface IAnyData { interface IAnyData {
[x:string]: any [x:string]: any
} }
@ -82,7 +97,7 @@ type IAPIEvent<I extends IAnyData, O extends IAnyData> = {
/** /**
* *
*/ */
class API<I extends IAnyData, O extends IAnyData> { class API<I extends IAnyData, O extends IAnyData> extends EventEmitter<IAPIEvent<I, O>> {
/** /**
* URL * URL
@ -101,15 +116,6 @@ class API<I extends IAnyData, O extends IAnyData> {
*/ */
private LogLabel:LogLabel = API.defaultLogLabel; private LogLabel:LogLabel = API.defaultLogLabel;
/**
*
*/
private emitter:Emitter<IAPIEvent<I, O>>;
public get on() { return this.emitter.on };
public get off() { return this.emitter.on };
public get emit() { return this.emitter.emit };
/** /**
* Api ID * Api ID
*/ */
@ -151,16 +157,6 @@ class API<I extends IAnyData, O extends IAnyData> {
//#endregion wx.request //#endregion wx.request
/**
*
* data
* @param data API需要的全部数据
*/
public constructor(data?: Partial<I>) {
this.data = data ?? {};
this.emitter = mitt<IAPIEvent<I, O>>();
}
/** /**
* *
*/ */
@ -172,8 +168,12 @@ class API<I extends IAnyData, O extends IAnyData> {
/** /**
* *
* data
* @param data API需要的全部数据
*/ */
public initData() { public param(data?: Partial<I>) {
this.data = data;
if (this.data === void 0) { if (this.data === void 0) {
Logger.log(`数据初始化异常: 没有输入 [data] 数据!`, Logger.log(`数据初始化异常: 没有输入 [data] 数据!`,
@ -225,12 +225,6 @@ class API<I extends IAnyData, O extends IAnyData> {
// 触发数据初始化事件 // 触发数据初始化事件
this.emit("initData", this.data); this.emit("initData", this.data);
}
/**
*
*/
public collectData() {
if (this.data === void 0) { if (this.data === void 0) {
Logger.log(`收集请求数据异常: 没有输入 [data] 数据!`, Logger.log(`收集请求数据异常: 没有输入 [data] 数据!`,
@ -298,4 +292,4 @@ enum HTTPMethod {
} }
export default API; export default API;
export { API, IParamSetting } export { API, IParamSetting, IAppAPIParam, HTTPMethod }

View File

@ -18,102 +18,92 @@ export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<
EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events> EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>
>; >;
export interface Emitter<Events extends Record<EventType, unknown>> { type GenericEventHandler<Events extends Record<EventType, unknown>> =
all: EventHandlerMap<Events>; | Handler<Events[keyof Events]>
| WildcardHandler<Events>;
export class EventEmitter<Events extends Record<EventType, unknown>> {
/**
* A Map of event names to registered handler functions.
*/
public all: EventHandlerMap<Events>;
public constructor() {
this.all = new Map();
}
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void; on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
on(type: '*', handler: WildcardHandler<Events>): void; on(type: '*', handler: WildcardHandler<Events>): void;
/**
* Register an event handler for the given type.
* @param {string|symbol} type Type of event to listen for, or `'*'` for all events
* @param {Function} handler Function to call in response to given event
* @memberOf mitt
*/
public on<Key extends keyof Events>(type: Key, handler: GenericEventHandler<Events>) {
const handlers: Array<GenericEventHandler<Events>> | undefined = this.all!.get(type);
if (handlers) {
handlers.push(handler);
}
else {
this.all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
}
}
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void; off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
off(type: '*', handler: WildcardHandler<Events>): void; off(type: '*', handler: WildcardHandler<Events>): void;
emit<Key extends keyof Events>(type: Key, event: Events[Key]): void; /**
emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void; * Remove an event handler for the given type.
} * If `handler` is omitted, all handlers of the given type are removed.
* @param {string|symbol} type Type of event to unregister `handler` from, or `'*'`
/** * @param {Function} [handler] Handler function to remove
* Mitt: Tiny (~200b) functional event emitter / pubsub. * @memberOf mitt
* @name mitt */
* @returns {Mitt} public off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler<Events>) {
*/ const handlers: Array<GenericEventHandler<Events>> | undefined = this.all!.get(type);
export default function mitt<Events extends Record<EventType, unknown>>( if (handlers) {
all?: EventHandlerMap<Events> if (handler) {
): Emitter<Events> { handlers.splice(handlers.indexOf(handler) >>> 0, 1);
type GenericEventHandler =
| Handler<Events[keyof Events]>
| WildcardHandler<Events>;
all = all || new Map();
return {
/**
* A Map of event names to registered handler functions.
*/
all,
/**
* Register an event handler for the given type.
* @param {string|symbol} type Type of event to listen for, or `'*'` for all events
* @param {Function} handler Function to call in response to given event
* @memberOf mitt
*/
on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
if (handlers) {
handlers.push(handler);
} }
else { else {
all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>); this.all!.set(type, []);
}
},
/**
* Remove an event handler for the given type.
* If `handler` is omitted, all handlers of the given type are removed.
* @param {string|symbol} type Type of event to unregister `handler` from, or `'*'`
* @param {Function} [handler] Handler function to remove
* @memberOf mitt
*/
off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {
const handlers: Array<GenericEventHandler> | undefined = all!.get(type);
if (handlers) {
if (handler) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
else {
all!.set(type, []);
}
}
},
/**
* Invoke all handlers for the given type.
* If present, `'*'` handlers are invoked after type-matched handlers.
*
* Note: Manually firing '*' handlers is not supported.
*
* @param {string|symbol} type The event type to invoke
* @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
* @memberOf mitt
*/
emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {
let handlers = all!.get(type);
if (handlers) {
(handlers as EventHandlerList<Events[keyof Events]>)
.slice()
.map((handler) => {
handler(evt!);
});
}
handlers = all!.get('*');
if (handlers) {
(handlers as WildCardEventHandlerList<Events>)
.slice()
.map((handler) => {
handler(type, evt!);
});
} }
} }
}; }
emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
/**
* Invoke all handlers for the given type.
* If present, `'*'` handlers are invoked after type-matched handlers.
*
* Note: Manually firing '*' handlers is not supported.
*
* @param {string|symbol} type The event type to invoke
* @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
* @memberOf mitt
*/
emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {
let handlers = this.all!.get(type);
if (handlers) {
(handlers as EventHandlerList<Events[keyof Events]>)
.slice()
.map((handler) => {
handler(evt!);
});
}
handlers = this.all!.get('*');
if (handlers) {
(handlers as WildCardEventHandlerList<Events>)
.slice()
.map((handler) => {
handler(type, evt!);
});
}
}
} }

View File

@ -1,4 +1,4 @@
import mitt, { Emitter, EventHandlerMap, EventType, Handler, WildcardHandler } from "./EventEmitter"; import { EventEmitter, EventType } from "./EventEmitter";
import { LogLabel, LogStyle } from "./LogLabel"; import { LogLabel, LogStyle } from "./LogLabel";
import { Logger } from "./Logger"; import { Logger } from "./Logger";
import { LevelLogLabel } from "./PresetLogLabel"; import { LevelLogLabel } from "./PresetLogLabel";
@ -64,7 +64,8 @@ class Modular<
DEP extends Depends<M> = Depends<M>, DEP extends Depends<M> = Depends<M>,
E extends Record<EventType, unknown> = Record<EventType, unknown>, E extends Record<EventType, unknown> = Record<EventType, unknown>,
TD extends IAnyTypeObject = IAnyTypeObject> TD extends IAnyTypeObject = IAnyTypeObject>
implements WXContext<TD, IAnyTypeObject>, Emitter<E> { extends EventEmitter<E>
implements WXContext<TD, IAnyTypeObject> {
// [x:string]: any; // [x:string]: any;
@ -121,6 +122,8 @@ implements WXContext<TD, IAnyTypeObject>, Emitter<E> {
*/ */
public constructor(manager:M, nameSpace:string, depend?: DEP) { public constructor(manager:M, nameSpace:string, depend?: DEP) {
super();
// 保存微信上下文 // 保存微信上下文
this.manager = manager; this.manager = manager;
@ -131,34 +134,6 @@ implements WXContext<TD, IAnyTypeObject>, Emitter<E> {
this.functionList = new Set<string>(); this.functionList = new Set<string>();
this.paramList = new Set<string>(); this.paramList = new Set<string>();
this.nameSpace = nameSpace; this.nameSpace = nameSpace;
this.emitter = mitt<E>();
}
/**
*
*/
private emitter:Emitter<E>;
public get all():EventHandlerMap<E> { return this.emitter.all };
on<Key extends keyof E>(type: Key, handler: Handler<E[Key]>): void;
on(type: "*", handler: WildcardHandler<E>): void;
on(type: any, handler: any): void {
return this.emitter.on(type, handler);
}
off<Key extends keyof E>(type: Key, handler?: Handler<E[Key]>): void;
off(type: "*", handler: WildcardHandler<E>): void;
off(type: any, handler?: any): void {
return this.emitter.off(type, handler);
}
emit<Key extends keyof E>(type: Key, event: E[Key]): void;
emit<Key extends keyof E>(type: undefined extends E[Key] ? Key : never): void;
emit(type: any, event?: any): void {
return this.emitter.emit(type, event);
} }
public setData(data:Partial<TD>, callback?: () => void):void { public setData(data:Partial<TD>, callback?: () => void):void {

View File

@ -42,21 +42,24 @@ implements Partial<ILifetime> {
info: {} info: {}
} }
public constructor(data:ITestApiInput) { public constructor() {
super(data); super();
this.on("initData", (data) => { this.initLabel();
console.log("initData", data)
this.emit("initData", {})
this.on("initData", (d) => {
}) })
this.on("parseRequestData", (data) => { this.on("parseRequestData", (data) => {
console.log("parseRequestData", data) console.log("parseRequestData", data)
}) })
this.initLabel();
this.initData();
this.collectData();
} }
} }
let api = new TestApi({ let api = new TestApi();
api.param({
name: "123", name: "123",
id: 456, id: 456,
info: { info: {