@@ -24,7 +24,7 @@ class Config {
2424 * A Set to store callback functions that subscribe to changes in this config's value.
2525 * @private
2626 */
27- #subscribers = new Set ( ) ;
27+ #subscribers = { } ;
2828
2929 /**
3030 * The strategy to use when merging new values into this config.
@@ -80,8 +80,13 @@ class Config {
8080 * @param {any } oldValue - The old value of the config.
8181 */
8282 notify ( newValue , oldValue ) {
83- for ( const callback of this . #subscribers) {
84- callback ( newValue , oldValue )
83+ for ( const id in this . #subscribers) {
84+ if ( this . #subscribers. hasOwnProperty ( id ) ) {
85+ const subscriberSet = this . #subscribers[ id ] ;
86+ for ( const callback of subscriberSet ) {
87+ callback ( newValue , oldValue ) ;
88+ }
89+ }
8590 }
8691 }
8792
@@ -123,12 +128,31 @@ class Config {
123128 /**
124129 * Subscribes a callback function to changes in this config's value.
125130 * The callback will be invoked with `(newValue, oldValue)` whenever the config changes.
126- * @param {Function } callback - The function to call when the config value changes.
131+ * @param {Object } options - An object containing the subscription details.
132+ * @param {String } options.id - A unique ID for the subscription, useful for debugging.
133+ * @param {Function } options.fn - The callback function.
127134 * @returns {Function } A cleanup function to unsubscribe the callback.
128135 */
129- subscribe ( callback ) {
130- this . #subscribers. add ( callback ) ;
131- return ( ) => this . #subscribers. delete ( callback )
136+ subscribe ( { id, fn} ) {
137+ if ( typeof id !== 'string' || id . length === 0 || typeof fn !== 'function' ) {
138+ throw new Error ( 'Config.subscribe: options must be an object with a non-empty string `id` and a function `fn`.' ) ;
139+ }
140+
141+ if ( ! this . #subscribers[ id ] ) {
142+ this . #subscribers[ id ] = new Set ( ) ;
143+ }
144+
145+ this . #subscribers[ id ] . add ( fn ) ;
146+
147+ return ( ) => {
148+ const subscriberSet = this . #subscribers[ id ] ;
149+ if ( subscriberSet ) {
150+ subscriberSet . delete ( fn ) ;
151+ if ( subscriberSet . size === 0 ) {
152+ delete this . #subscribers[ id ] ;
153+ }
154+ }
155+ } ;
132156 }
133157}
134158
0 commit comments