Blog>
Snippets

Dynamic Action Handling with Reflection

Use JavaScript's reflection capabilities to handle actions dynamically, including unknown actions, to decouple the action handling logic from specific action types.
class ActionHandler {
  constructor() {
    this.actions = {};
  }

  registerAction(actionName, handler) {
    this.actions[actionName] = handler;
  }

  handleAction(actionName, ...args) {
    const action = this.actions[actionName];
    if (action) {
      return action(...args);
    } else {
      console.warn(`Action '${actionName}' is not recognized.`);
      // Handle unknown actions or provide a default behavior here
    }
  }
}
Defines a class 'ActionHandler' with methods to register actions and dynamically handle them using the provided action name. When an action is called, it executes the corresponding handler if it exists, otherwise warns that the action is unknown.
// Instantiate ActionHandler
const actionHandler = new ActionHandler();
Creates an instance of the ActionHandler class.
// Example of registering a new action
actionHandler.registerAction('sayHello', (name) => `Hello, ${name}!`);
Registers a new action 'sayHello' to the action handler.
// Dynamic action handling
const result = actionHandler.handleAction('sayHello', 'John');
console.log(result);
Dynamically handles the action 'sayHello' with the argument 'John'. Logs the result of the action handler to the console.
// Attempt to handle an unknown action
actionHandler.handleAction('unknownAction');
Tries to handle an action that has not been registered, triggering the default behavior for unknown actions.