javascript / expert
Snippet
WeakMap-Backed Vue Custom Directive for Decoupled Event Streams
Using a WeakMap to pair DOM elements with internal handler closures inside Vue Custom Directives guarantees memory-safe event binding lifecycle control without polluting DOM element properties.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const directiveStates = new WeakMap();export const vEventStream = {mounted(el, binding) {const handler = (event) => {if (binding.value && typeof binding.value === 'function') {binding.value(event);}};directiveStates.set(el, handler);el.addEventListener(binding.arg || 'click', handler);},unmounted(el, binding) {const handler = directiveStates.get(el);if (handler) {el.removeEventListener(binding.arg || 'click', handler);directiveStates.delete(el);}}};
vue
Breakdown
1
const directiveStates = new WeakMap();
Stores state references keyed by DOM node instances without preventing garbage collection.
2
directiveStates.set(el, handler);
Associates the specific event listener closure with the target DOM element.
3
el.removeEventListener(binding.arg || 'click', handler);
Cleanly detaches listener reference upon unmounting to eliminate potential memory leaks.