Merge pull request 'Add EventEmitter into Module, Optimize Manger so that it can load data' (#8) from dev-mrkbear into master

Reviewed-on: http://git.mrkbear.com/MrKBear/mini-dlpu-v3/pulls/8
This commit is contained in:
MrKBear 2021-12-01 16:31:55 +08:00
commit 0528c2865d
4 changed files with 304 additions and 62 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,7 @@
import mitt, { Emitter, EventHandlerMap, EventType, Handler, WildcardHandler } from "./EventEmitter";
import { LogLabel, LogStyle } from "./LogLabel";
import { Logger } from "./Logger";
import { LevelLogLabel } from "./PresetLogLabel";
/** /**
* *
@ -52,13 +56,15 @@ type Depends<M extends Manager<AnyWXContext>> = {
* *
* @template M Manager * @template M Manager
* @template DEP * @template DEP
* @template E
* @template TD Data * @template TD Data
*/ */
class Modular< class Modular<
M extends Manager<AnyWXContext> = Manager<AnyWXContext>, M extends Manager<AnyWXContext> = Manager<AnyWXContext>,
DEP extends Depends<M> = Depends<M>, DEP extends Depends<M> = Depends<M>,
E extends Record<EventType, unknown> = Record<EventType, unknown>,
TD extends IAnyTypeObject = IAnyTypeObject> TD extends IAnyTypeObject = IAnyTypeObject>
implements WXContext<TD, IAnyTypeObject> { implements WXContext<TD, IAnyTypeObject>, Emitter<E> {
// [x:string]: any; // [x:string]: any;
@ -87,17 +93,17 @@ implements WXContext<TD, IAnyTypeObject> {
/** /**
* 使 * 使
*/ */
private functionList:Set<string>; public functionList:Set<string>;
/** /**
* 使 * 使
*/ */
private paramList:Set<string>; public paramList:Set<string>;
/** /**
* *
*/ */
private nameSpace:string; public nameSpace:string;
// 映射主上下文属性 // 映射主上下文属性
public get is():string { return this.context.is }; public get is():string { return this.context.is };
@ -125,6 +131,34 @@ implements WXContext<TD, IAnyTypeObject> {
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 {
@ -293,40 +327,44 @@ class Manager<WXC extends AnyWXContext = AnyWXContext> {
* *
* @param key * @param key
*/ */
public creatHooks(key:keyof ILifetime):ILifetime[keyof ILifetime] { public creatHooks(key:keyof ILifetime):(...arg: any[]) => Promise<any> {
return (...arg: any[]) => { return async (...arg: any[]) => {
let hooks:Promise<any>[] = []; let hooks:Promise<any>[] = [];
let simple:any;
for(let i = 0; i < this.modules.length; i++) { for(let i = 0; i < this.modules.length; i++) {
let res: Promise<any> | any = let fn:Function = (this.modules[i] as IAnyTypeObject)[key];
(this.modules[i] as IAnyTypeObject)[key](...arg);
if(fn === void 0) continue;
let res: Promise<any> | any = fn.apply(this.modules[i], arg);
if (res instanceof Promise) { if (res instanceof Promise) {
hooks.push(res); hooks.push(res);
} else { } else {
hooks.push(Promise.resolve(res)); hooks.push(Promise.resolve(res));
} }
if (
key === "onShareAppMessage" ||
key === "onShareTimeline" ||
key === "onAddToFavorites"
) {
// 如果返回值有特殊含义在处理时进行 MinIn
simple = Object.assign({}, simple, res);
} else {
simple = res;
}
} }
if(hooks.length === 0) return; if (
if(hooks.length === 1) return simple; key === "onShareAppMessage" ||
key === "onShareTimeline" ||
key === "onAddToFavorites"
) {
// 如果返回值有特殊含义在处理时进行 MinIn
return Promise.all(hooks).then((res) => {
let simple:IAnyTypeObject = {};
for(let i = 0; i < res.length; i++) {
simple = Object.assign({}, simple, res);
}
return Promise.resolve(simple);
})
}
return Promise.all(hooks); return Promise.all(hooks);
} }
@ -344,13 +382,81 @@ class Manager<WXC extends AnyWXContext = AnyWXContext> {
/** /**
* *
* @param query onLoad
*/ */
public loadAllModule(query:Record<string, string | undefined>) { public loadAllModule(query:Record<string, string | undefined>) {
// 创建全部钩子
this.creatAllHooks(); this.creatAllHooks();
// 加载全部模组数据
for(let i = 0; i < this.modules.length; i++) {
if(this.modules[i].data)
for(let key in this.modules[i].data) {
if(this.context.data === void 0) this.context.data = {};
if(this.modules[i].data !== void 0) {
this.context.data[`${ this.modules[i].nameSpace }$${ key }`] =
( this.modules[i].data as IAnyTypeObject )[key];
// this.modules[i]
}
}
}
// 将全部数据发布到视图层
if(this.context.data !== void 0)
this.context.setData(this.context.data);
// 调用全部模块的 onLoad 周期
let res = this.creatHooks("onLoad")(query as any); let res = this.creatHooks("onLoad")(query as any);
// 打印每个模块的键值对使用情况
for(let i = 0; i < this.modules.length; i++) {
let data:string[] = [];
let func:string[] = [];
for(let key of this.modules[i].paramList) {
data.push(`[${ key }]`);
}
for(let key of this.modules[i].functionList) {
func.push(`[${ key }]`);
}
let log:string = `模块 [${ this.modules[i].nameSpace }] 加载完成...\n`;
if(data.length > 0) log += `Using Props: ${ data.join(", ") }\n`;
if(func.length > 0) log += `Using Function: ${ func.join(", ") }\n`;
Logger.log(log, LevelLogLabel.TraceLabel, Manager.AddModuleLabel);
}
return res; return res;
} }
/**
*
*/
public static readonly AddModuleLabel = new LogLabel("addModule",
new LogStyle().setBorder("4px", `1px solid #8600FF`)
.setColor("#FF00FF", "rgba(54, 0, 255, .2)").setBlank("0 5px")
)
/**
* Manager
* @param fn
*/
public static Page(fn:(manager:Manager<AnyWXContext>) => void) {
Page({
async onLoad(query) {
let manager = new Manager(this);
fn(manager);
manager.loadAllModule(query);
}
})
}
} }
export { Manager, Modular, AnyWXContext, WXContext, ILifetime} export { Manager, Modular, AnyWXContext, WXContext, ILifetime}

View File

@ -2,67 +2,84 @@ import { Logger } from "../../core/Logger";
import { LevelLogLabel, LifeCycleLogLabel } from "../../core/PresetLogLabel"; import { LevelLogLabel, LifeCycleLogLabel } from "../../core/PresetLogLabel";
import { Manager, Modular, AnyWXContext, ILifetime } from "../../core/Module"; import { Manager, Modular, AnyWXContext, ILifetime } from "../../core/Module";
Page({ let manager;
/** // Page({
*
*/
onLoad: async function () {
this; // /**
// * 课程表页面加载
// */
// onLoad: async function (query) {
let manager = new Manager(this); // manager = new Manager(this);
let m1 = manager.addModule(M1, "m1"); // console.log(manager);
let m2 = manager.addModule(M2, "m2", {m1});
let manager2 = new Manager(this);
let m22 = manager.addModule(M2, "m1", {m1});
this.setData; // // this.setData;
Logger.log("课程表 (Timetable) 页面加载...", // // Logger.log("课程表 (Timetable) 页面加载...",
LevelLogLabel.TraceLabel, LifeCycleLogLabel.OnLoadLabel); // // LevelLogLabel.TraceLabel, LifeCycleLogLabel.OnLoadLabel);
let systemInfo = wx.getSystemInfoSync(); // // let systemInfo = wx.getSystemInfoSync();
//状态栏高度 // // //状态栏高度
let statusBarHeight = Number(systemInfo.statusBarHeight); // // let statusBarHeight = Number(systemInfo.statusBarHeight);
let menu = wx.getMenuButtonBoundingClientRect() // // let menu = wx.getMenuButtonBoundingClientRect()
//导航栏高度 // // //导航栏高度
let navBarHeight = menu.height + (menu.top - statusBarHeight) * 2 // // let navBarHeight = menu.height + (menu.top - statusBarHeight) * 2
//状态栏加导航栏高度 // // //状态栏加导航栏高度
let navStatusBarHeight = statusBarHeight + menu.height + (menu.top - statusBarHeight) * 2 // // let navStatusBarHeight = statusBarHeight + menu.height + (menu.top - statusBarHeight) * 2
console.log('状态栏高度',statusBarHeight) // // console.log('状态栏高度',statusBarHeight)
console.log('导航栏高度',navBarHeight) // // console.log('导航栏高度',navBarHeight)
console.log('状态栏加导航栏高度',navStatusBarHeight) // // console.log('状态栏加导航栏高度',navStatusBarHeight)
this.setData({barh: navStatusBarHeight}); // // this.setData({barh: navStatusBarHeight});
} // }
// })
Manager.Page((manager)=>{
let m1 = manager.addModule(M1, "m1");
let m2 = manager.addModule(M2, "m2", {m1});
}) })
class M1<M extends Manager> extends Modular<M, {}> {
class M1<M extends Manager> extends Modular<M, {}> implements Partial<ILifetime> {
data = {
a:1,
b:{}
}
public onLoad(){ public onLoad(){
} }
public onReady() {
console.log(this);
this.emit("lll", {a:1})
}
} }
class M2<M extends Manager> extends Modular<M, {m1:M1<M>}> { class M2<M extends Manager> extends Modular<M, {m1:M1<M>}> {
public onLoad() {
// this.setData();
}
// hhh(){
// }
hh(){} data = {
a: 1
}
public onLoad() {
this.setData({a:1});
this.depends?.m1.on("lll", (e)=>{
console.log(e)
})
console.log(this);
}
} }

View File

@ -1,3 +1,3 @@
<view class="status-bar" style="height:{{barh}}px"></view> <view class="status-bar" style="height:{{barh}}px"></view>
<text>pages/Timetable/Timetable.wxml</text> <text>pages/Timetable/Timetable.wxml{{m1$a}}</text>