Route communication between components through one hub, instead of wiring every component directly to every other.
A form where each field needs to enable/disable other fields based on its own value — if every field directly references every other field it might affect, the field count and the reference count both grow together, and reasoning about the whole form means reading every field.
Each component notifies the mediator when something happens to it, instead of notifying other components directly. The mediator holds the logic for how components affect each other and calls their public methods in response.
`CountryField` and `ShippingField` never talk to each other directly — the mediator decides that selecting an unsupported country disables shipping.
class FormMediator {
register(name, field) { (this.fields ??= {})[name] = field; field.mediator = this; }
notify(sender, event) {
if (sender === "country" && event === "changed") {
const supported = this.fields.country.value !== "antarctica";
this.fields.shipping.setEnabled(supported);
}
}
}
class Field {
constructor(name) { this.name = name; this.enabled = true; }
setValue(value) { this.value = value; this.mediator.notify(this.name, "changed"); }
setEnabled(enabled) {
this.enabled = enabled;
console.log(`${this.name}: ${enabled ? "enabled" : "disabled"}`);
}
}
const mediator = new FormMediator();
const country = new Field("country");
const shipping = new Field("shipping");
mediator.register("country", country);
mediator.register("shipping", shipping);
country.setValue("antarctica"); // shipping: disabled
country.setValue("canada"); // shipping: enabled