tapable介绍 - SyncBailHook
SyncBailHook
为勾子加了个保险,当return
返回不是undefine
就会停止
2.use.js
let {SyncBailHook} = require('tapable') // 解构同步勾子
class Lesson {
constructor () {
this.hooks = {
// 订阅勾子
arch: new SyncBailHook(['name']),
}
}
start () {
// 发布
this.hooks.arch.call('may')
}
tap () { // 注册监听函数,订阅
this.hooks.arch.tap('node', function (name) {
console.log('node', name)
return '停止学习' // 会停止
// return undefined
})
this.hooks.arch.tap('react', function (name) {
console.log('react', name)
})
}
}
let l = new Lesson()
l.tap(); //注册两个函数
l.start() // 启动勾子
2.theory.js
class SyncBailHook { // 勾子是同步的
constructor(args) { // args => ['name']
this.tasks = []
}
tap (name, task) {
this.tasks.push(task)
}
call (...args) {
let ret; // 当前函数的返回值
let index = 0; // 当前要执行的第一个
do {
ret = this.tasks[index](...args)
} while (ret === undefined && index < this.tasks.length)
}
}
let hook = new SyncBailHook(['name'])
hook.tap('react', function (name) {
console.log('react', name);
return '停止学习'
// return undefined
})
hook.tap('node', function (name) {
console.log('node', name);
})
hook.call('jw')