support expression in event handler

This commit is contained in:
Geoff Doty 2025-03-29 11:46:43 -04:00
parent 8f30754bcc
commit 747f701d0c
1 changed files with 25 additions and 8 deletions

View File

@ -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]) {