support expression in event handler
This commit is contained in:
parent
8f30754bcc
commit
747f701d0c
33
src/Mite.js
33
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]) {
|
||||
|
|
Loading…
Reference in New Issue