Skip to content

Commit

Permalink
fix: used variables by dynamically added dom are being removed during…
Browse files Browse the repository at this point in the history
… disposal of nodes
  • Loading branch information
jorenrui committed Feb 9, 2024
1 parent ad24fea commit e8943dc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
14 changes: 11 additions & 3 deletions lib/entity.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,13 +439,19 @@ export default class Entity {

dispose() {
const elements = [this.element, ...this.element.querySelectorAll('*')]
const variables = []

// Remove event bindings
for (const element of elements) {
if (element.nodeType !== 1) continue

const entity = MiniJS.elements.find(
(entity) => entity.element === element
)
entity?.removeEventBindings()
if (!entity) continue

variables.push(...entity.variables)
entity.removeEventBindings()
}

// Remove disposed elements
Expand All @@ -459,11 +465,13 @@ export default class Entity {
[]
)

const unusedVariables = MiniJS.variables.filter(
const unusedVariables = variables.filter(
(variable) => !usedVariables.includes(variable)
)

MiniJS.variables = [...usedVariables]
MiniJS.variables = MiniJS.variables.filter(
(variable) => !unusedVariables.includes(variable)
)

unusedVariables.forEach((variable) => {
if (variable.startsWith('el.')) {
Expand Down
15 changes: 7 additions & 8 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,18 +120,17 @@ const MiniJS = (() => {
observeDOM(document.body, (mutation) => {
mutation.forEach((record) => {
record.removedNodes.forEach((node) => {
if (node.nodeType !== 1) return
const entity = _elements.find((entity) => entity.element === node)
entity?.dispose()
})

if (record.addedNodes.length) {
record.addedNodes.forEach((node) => {
if (node.nodeType !== 1) return
const entity = new Entity(node)
entity.init()
entity.initChildren()
})
}
record.addedNodes.forEach((node) => {
if (node.nodeType !== 1) return
const entity = new Entity(node)
entity.init()
entity.initChildren()
})
})
})
}
Expand Down

0 comments on commit e8943dc

Please sign in to comment.