ts-lib-extended
Version:
Additional types and tools for typescript
70 lines (69 loc) • 1.86 kB
JavaScript
import { Disposable } from './disposable/index.js';
/**
* extend from this core class to get quick scope support
*
* @export
* @abstract
* @class ScopedInstanceCore
* @template {InstanceScope} S
* @extends {Disposable}
* @implements {ScopedInstance<S>}
* @since 4.0.0
*/
export class ScopedInstanceCore extends Disposable {
constructor() {
super();
this._source = new Map();
this._disposers.push(() => {
this._source.forEach((scope_) => this.disposeScope(scope_));
this._source.clear();
});
}
scope(id_) {
this.validateDisposed(this);
let scope = this._source.get(id_);
if (!scope) {
scope = this.createScope(id_);
this._source.set(id_, scope);
}
return scope;
}
get scopes() {
this.validateDisposed(this);
return [...this._source.values()];
}
}
/**
* use this as scope base to access core features
*
* @export
* @abstract
* @class InstanceScopeCore
* @template T
* @template {string} Variant instance variants (e.g. 'dark' | 'light')
* @extends {Disposable}
* @implements {InstanceScopeVariants<T>}
* @since 4.0.0
*/
export class InstanceScopeCore extends Disposable {
constructor(scopeId) {
super();
this.scopeId = scopeId;
this._source = new Map();
this._disposers.push(() => {
this._source.forEach((variante_) => this.disposeInstance(variante_));
this._source.clear();
});
}
get variants() {
return [...this._source.values()];
}
getOrCreateInstance(variant_) {
let instance = this._source.get(variant_);
if (!instance) {
instance = this.createInstance(variant_);
this._source.set(variant_, instance);
}
return instance;
}
}