Skip to content

Commit e8943dc

Browse files
committed
fix: used variables by dynamically added dom are being removed during disposal of nodes
1 parent ad24fea commit e8943dc

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

lib/entity.js

+11-3
Original file line numberDiff line numberDiff line change
@@ -439,13 +439,19 @@ export default class Entity {
439439

440440
dispose() {
441441
const elements = [this.element, ...this.element.querySelectorAll('*')]
442+
const variables = []
442443

443444
// Remove event bindings
444445
for (const element of elements) {
446+
if (element.nodeType !== 1) continue
447+
445448
const entity = MiniJS.elements.find(
446449
(entity) => entity.element === element
447450
)
448-
entity?.removeEventBindings()
451+
if (!entity) continue
452+
453+
variables.push(...entity.variables)
454+
entity.removeEventBindings()
449455
}
450456

451457
// Remove disposed elements
@@ -459,11 +465,13 @@ export default class Entity {
459465
[]
460466
)
461467

462-
const unusedVariables = MiniJS.variables.filter(
468+
const unusedVariables = variables.filter(
463469
(variable) => !usedVariables.includes(variable)
464470
)
465471

466-
MiniJS.variables = [...usedVariables]
472+
MiniJS.variables = MiniJS.variables.filter(
473+
(variable) => !unusedVariables.includes(variable)
474+
)
467475

468476
unusedVariables.forEach((variable) => {
469477
if (variable.startsWith('el.')) {

lib/main.js

+7-8
Original file line numberDiff line numberDiff line change
@@ -120,18 +120,17 @@ const MiniJS = (() => {
120120
observeDOM(document.body, (mutation) => {
121121
mutation.forEach((record) => {
122122
record.removedNodes.forEach((node) => {
123+
if (node.nodeType !== 1) return
123124
const entity = _elements.find((entity) => entity.element === node)
124125
entity?.dispose()
125126
})
126127

127-
if (record.addedNodes.length) {
128-
record.addedNodes.forEach((node) => {
129-
if (node.nodeType !== 1) return
130-
const entity = new Entity(node)
131-
entity.init()
132-
entity.initChildren()
133-
})
134-
}
128+
record.addedNodes.forEach((node) => {
129+
if (node.nodeType !== 1) return
130+
const entity = new Entity(node)
131+
entity.init()
132+
entity.initChildren()
133+
})
135134
})
136135
})
137136
}

0 commit comments

Comments
 (0)