CodingNic

Events & Keyboard Input

Centralize Calculator Actions

Events & Keyboard Input 25 min read

Centralize Calculator Actions

Task

Create one action handler that translates a calculator action into a method call.

Open

Open:

js/ui.js

Move the button behavior into a single function.

javascript
function handleAction(action, value) {
  switch (action) {
    case 'digit':
      calculator.inputDigit(value);
      break;

    case 'decimal':
      calculator.inputDecimal();
      break;

    case 'operation':
      calculator.chooseOperation(value);
      break;

    case 'equals':
      try {
        calculator.equals();
      } catch (error) {
        console.error(error);
      }
      break;

    case 'clear':
      calculator.clear();
      break;

    case 'backspace':
      calculator.backspace();
      break;

    case 'percentage':
      calculator.percentage();
      break;

    case 'sign':
      calculator.toggleSign();
      break;
  }

  updateDisplay();
}

Then keep the button event listener small:

javascript
buttons.forEach((button) => {
  button.addEventListener('click', () => {
    handleAction(button.dataset.action, button.dataset.value);
  });
});

Why this matters

The button listener now only reads the user’s action. The calculator class owns the application behavior.

That means keyboard input can call handleAction() later instead of duplicating every calculator method.

Test

Click several types of controls:

  • number
  • decimal
  • operator
  • equals
  • clear
  • backspace

The calculator should behave exactly as it did before.

Checkpoint

All calculator controls now pass through one action-handling function.