From b420684b3faf3af49a11f36fc2724955803e0740 Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Thu, 15 May 2025 15:49:12 +1000 Subject: [PATCH] Enhance list rendering: add error handling for placeholder's parent node and improve DOM item detachment --- src/main.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main.ts b/src/main.ts index 18ea74e..e0aab45 100644 --- a/src/main.ts +++ b/src/main.ts @@ -418,6 +418,19 @@ export default (options: ComponentOptions) => { return } + const parentNode = placeholder.parentNode + if (!parentNode) { + console.error("Placeholder's parentNode is null. Cannot update list.") + return + } + + // Detach all currently rendered DOM items managed by this instance. + renderedItems.forEach(item => { + if (item.element.parentNode === parentNode) { + parentNode.removeChild(item.element); + } + }); + // Get key attribute if available const keyAttr = template.getAttribute('%key') if (!keyAttr) console.warn(`%key attribute not found in the template, which is not a recommended practice.`) @@ -690,7 +703,10 @@ export default (options: ComponentOptions) => { // Recursively process this item and its children this._processElementWithItemContext(itemElement, nestedItemContext) - // Add the element to the DOM + // TODO: detect list items existed inside the view, use replace instead of remove and re-add, + // to improve performance + + // Insert the item element into the DOM placeholder.parentNode?.insertBefore(itemElement, placeholder.nextSibling) }) }