zoukankan      html  css  js  c++  java
  • 10天掌握webpack 4.0 tapable (2) SyncBailHook

    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 的时候 说明 有返回值 执行结束 

  • 相关阅读:
    Python random模块下的常用函数小结
    MySQL 数据库连接
    LeetCode 376. 摆动序列 做题小结
    LeetCode 1005. K 次取反后最大化的数组和 做题小结
    LeetCode 455. 分发饼干 做题小结
    完美解决Python与anaconda之间的冲突问题
    LeetCode 122. 买卖股票的最佳时机 II 做题小结
    LeetCode 714. 买卖股票的最佳时机含手续费 做题小结
    如何去除有道云笔记广告(windows)
    baby web
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/12507624.html
Copyright © 2011-2022 走看看