import { AsArray } from '../../interface'; import { isFunc } from '../../utils'; import { IHookCallItem } from '../interface/i-hook-call-item'; /** * 串联钩子,按照注册顺序执行 * * @export * @class SyncSeriesHook * @template T 输入值类型 * @template C 上下文声明对象 */ export class SyncSeriesHook { /** * 已注册的钩子回调 * * @protected * @type {IHookCallItem[]} * @memberof SyncSeriesHook */ protected items: IHookCallItem[] = []; /** * 当前注册钩子个数 * * @author chitanda * @date 2021-04-30 14:04:43 * @readonly * @type {number} */ get size(): number { return this.items.length; } /** * 触发钩子,当某个钩子返回「null」时,中断后续执行。 * * @param {C} context * @param {...AsArray} args * @return {*} {C} * @memberof SyncSeriesHook */ callSync(context: C, ...args: AsArray): C { const _context: C = context || Object.create({}); let bol: any; for (let i = 0; i < this.items.length; i++) { const item = this.items[i]; if (item.fn) { bol = item.fn(_context, ...args); } if (bol === null) { console.warn( `因${ item.fn ? item.fn.name : null }方法返回值为「null」,钩子中断执行。`, item, ); break; } } return _context; } /** * 注册钩子 * * @param {((...args: AsArray) => void)} fn 回调 * @memberof SyncSeriesHook */ tap(fn: (context: C, ...args: AsArray) => void): void { if (fn && isFunc(fn)) { const opt: IHookCallItem = { mode: 'sync', }; opt.fn = fn as any; this.items.push(opt); } } /** * 删除钩子注册 * * @author chitanda * @date 2021-04-30 14:04:31 * @param {(context: C, ...args: AsArray) => void} callBack */ removeTap(callBack: (context: C, ...args: AsArray) => void): void { if (callBack) { for (let i = 0; i < this.items.length; i++) { const item = this.items[i]; if (callBack === item.fn) { this.items.splice(i, 1); } } } } /** * 释放已注册的钩子 * * @author chitanda * @date 2022-08-15 22:08:44 */ clear(): void { this.items = []; } }