oak-frontend-base/lib/types/Feature.js

85 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Feature = void 0;
const lodash_1 = require("oak-domain/lib/utils/lodash");
const mCallbacks = [];
let mActionStackDepth = 0;
class Feature {
callbacks;
constructor() {
this.callbacks = [];
}
subscribe(callback) {
this.callbacks.push(callback);
return () => {
(0, lodash_1.pull)(this.callbacks, callback);
};
}
publish(arg) {
this.callbacks.forEach(ele => ele(arg)
/* ele => {
try {
ele(arg);
}
catch(err) {
// publish不应当被任何render的流程堵塞
console.warn('publish catch err', err);
}
} */
);
}
clearSubscribes() {
this.callbacks = [];
}
}
exports.Feature = Feature;
;
/* export function subscribe(callback: () => any) {
mCallbacks.push(callback);
return () => {
pull(mCallbacks, callback);
};
}*/
/**
* 方法注解,使函数调用最后一层堆栈时唤起所有登记的回调
* @param target
* @param propertyName
* @param descriptor
*/
/* export function Action(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<any>) {
const method = descriptor.value!;
descriptor.value = async function (...params: any[]) {
mActionStackDepth++;
if (mActionStackDepth > 1000) {
console.error(`action[${method.name}]调用的层级超过了20请检查是否存在无限递归`);
}
let result;
try {
result = method.apply(this, params);
if (result instanceof Promise) {
await result;
}
else {
console.error(`方法${method.name}被定义为action但不是异步函数可能会引起对象解构和重渲染之间的不正确同步`);
}
}
catch (err) {
// console.error(err, method.name);
mActionStackDepth--;
throw err;
}
mActionStackDepth--;
if (mActionStackDepth === 0) {
const results = mCallbacks.map(
ele => ele()
).filter(
ele => ele instanceof Promise
);
if (results.length > 0) {
await Promise.all(results);
}
}
return result;
}
} */