2020-02-01 18:15:58 +08:00
|
|
|
import utils from '../services/utils.js';
|
|
|
|
|
2020-01-16 04:36:01 +08:00
|
|
|
export default class Component {
|
|
|
|
/** @param {AppContext} appContext */
|
|
|
|
constructor(appContext) {
|
2020-02-01 18:15:58 +08:00
|
|
|
this.componentId = `comp-${this.constructor.name}-` + utils.randomString(10);
|
2020-01-16 04:36:01 +08:00
|
|
|
this.appContext = appContext;
|
|
|
|
/** @type Component[] */
|
|
|
|
this.children = [];
|
2020-01-19 01:01:16 +08:00
|
|
|
this.initialized = Promise.resolve();
|
2020-01-16 04:36:01 +08:00
|
|
|
}
|
|
|
|
|
2020-01-20 03:18:02 +08:00
|
|
|
async eventReceived(name, data, sync = false) {
|
2020-01-19 01:01:16 +08:00
|
|
|
await this.initialized;
|
|
|
|
|
2020-01-25 17:25:06 +08:00
|
|
|
// console.log(`Received ${name} to ${this.componentId}`);
|
2020-01-19 01:01:16 +08:00
|
|
|
|
2020-01-16 04:36:01 +08:00
|
|
|
const fun = this[name + 'Listener'];
|
|
|
|
|
2020-01-19 02:46:30 +08:00
|
|
|
let propagateToChildren = true;
|
|
|
|
|
2020-02-02 18:44:08 +08:00
|
|
|
const start = Date.now();
|
|
|
|
|
2020-01-16 04:36:01 +08:00
|
|
|
if (typeof fun === 'function') {
|
2020-01-19 02:46:30 +08:00
|
|
|
propagateToChildren = await fun.call(this, data) !== false;
|
2020-01-16 04:36:01 +08:00
|
|
|
}
|
|
|
|
|
2020-02-02 18:44:08 +08:00
|
|
|
const end = Date.now();
|
|
|
|
|
|
|
|
if (end - start > 10) {
|
|
|
|
console.log(`Event ${name} in component ${this.componentId} took ${end-start}ms`);
|
|
|
|
}
|
|
|
|
|
2020-01-19 02:46:30 +08:00
|
|
|
if (propagateToChildren) {
|
2020-01-25 03:15:53 +08:00
|
|
|
const promise = this.triggerChildren(name, data, sync);
|
2020-01-20 03:18:02 +08:00
|
|
|
|
2020-01-25 03:15:53 +08:00
|
|
|
if (sync) {
|
|
|
|
await promise;
|
2020-01-19 02:46:30 +08:00
|
|
|
}
|
2020-01-16 04:36:01 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-20 03:18:02 +08:00
|
|
|
trigger(name, data, sync = false) {
|
|
|
|
this.appContext.trigger(name, data, sync);
|
2020-01-16 04:36:01 +08:00
|
|
|
}
|
2020-01-25 03:15:53 +08:00
|
|
|
|
|
|
|
async triggerChildren(name, data, sync = false) {
|
|
|
|
for (const child of this.children) {
|
|
|
|
let promise = child.eventReceived(name, data, sync);
|
|
|
|
|
|
|
|
if (sync) {
|
|
|
|
await promise;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-01-16 04:36:01 +08:00
|
|
|
}
|