Can anybody explain for what and when we are going to use EventBus methods? Also what kind the activities of the same.
EventBus in UI5 is a tool with which we can leverage publish-subscribe pattern in our app.
Currently, there are two APIs which return their own instance of EventBus
:
Globally: sap.ui.getCore().getEventBus();
for
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.
FLP destroys the component every time when the user navigates back Home.
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) { /*...*/ });
With EventBus, we can fire (via publish()
), and listen (via subscribe()
) to our own custom events freely:
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:
{ // 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.
},
}
{ // 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With