Search code examples
javascriptevent-bussapui5

SAPUI5 EventBus: Prevent stacking the same subsciptions


When i click a button, i want to subscribe to an event

EventBus.subscribe("sChannelFoo", "sIdBar", function(){
alert("FOOBAR!");
});

I subscribe on "sChannelFoo" and sIdBar" throughout my code. What is a neat solution to make sure that I subscribe to this event only once with this button, even if I click my button several times?

If I have 1000 other buttons, I want them to also be able to subscribe exactly once to "sChannelFoo" and "sIdBar". The other 1000 buttons may have the same function or a different one.


Solution

  • You could use the method attachEventOnce on your Button control: https://openui5.hana.ondemand.com/docs/api/symbols/sap.ui.base.EventProvider.html#attachEventOnce

    With the registered handler function you can invoke the subscription to the event bus:

    oButton.attachEventOnce('press', function() {
        EventBus.subscribe("sChannelFoo", "sIdBar", function() {
            alert(FOOBAR!");
         });
    }