← Back to scenarios
ScenarioCatalog DB

UI mediator

Coordinate form-control enabling, validation, and updates through a UI mediator.

Problem

A form must coordinate interactions among controls without embedding direct dependencies between every field, validator, action, and display component.

Related patterns

Implementations

Mediator

TypeScriptApplication

Mediator in TypeScript

Coordinates form fields through a mediator so individual controls do not need direct knowledge of one another.

TypeScript
interface FormMediator {
  notify(sender: FormField, event: "changed"): void;
}

abstract class FormField {
  constructor(protected readonly mediator: FormMediator) {}

  abstract changed(): void;
}

class CountryField extends FormField {
  private value = "";

  setValue(value: string) {
    this.value = value;
    this.changed();
  }

  changed() {
    this.mediator.notify(this, "changed");
  }

  getValue() {
    return this.value;
  }
}

class StateField extends FormField {
  private enabled = false;

  setEnabled(enabled: boolean) {
    this.enabled = enabled;
    console.log(`State field enabled: ${enabled}`);
  }

  changed() {
    this.mediator.notify(this, "changed");
  }
}

class CheckoutFormMediator implements FormMediator {
  country!: CountryField;
  state!: StateField;

  notify(sender: FormField, event: "changed") {
    if (sender === this.country && event === "changed") {
      this.state.setEnabled(this.country.getValue() === "US");
    }
  }
}

const mediator = new CheckoutFormMediator();
mediator.country = new CountryField(mediator);
mediator.state = new StateField(mediator);

mediator.country.setValue("US");
mediator.country.setValue("DE");

Associated technologies