The manager of sequential hooks to work with tapable
.
progress-hooks
applies the taps(plugins) only if the previous hook has been called.
Usually, it used to replace the code slice this.hooks = {}
of the tapable
example
$ npm i progress-hooks
const {
SyncHook,
AsyncParallelHook
} = require('tapable')
const {
Hooks,
ADD,
CLEAN,
COUNT
} = require('progress-hooks')
class Car {
constructor () {
// this.hooks = {
// accelerate: new SyncHook(['newSpeed']),
// brake: new SyncHook()
// }
// Instead of the code above, we create hooks by `new Hooks()`
this.hooks = new Hooks({
accelerate: new SyncHook(['newSpeed']),
brake: {
hook: new SyncHook(),
// The car needs to brake twice, then stop
plan: 2
},
stop: new SyncHook()
})
}
}
const car = new Car()
let speed = 0
// The `LoggerPlugin` method is not actually tapped into the `car.hooks.brake`,
// but instead, it is held by `progress-hooks`
car.hooks.brake.tap('LoggerPlugin', () => {
if (speed === 0) {
throw new Error('can not brake')
}
console.log('brake')
})
car.hooks.stop.tap('StopEnginePlugin', () => {
console.log('stopped')
})
// And it will not be called
car.hooks.brake.call()
car.hooks.accelerate.tap('SetterPlugin', newSpeed => {
speed = newSpeed
})
car.hook.accelerate.call(120)
// And after `car.hook.accelerate.call()` is invoked,
// The `LoggerPlugin` will be applied
car.hooks.brake.call()
// prints: 'brake'
car.hooks.stop.call()
// nothing `console.log`ged, because of `plan: 2`
car.hooks.brake.call()
car.hooks.stop.call()
// prints: stopped
- rawHooks
{[string]: tapable.Hook | PlannedHook}
- options?
Object
- disableAfterCalled?
boolean=true
Iftrue
(the default value) the hook will be disabled after called.
- disableAfterCalled?
interface PlannedHook {
hook: tapable.Hook
// If plan is `2`, then the next hook will not be activated
// until the current hook has been called twice
plan: number
}
Returns hooks
The returned hooks
is a relatively clean object that we can get all hook names just with Object.keys(hooks)
:
Object.keys(car.hooks)
// ['accelerate', 'brake']
Adds a new hook.
const hooks = new Hooks()
hooks[ADD]('accelerate', new SyncHook(['newSpeed']))
Cleans hook taps if the hook is not enabled, so that we could reload plugins.
MIT