From cbb0c9c1d78b5b46ec7ea3930ede7971d5beffdc Mon Sep 17 00:00:00 2001 From: Pieter Vander Vennet Date: Fri, 5 May 2023 00:58:26 +0200 Subject: [PATCH] Core: add 'onDestroy'-callback to mappedStore to unregister --- Logic/UIEventSource.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Logic/UIEventSource.ts b/Logic/UIEventSource.ts index 6aa823055c..e0aa166229 100644 --- a/Logic/UIEventSource.ts +++ b/Logic/UIEventSource.ts @@ -407,7 +407,8 @@ class MappedStore extends Store { f: (t: TIn) => T, extraStores: Store[], upstreamListenerHandler: ListenerTracker | undefined, - initialState: T + initialState: T, + onDestroy?: (f: () => void) => void ) { super() this._upstream = upstream @@ -417,6 +418,9 @@ class MappedStore extends Store { this._upstreamPingCount = upstreamListenerHandler?.pingCount this._extraStores = extraStores this.registerCallbacksToUpstream() + if(onDestroy !== undefined){ + onDestroy(() => this.unregisterFromUpstream()) + } } private _data: T @@ -677,6 +681,7 @@ export class UIEventSource extends Store implements Writable { * Given a function 'f', will construct a new UIEventSource where the contents will always be "f(this.data)' * @param f: The transforming function * @param extraSources: also trigger the update if one of these sources change + * @param onDestroy: a callback that can trigger the destroy function * * const src = new UIEventSource(10) * const store = src.map(i => i * 2) @@ -695,8 +700,8 @@ export class UIEventSource extends Store implements Writable { * srcSeen // => 21 * lastSeen // => 42 */ - public map(f: (t: T) => J, extraSources: Store[] = []): Store { - return new MappedStore(this, f, extraSources, this._callbacks, f(this.data)) + public map(f: (t: T) => J, extraSources: Store[] = [], onDestroy?: (f : () => void ) => void): Store { + return new MappedStore(this, f, extraSources, this._callbacks, f(this.data), onDestroy) } /** * Monoidal map which results in a read-only store. 'undefined' is passed 'as is'