What memory management benefit does this implementation provide?
const registry = new WeakMap();
class EventEmitter {
constructor() {
registry.set(this, new Set());
}
addEventListener(listener) {
registry.get(this).add(listener);
}
removeEventListener(listener) {
registry.get(this).delete(listener);
}
emit(event) {
registry.get(this).forEach(listener => listener(event));
}
}
This implementation provides automatic cleanup: 1) When an EventEmitter instance becomes eligible for garbage collection, its listener registry is automatically cleaned up, 2) No explicit cleanup code is needed when destroying emitter instances, 3) This prevents memory leaks that could occur if listener references were stored differently, 4) The WeakMap ensures that the Set of listeners doesn't keep the emitter alive, 5) This is particularly valuable in systems with dynamic creation and destruction of emitters, 6) The pattern combines the benefits of WeakMap with traditional event handling, 7) It demonstrates how WeakMap can improve memory management in event systems, 8) This approach scales well with many emitter instances.