3.0.0 • Published 6 years ago

@drupe/hooks v3.0.0

Weekly downloads
3
License
MIT
Repository
gitlab
Last release
6 years ago

@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 typeUsage
ParallelHookThe parallel hook calls all handler functions at once and waits for them to finish.
SeriesHookThe 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.
3.0.0

6 years ago

1.2.0

6 years ago

1.1.0

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago