Pattern 20/22 · Behavioral
Mediator
Pull all the communication logic between a group of objects into exactly one place, so the objects only talk to that place and never to each other.
01 — It starts with code that is breaking
Problem
A shop's checkout form has seven fields: country, province, shipping method, delivery date, voucher, gift wrap, address note. On day one everything is fine: when CountrySelect changes, ProvinceSelect changes its list. You write a handler in CountrySelect.vue: call the API for provinces, then assign them straight into the other component via a ref. One arrow, three lines of code. Cheap.
Then vouchers arrive. SHIP20 takes 20k off, only for in-province orders, and once a voucher is applied the delivery date must be pushed back at least 2 days. You open VoucherInput.vue, add a ref to ShippingMethod.vue to disable the "standard" option, add a ref to DeliveryDate.vue to change min. Two weeks later: if the customer manually re-enables "standard", the voucher must cancel itself — so ShippingMethod.vue has to import VoucherInput.vue. The circle closes.
Count the arrows: n components talking directly to each other form n(n-1)/2 pairs. Seven fields is 21 arrows; an eighth field makes 28; ten fields is 45. Nobody can keep 45 arrows in their head, and every arrow is ownerless — it squats in the file of whichever component fires it. The immediate consequence: circular imports leave one side with undefined at runtime, and the bundler only warns instead of stopping you.
Testing and reuse die first. To test VoucherInput on its own, you have to mount three other components or mock three refs — 60 lines of fixtures for a 4-line rule. Want to move CountrySelect to the address form? It drags along ProvinceSelect and ShippingZone, even though that form has no shipping. And bugs like "the voucher doesn't reset when the province changes" live on in production for a long time, because the rule is spread across three files, none of which is wrong — only their combination is.
The root problem isn't "this component is badly written". The root problem: the coordination logic between components lives scattered inside the components themselves, and each component has to know the identity of the others. So cost grows with the number of pairs, not the number of fields — and new features are always measured in fields.
02 — The idea, before touching code
Solution
Mediator: put all the communication logic into a single object. The components (called colleagues) stop looking at each other. They only report "my field changed" to the mediator, and read whatever has been derived from the mediator. n components → n arrows, all pointing at one spot.
The mediator holds the whole group's state and derives the rest: which provinces are currently valid, which methods are allowed, the earliest delivery date, which fields are required. Components shrink into "chips": show one field, emit one event. Adding a field = adding state + adding a rule in the mediator; no existing component gets edited.
Good news: in Vue you already have this thing. A domain Pinia store, or a domain composable like useCheckout(), is a mediator — shared state, derived getters, actions that change state, and components only ever go one way into it. The pattern doesn't make you add a library or a class; it makes you put the coordination logic in exactly one named place and keep the arrows one-way: component → mediator, never component → component.
03 — Doing it for real, one code fragment per step
Step by step
List the arrows before writing any component
Before creating the first .vue file, write down who needs to know whom. One rule per line: "country changes → province resets", "voucher changes → method gets locked", "province changes → zone changes → method gets locked". Don't code yet, count.
Seven rule lines means seven lines of mediator logic — acceptable. If you count 20 lines and they depend on each other in a cycle (A → B → C → A), you don't need a pattern, you need to run, because a mediator can't save a contradictory rule set either.
country changes -> province reset + reload options
province changes -> recompute zone (inner-city / outer-city)
zone changes -> method: outer-city disables "express"
voucher changes -> method: disable "standard"; deliveryDate.min = +2 days
method changes -> cancel voucher if the voucher relies on "standard"
deliveryDate -> show the "earliest delivery is ..." line
tickets > 10 -> company becomes required
=> 7 rules, 7 fields. Arrows if components call each other: 7*6/2 = 21.Write the "bad smell" version to see the cross-component refs
This is the code everyone writes the first time, and it looks perfectly valid. Look at exactly where it rots: this component holds refs to other components and calls their methods.
<script setup lang="ts">
// CountrySelect knows the names, the APIs, even the internal methods of 2 other components
const provinceRef = ref<InstanceType<typeof ProvinceSelect>>()
const zoneRef = ref<InstanceType<typeof ShippingZone>>()
async function onCountryChange(code: string) {
const list = await $fetch('/api/provinces?country=' + code)
provinceRef.value?.setOptions(list) // arrow 1
provinceRef.value?.clear() // arrow 2
zoneRef.value?.recalc(code, provinceRef.value?.value) // arrow 3
}
</script>
<template>
<select :value="country" @change="onCountryChange( ($event.target as HTMLSelectElement).value )">
<option v-for="c in countries" :key="c">{{ c }}</option>
</select>
<ProvinceSelect ref="provinceRef" />
<ShippingZone ref="zoneRef" />
</template>VoucherInput imports this file, this file imports ShippingZone, ShippingZone imports VoucherInput — circular.Declare the mediator: shared state lives in one store
The mediator is a domain Pinia store (or a composable using module-level reactive). It holds the whole group's state and a set() function — the only way to change that state.
Notice it imports no components and doesn't know ProvinceSelect exists. Dependencies go one way only: component → store.
import { defineStore } from 'pinia'
import { derive } from '~/utils/checkout-rules'
export const useCheckoutStore = defineStore('checkout', () => {
const fields = ref({
country: 'VN',
province: '',
method: 'standard' as 'standard' | 'express',
voucher: '',
tickets: 1,
company: '',
})
/** Every change goes through here: the mediator is the only place that knows the reset rules. */
function set<K extends keyof Fields>(key: K, value: Fields[K]) {
fields.value[key] = value
if (key === 'country') fields.value.province = ''
if (key === 'province' && !derive(fields.value).methods.includes(fields.value.method))
fields.value.method = 'standard'
if (key === 'method' && fields.value.voucher === 'SHIP20' && value !== 'express')
fields.value.voucher = ''
}
return { fields, derived: computed(() => derive(fields.value)), set }
})if left.Shrink components into "chips": read your field, call set()
Now a component only knows one field. It imports nobody, holds no refs, and doesn't know vouchers exist. The whole spirit of the pattern is in this step: components get dumb on purpose.
<script setup lang="ts">
const form = useCheckoutStore()
const read = (e: Event) => (e.target as HTMLSelectElement).value
</script>
<template>
<select :value="form.fields.country" @change="form.set('country', read($event))">
<option v-for="c in form.derived.countries" :key="c" :value="c">{{ c }}</option>
</select>
</template>ProvinceField.vue is exactly the same length, only the field name differs. No file imports any other.Force all derivation into one pure function
The "computed" part (options, locked fields, earliest date, required fields) goes into one pure function: fields in, derived data out. No await, no DOM, no store. This is the part you can test with expect without mounting anything.
More importantly for later: since every rule is the return value of a function, you can log it, snapshot it, and let another dev run a rule with fake inputs. Rules spread across the computeds of 6 components can't do that.
export type Fields = {
country: string, province: string, method: 'standard' | 'express', voucher: string, tickets: number, company: string
}
export const derive = (f: Fields) => ({
countries: ['VN', 'US', 'JP'],
provinces: PROVINCES[f.country] ?? [],
zone: f.province === 'HCM' || f.province === 'HN' ? 'inner-city' : 'outer-city',
methods: f.province && f.zone === 'outer-city' ? (['standard'] as const) : (['standard', 'express'] as const),
minDeliveryDays: f.voucher === 'SHIP20' ? 2 : 1,
companyRequired: f.tickets > 10,
})expect(derive({ ...base, province: "DN" }).methods).toEqual(["standard"]). One line, no fixtures.Don't let the mediator reach back into components
The most common trap: you move all the logic into the store, and then the store still holds component refs "to call them faster". You moved where the refs live, you didn't get rid of them. The store must not know about InstanceType<typeof ProvinceSelect>, and must not call a component's setOptions, focus() or validate().
The rule: the mediator returns data; components handle turning data into DOM. Want to focus an input when there's an error? The store sets fields.touched.company = true, the component watches that and focuses. Still one-way.
// WRONG: the mediator holds refs, still a spider web, just at a different address
const componentRefs = new Map<string, ComponentPublicInstance>()
function focusError(field: string) {
componentRefs.get(field)?.$el.querySelector('input')?.focus()
}
// RIGHT: the mediator only changes state, components react on their own
const focusRequest = ref<string | null>(null)
function scrollToFirstError() {
focusRequest.value = firstInvalidField(fields.value)
}Tell mediator apart from facade and event bus
Facade also gathers many objects behind one API, but the relationship is one-way with no conversation: the client calls facade.checkout(), the facade holds none of the client's state, and the objects inside don't know the facade exists. A mediator has the whole group's shared state and works both ways: colleagues report up, the mediator derives, colleagues read back down.
An event bus is an observer dressed up as a mediator: it forwards messages rather than deciding. A bus holds no state, has no rules, and has no owner. Use a bus for cart:add and six months later nobody knows who's listening, and removing a listener makes your hands shake — that's how an "event-driven architecture" decays into a landfill. A mediator differs in that it owns the rules: it can reject, transform, or say "this method isn't valid right now".
The short comparison: facade = "I give you a simple API"; bus = "I deliver messages for you"; mediator = "I divide things up, and I remember everything".
// Facade: one-way, stateless, the client never gets called back
class CheckoutFacade {
async placeOrder(cart: Cart) {
const fee = await shipping.quote(cart)
return orders.create(cart, fee)
}
}
// Event bus: forwards, no state, no decisions, no owner
bus.emit('cart:add', sku) // who's listening? The compiler doesn't know. Grep finds 7 places, 3 of them typos.
// Mediator: state + decisions + calling back with data
class CheckoutForm {
set(key: keyof Fields, value: unknown) {
this.fields[key] = value
const next = derive(this.fields) // centralized derivation
if (!next.methods.includes(this.fields.method)) this.fields.method = 'standard'
return next // colleagues read this to render
}
}The final test: which way the arrows point
Once the refactor is done, run three questions. If the answer to any of them is "no", redo the matching step.
# 1. Does any component import one of its sibling components?
grep -rn "^import.*Field" components/checkout/ | grep -v index
# 2. Does anything call another component's methods?
grep -rn "\.value\?\.\(set\|clear\|focus\|validate\|recalc\)" components/
# 3. Add a NEW field: how many existing files do you edit?
# Pass: mediator + rules + 1 new component. No existing component files.
# 4. Does testing the coordination logic require mounting components? Pass: no.04 — Who talks to whom
Structure
- MediatorOne object (store/composable) that holds the whole group's shared state, contains the rules, and is the only place state can change.
- ColleagueA component/field. Knows only the mediator and its own field. Doesn't import, call, or hold refs to other colleagues.
- DerivedStateWhat gets derived from the fields: options, locked fields, min/max, required. Usually a pure function `derive(fields)`.
- ClientThe user interacting with any field; or the parent page that creates the mediator and attaches the colleagues.
BEFORE: n components call each other -> n(n-1)/2 arrows, none with an owner
Country <----> Province Voucher <----> Shipping
| \ | | \ |
| \ | | \ |
v v v v v v
Zone Date <---- Company Date Zone Company
(21 arrows for 7 fields, 45 for 10 fields)
AFTER: every colleague knows only the mediator -> n arrows
user edits 1 field
|
v
+-----------------------------------+
| Mediator (checkout store) |
| fields: country, province, ... |
| set(key, value) <- write |
| derived = derive(fields) -> read |
+----+----------+------------+------+
read | | | read
v v v
+----------+ +---------+ +----------+
| Country | | Voucher | | Delivery | chip: knows only 1 field
+----------+ +---------+ +----------+ no imports of each other05 — Edit freely, run it right here
Try it: a chat room — users only talk to the room
// Before: n users need n*(n-1)/2 direct links (3 users = 3, 20 users = 190).
// After: n users need n links to ONE mediator.
class ChatRoom {
private members = new Map<string, (line: string) => void>()
join(name: string, inbox: (line: string) => void) {
this.members.set(name, inbox)
}
/** The only place that knows who receives what. */
send(from: string, to: string, text: string) {
const line = from + ': ' + text
if (to === '*') {
const targets = [...this.members.keys()].filter(n => n !== from)
console.log(from + ' broadcast -> ' + targets.length + ' people')
for (const name of targets) this.members.get(name)!(line)
return
}
if (!this.members.has(to)) {
console.log(' ! ' + to + ' is not in the room, message dropped')
return
}
console.log(from + ' -> ' + to)
this.members.get(to)!(line)
}
}
const inbox = (name: string) => (line: string) => console.log(' [' + name + '] ' + line)
const room = new ChatRoom()
room.join('ann', inbox('ann'))
room.join('ben', inbox('ben'))
room.join('cara', inbox('cara'))
room.send('ann', '*', 'hi everyone')
room.send('ben', 'cara', 'see you later')
room.send('cara', 'guest', 'who is this')ann broadcast -> 2 people
[ben] ann: hi everyone
[cara] ann: hi everyone
ben -> cara
[cara] ben: see you later
! guest is not in the room, message droppedThe same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- A form with many interdependent fields (country → province, start → end, voucher → method) where the number of rules has outgrown what you can hold in your head — in practice, around 5 cross-field rules is where it starts to hurt.
- Multi-step wizards/steppers, where a later step depends on the aggregate of earlier steps rather than just the field right before it.
- You're hitting circular imports between sibling components, or you're
injecting a component ref to "call its sibling's function". - Dashboard/game UI: many widgets reacting to the same action (board, minimap, HUD, log panel). A broker instead of refs.
- You need to test the coordination logic without mounting any components: the mediator is a plain object, the rules are pure functions.
- A genuine hub on the server side: chat rooms, message brokers, matchmaking — where the sender has no idea who the receiver is.
Don't use it when
- The mediator becomes a landfill. You gather the communication logic, then while you're at it, stuff in the API client, currency formatting, permission checks, email sending. 700 lines later you have a new
App.vue, except it doesn't render. A mediator only holds coordination between fields; a rule that concerns a single field stays with that field. - The mediator reaches back into colleagues (holds refs, calls
setOptions(),validate(),focus()). It looks like a mediator, but it's still the spider web, just relocated. A mediator returns data, not DOM operations. - Using a global event bus instead of a mediator. A bus has no state, no rules, no owner — it just delivers mail. Six months later nobody knows who listens to
cart:add, and every refactor is a gamble. If you must have a bus: put the event names in a typed map, and call it a bus, not an architecture. - Over-engineering. Two fields, one rule, a single form, low odds of change?
@change+ onecomputedis enough, don't build a store. A mediator charges you up front with a layer of abstraction; it only turns a profit if the number of rules keeps growing. - Mediator + async: two rules writing the same field, or two province/city requests coming back out of order → wrong state with correct code. The mediator should be the only place that
awaits, and should guard results with a request token.
07 — You have met it already, just not by name
In real code
Domain-scoped Pinia stores
A useCheckoutStore() store holds cross-field state, with a derived getter and a set() action; field components inject it instead of holding refs to each other. That is the Mediator, and it's the approach the Vue docs recommend when siblings need to share state.
Domain composable + provide/inject
The parent page calls const form = useCheckoutForm() once and then provide(formKey, form); every field component injects it. One single instance, with the coordination logic inside the composable. createSharedComposable (VueUse) does exactly this instance sharing without needing a DI key.
Redux / Vuex
The whole architecture is a packaged Mediator: components don't dispatch to other components, they only send actions to the store; reducers (the only place with rules) return the new state. Redux DevTools shows you the entire "conversation" going through the mediator — something an event bus can never show you.
Socket.IO rooms / message brokers
The server holds the list of rooms and decides who receives which message; a client knows only its own socket and nothing about other clients. RabbitMQ/Kafka exchanges with routing keys are the backend version of the same idea: the sender doesn't address the receiver.
08 — Try it yourself
Exercise
An event sign-up form has five fields: `country`, `province`, `method`, `tickets`, `company`. Rules: `country` changes → `province` resets and its options reload; an outer-city `province` → disable `express`; `tickets > 10` → `company` becomes required. Build a mediator (composable or Pinia store) so that **the five field components don't import each other** and adding a new rule only touches the mediator + the rules file.
Hints, open them one at a time:
- Write the 3 rule lines on paper first. Each line looks like "field A changes → what happens to field B".
- Split the derived rules (
zone,methods,companyRequired) into a pure functionderive(fields)that returns an object — components just render that object. - A reset rule (country changes, so province loses its value) isn't derived, it's a mutation: put it in
set(), the only place allowed to change state.
Mediator = state + set() + derived. set() holds the reset rules; derive() holds the derived rules. Components only read derived and call set(field, value). A new rule = editing 2 files (rules, mediator), no component files touched.
// composables/useSignupForm.ts — the mediator, imports no components
type Fields = { country: string, province: string, method: 'standard' | 'express', tickets: number, company: string }
export const derive = (f: Fields) => {
const zone = f.province === 'HCM' || f.province === 'HN' ? 'inner-city' : 'outer-city'
return {
zone,
provinces: PROVINCES[f.country] ?? [],
methods: f.province && zone === 'outer-city' ? (['standard'] as const) : (['standard', 'express'] as const),
companyRequired: f.tickets > 10,
}
}
export function useSignupForm() {
const fields = ref<Fields>({ country: 'VN', province: '', method: 'standard', tickets: 1, company: '' })
const derived = computed(() => derive(fields.value))
function set<K extends keyof Fields>(key: K, value: Fields[K]) {
fields.value[key] = value
if (key === 'country') fields.value.province = ''
if (key === 'province' && !derive(fields.value).methods.includes(fields.value.method))
fields.value.method = 'standard'
}
return { fields, derived, set }
}
// ProvinceField.vue: const form = useSignupForm()
// <select :value="form.fields.province" @change="form.set('province', read($event))">
// <option v-for="p in form.derived.provinces" :key="p">{{ p }}</option>
// </select>09 — Read them in pairs to see the essence
Related patterns
- FacadeBoth gather many objects behind one door, but a facade is a one-way API for outside clients; a mediator is a referee with shared state for the members inside.
- ObserverA mediator often uses Observer internally: colleagues emit events up to the mediator, and the mediator notifies back down. The difference: a mediator also holds the rules and has the power to say no.
- Chain of ResponsibilityBoth cut the "caller knows the receiver" link. A chain lets the request run through many handlers until one handles it; a mediator concentrates the handling in one place.
- CommandMediator + Command: colleagues don't call each other's actions directly but send command objects to the mediator, which gives you undo, queuing and logging for the whole coordination flow.