* Creates an arrow function to be used as handler function for event bindings. The handler * function has a single parameter `$event` and the bound event's handler `AST` represented as a * TypeScript expression as its body. * * When `eventType` is set to `Infer`, the `$event` parameter will not
( event: BoundEvent, tcb: Context, scope: Scope, eventType: EventParamType | string, assertionExpression?: TcbExpr, )
| 284 | * bindings. Alternatively, an explicit type can be passed for the `$event` parameter. |
| 285 | */ |
| 286 | function tcbCreateEventHandler( |
| 287 | event: BoundEvent, |
| 288 | tcb: Context, |
| 289 | scope: Scope, |
| 290 | eventType: EventParamType | string, |
| 291 | assertionExpression?: TcbExpr, |
| 292 | ): TcbExpr { |
| 293 | const handler = tcbEventHandlerExpression(event.handler, tcb, scope); |
| 294 | const statements: TcbExpr[] = []; |
| 295 | |
| 296 | if (assertionExpression !== undefined) { |
| 297 | statements.push(assertionExpression); |
| 298 | } |
| 299 | |
| 300 | statements.push(handler); |
| 301 | |
| 302 | let eventParamType: string | undefined; |
| 303 | if (eventType === EventParamType.Infer) { |
| 304 | eventParamType = undefined; |
| 305 | } else if (eventType === EventParamType.Any) { |
| 306 | eventParamType = 'any'; |
| 307 | } else { |
| 308 | eventParamType = eventType; |
| 309 | } |
| 310 | |
| 311 | // Obtain all guards that have been applied to the scope and its parents, as they have to be |
| 312 | // repeated within the handler function for their narrowing to be in effect within the handler. |
| 313 | const guards = scope.guards(); |
| 314 | let body = `{\n${getStatementsBlock(statements)} }`; |
| 315 | |
| 316 | if (guards !== null) { |
| 317 | // Wrap the body in an `if` statement containing all guards that have to be applied. |
| 318 | body = `{ if (${guards.print()}) ${body} }`; |
| 319 | } |
| 320 | |
| 321 | const eventParam = new TcbExpr( |
| 322 | `${EVENT_PARAMETER}${eventParamType === undefined ? '' : ': ' + eventParamType}`, |
| 323 | ); |
| 324 | eventParam.addExpressionIdentifier(ExpressionIdentifier.EVENT_PARAMETER); |
| 325 | |
| 326 | // Return an arrow function instead of a function expression to preserve the `this` context. |
| 327 | return new TcbExpr(`(${eventParam.print()}): any => ${body}`); |
| 328 | } |
no test coverage detected