UNPKG

minsky-kit

Version:
118 lines (92 loc) 3.4 kB
/* eslint no-console: "off" */ // imports import Config from '../Config'; import Logger from './Logger'; // private static properties const plugins = {}; const instances = {}; // Class definition export default class Core { // constructor constructor (args = {}, objectName = 'Core') { // set private properties this._objectName = objectName; this._debug = args.debug || false; this.autoInit = (typeof args.autoInit === 'boolean') ? args.autoInit : true; // default true // auto init if (this.autoInit) this.initialize(args); // check if log key is present in Config, if not => add for quick log/toggle in console if (!Config.logger.activate[this._objectName]) Config.logger.activate[this._objectName] = false; // add itself to instances object if (!instances[this._objectName]) instances[this._objectName] = []; instances[this._objectName].push(this); // add to window object when in debug mode if (this._debug) { window.debug = window.debug || {}; let key = this.objectName; if (window.debug[key]) { let index = 1; while (window.debug[key + index] !== undefined) { index++; } key += index; } window.debug[key] = this; if (!this._debugMentioned) { this.log(`Debug mode is enabled, instances of this class are accessible in window.debug.${key}`); this._debugMentioned = true; } } this.log('constructed'); } // methods initialize () { this.log('initialized'); } log (...values) { if (!Config.logger.activate[this._objectName] && !this._debug && values[0] !== 'error' && (Config.globals.mode !== 'production' && values[0] !== 'warn')) return; Logger.set(this._objectName, (console[values[0]]) ? values.shift() : 'log'); Logger.log(...values); } destroy () { // remove itself from the instances collection const index = instances[this._objectName].indexOf(this); if (index > -1) instances[this._objectName].splice(index, 1); // run plugins if (this.plugins) { this.plugins.run('destroy'); // destroy instances this.plugins.destroy(); } this.log('destroyed'); } // getters & setters get objectName () { return this._objectName; } // statics static get plugins () { return plugins; } static get instances () { return getInstances(); } } // util methods export function provideDefault (obj, dValues) { if (typeof obj === 'object' && typeof dValues === 'object') { for (const key of Object.keys(dValues)) { if (obj[key] === undefined) { obj[key] = dValues[key]; } else if (typeof obj[key] === 'object' && typeof dValues[key] === 'object') { provideDefault(obj[key], dValues[key]); } } } } export function getInstances () { // clone it so the global array can not be messed up const result = {}; for (const key of Object.keys(instances)) { result[key] = [...instances[key]]; } return result; } window.getInstances = getInstances;