首页 > Web开发 > 详细

10天掌握webpack 4.0 tapable (2) SyncBailHook

时间:2020-03-16 23:26:39      阅读:74      评论:0      收藏:0      [点我收藏+]
  1. BailHook中的回调函数也是顺序执行的
  2. 调用call时传入的参数也可以传给回调函数
  3. 当回调函数返回非undefined值的时候会停止调用后续的回调

 

使用:

const {
  SyncBailHook
} = require("tapable");
//所有的钩子构造函数, 都接受一个可选的参数, (这个参数最好是数组, 不是tapable内部也把他变成数组), 这是一个参数的字符串名字列表
//const hook = new SyncHook(["arg1", "arg2", "arg3"]);
class lession {
  constructor() {
    //最好的实践就是把所有的钩子暴露在一个类的hooks属性里面:
    this.hooks = {
      arch: new SyncBailHook(["name"]),
    }
  }
  // 注册监听函数
  tap() {
    this.hooks.arch.tap(‘node‘, function (name) {
      console.log(‘node‘, name)
      return ‘想停止学习node‘
    })
    this.hooks.arch.tap(‘vue‘, function (name) {
      console.log(‘vue‘, name)
    })
    this.hooks.arch.tap(‘react‘, function (name) {
      console.log(‘react‘, name)
    })
  }
  start() {
    this.hooks.arch.call(‘jw‘);
  }
}
let ls = new lession();
//注册
ls.tap()
//启动
ls.start()

  原理:

class SyncHook {
  constructor(args) {
    this.tasks = []
  }
  tap(name, task) {
    this.tasks.push(task)
  }
  call(...args) {
    // this.tasks.forEach((task) => {
    //   task(...args)
    // })
    let ret;
    let index = 0;
    do {
      ret = this.tasks[index++](...args)
    } while (ret == undefined && index < this.tasks.length);
  }
}
let hook = new SyncHook([name]);
hook.tap(react, function (name) {
  console.log(react, name)
  return 停止执行
})
hook.tap(vue, function (name) {
  console.log(vue, name)
})
hook.tap(node, function (name) {
  console.log(node, name)
})
hook.call(jw)

我们在call 函数里面做 一个 dewhile 循环 

当 返回值为 underfind  并且数组的长度大于 index  让 函数循环执行 

当返回值 不为underfind 的时候 说明 有返回值 执行结束 

 

10天掌握webpack 4.0 tapable (2) SyncBailHook

原文:https://www.cnblogs.com/guangzhou11/p/12507624.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!