From 747f701d0c70050f46ae4827c9dfe6abb42a8ec4 Mon Sep 17 00:00:00 2001 From: Geoff Doty Date: Sat, 29 Mar 2025 11:46:43 -0400 Subject: [PATCH] support expression in event handler --- src/Mite.js | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/Mite.js b/src/Mite.js index cda4b41..9501780 100644 --- a/src/Mite.js +++ b/src/Mite.js @@ -92,15 +92,32 @@ export class Mite { } } else if (node.nodeType === Node.ELEMENT_NODE) { for (const attr of node.attributes) { - const matches = attr.value.match(/{(\w+)}/g); - if (matches) { - if (attr.name.startsWith("@")) { - const eventName = attr.name.slice(1); - const methodName = attr.value.slice(1, -1); - if (this.methods[methodName]) { - node.addEventListener(eventName, this.methods[methodName]); + if (attr.name.startsWith("@")) { + const eventName = attr.name.slice(1); + const expression = attr.value.match(/^{(.+)}$/); // Extract content inside {} + if (expression) { + const exprContent = expression[1].trim(); + + // Check method or expression + if (this.methods[exprContent]) { + // Existing behavior: bind a method from this.methods + node.addEventListener(eventName, this.methods[exprContent]); + } else { + // evaluate the expression dynamically + try { + const handler = new Function( + "event", + `with (this.data) { ${exprContent}; }` + ).bind(this); + node.addEventListener(eventName, handler); + } catch (e) { + console.error(`Invalid expression in ${attr.name}: ${exprContent}`, e); + } } - } else { + } + } else { + const matches = attr.value.match(/{(\w+)}/g); + if (matches) { matches.forEach(token => { const key = token.slice(1, -1); if (this.data[key]) {