本文共 1967 字,大约阅读时间需要 6 分钟。
TypeScript 没有类似C语言那样的#define功能,在Vue中实现反射机制进行事件扩展,需要在另一个文件进行import ‘xxx’; 这样的话,这样的话,会破坏系统架构。如何让二次开发只关注事件本身,让工程自动参与编译,让用户只用写自己的事件就行了呢?
需要解决的问题:如何不使用import ‘xxx’,来激活已注册的事件?
// ievent_handler.ts 文件export abstract class IEventHandler{ constructor(); abstract name():void;}
// event_handler_mgr.ts 文件
export class EventHandlerManager { private static _instance: EventHandlerManager; public static instance(): EventHandlerManager { if (!this._instance) { this._instance = new EventHandlerManager(); } return this._instance; } menuHandler = new Map(); private search(menuName: string): Module.IEventHandler|undefined { return this.menuHandler.get(menuName); } public register(eh: EventHandler) { const ehName: string = eh.name(); const event = this.search(ehName); if( event === null ){ this.menuHandler.set(ehName, event); } }}
// hello_event_handler.ts
import { EventHandlerManager } from "./event_handler_mgr";export class SayHello extends EventHandler { constructor() { super(); } public name():string{ return 'sayHello' }}EventHandlerManager.instance().register(new SayHello());
对于hello_event_handler.ts文件,必须要在其他的文件里执行类似 import 'hello_event_handler.ts'
这样的语句才行,如果没有这句话,那么hello_event_handler.ts这个文件不会参与编译,SayHello也不会存在于注册表中。如果有很多的event_handler文件,那么会严重破坏已有的文件结构和程序架构.
// 未修改之前,在plugins.js中添加所有的event_handler,例如
// plugins.jsimport './plugins/hello_event_handler.ts'import './plugins/circle_event_handler.ts'import './plugins/base/file_event_handler.ts'import './plugins/utility/string_event_handler.ts'// ...
// 优化后:
// plugins.jsconst contextEvent = require.context('./plugins/', true, /\.ts$/);contextEvent.keys().forEach((tsFile) => { //本行代码是文件能够成功引入的关键 contextEvent(tsFile); // 这句话,会执行到所有脚本里的注册函数,实现了注册的目的});
这样的话,开发者只需要按照要求,写好event_handler事件,放到plugins下就行了。
如果您有更好的解决方案,欢迎留言
转载地址:http://omvmb.baihongyu.com/