How to use getEventBus method in SAPUI5

Kitty picture Kitty · Aug 19, 2014 · Viewed 12.6k times · Source

I am trying to understand getEventBus(). Can somebody provide a tutorial or best example where and how we can implement getEventBus().

Answer

Tim Gerlach picture Tim Gerlach · Aug 19, 2014

I´ve provided an example to answer another question here.

To put it in a nutshell, you can call sap.ui.getCore().getEventBus() to get access to the EventBus instance. As it comes from the core it´s the same across all of your views/controllers. The EventBus provides you with the publish/subscribe functionality. This for example enables you to publish an event in Controller A and notify the subscribed Controller B. A simple example largely from my other answer:

Subscribing to the EventBus:

var eventBus = sap.ui.getCore().getEventBus();
eventBus.subscribe("channel1", "event1", this.handleEvent1, this);

Of course you can name your channel and events as you wish. The third parameter indicates the function, that will be called in case of published events. The last paramter is the scope, 'this' will point to in the given function.

Your handleEvent1 function could look like this:

handleEvent1 : function(channel, event, data) {
    var customData = data.customData
}

Publishing events to the EventBus:

var customData = {}  // anything you eventually want to pass
var eventBus = sap.ui.getCore().getEventBus();

eventBus.publish("channel1", "event1", 
    {
        customData: customData
    }
);

If you have more questions about it let me know so I´ll extend it.