tapPromise 函数 (绑定hooks方法)tapable 库,创建自定义插件的库

tapPromise 函数 (绑定hooks方法)tapable 库,创建自定义插件的库

刚看到了一个插件的use函数

// 引入组件
  use(plugin: IPluginClass, options?: IPluginOption) {
    if (this._checkPlugin(plugin) && this.canvas) {
      this._saveCustomAttr(plugin);
      const pluginRunTime = new plugin(this.canvas, this, options || {}) as IPluginClass;
      // 添加插件名称
      pluginRunTime.pluginName = plugin.pluginName;
      this.pluginMap[plugin.pluginName] = pluginRunTime;
      this._bindingHooks(pluginRunTime);
      this._bindingHotkeys(pluginRunTime);
      this._bindingApis(pluginRunTime);
    }
  }

然后就看了下绑定hooks的函数 this._bindingHooks(pluginRunTime);

// 绑定hooks方法
  private _bindingHooks(plugin: IPluginTempl) {
    this.hooks.forEach((hookName) => {
      const hook = plugin[hookName];
      if (hook) {
        this.hooksEntity[hookName].tapPromise(plugin.pluginName + hookName, function () {
          // eslint-disable-next-line prefer-rest-params
          const result = hook.apply(plugin, [...arguments]);
          // hook 兼容非 Promise 返回值
          return result instanceof Promise ? result : Promise.resolve(result);
        });
      }
    });
  }

这里面有个 tapPromise 函数,我整站搜了一下,没有这个函数的定义。所以就看下 hooksEntity 是什么type吧

public hooksEntity: {
    [propName: string]: AsyncSeriesHook<any, any>;
  } = {};

这个type用的这个AsyncSeriesHook

看下定义

export class AsyncSeriesHook<T, AdditionalOptions = UnsetAdditionalOptions> extends AsyncHook<T, void, AdditionalOptions> {}

这个定义是在 tapable.d.ts 文件里面定义的。
用的肯定就是 tapable 这个库,上npm库上找一下

npm库地址:https://www.npmjs.com/package/tapable
github地址:https://github.com/webpack/tapable

库的函数说明:
For sync hooks, tap is the only valid method to add a plugin. Async hooks also support async plugins:

myCar.hooks.calculateRoutes.tapPromise("GoogleMapsPlugin", (source, target, routesList) => {
	// return a promise
	return google.maps.findRoute(source, target).then(route => {
		routesList.add(route);
	});
});
myCar.hooks.calculateRoutes.tapAsync("BingMapsPlugin", (source, target, routesList, callback) => {
	bing.findRoute(source, target, (err, route) => {
		if(err) return callback(err);
		routesList.add(route);
		// call the callback
		callback();
	});
});

// You can still use sync plugins
myCar.hooks.calculateRoutes.tap("CachedRoutesPlugin", (source, target, routesList) => {
	const cachedRoute = cache.get(source, target);
	if(cachedRoute)
		routesList.add(cachedRoute);
})

tapPromise - tapable 代码追踪完毕~

reference:
https://github.com/nihaojob/vue-fabric-editor
npm库地址:https://www.npmjs.com/package/tapable
github地址:https://github.com/webpack/tapable
最后推个 events
https://www.npmjs.com/package/events

posted @ 2024-06-06 10:57  彭成刚  阅读(15)  评论(0编辑  收藏  举报