Events Module
This file defines the Events
class, which is responsible for managing and dispatching hook events to modules that have methods decorated with the @Hook
decorator in the @sodacore/core
library. It enables modules to respond to application lifecycle events or custom hooks in a centralized and extensible way.
Features
- Hook Discovery: Scans all registered modules for methods decorated with
@Hook
and stores them for event dispatching. - Event Dispatching: Invokes all methods matching a given hook type across all modules.
- Logging: Logs event dispatch activity for traceability and debugging.
Usage
typescript
import Events from './module/events';
const events = new Events(config);
await events.init();
// Dispatch a hook event (e.g., 'onInit')
await events.dispatch('onInit', { foo: 'bar' });
API
Constructor
typescript
constructor(config: IConfig)
- config: The configuration object for the events module.
Methods
async init(): Promise<void>
Initializes the events module by scanning all modules in the Registry
for methods decorated with @Hook
. Stores modules with hook methods for later dispatch.
async dispatch(type: IHookType, context?: Record<string, any>, fromPlugin?: string): Promise<void>
Dispatches the specified hook event to all modules that have methods decorated with the matching hook type.
- type: The hook type to dispatch (e.g.,
'onInit'
,'onShutdown'
). - context: Optional context object to pass to each hook method.
- fromPlugin: Optional plugin name for logging purposes.
How It Works
Initialization:
- On
init()
, iterates through all modules in theRegistry
. - Checks for methods with hook metadata and stores those modules.
- On
Dispatching:
- On
dispatch()
, iterates through stored modules. - For each module, retrieves methods decorated with
@Hook
. - Checks if the hook type matches the dispatched type.
- If so, invokes the method with the provided context.
- On
Notes
- Only methods decorated with the
@Hook
decorator and matching the dispatched type will be called. - The
Events
module should be initialized before dispatching events. - Useful for implementing application lifecycle hooks, plugin hooks, or custom event-driven logic.