SyncWaterfallHook
SyncWaterfallHook,同步瀑布钩子,上一个监听函数的返回值会传递给下一个监听函数
SyncWaterfallHook的使用
let {SyncWaterfallHook} = require('tapable');//SyncWaterfallHook,同步瀑布钩子,上一个监听函数的返回值会传递给下一个监听函数
class Lesson{
constructor(){
this.hooks = {
arch: new SyncWaterfallHook(['name'])
}
}
tap(){
this.hooks.arch.tap('node',function(name){
console.log('node',name)
return 'node学的还不错'
})
this.hooks.arch.tap('react',function(data){
console.log('react',data)
})
}
start(){
this.hooks.arch.call('yuhua');
}
}
let l = new Lesson();
l.tap();
l.start();
SyncWaterfallHook原理实现
class SyncWaterfallHook {//钩子是同步的
constructor(args){//args => ['name']
this.tasks = [];
}
call(...args){
let [first,...others] = this.tasks;
let ret = first(...args);
others.reduce((a,b) => {
return b(a);
},ret)
}
tap(name,task){
this.tasks.push(task);
}
}
let hook = new SyncWaterfallHook(['name']);
hook.tap('react',function(name){
console.log('react',name)
return 'react ok'
})
hook.tap('node',function(data){
console.log('node',data)
return 'node ok'
})
hook.tap('webpack',function(data){
console.log('node',data)
})
hook.call('yuhua');