# 二.SyncBailHook
前言
同步执行全部直到有返回值,队列顺序
- BailHook 中回调函数也是顺序执行的
- 调用 call 时传入的参数也可以传给回调函数
- 当回调函数返回非 undefined 值的时候会停止调用后续的回调
# 1.使用方式
let { SyncBailHook } = require("tapable")
class Lesson {
constructor() {
this.hooks = {
arch: new SyncBailHook(["name"]),
}
}
tap() {
//注册监听函数
this.hooks.arch.tap("node", function (name) {
console.log("node", name)
return "stop"
})
this.hooks.arch.tap("react", function (name) {
console.log("react", name)
})
}
statr() {
this.hooks.arch.call("123")
}
}
let l = new Lesson()
l.tap() //注册这两个事件
l.statr() //启动钩子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
运行得到:
node 123
1
# 2.原理实现
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("node", function (name) {
5
console.log("node", name)
return "stop"
})
hook.tap("react", function (name) {
console.log("react", name)
})
hook.call("123")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27