Event Bubbling

The Event Bubbling strategy implements a bubbling event pattern, where events propagate upward through the middleware tree from child to parent nodes.

Implementation

private async bubbleEvent(event: MiddlewareEvent, node: TreeNode): Promise<void> {
    await node.node.handleEvent(event); // Current node processes event
    if (!event.handled && node.parent) {
        await this.bubbleEvent(event, node.parent); // Propagate upwards
    }
}

Key Features

  • Automatic Propagation: Events flow automatically from child to parent
  • Late Interception: Parent nodes handle events after children
  • Propagation Control: Stop event flow by marking as handled
  • Async Support: Full support for asynchronous event handlers

Usage Example

const router = new TreeBubbleRoutingStrategy();
const parent = new CoreElement();
const child = new CoreElement();

parent.addChild(child);

// Event will bubble from child to parent
child.on("message", async (ctx, next) => {
    console.log("Child handling message first");
    ctx.state.processed = true;
    await next();
});

parent.on("message", async (ctx, next) => {
    if (ctx.state.processed) {
        console.log("Parent received processed message");
    }
    await next();
});

// Route an event using bubble strategy
await router.routeEvent(new MiddlewareEvent("message"), child);

Best Practices

  1. Use for Notifications

    • Perfect for notifying parents of child state changes
    • Aggregate responses from multiple children
    • Handle completion events
  2. State Management

    • Use context.state to pass data upward
    • Transform data at each level if needed
    • Clear state when processing completes
  3. Error Handling

    • Catch and handle errors at appropriate levels
    • Allow parent nodes to recover from child errors
    • Maintain error context during propagation

XAML Integration

<TreeGeometry xmlns="http://schemas.codeium.com/middleware/2023">
    <MQTTConnector Name="MQTTConnector" Path=":mqtt" 
                   onMessageComplete="handleMessageComplete">
        <JWTAuthorizationComponent Name="JWTAuthorization" 
                                  Path=":jwt" 
                                  onAuthComplete="handleAuthComplete">
            <TerminalComponent Name="Terminal" 
                             Path=":terminal" 
                             onCommand="handleCommand" />
        </JWTAuthorizationComponent>
    </MQTTConnector>
</TreeGeometry>

In this example, command events from the Terminal component will bubble up through the tree, allowing parent components to react to completed operations.