@ray-core/runtime
Version:
Ray 是一个全新的基于 React 的小程序开发框架
100 lines (99 loc) • 3.48 kB
JavaScript
;
/**
* 组件实例绑定的回调函数缓存
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.setPrototypeTo = exports.gStore = exports.getGlobalStore = exports.initGlobalStore = void 0;
var g = process.env.GLOBAL_GLOBAL;
var ctxId = process.env.GLOBAL_CTX_NAME;
var initGlobalStore = function (name, initCb) {
var k = "__".concat(name).concat(ctxId === undefined ? '' : ctxId, "__");
if (!(k in g)) {
g[k] = initCb();
}
return g[k];
};
exports.initGlobalStore = initGlobalStore;
var getGlobalStore = function (name) {
var k = "__".concat(name).concat(ctxId, "__");
if (!(k in g)) {
throw new Error("Please init ".concat(name, " use initGlobalStore('").concat(name, "')"));
}
return g[k];
};
exports.getGlobalStore = getGlobalStore;
var GCaches = (0, exports.initGlobalStore)('GCaches', function () {
/**
* 类 `Caches`实例会挂在组件实例的原型链末端
*/
var Caches = /** @class */ (function () {
function Caches() {
this._ctxId = ctxId;
}
return Caches;
}());
return Caches;
});
var gCaches = (0, exports.initGlobalStore)('g_caches_inst', function () { return new GCaches(); });
var Store = /** @class */ (function () {
function Store() {
this.cbIds = [];
this.vNodes = new Map();
}
Store.prototype.setCallback = function (key, fn) {
gCaches[key] = fn;
if (!this.cbIds.includes(key)) {
this.cbIds.push(key);
}
};
Store.prototype.getCallback = function (key) {
var _a;
return (_a = gCaches[key]) === null || _a === void 0 ? void 0 : _a.__original;
};
Store.prototype.unsetCallback = function (key) {
if (key) {
if (typeof key === 'string') {
key = [key];
}
key.forEach(function (k) { return delete gCaches[k]; });
return;
}
this.cbIds.forEach(function (k) { return delete gCaches[k]; });
};
Store.prototype.setVNode = function (id, node) {
this.vNodes.set(id, node);
};
Store.prototype.getVNode = function (id) {
return this.vNodes.get(id);
};
Store.prototype.unsetVNode = function (id) {
this.vNodes.delete(id);
};
return Store;
}());
exports.gStore = (0, exports.initGlobalStore)('g_store_inst', function () { return new Store(); });
var setPrototypeTo = function setPrototypeTo(target) {
// 微信小程序 页面、组件的构造函数相同,所以其实例(inst)拥有相同的原型链
// 微信小程序 input 事件处理函数仅能在 inst 或 inst.__proto__ 上查询到。其它事件处理函数可以在原型链上的任意节点上查询到
// 所以将回调函数存储对象设置为其实例的直接原型,即 inst.__proto__
// input 事件直接绑在相应实例上,其他事件绑在原型链上
if ('__store' in target) {
return;
}
target.__store = true;
var p = Object.getPrototypeOf(target);
var o = target;
while (p) {
// 微信小程序 原型链顶端对象是共享的,注册只需要注入一次
if (p.constructor === GCaches) {
return;
}
if (p === Object.prototype) {
break;
}
o = p;
p = Object.getPrototypeOf(p);
}
Object.setPrototypeOf(o, gCaches);
};
exports.setPrototypeTo = setPrototypeTo;