Handler调用时保留this

This commit is contained in:
Kokomi 2023-10-16 04:11:44 +08:00
parent 6e14f47513
commit d6fdf6f53c
2 changed files with 10 additions and 5 deletions

View File

@ -1,9 +1,10 @@
import util from 'node:util'
import lodash from 'lodash' import lodash from 'lodash'
let events = {} let events = {}
let Handler = { let Handler = {
add (cfg) { add (cfg) {
let { ns, fn, property = 50 } = cfg let { ns, fn, self, property = 50 } = cfg
let key = cfg.key || cfg.event let key = cfg.key || cfg.event
if (!key || !fn) { if (!key || !fn) {
return return
@ -15,6 +16,7 @@ let Handler = {
property, property,
fn, fn,
ns, ns,
self,
key key
}) })
events[key] = lodash.orderBy(events[key], ['priority'], ['asc']) events[key] = lodash.orderBy(events[key], ['priority'], ['asc'])
@ -38,7 +40,8 @@ let Handler = {
} }
}, },
async callAll (key, e, args) { async callAll (key, e, args) {
return await Handler.callAll(key, e, args, true) // 暂时屏蔽调用
// return Handler.call(key, e, args, true)
}, },
async call (key, e, args, allHandler = false) { async call (key, e, args, allHandler = false) {
let ret let ret
@ -51,9 +54,9 @@ let Handler = {
} }
done = false done = false
} }
ret = fn(e, args, reject) ret = fn.call(obj.self, e, args, reject)
if (ret) { if (util.types.isPromise(ret)) {
await ret ret = await ret
} }
if (done && !allHandler) { if (done && !allHandler) {
logger.mark(`[Handler][Done]: [${obj.ns}][${key}]`) logger.mark(`[Handler][Done]: [${obj.ns}][${key}]`)

View File

@ -82,6 +82,7 @@ class PluginsLoader {
Handler.add({ Handler.add({
ns: plugin.namespace || File.name, ns: plugin.namespace || File.name,
key: key, key: key,
self: plugin,
property: priority || plugin.priority || 500, property: priority || plugin.priority || 500,
fn: plugin[fn] fn: plugin[fn]
}) })
@ -795,6 +796,7 @@ class PluginsLoader {
Handler.add({ Handler.add({
ns: plugin.namespace || File.name, ns: plugin.namespace || File.name,
key: key, key: key,
self: plugin,
property: priority || plugin.priority || 500, property: priority || plugin.priority || 500,
fn: plugin[fn] fn: plugin[fn]
}) })