Add EventEmitter into Module

This commit is contained in:
MrKBear 2021-12-01 14:04:07 +08:00
parent 7fa3a215cf
commit da658cb371
3 changed files with 168 additions and 13 deletions

View File

@ -0,0 +1,119 @@
export type EventType = string | symbol;
// An event handler can take an optional event argument
// and should not return a value
export type Handler<T = unknown> = (event: T) => void;
export type WildcardHandler<T = Record<string, unknown>> = (
type: keyof T,
event: T[keyof T]
) => void;
// An array of all currently registered event handlers for a type
export type EventHandlerList<T = unknown> = Array<Handler<T>>;
export type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;
// A map of event types and their corresponding event handlers.
export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<
keyof Events | '*',
EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>
>;
export interface Emitter<Events extends Record<EventType, unknown>> {
all: EventHandlerMap<Events>;
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
on(type: '*', handler: WildcardHandler<Events>): void;
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): 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;
}
/**
* Mitt: Tiny (~200b) functional event emitter / pubsub.
* @name mitt
* @returns {Mitt}
*/
export default function mitt<Events extends Record<EventType, unknown>>(
all?: EventHandlerMap<Events>
): Emitter<Events> {
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 {
all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>);
}
},
/**
* 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!);
});
}
}
};
}

View File

@ -1,3 +1,4 @@
import mitt, { Emitter, EventHandlerMap, EventType, Handler, WildcardHandler } from "./EventEmitter";
/**
*
@ -52,13 +53,15 @@ type Depends<M extends Manager<AnyWXContext>> = {
*
* @template M Manager
* @template DEP
* @template E
* @template TD Data
*/
class Modular<
M extends Manager<AnyWXContext> = Manager<AnyWXContext>,
DEP extends Depends<M> = Depends<M>,
E extends Record<EventType, unknown> = Record<EventType, unknown>,
TD extends IAnyTypeObject = IAnyTypeObject>
implements WXContext<TD, IAnyTypeObject> {
implements WXContext<TD, IAnyTypeObject>, Emitter<E> {
// [x:string]: any;
@ -125,6 +128,34 @@ implements WXContext<TD, IAnyTypeObject> {
this.functionList = new Set<string>();
this.paramList = new Set<string>();
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 {
@ -301,8 +332,10 @@ class Manager<WXC extends AnyWXContext = AnyWXContext> {
for(let i = 0; i < this.modules.length; i++) {
let res: Promise<any> | any =
(this.modules[i] as IAnyTypeObject)[key](...arg);
let fn:Function = (this.modules[i] as IAnyTypeObject)[key];
if(fn === void 0) continue;
let res: Promise<any> | any = fn.apply(this.modules[i], arg);
if (res instanceof Promise) {
hooks.push(res);

View File

@ -7,7 +7,7 @@ Page({
/**
*
*/
onLoad: async function () {
onLoad: async function (query) {
this;
@ -15,8 +15,7 @@ Page({
let m1 = manager.addModule(M1, "m1");
let m2 = manager.addModule(M2, "m2", {m1});
let manager2 = new Manager(this);
let m22 = manager.addModule(M2, "m1", {m1});
manager.loadAllModule(query);
this.setData;
@ -48,21 +47,25 @@ Page({
})
class M1<M extends Manager> extends Modular<M, {}> {
class M1<M extends Manager> extends Modular<M, {}> implements Partial<ILifetime> {
public onLoad(){
}
public onReady() {
console.log(this);
this.emit("lll", {a:1})
}
}
class M2<M extends Manager> extends Modular<M, {m1:M1<M>}> {
public onLoad() {
// this.setData();
this.setData({a:1});
this.depends?.m1.on("lll", (e)=>{
console.log(e)
})
console.log(this);
}
// hhh(){
// }
hh(){}
}