11type ObserverCallback = ( ) => void
22
3- class MutationObserverService {
3+ export interface MutationObserverOptions {
4+ childList ?: boolean
5+ subtree ?: boolean
6+ attributes ?: boolean
7+ characterData ?: boolean
8+ debounceTime ?: number
9+ }
10+
11+ export class MutationObserverService {
412 private observer : MutationObserver | null = null
513 private callbacks : Set < ObserverCallback > = new Set ( )
614 private timeouts : Map < ObserverCallback , NodeJS . Timeout > = new Map ( )
715 private isProcessing = false
16+ private options : MutationObserverOptions
17+
18+ constructor (
19+ options : MutationObserverOptions = {
20+ childList : true ,
21+ subtree : true ,
22+ debounceTime : 200 ,
23+ }
24+ ) {
25+ this . options = options
26+ }
827
928 initialize ( ) {
1029 if ( this . observer ) return
@@ -22,18 +41,35 @@ class MutationObserverService {
2241 const timeout = setTimeout ( ( ) => {
2342 callback ( )
2443 this . isProcessing = false
25- } , 200 ) // Slightly increased debounce time
44+ } , this . options . debounceTime )
2645
2746 this . timeouts . set ( callback , timeout )
2847 } )
2948 } )
3049
3150 this . observer . observe ( document . body , {
32- childList : true ,
33- subtree : true ,
51+ childList : this . options . childList ,
52+ subtree : this . options . subtree ,
53+ attributes : this . options . attributes ,
54+ characterData : this . options . characterData ,
3455 } )
3556 }
3657
58+ /* service-level cleanup but we don't usually need this */
59+ cleanup ( ) {
60+ // 1. Disconnect the MutationObserver
61+ this . observer ?. disconnect ( )
62+ // 2. Clear the observer reference
63+ this . observer = null
64+ // 3. Clear all pending timeouts
65+ this . timeouts . forEach ( ( timeout ) => clearTimeout ( timeout ) )
66+ this . timeouts . clear ( )
67+ // 4. Clear all callbacks
68+ this . callbacks . clear ( )
69+ // 5. Reset processing flag
70+ this . isProcessing = false
71+ }
72+
3773 subscribe ( callback : ObserverCallback ) {
3874 this . callbacks . add ( callback )
3975 return ( ) => this . unsubscribe ( callback )
@@ -48,5 +84,3 @@ class MutationObserverService {
4884 }
4985 }
5086}
51-
52- export const mutationObserver = new MutationObserverService ( )
0 commit comments