Enhance arrow function handler: improve syntax validation and parameter formatting for better error handling
This commit is contained in:
parent
e9ddbcdf47
commit
ae48c89291
20
src/main.ts
20
src/main.ts
|
@ -292,9 +292,18 @@ export default (options: ComponentOptions) => {
|
||||||
element.addEventListener(eventName, (event: Event) => {
|
element.addEventListener(eventName, (event: Event) => {
|
||||||
try {
|
try {
|
||||||
// Arrow function parsing
|
// Arrow function parsing
|
||||||
const arrowIndex = handlerValue.indexOf('=>')
|
const splitted = handlerValue.split('=>')
|
||||||
const paramsStr = handlerValue.substring(0, arrowIndex).trim()
|
if (splitted.length !== 2) {
|
||||||
let bodyStr = handlerValue.substring(arrowIndex + 2).trim()
|
throw new Error(`Invalid arrow function syntax: ${handlerValue}`)
|
||||||
|
}
|
||||||
|
const paramsStr = (() => {
|
||||||
|
if (splitted[0].includes('(')) {
|
||||||
|
return splitted[0].trim()
|
||||||
|
} else {
|
||||||
|
return `(${splitted[0].trim()})`
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
const bodyStr = splitted[1].trim()
|
||||||
|
|
||||||
// Check if the function body is wrapped in {}
|
// Check if the function body is wrapped in {}
|
||||||
const isMultiline = bodyStr.startsWith('{') && bodyStr.endsWith('}')
|
const isMultiline = bodyStr.startsWith('{') && bodyStr.endsWith('}')
|
||||||
|
@ -302,11 +311,12 @@ export default (options: ComponentOptions) => {
|
||||||
// If it is a multiline function body, remove the outer braces
|
// If it is a multiline function body, remove the outer braces
|
||||||
if (isMultiline) {
|
if (isMultiline) {
|
||||||
// Remove the outer braces
|
// Remove the outer braces
|
||||||
|
let bodyStr = handlerValue.split('=>')[1].trim()
|
||||||
bodyStr = bodyStr.substring(1, bodyStr.length - 1)
|
bodyStr = bodyStr.substring(1, bodyStr.length - 1)
|
||||||
|
|
||||||
// Build code for multiline arrow function
|
// Build code for multiline arrow function
|
||||||
const functionCode = `
|
const functionCode = `
|
||||||
return function(${paramsStr}) {
|
return function${paramsStr} {
|
||||||
${bodyStr}
|
${bodyStr}
|
||||||
}
|
}
|
||||||
`
|
`
|
||||||
|
@ -320,7 +330,7 @@ export default (options: ComponentOptions) => {
|
||||||
} else {
|
} else {
|
||||||
// Single line arrow function, directly return expression result
|
// Single line arrow function, directly return expression result
|
||||||
const functionCode = `
|
const functionCode = `
|
||||||
return function(${paramsStr}) {
|
return function${paramsStr} {
|
||||||
return ${bodyStr}
|
return ${bodyStr}
|
||||||
}
|
}
|
||||||
`
|
`
|
||||||
|
|
Loading…
Reference in New Issue
Block a user