Micro Frontends Architecture with Module Federation · 课时

跨应用通信的事件总线

学习实现事件总线,在不同微前端之间进行解耦通信。

第 1 / 4 课12 个步骤

跨应用通信的事件总线 是 CoddyKit 上的免费 Micro Frontends Architecture with Module Federation 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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) emit events to the bus, often with some data. They don't care who listens.
  • Subscribers (other MFEs) listen (or on) 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 emit events, subscribers on (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!

免费开始

用 AI 导师学习 JavaScript — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「跨应用通信的事件总线」课时是免费的吗?

是的 — 「跨应用通信的事件总线」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Micro Frontends Architecture with Module Federation 课程的其余内容,请升级到 CoddyKit PRO。 Micro Frontends Architecture with Module Federation 课程共包含 4 节课。

「跨应用通信的事件总线」这节课中我会学到什么?

学习实现事件总线,在不同微前端之间进行解耦通信。 你通过在浏览器中直接运行的动手代码来练习 Micro Frontends Architecture with Module Federation,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Micro Frontends Architecture with Module Federation 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Micro Frontends Architecture with Module Federation 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「跨应用通信的事件总线」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Micro Frontends Architecture with Module Federation 课中编写并运行代码吗?

能。每节 Micro Frontends Architecture with Module Federation 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 跨应用通信的事件总线
  2. 共享状态管理
  3. 自定义通信方案
  4. 使用自定义 DOM 事件进行通信
← 返回 Micro Frontends Architecture with Module Federation