The problem: When you have multiple application, such as in micro front-end, you need to find a way to communicate between them.
This is an event based proof of concept (POC),of how three application and an analitycs layer can communicate.
This had been inspired by MicroFrontend and Eev
There is three applications:
Header app
Product app
Log app
And there is on analytics layer called tracking
Note: I simplified it for demo purpose. In a full micro front-end app, you'll probably have more apps like basket, checkout, catalog...
The tracking layer expose an object called TrackingEvent
which will be dispatched.
The tracking layer is responsible to catch and handle ALL dispached trackingEvents, and sync it with the analitycs side.
When you want to track an event, you have to:
- Create a new TrackingEvent and providing it the data you need
- Dispatch your custom event
Example:
const type = trackingEventName;
const payload = { your: 'datas', goes: 'here' };
const e = new TrackingEvent(type, payload);
e.dispatch();
Easy, isn't it ?
It works this way:
document.addEventListener('trackingEvent', function (event) {
/**
* Process the event here.
* Please note that event is the CustomEvent object.
* Your data are stored into event.details
*/
const { type, payload } = event.details;
axios
.post('analytics-api' { type, payload })
.then(res => /* */)
.catch(err => /* */);
});
The TrackingEvent
object is just some syntaxic sugar added on top of CustomEvent api.
Its main purpose is to simplify the developer by abstracting the not so complicated CustomEvent api and reducing boilerplate.
It does two things:
- Wrap your data into one object (by convention, we have a
type
and apayload
, juste like redux store pattern), - Create a CustomEvent, set your customData into this event, and dispatch it.
When you catch a CustomEvent, you will need to access to event.details key to retrieve the data you store in the custom event.
And because sometimes, code is more expressive than word, check this out:
class TrackingEvent {
constructor(type, payload) {
this.type = type;
this.payload = payload;
}
dispatch() {
const { type, payload } = this;
const dispatchedAt = new Date();
const detail = { type, payload, dispatchedAt };
const event = new CustomEvent('trackingEvent', { detail });
document.dispatchEvent(event);
}
}