92 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-02-01 11:15:58 +01:00
import utils from '../services/utils.js';
import Mutex from "../services/mutex.js";
2020-02-01 11:15:58 +01:00
2020-01-15 21:36:01 +01:00
export default class Component {
2020-02-27 00:58:10 +01:00
constructor() {
2020-02-02 18:46:50 +01:00
this.componentId = `comp-${this.constructor.name}-` + utils.randomString(6);
2020-01-15 21:36:01 +01:00
/** @type Component[] */
this.children = [];
2020-01-18 18:01:16 +01:00
this.initialized = Promise.resolve();
this.mutex = new Mutex();
2020-01-15 21:36:01 +01:00
}
2020-02-27 00:58:10 +01:00
setParent(parent) {
/** @type Component */
this.parent = parent;
2020-02-27 10:03:14 +01:00
return this;
}
child(component) {
component.setParent(this);
this.children.push(component);
return this;
2020-02-27 00:58:10 +01:00
}
2020-02-16 19:21:17 +01:00
async handleEvent(name, data) {
2020-01-18 18:01:16 +01:00
await this.initialized;
const fun = this[name + 'Event'];
2020-01-15 21:36:01 +01:00
2020-02-02 11:44:08 +01:00
const start = Date.now();
2020-02-15 10:41:21 +01:00
await this.callMethod(fun, data);
2020-01-15 21:36:01 +01:00
2020-02-02 11:44:08 +01:00
const end = Date.now();
if (end - start > 10 && glob.PROFILING_LOG) {
2020-02-02 11:44:08 +01:00
console.log(`Event ${name} in component ${this.componentId} took ${end-start}ms`);
}
2020-02-16 19:21:17 +01:00
await this.handleEventInChildren(name, data);
2020-01-15 21:36:01 +01:00
}
2020-02-16 19:21:17 +01:00
async triggerEvent(name, data) {
await this.parent.triggerEvent(name, data);
2020-01-15 21:36:01 +01:00
}
2020-01-24 20:15:53 +01:00
2020-02-16 19:21:17 +01:00
async handleEventInChildren(name, data) {
const promises = [];
2020-01-24 20:15:53 +01:00
for (const child of this.children) {
2020-02-16 19:21:17 +01:00
promises.push(child.handleEvent(name, data));
}
2020-01-24 20:15:53 +01:00
2020-02-12 20:31:31 +01:00
await Promise.all(promises);
2020-01-24 20:15:53 +01:00
}
2020-02-15 09:43:47 +01:00
2020-02-16 11:22:37 +01:00
async triggerCommand(name, data = {}) {
const called = await this.handleCommand(name, data);
2020-02-15 10:41:21 +01:00
if (!called) {
await this.parent.triggerCommand(name, data);
}
}
async handleCommand(name, data) {
const fun = this[name + 'Command'];
return await this.callMethod(fun, data);
}
2020-02-15 10:41:21 +01:00
async callMethod(fun, data) {
if (typeof fun !== 'function') {
return false;
}
let release;
2020-02-15 09:43:47 +01:00
2020-02-15 10:41:21 +01:00
try {
release = await this.mutex.acquire();
await fun.call(this, data);
return true;
} finally {
if (release) {
release();
}
}
2020-02-15 09:43:47 +01:00
}
2020-01-15 21:36:01 +01:00
}