0Pricing
Micro Frontends Architecture with Module Federation · レッスン

アプリ間通信のためのイベントバス

異なるMicro Frontend間の疎結合な通信を実現するイベントバスの実装方法を学びます。

「アプリ間通信のためのイベントバス」はCoddyKit上の無料Micro Frontends Architecture with Module Federationレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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!

よくある質問

「アプリ間通信のためのイベントバス」レッスンは無料ですか?

はい。「アプリ間通信のためのイベントバス」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Micro Frontends Architecture with Module Federationコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Micro Frontends Architecture with Module Federationコースには全4レッスンが含まれています。

「アプリ間通信のためのイベントバス」で何を学びますか?

異なるMicro Frontend間の疎結合な通信を実現するイベントバスの実装方法を学びます。 ブラウザで直接実行するハンズオンコードでMicro Frontends Architecture with Module Federationを演習し、24時間対応の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に戻る