앱 간 통신을 위한 이벤트 버스
서로 다른 마이크로 프런트엔드 사이에서 결합도를 낮춘 통신을 구현하는 이벤트 버스를 학습합니다.
앱 간 통신을 위한 이벤트 버스은(는) CoddyKit의 무료 Micro Frontends Architecture with Module Federation 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Micro Frontends Architecture with Module Federation 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Micro Frontends Architecture with Module Federation 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
MFE Communication Challenges
In a Micro Frontend (MFE) architecture, different applications run independently. But what happens when one MFE needs to tell another MFE something?
Direct communication can create tight dependencies, making your system harder to maintain and scale. We need a way for MFEs to talk without knowing too much about each other.
Meet the Event Bus
An Event Bus is a design pattern that provides a central hub for communication between different parts of an application, or in our case, different Micro Frontends.
Think of it like a community bulletin board where anyone can post a message, and anyone interested can read it.
How it Works: Publish/Subscribe
The Event Bus operates on a Publish/Subscribe (or Pub/Sub) model:
- Publishers (MFEs)
emitevents to the bus, often with some data. They don't care who listens. - Subscribers (other MFEs)
listen(oron) for specific events. They react when an event they're interested in is published.
This keeps communication decoupled.
Designing Our Event Bus
A simple Event Bus needs a few core methods:
on(eventName, callback): To subscribe to an event.emit(eventName, data): To publish an event with optional data.off(eventName, callback): To unsubscribe from an event (important for cleanup).
Let's build a basic JavaScript version.
Building the Bus Core
Here's a basic JavaScript class for an EventBus. It uses an internal object, listeners, to store all registered callbacks for each event name.
Try running this example:
class EventBus {
constructor() {
this.listeners = {};
}
on(eventName, callback) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(callback);
}
emit(eventName, data) {
if (this.listeners[eventName]) {
this.listeners[eventName].forEach(callback => {
callback(data);
});
}
}
off(eventName, callback) {
if (!this.listeners[eventName]) return;
this.listeners[eventName] = this.listeners[eventName].filter(
listener => listener !== callback
);
}
}
const bus = new EventBus();
console.log("EventBus initialized!");Sending Messages (Publish)
To send a message, one Micro Frontend will call the emit method on the shared Event Bus instance. It provides the event name and any relevant data.
The Event Bus then broadcasts this event to all registered listeners.
Publishing in Action
Here, we simulate an MFE publishing a 'user:loggedIn' event. Notice how the mfeAPublisher function uses bus.emit().
Run the code and see the output:
class EventBus {
constructor() {
this.listeners = {};
}
on(eventName, callback) {
if (!this.listeners[eventName]) this.listeners[eventName] = [];
this.listeners[eventName].push(callback);
}
emit(eventName, data) {
if (this.listeners[eventName]) {
this.listeners[eventName].forEach(callback => callback(data));
}
}
off(eventName, callback) {
if (!this.listeners[eventName]) return;
this.listeners[eventName] = this.listeners[eventName].filter(
listener => listener !== callback
);
}
}
const bus = new EventBus();
// MFE A publishes an event
function mfeAPublisher() {
const data = { user: "Alice", action: "loggedIn" };
bus.emit("user:loggedIn", data);
console.log("MFE A published 'user:loggedIn'");
}
mfeAPublisher();Receiving Messages (Subscribe)
Another Micro Frontend that wants to react to this event will use the on method to subscribe. It provides the event name it's interested in and a callback function to execute when that event occurs.
The callback function receives the data published with the event.
Subscribing and Reacting
Now let's put it all together. One MFE subscribes to the user:loggedIn event, and another MFE publishes it. When you run this, you'll see both actions logged.
Observe the flow of communication:
class EventBus {
constructor() {
this.listeners = {};
}
on(eventName, callback) {
if (!this.listeners[eventName]) this.listeners[eventName] = [];
this.listeners[eventName].push(callback);
}
emit(eventName, data) {
if (this.listeners[eventName]) {
this.listeners[eventName].forEach(callback => callback(data));
}
}
off(eventName, callback) {
if (!this.listeners[eventName]) return;
this.listeners[eventName] = this.listeners[eventName].filter(
listener => listener !== callback
);
}
}
const bus = new EventBus();
// MFE B subscribes to an event
function mfeBSubscriber(data) {
console.log("MFE B received 'user:loggedIn' event:");
console.log(data);
}
bus.on("user:loggedIn", mfeBSubscriber);
console.log("MFE B subscribed to 'user:loggedIn'");
// MFE A publishes an event
function mfeAPublisher() {
const data = { user: "Alice", action: "loggedIn" };
bus.emit("user:loggedIn", data);
console.log("MFE A published 'user:loggedIn'");
}
mfeAPublisher();When to Use an Event Bus
Pros:
- Decoupling: MFEs don't need to know about each other.
- Simplicity: Easy to implement for basic broadcast needs.
- Flexibility: New subscribers can be added without changing publishers.
Cons:
- Debugging: Hard to trace event flow (event spaghetti).
- No direct response: Not suitable for request/response patterns.
- Global state: The bus itself can become a single point of failure or a source of implicit dependencies.
Event Bus Quick Check
An Event Bus is a powerful tool for communication in Micro Frontends. Which of the following statements accurately describe its benefits?
Recap: Event Bus Essentials
You've learned about the Event Bus pattern for inter-Micro Frontend communication.
- It uses a Publish/Subscribe model.
- Publishers
emitevents, subscriberson(listen for) them. - It promotes decoupled communication, reducing direct dependencies.
- While simple and flexible, be aware of potential debugging challenges and ensure proper cleanup (
off).
Next, we'll explore shared state management!
자주 묻는 질문
“앱 간 통신을 위한 이벤트 버스” 강의는 무료인가요?
네 — “앱 간 통신을 위한 이벤트 버스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Micro Frontends Architecture with Module Federation 강의 전체를 잠금 해제할 수 있습니다. Micro Frontends Architecture with Module Federation 강의에는 총 4개의 강의가 포함되어 있습니다.
“앱 간 통신을 위한 이벤트 버스”에서 뭘 배우나요?
서로 다른 마이크로 프런트엔드 사이에서 결합도를 낮춘 통신을 구현하는 이벤트 버스를 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Micro Frontends Architecture with Module Federation을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Micro Frontends Architecture with Module Federation을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Micro Frontends Architecture with Module Federation은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“앱 간 통신을 위한 이벤트 버스” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Micro Frontends Architecture with Module Federation 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Micro Frontends Architecture with Module Federation 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 앱 간 통신을 위한 이벤트 버스
- 공유 상태 관리
- 맞춤형 통신 솔루션
- Custom DOM 이벤트로 통신하기