custom-app-event
Version:
基于typescript, 实现一个简单的event库,快速集成发布订阅模式
112 lines (111 loc) • 3.72 kB
JavaScript
"use strict";
/*
* @Description: AppEvent类
* @version:
* @Date: 2021-11-04 14:21:01
* @LastEditTime: 2021-11-09 10:47:15
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppEvent = void 0;
const utils_1 = require("./utils");
/**
* 定义事件类
*/
class AppEvent {
constructor(init) {
/**
* 开启则打印log
*/
this.debug = false;
/**
* 生成随机tag的位数
*/
this.tagLen = 8;
/**
* 使用Map()结构,保存订阅者的信息
*/
this.eventObj = new Map();
this.debug = (init === null || init === void 0 ? void 0 : init.debug) === undefined ? false : init.debug;
this.tagLen = (init === null || init === void 0 ? void 0 : init.tagLen) === undefined ? 8 : init.tagLen;
}
/**
* 暴露获取所有的event事件, 数据结构: Map()
*/
get events() {
return this.eventObj;
}
/**
* 添加事件
* @param eventName 事件名称
* @param event 事件
* @param tag [可选]自定义TagName
*/
addListen(eventName, event, tag) {
if (!this.eventObj.has(eventName)) {
this.eventObj.set(eventName, new Map());
}
const currentTag = tag !== null && tag !== void 0 ? tag : (0, utils_1.randomStringTag)(this.tagLen);
this.eventObj.get(eventName).set(currentTag, event);
this.printLog('add', eventName, currentTag);
return currentTag;
}
/**
* 通知事件,如果不指定tag,则通知所有对应事件的订阅,如果指定tag,则只通知对应tag的订阅者
* @param eventName 事件名称
* @param options {value: 参数, tag: 每一个订阅者唯一tag}
*/
notification(eventName, options) {
var _a;
// 先判断eventName是否存在
if (this.eventObj.has(eventName)) {
// 区分tag是否有值,来执行不同的分支
if ((options === null || options === void 0 ? void 0 : options.tag) !== undefined) {
(_a = this.eventObj.get(eventName).get(options.tag)) === null || _a === void 0 ? void 0 : _a(options.value);
}
else {
this.eventObj.get(eventName).forEach((fun) => {
fun(options === null || options === void 0 ? void 0 : options.value);
});
}
this.printLog('notification', eventName, options === null || options === void 0 ? void 0 : options.tag, options === null || options === void 0 ? void 0 : options.value);
}
}
/**
* 移除事件, 指定tag则移除对应的tag,如果不指定则移除全部
* @param eventName 事件名称
* @param tag 唯一事件标签
*/
removeListen(eventName, tag) {
// 先判断eventName是否存在
if (this.eventObj.has(eventName)) {
// 区分tag是否有值,来执行不同的分支
if (tag) {
this.eventObj.get(eventName).delete(tag);
}
else {
this.eventObj.delete(eventName);
}
this.printLog('remove', eventName, tag);
}
}
/**
* 打印日志
* @param type
* @param eventName
*/
printLog(type, eventName, tag, value) {
if (this.debug) {
const log = {
type: type,
eventName: eventName,
events: this.eventObj,
};
if (tag)
log['tag'] = tag;
if (value)
log['value'] = value;
console.log(log);
}
}
}
exports.AppEvent = AppEvent;