From 99d259704470b2251ea031d8af02ac1557c3f83a Mon Sep 17 00:00:00 2001
From: Joeylene <23741509+jorenrui@users.noreply.github.com>
Date: Fri, 9 Feb 2024 14:58:35 +0800
Subject: [PATCH] feat: detect and apply changes to dynamic attributes
---
demo/observer.html | 13 ++++++++++++-
lib/entity.js | 12 ++++++++++++
lib/generators/observer.js | 6 +++++-
lib/main.js | 10 ++++++++++
4 files changed, 39 insertions(+), 2 deletions(-)
diff --git a/demo/observer.html b/demo/observer.html
index fa8a43f..69254ae 100644
--- a/demo/observer.html
+++ b/demo/observer.html
@@ -20,6 +20,12 @@
>
list item (click to delete)
+
+
diff --git a/lib/entity.js b/lib/entity.js
index 93a2a83..aaa8b6b 100644
--- a/lib/entity.js
+++ b/lib/entity.js
@@ -265,6 +265,18 @@ export default class Entity {
}
}
+ async evaluateAttribute(attribute) {
+ if (attribute === ':class') this.evaluateClass()
+ else if (attribute === ':text') this.evaluateText()
+ else if ([':value', ':checked'].includes(attribute)) this.evaluateValue()
+ else if (attribute === ':each') this.evaluateEach()
+ else {
+ if (!this.dynamicAttributes.includes(attribute))
+ this.dynamicAttributes.push(attribute)
+ this.evaluateDynamicAttributes()
+ }
+ }
+
async evaluateAll() {
await this.evaluateValue()
await this.evaluateClass()
diff --git a/lib/generators/observer.js b/lib/generators/observer.js
index d936815..495dae0 100644
--- a/lib/generators/observer.js
+++ b/lib/generators/observer.js
@@ -9,7 +9,11 @@ export function observeDOM(obj, callback) {
const mutationObserver = new MutationObserver(callback)
// have the observer observe for changes in children
- mutationObserver.observe(obj, { childList: true, subtree: true })
+ mutationObserver.observe(obj, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ })
return mutationObserver
// browser support fallback
diff --git a/lib/main.js b/lib/main.js
index 4494e21..0b8ee72 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -108,6 +108,16 @@ const MiniJS = (() => {
function _listenToDOMChanges() {
observeDOM(document.body, (mutation) => {
mutation.forEach((record) => {
+ if (
+ record.type === 'attributes' &&
+ record.attributeName.startsWith(':')
+ ) {
+ const entity = _elements.find(
+ (entity) => entity.element === record.target
+ )
+ entity?.evaluateAttribute(record.attributeName)
+ }
+
record.removedNodes.forEach((node) => {
if (node.nodeType !== 1) return
const entity = _elements.find((entity) => entity.element === node)