@sanpjs/runtime
Version:
San Pro Runtime
108 lines • 3.78 kB
JavaScript
"use strict";
/**
* @file San Pro 基础组件类 BaseComponent 的定义
* 支持:
* 1. 全局组件;
* 2. provide/inject 跨组件传递数据
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseComponent = exports.registerComponent = void 0;
const san_1 = require("san");
const globalComponents = {};
const registerComponent = function (components) {
Object.assign(globalComponents, components);
};
exports.registerComponent = registerComponent;
class BaseComponent extends san_1.Component {
provide;
inject;
__activeWatcher;
__watchers;
detached;
static components = globalComponents;
constructor(options) {
// @ts-ignore
super(options);
this.__addCreatedHook();
}
__addCreatedHook() {
const created = this.created;
this.created = created
? () => {
this.__createdProvider();
created.call(this);
}
: () => {
this.__createdProvider();
};
const detached = this.detached;
this.detached = detached
? () => {
this.__removeProvider();
detached.call(this);
}
: () => {
this.__removeProvider();
};
}
__createdProvider() {
if (this.provide) {
this.provide.forEach(key => {
this.watch(key, val => {
// 触发子组件的更新
this.__watchers &&
this.__watchers.forEach(comp => {
// 避免循环调用
if (this.__activeWatcher === comp) {
this.__activeWatcher = undefined;
return;
}
comp.data.set(key, val);
});
});
});
}
if (this.inject) {
this.inject.forEach(item => {
let { key, reactive = false } = typeof item === 'string' ? { key: item } : item;
// 获取父级组件的更新
let comp = this;
while ((comp = comp.parentComponent)) {
if (comp.provide && comp.provide.indexOf(key) > -1) {
// 初始化数据
this.data.set(key, comp.data.get(key));
// 监听数据的变化
comp.__watchers = comp.__watchers || [];
comp.__watchers.push(this);
// 组件的响应式更新
if (reactive) {
let ancestor = comp;
this.watch(key, val => {
ancestor.data.set(key, val);
ancestor.__activeWatcher = this;
});
}
break;
}
}
});
}
}
__removeProvider() {
if (this.inject) {
this.inject.forEach(item => {
let { key } = typeof item === 'string' ? { key: item } : item;
// 获取父级组件的更新
let comp = this;
while ((comp = comp.parentComponent)) {
if (comp.provide && comp.provide.indexOf(key) > -1 && comp.__watchers) {
comp.__watchers.splice(comp.__watchers.indexOf(this), 1);
break;
}
}
});
}
}
}
exports.BaseComponent = BaseComponent;
//# sourceMappingURL=Component.js.map