Skip to content

Commit 5e7f2bf

Browse files
committed
fix(listenForBind): memoize calls based on given node
This ensures only one listener is added per node.
1 parent df52b47 commit 5e7f2bf

1 file changed

Lines changed: 6 additions & 1 deletion

File tree

src/bind.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export function bind(controller: HTMLElement): void {
1414
listenForBind(controller.ownerDocument)
1515
}
1616

17+
const observers = new WeakMap<Node, Subscription>()
1718
/**
1819
* Set up observer that will make sure any actions that are dynamically
1920
* injected into `el` will be bound to it's controller.
@@ -22,6 +23,7 @@ export function bind(controller: HTMLElement): void {
2223
* stop further live updates.
2324
*/
2425
export function listenForBind(el: Node = document): Subscription {
26+
if (observers.has(el)) return observers.get(el)!
2527
let closed = false
2628
const observer = new MutationObserver(mutations => {
2729
for (const mutation of mutations) {
@@ -37,15 +39,18 @@ export function listenForBind(el: Node = document): Subscription {
3739
}
3840
})
3941
observer.observe(el, {childList: true, subtree: true, attributes: true, attributeFilter: ['data-action']})
40-
return {
42+
const subscription = {
4143
get closed() {
4244
return closed
4345
},
4446
unsubscribe() {
4547
closed = true
48+
observers.delete(el)
4649
observer.disconnect()
4750
}
4851
}
52+
observers.set(el, subscription)
53+
return subscription
4954
}
5055

5156
interface Subscription {

0 commit comments

Comments
 (0)