SyncLoopHook
SyncLoopHook,同步遇到某个不返回undefined的监听函数,就重复执行
SyncLoopHook的使用
let {SyncLoopHook} = require('tapable');//SyncLoopHook,同步遇到某个不返回undefined的监听函数,就重复执行
class Lesson{
constructor(){
this.index = 0;
this.hooks = {
arch: new SyncLoopHook(['name'])
}
}
tap(){
this.hooks.arch.tap('node',(name) => {
console.log('node',name)
return ++this.index === 3? undefined : '继续学';
})
this.hooks.arch.tap('react',(data) => {
console.log('react',data)
})
}
start(){
this.hooks.arch.call('yuhua');
}
}
let l = new Lesson();
l.tap();
l.start();
SyncLoopHook原理实现
class SyncLoopHook {//钩子是同步的
constructor(args){//args => ['name']
this.tasks = [];
}
call(...args){
this.tasks.forEach((task) => {
let ret;
do{
ret = task(...args);
}while(ret !== undefined);
})
}
tap(name,task){
this.tasks.push(task);
}
}
let hook = new SyncLoopHook(['name']);
let total = 0;
hook.tap('react',function(name){
console.log('react',name)
return ++total === 3? undefined :'继续学';
})
hook.tap('node',function(name){
console.log('node',name)
})
hook.tap('webpack',function(name){
console.log('node',name)
})
hook.call('yuhua');