28、tapable(4)——SyncWaterfallHook

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');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值