Skip to content

Commit

Permalink
1
Browse files Browse the repository at this point in the history
  • Loading branch information
weixiangmeng521 committed Dec 21, 2023
1 parent 69a0d57 commit cef68d6
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 71 deletions.
4 changes: 2 additions & 2 deletions lib/internal/service.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ export declare class Teleport {
* Registers a handler function for the specified event.
* @template T - The type of data received by the event.
* @param {string | symbol} name - The name or symbol of the event.
* @param {(data: T) => void} handler - The handler function to process the event data.
* @param {(data: any) => void} handler - The handler function to process the event data.
*/
receive<T>(name: string | symbol, handler: (data: T) => void): void;
receive(name: string | symbol, handler: (data: any) => void): void;
/**
* Listens for multiple events with a common handler.
* When any of the specified events is emitted, the provided handler will be called.
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Teleport {
* Registers a handler function for the specified event.
* @template T - The type of data received by the event.
* @param {string | symbol} name - The name or symbol of the event.
* @param {(data: T) => void} handler - The handler function to process the event data.
* @param {(data: any) => void} handler - The handler function to process the event data.
*/
receive(name, handler) {
this._teleportSingleton.receive(name, handler);
Expand Down
32 changes: 19 additions & 13 deletions lib/internal/teleport.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,32 @@ export declare class TeleportSingleton {
/**
* Map to store the count of times each individual event has been triggered.
* Key: Event name or symbol, Value: Number of times triggered.
* @protected
*/
protected _eventCountMap: Map<string | symbol, number>;
/**
* Array to store lists of events that are considered as a single multi-event.
* Each list represents a combination of events to be treated collectively.
* @protected
*/
protected _multiEventsList: string[][];
/**
* Map to store the last recorded trace of the total number of times a multi-event has been triggered.
* Key: Combined event name or symbol, Value: Last recorded trace of triggered times.
* @protected
*/
protected _eventsUpdateMap: Map<string | symbol, number>;
/**
* Map to store arbitrary data associated with individual events.
* Key: Event name or symbol, Value: Associated data.
* @protected
*/
protected _eventsDataMap: Map<string | symbol, any>;
/**
* Private constructor to enforce singleton pattern.
*/
private constructor();
/**
* Method to get or create the singleton instance.
* @returns The singleton instance of TeleportSingleton.
*/
static getInstance(): TeleportSingleton;
/**
* Clears the map storing the count of times each individual event has been triggered.
*/
Expand Down Expand Up @@ -71,7 +72,7 @@ export declare class TeleportSingleton {
* @param name - Combined event name.
* @returns The last recorded trace of triggered times for the multi-event.
*/
protected _getEventsUpdateMap: (name: string) => number;
protected _getEventsUpdateMap: (name: string | symbol) => number;
/**
* Adds or updates arbitrary data associated with individual events to the map.
* @param name - Event name.
Expand Down Expand Up @@ -100,7 +101,7 @@ export declare class TeleportSingleton {
* @param nameList - List of event names.
* @returns The generated token.
*/
protected _generateMultiEventsToken: (nameList: string[]) => string;
protected _generateMultiEventsToken: (nameList: string[]) => symbol;
/**
* Checks for multi-event conditions and triggers automatic emission if conditions are met.
* @protected
Expand All @@ -113,11 +114,6 @@ export declare class TeleportSingleton {
* @param {string[]} eventsList - The list of events to be combined and emitted.
*/
protected _autoEmit(eventsList: string[]): void;
/**
* Method to get or create the singleton instance.
* @returns The singleton instance of TeleportSingleton.
*/
static getInstance(): TeleportSingleton;
/**
* Method to add handlers to the wait queue.
* @param name - The name or symbol of the event.
Expand All @@ -137,14 +133,24 @@ export declare class TeleportSingleton {
* @param callback - Optional callback to be executed after emitting the event.
*/
emit<T>(name: string | symbol, data: T, callback?: () => void): TeleportSingleton;
/**
* After emit data then execute.
* @param name event name
*/
private _afterEmit;
/**
* handler‘s wrapper
* @param handler
* @param mode 0 => single, 1=> multiple
*/
private _eventHandler;
/**
* Method to receive an event and handle it with a provided handler.
* @template T - The type of data received by the event.
* @param name - The name or symbol of the event.
* @param handler - The handler function to process the event data.
* @returns The TeleportSingleton instance for chaining.
*/
receive<T>(name: string | symbol, handler: (data: T) => void): TeleportSingleton;
receive(name: string | symbol, handler: (data: any) => void): TeleportSingleton;
/**
* Method to handle multiple events with a common handler.
* @param nameList - The list of event names.
Expand Down
103 changes: 49 additions & 54 deletions lib/internal/teleport.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,21 @@ class TeleportSingleton {
/**
* Map to store the count of times each individual event has been triggered.
* Key: Event name or symbol, Value: Number of times triggered.
* @protected
*/
this._eventCountMap = new Map();
/**
* Array to store lists of events that are considered as a single multi-event.
* Each list represents a combination of events to be treated collectively.
* @protected
*/
this._multiEventsList = [];
/**
* Map to store the last recorded trace of the total number of times a multi-event has been triggered.
* Key: Combined event name or symbol, Value: Last recorded trace of triggered times.
* @protected
*/
this._eventsUpdateMap = new Map();
/**
* Map to store arbitrary data associated with individual events.
* Key: Event name or symbol, Value: Associated data.
* @protected
*/
this._eventsDataMap = new Map();
/**
Expand Down Expand Up @@ -126,31 +122,51 @@ class TeleportSingleton {
* @returns The generated token.
*/
this._generateMultiEventsToken = (nameList) => {
return nameList.join(",");
return Symbol.for(`Teleport:${nameList.join(",")}`);
};
/**
* handler‘s wrapper
* @param handler
* @param mode 0 => single, 1=> multiple
*/
this._eventHandler = (handler, mode) => {
return (emitData) => {
if (mode === 0)
handler(emitData.data);
if (mode === 1)
handler(...emitData.data);
emitData.callback && emitData.callback();
};
};
}
/**
* Method to get or create the singleton instance.
* @returns The singleton instance of TeleportSingleton.
*/
static getInstance() {
if (!TeleportSingleton._instance) {
this._instance = new TeleportSingleton();
}
return this._instance;
}
/**
* Checks for multi-event conditions and triggers automatic emission if conditions are met.
* @protected
*/
_checkMultiEvents() {
var _a, _b, _c;
var _a, _b;
for (let i = 0; i < this._multiEventsList.length; i++) {
const eventsList = (_a = this._multiEventsList[i]) !== null && _a !== void 0 ? _a : [];
const timesArr = new Array(eventsList.length).fill(0);
for (let j = 0; j < eventsList.length; j++) {
const eventName = (_b = eventsList[j]) !== null && _b !== void 0 ? _b : "";
const triggeredTimes = this._getEventsTimes(eventName);
timesArr[j] = triggeredTimes;
}
const isNotContainsZero = timesArr.indexOf(0) === -1;
// every event that be executed times
const timesArr = eventsList.map((eventName) => this._getEventsTimes(eventName));
// is that one of the event that executed times not 0
const isNotContainsZero = !timesArr.includes(0);
const updatedEventName = this._generateMultiEventsToken(eventsList);
const lastTrace = (_c = this._getEventsUpdateMap(updatedEventName)) !== null && _c !== void 0 ? _c : 0;
const currentUpdateTimes = timesArr.reduce((x, y) => x + y, 0);
const lastTrace = (_b = this._getEventsUpdateMap(updatedEventName)) !== null && _b !== void 0 ? _b : 0;
const currentUpdateTimes = timesArr.reduce((pre, cur) => pre + cur, 0);
if (isNotContainsZero) {
if (currentUpdateTimes !== lastTrace) {
if (currentUpdateTimes !== lastTrace)
this._autoEmit(eventsList);
}
this._add2EventsUpdateMap(updatedEventName, currentUpdateTimes);
}
}
Expand All @@ -163,34 +179,19 @@ class TeleportSingleton {
*/
_autoEmit(eventsList) {
const multiEventsName = this._generateMultiEventsToken(eventsList);
const dataList = [];
eventsList.forEach((eventName) => {
const _data = this._getEventsDataMap(eventName);
dataList.push(_data);
});
const dataList = eventsList.map(eventName => this._getEventsDataMap(eventName));
const emitData = { data: dataList };
const subject = this._eventMap.get(multiEventsName);
if (!subject) {
const _subject = new subject_1.Subject();
this._eventMap.set(multiEventsName, _subject);
this._add2WaitMap(multiEventsName, (_name) => {
return this._add2WaitMap(multiEventsName, (_name) => {
const ptr = this._eventMap.get(_name);
ptr === null || ptr === void 0 ? void 0 : ptr.next(emitData);
});
return;
}
subject.next(emitData);
}
/**
* Method to get or create the singleton instance.
* @returns The singleton instance of TeleportSingleton.
*/
static getInstance() {
if (!TeleportSingleton._instance) {
this._instance = new TeleportSingleton();
}
return this._instance;
}
/**
* Method to add handlers to the wait queue.
* @param name - The name or symbol of the event.
Expand Down Expand Up @@ -227,10 +228,6 @@ class TeleportSingleton {
* @param callback - Optional callback to be executed after emitting the event.
*/
emit(name, data, callback) {
const afterEmit = () => {
this._addEventsTimes(name);
this._checkMultiEvents();
};
const emitData = {
data: data,
callback: callback,
Expand All @@ -243,35 +240,38 @@ class TeleportSingleton {
this._add2WaitMap(name, (_name) => {
const ptr = this._eventMap.get(_name);
ptr === null || ptr === void 0 ? void 0 : ptr.next(emitData);
afterEmit();
this._afterEmit(name);
});
return this;
}
subject.next(emitData);
afterEmit();
this._afterEmit(name);
return this;
}
/**
* After emit data then execute.
* @param name event name
*/
_afterEmit(name) {
this._addEventsTimes(name);
this._checkMultiEvents();
}
/**
* Method to receive an event and handle it with a provided handler.
* @template T - The type of data received by the event.
* @param name - The name or symbol of the event.
* @param handler - The handler function to process the event data.
* @returns The TeleportSingleton instance for chaining.
*/
receive(name, handler) {
var _a;
const eventHandler = (emitData) => {
handler(emitData.data);
emitData.callback && emitData.callback();
};
const subject = this._eventMap.get(name);
if (!subject) {
const ptr = new subject_1.Subject();
this._eventMap.set(name, ptr);
ptr.subscribe({ next: eventHandler });
ptr.subscribe({ next: this._eventHandler(handler, 0) });
return this;
}
subject.subscribe({ next: eventHandler });
subject.subscribe({ next: this._eventHandler(handler, 0) });
if (((_a = this._waitQueueMap.get(name)) !== null && _a !== void 0 ? _a : []).length) {
this._fireWaitHandlers(name);
}
Expand All @@ -289,20 +289,15 @@ class TeleportSingleton {
nameList.forEach((eventName) => {
this.receive(eventName, () => { });
});
const eventHandler = (emitData) => {
const obj = emitData;
handler(...obj.data);
emitData.callback && emitData.callback();
};
const eventsNameList = this._generateMultiEventsToken(nameList);
const subject = this._eventMap.get(eventsNameList);
if (!subject) {
const ptr = new subject_1.Subject();
this._eventMap.set(eventsNameList, ptr);
ptr.subscribe({ next: eventHandler });
ptr.subscribe({ next: this._eventHandler(handler, 1) });
return this;
}
subject.subscribe({ next: eventHandler });
subject.subscribe({ next: this._eventHandler(handler, 1) });
if (((_a = this._waitQueueMap.get(eventsNameList)) !== null && _a !== void 0 ? _a : []).length) {
this._fireWaitHandlers(eventsNameList);
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@mwx47/teleport",
"version": "1.1.6",
"version": "1.1.7",
"description": "A library for managing and communicating events in your application through a singleton pattern. This pattern ensures that there is a single instance of the event manager, making it easy to coordinate and handle events across different parts of your codebase.",
"main": "./src/index.js",
"keywords": [
Expand Down

0 comments on commit cef68d6

Please sign in to comment.