Logo of hookable

hookable

可等待的 Hook

可等待的钩子系统。

安装

使用 yarn

yarn add hookable

使用 npm

npm install hookable

用法

方法A:创建一个 hookable 实例

import { createHooks } from 'hookable'

// Create a hookable instance
const hooks = createHooks()

// Hook on 'hello'
hooks.hook('hello', () => { console.log('Hello World' )})

// Call 'hello' hook
hooks.callHook('hello')

方法B:从 Hookable 扩展您的基类

import { Hookable } from 'hookable'

export default class FooLib extends Hookable {
  constructor() {
    // Call to parent to initialize
    super()
    // Initialize Hookable with custom logger
    // super(consola)
  }

  async someFunction() {
    // Call and wait for `hook1` hooks (if any) sequential
    await this.callHook('hook1')
  }
}

在插件中,注册任何钩子

const lib = new FooLib()

// Register a handler for `hook2`
lib.hook('hook2', async () => { /* ... */ })

// Register multiply handlers at once
lib.addHooks({
  hook1: async () => { /* ... */ },
  hook2: [ /* can be also an array */ ]
})

取消注册钩子

const lib = new FooLib()

const hook0 = async () => { /* ... */ }
const hook1 = async () => { /* ... */ }
const hook2 = async () => { /* ... */ }

// The hook() method returns an "unregister" function
const unregisterHook0 = lib.hook('hook0', hook0)
const unregisterHooks1and2 = lib.addHooks({ hook1, hook2 })

/* ... */

unregisterHook0()
unregisterHooks1and2()

// or

lib.removeHooks({ hook0, hook1 })
lib.removeHook('hook2', hook2)

触发一次钩子处理函数

const lib = new FooLib()

const unregister = lib.hook('hook0', async () => {
  // Unregister as soon as the hook is executed
  unregister()

  /* ... */
})

Hookable 类

constructor()

hook (name, fn)

为特定钩子注册处理函数。 fn 必须是一个函数。

返回一个 unregister 函数,当调用时,它将移除已注册的处理函数。

hookOnce (name, fn)

类似于 hook,但会在调用一次后取消注册该钩子。

返回一个 unregister 函数,当调用时,它会在首次调用前移除已注册的处理函数。

addHooks(configHooks)

扁平化并注册钩子对象。

示例

hookable.addHooks({
  test: {
    before: () => {},
    after: () => {}
  }
})

这会批量注册 test:beforetest:after 钩子。

返回一个 unregister 函数,当调用时,它将移除所有已注册的处理函数。

async callHook (name, ...args)

供类本身使用,用于按顺序调用特定钩子的处理函数。

callHookWith (name, callerFn)

如果您需要自定义控制钩子的调用方式,您可以提供一个自定义函数,该函数将接收特定钩子的处理函数数组。

callerFn 是一个回调函数,接受两个参数:hooksargs

  • hooks:要调用的用户钩子数组
  • args:每次调用钩子时应传递的参数数组

deprecateHook (old, name)

废弃名为 old 的钩子,推荐使用 name 钩子。

deprecateHooks (deprecatedHooks)

废弃对象中的所有钩子(键为旧钩子,值为新钩子)。

removeHook (name, fn)

移除特定的钩子处理函数,前提是存在 fn 处理函数。

removeHooks (configHooks)

移除多个钩子处理函数。

示例

const handler = async () => { /* ... */ }

hookable.hook('test:before', handler)
hookable.addHooks({ test: { after: handler } })

// ...

hookable.removeHooks({
  test: {
    before: handler,
    after: handler
  }
})

removeAllHooks

移除所有钩子处理函数。

beforeEach (syncCallback)

注册一个(同步)回调,该回调会在每个钩子被调用前执行。

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 hook
await hookable.callHook('test')

afterEach (syncCallback)

注册一个(同步)回调,该回调会在每个钩子被调用后执行。

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 []
await hookable.callHook('test')

createDebugger

自动记录每个被调用的钩子及其运行时间。

const debug = hookable.createDebugger(hooks, { tag: 'something' })

hooks.callHook('some-hook', 'some-arg')
// [something] some-hook: 0.21ms

debug.close()

迁移

4.x5.x

  • 类型检查已改进。您可以使用 Hookable<T>createHooks<T>() 提供类型接口 (c2e1e22)
  • 我们不再提供兼容 IE11 的 UMD 构建版本。相反,您应该使用支持 ESM 的打包工具(例如 webpack 或 rollup)进行转译(如果需要)。
  • Logger 参数已被移除。对于废弃的钩子,我们默认使用 console.warn
  • 包现在使用命名导出。您应该导入 { Hookable } 而不是 Hookable,或者使用新的 createHooks 工具函数
  • mergeHooks 工具函数已独立导出。您应该将 Hookable.mergeHooksthis.mergeHooks 替换为新的 { mergeHooks } 导出。
  • 在 5.0.0 之前的版本中,当使用 callHook 时,如果其中一个钩子回调发生错误,我们会全局处理错误,并调用全局 error 钩子以及 console.error,然后解决 callHook 的 Promise!这有时会导致混淆行为,让我们误以为代码运行成功但实际上没有。v5 引入了一项重大更改:当钩子抛出错误时,callHook 也会拒绝(reject),而不是触发全局 error 事件。这意味着您现在在使用 callHook 时应该谨慎处理所有错误。

致谢

摘自 Nuxt 钩子系统,该系统最初由 Sébastien Chopin 引入。

感谢 Joe Paice 捐赠了 hookable 包名。

许可

MIT - 用💖制作