3.0.0 • Published 6 years ago
@drupe/hooks v3.0.0
@drupe/hooks
Simple async hooks.
Installation
npm i @drupe/hooks
Usage
Each hook holds a set of handler functions that are subscribed to the hook. Handler functions may return a promise to wait for them to finish.
Hook type | Usage |
---|---|
ParallelHook | The parallel hook calls all handler functions at once and waits for them to finish. |
SeriesHook | The series hook calls each handler function and waits for it to finish before calling the next handler function. |
new Hook()
Create a new hook instance of the specific hook type.
const {ParallelHook} = require('@drupe/hooks')
const hook = new ParallelHook()
hook.add(handler)
Add a handler function to the hook. Adding the same handler function twice has no effect.
const handler = hook.add(async message => {
console.log(message)
})
- handler
<function>
- The handler function to add. - returns
<function>
- The same handler function.
hook.delete(handler)
Delete a handler function if it exists.
hook.delete(handler)
- handler
<any>
- A handler function to delete.
hook.call(...args)
Call all handler functions according to the hook type.
await hook.call('Hello World!')
- args
<...any>
- The arguments passed to each handler function. - returns
<Promise>
hook.callLazy(getArgs)
Call all handler functions according to the hook type.
await hook.callLazy(() => {
return ['Hello World!']
})
- getArgs
<function>
- A function to get the arguments. Of no handler function exists, this function is not called. - returns
<Promise>
Implementing a hook
You can also implement a custom hook.
const {Hook} = require('@drupe/hooks')
class MyHook extends Hook {
async _call(handlers, args) {
// TODO: Call all handlers.
}
}
- handlers
<Set>
- The set of all handler functions. - args
<array>
- The array of arguments.