What is the EventBus in SAPUI5 for?

EventBus in UI5 is a tool with which we can leverage publish-subscribe pattern in our app.

How do we get EventBus?

Currently, there are two APIs which return their own instance of EventBus:

  • Globally: sap.ui.getCore().getEventBus(); for

    • Standalone apps.
    • Component apps and their container app where developers have control over both.
  • Component-based: this.getOwnerComponent().getEventBus(); // this == controller. Especially for apps targeting Fiori Launchpad (FLP) where SAP explicitly warns not to get the EventBus from the core but from the component:

    If you need an event bus, use the event bus of the component. By this, you avoid conflicting event names and make sure that your listeners are automatically removed when the component is unloaded. Do not use the global event bus.

Note

  1. FLP destroys the component every time when the user navigates back Home.

  2. Make sure to have the module sap/ui/core/EventBus required before calling getEventBus() to properly declare the dependency and to avoid possible sync XHR when requiring it.

    sap.ui.define([ // or sap.ui.require
      // ...,
      "sap/ui/core/EventBus",
    ], function(/*...,*/ EventBus) { /*...*/ });
    

What is it for?

With EventBus, we can fire (via publish()), and listen (via subscribe()) to our own custom events freely:

  • Without having to use or extend any Control / ManagedObject / EventProvider classes,
  • Without knowing the existence of other involved listeners (if any),
  • Without accessing the object that fires the event (publisher). E.g.: No need to call thatManagedObj.attach*().

Publishers and subscribers stay ignorant to each other which makes loose coupling possible.

Analogous to the real world, EventBus is like a radio station. Once it starts to broadcast about all sorts of things on various channels, those, who are interested, can listen to a particular channel, get notified about a certain event, and do something productive with the given data. Here is an image that illustrates the basic behavior of an EventBus:

sapui5 event bus

Sample code

Subscribe

{ // Controller A
  onInit: function() {
    const bus = this.getOwnerComponent().getEventBus();
    bus.subscribe("channelABC", "awesomeEvent", this.shouldDoSomething, this);
  },
  
  shouldDoSomething: function(channelId, eventId, parametersMap) {
    // Get notified when e.g. "doSomething" from Controller B is called.
  },
}

Publish

{ // Controller B
  doSomething: function(myData) {
    const bus = this.getOwnerComponent().getEventBus();
    bus.publish("channelABC", "awesomeEvent", { myData }); // broadcast the event
  },
}

See API reference: sap/ui/core/EventBus

Leave a Comment