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.
How do we get EventBus?
Currently, there are two APIs which return their own instance of sap/ui/core/EventBus
:
- Globally:
(Deprecated since UI5 1.119) *sap.ui.getCore().getEventBus();
- Component-based:
this.getOwnerComponent().getEventBus()
. It is recommended to get the EventBus from the component since it reduces the chance of accidentally reusing existing event names. Additionally, it ensures that your listeners are properly removed once the component gets destroyed, e.g. when the user navigates back to "Home" in Fiori launchpad.
Either way, before calling getEventBus()
, make sure to have the module sap/ui/core/EventBus
required to properly declare the dependency and to avoid possible sync XHR when requiring it.
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:
Sample code
API reference: sap/ui/core/EventBus
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();
// Broadcast the event:
bus.publish("channelABC", "awesomeEvent", Object.freeze({
// with myData
...
}));
},
}
* With UI5 1.119 and above, use sap/ui/core/EventBus.getInstance
for global usage instead.
subscriber
in the context you mentioned? –
Impotence shouldDoSomething
function. Try and let us know if it worked! –
Stripteaser © 2022 - 2024 — McMap. All rights reserved.