Awaitable hooks system.
npx nypm i hookableMethod A: Create a hookable instance:
import{Hookable}from"hookable";// Create a hookable instanceconsthooks=newHookable();// Hook on 'hello'hooks.hook("hello",()=>{console.log("Hello World");});// Call 'hello' hookhooks.callHook("hello");Tip
You can use HookableCore alternatively for less bundle and runtime footprint if simple hook/callHook functionality is only needed.
Method B: Extend your base class from Hookable:
import{Hookable}from"hookable";exportdefaultclassFooLibextendsHookable{constructor(){// Call to parent to initializesuper();// Initialize Hookable with custom logger// super(consola)}asyncsomeFunction(){// Call and wait for `hook1` hooks (if any) sequentialawaitthis.callHook("hook1");}}Inside plugins, register for any hook:
constlib=newFooLib();// Register a handler for `hook2`lib.hook("hook2",async()=>{/* ... */});// Register multiply handlers at oncelib.addHooks({hook1: async()=>{/* ... */},hook2: [/* can be also an array */],});Unregistering hooks:
constlib=newFooLib();consthook0=async()=>{/* ... */};consthook1=async()=>{/* ... */};consthook2=async()=>{/* ... */};// The hook() method returns an "unregister" functionconstunregisterHook0=lib.hook("hook0",hook0);constunregisterHooks1and2=lib.addHooks({ hook1, hook2 });/* ... */unregisterHook0();unregisterHooks1and2();// orlib.removeHooks({ hook0, hook1 });lib.removeHook("hook2",hook2);Triggering a hook handler once:
constlib=newFooLib();constunregister=lib.hook("hook0",async()=>{// Unregister as soon as the hook is executedunregister();/* ... */});Register a handler for a specific hook. fn must be a function.
Returns an unregister function that, when called, will remove the registered handler.
Similar to hook but unregisters hook once called.
Returns an unregister function that, when called, will remove the registered handler before first call.
Flatten and register hooks object.
Example:
hookable.addHooks({test: {before: ()=>{},after: ()=>{},},});This registers test:before and test:after hooks at bulk.
Returns an unregister function that, when called, will remove all the registered handlers.
Used by class itself to sequentially call handlers of a specific hook.
If you need custom control over how hooks are called, you can provide a custom function that will receive an array of handlers of a specific hook.
callerFn if a callback function that accepts 3 arguments, hooks, args and name:
hooks: Array of user hooks to be calledargs: Array of arguments that should be passed each time calling a hookname: Name of the hook
Deprecate hook called old in favor of name hook.
Deprecate all hooks from an object (keys are old and values or newer ones).
Remove a particular hook handler, if the fn handler is present.
Remove multiple hook handlers.
Example:
consthandler=async()=>{/* ... */};hookable.hook("test:before",handler);hookable.addHooks({test: {after: handler}});// ...hookable.removeHooks({test: {before: handler,after: handler,},});Remove all hook handlers.
Registers a (sync) callback to be called before each hook is being called.
hookable.beforeEach((event)=>{console.log(`${event.name} hook is being called with ${event.args}`);});hookable.hook("test",()=>{console.log("running test hook");});// test hook is being called with []// running test hookawaithookable.callHook("test");Registers a (sync) callback to be called after each hook is being called.
hookable.afterEach((event)=>{console.log(`${event.name} hook called with ${event.args}`);});hookable.hook("test",()=>{console.log("running test hook");});// running test hook// test hook called with []awaithookable.callHook("test");Automatically logs each hook that is called and how long it takes to run.
constdebug=hookable.createDebugger(hooks,{tag: "something"});hooks.callHook("some-hook","some-arg");// [something] some-hook: 0.21msdebug.close();- Type checking improved. You can use
Hookable<T>orcreateHooks<T>()to provide types interface (c2e1e22) - We no longer provide an IE11 compatible umd build. Instead, you should use an ESM-aware bundler such as webpack or rollup to transpile if needed.
- Logger param is dropped. We use
console.warnby default for deprecated hooks. - Package now uses named exports. You should import
{ Hookable }instead ofHookableor use newcreateHooksutil mergeHooksutil is exported standalone. You should replaceHookable.mergeHooksandthis.mergeHookswith new{ mergeHooks }export- In versions < 5.0.0 when using
callHookif an error happened by one of the hook callbacks, we was handling errors globally and call globalerrorhook +console.errorinstead and resolvecallHookpromise! This sometimes makes confusing behavior when we think code worked but it didn't. v5 introduced a breaking change that when a hook throws an error,callHookalso rejects instead of a globalerrorevent. This means you should be careful to handle all errors when usingcallHooknow.
Extracted from Nuxt hooks system originally introduced by Sébastien Chopin
Thanks to Joe Paice for donating hookable package name.
MIT - Made with 💖