refactor: Simplify and optimize event handling and listener management
This commit is contained in:
Vendored
+2
-5
@@ -636,10 +636,7 @@ export namespace Event {
|
||||
/** 回调 */
|
||||
callback: (event: {
|
||||
/** 事件参数 */
|
||||
params: {
|
||||
/** 末影龙复活后的uniqueId */
|
||||
0: number
|
||||
},
|
||||
params: {},
|
||||
/** 拦截事件 */
|
||||
cancel: () => void,
|
||||
/** 设置拦截状态 */
|
||||
@@ -668,7 +665,7 @@ export namespace Event {
|
||||
callback: (event: {
|
||||
/** 事件参数 */
|
||||
params: {
|
||||
/** 末影人实体 */
|
||||
/** 末影龙实体 */
|
||||
0: Entity
|
||||
},
|
||||
/** 获取事件ID */
|
||||
|
||||
+6
-5
@@ -7,7 +7,7 @@ const getPluginName = () => {
|
||||
} catch (error) {
|
||||
return error.stack.trim().match(/plugins\\(.*)\\.*\.js:[0-9]+\)$/i)?.[1] || "Unknown";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
Event: {
|
||||
@@ -37,6 +37,7 @@ module.exports = {
|
||||
*/
|
||||
listen: function (eventName, callback) {
|
||||
try {
|
||||
if (typeof callback !== "function") return false;
|
||||
const eventReflection = {
|
||||
onServerStopping: "ll::ServerStoppingEvent",
|
||||
onClientLogin: "gmlib::ClientLoginAfterEvent",
|
||||
@@ -75,6 +76,7 @@ module.exports = {
|
||||
* @returns {number}
|
||||
*/
|
||||
emplaceListener: function (eventName, callback, priority = this.EventPriority.Normal, pluginName = getPluginName()) {
|
||||
if (typeof callback !== "function") throw new Error("callback must be a function!");
|
||||
const /** @type {number} */ eventId = ll.imports("GMLIB_Event_API", "emplaceListener")(pluginName, eventName, priority);
|
||||
if (eventId === -1) throw new Error(`Event ${eventName} creation failed!`);
|
||||
ll.exports((...data) => {
|
||||
@@ -83,7 +85,7 @@ module.exports = {
|
||||
callback({
|
||||
params: data,
|
||||
cancel: () => result = true,
|
||||
setCancelled: (/** @type {boolean} */value) => result = value,
|
||||
setCancelled: (/** @type {boolean} */value) => { result = value; },
|
||||
isCancelled: () => result,
|
||||
getId: () => eventId,
|
||||
getEventType: () => eventName
|
||||
@@ -95,8 +97,7 @@ module.exports = {
|
||||
}
|
||||
return result;
|
||||
}, pluginName, eventName + "_" + eventId);
|
||||
if (this.mEventData[eventName] === undefined) this.mEventData[eventName] = [];
|
||||
this.mEventData[eventName].push(eventId);
|
||||
(this.mEventData[eventName] ??= []).push(eventId);
|
||||
return eventId;
|
||||
},
|
||||
|
||||
@@ -140,7 +141,7 @@ module.exports = {
|
||||
* @param {string | undefined} eventName
|
||||
* @returns {number[] | Object.<string, number[]>}
|
||||
*/
|
||||
getListener: function(eventName) {
|
||||
getListener: function (eventName) {
|
||||
return eventName === undefined ? this.mEventData : this.mEventData[eventName] ?? [];
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user