Not-related Components
suggest changeIf your components do not have a parent-child relationship (or are only distantly related, such as a great-great-grandchild), the way to communicate is a signal that one component subscribes to and the other writes to.
Those are the two basic operations of any event system: subscribe/listen to an event to be notified, and send/trigger/publish/dispatch an event to notify whoever wants to know.
There are at least 3 patterns to do that. You can find a comparison here.
Here is a brief summary:
- Pattern 1: Event Emitter/Target/Dispatcher: the listeners need to reference the source to subscribe.
- to subscribe:
otherObject.addEventListener('click', () => { alert('click!'); }); - to dispatch:
this.dispatchEvent('click');
- to subscribe:
- Pattern 2: Publish/Subscribe: you don’t need a specific reference to the source that triggers the event. A global object, accessible everywhere, handles all the events.
- to subscribe:
globalBroadcaster.subscribe('click', () => { alert('click!'); }); - to dispatch:
globalBroadcaster.publish('click');
- to subscribe:
- Pattern 3: Signals: similar to Event Emitter/Target/Dispatcher, but you don’t use arbitrary strings. Each object that can emit events has a specific property for each event, so you know exactly which events an object can emit.
- to subscribe:
otherObject.clicked.add( () => { alert('click'); }); - to dispatch:
this.clicked.dispatch();
- to subscribe:
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents