SyncHook
这是同步钩子,能够同步执行注册的监听函数
SyncHook使用
let {SyncHook} = require('tapable');
class Lesson {
constructor(){
this.hooks = {
arch: new SyncHook(['name'])
}
}
tap(){//注册监听函数
this.hooks.arch.tap('node',function(name){
console.log('node',name)
})
this.hooks.arch.tap('react',function(name){
console.log('react',name)
})
}
start(){
this.hooks.arch.call('yuhua');
}
}
let l = new Lesson();
l.tap();//注册两个监听函数(时间)
l.start();//启动钩子
SyncHook原理实现
class SyncHook {//钩子是同步的
constructor(args){//args => ['name']
this.tasks = [];
}
call(...args){
this.tasks.forEach((task) => task(...args))
}
tap(name,task){
this.tasks.push(task);
}
}
let hook = new SyncHook(['name']);
hook.tap('react',function(name){
console.log('react',name)
})
hook.tap('node',function(name){
console.log('node',name)
})
hook.call('yuhua');