ts-lib-extended
Version:
Additional types and tools for typescript
50 lines (49 loc) • 1.14 kB
JavaScript
/**
* Subscribable listener to certain events
*
* @export
* @class Event
* @template TSender
* @template {EventArgs | void} [TArgs=void]
* @since 1.0.0
*/
export class Event {
constructor(subscribe_, unsubscribe_, detachEventProxy_) {
this._subscription = {
subscribe: subscribe_,
unsubscribe: unsubscribe_
};
detachEventProxy_(() => this.detach());
}
/**
* subrcribe to event
*
* @readonly
* @type {EventSubscription<TSender, TArgs>}
* @memberof Event
* @since 1.0.0
*/
get subscribe() {
return this.validateDetached(this._subscription?.subscribe);
}
/**
* unsubrcribe from event
*
* @readonly
* @type {EventUnsubscription}
* @memberof Event
* @since 1.0.0
*/
get unsubscribe() {
return this.validateDetached(this._subscription?.unsubscribe);
}
validateDetached(value_) {
if (value_ === undefined) {
throw new Error('Event is detached!');
}
return value_;
}
detach() {
this._subscription = undefined;
}
}