Global EventBus events

Revision as of 06:09, 9 October 2024 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Intro

You can now use the event bus events below in order to manage page navigation, sessions and loading states outside of the portals app (e.g. in custom components:

  • elementHover - now you can invoke the element over to turbo-load into memory from external applications
  • elementClick - now you can invoke the element click to turbo-load into memory from external applications and navigate to the page
  • sessionUpdate - you can set the session externally
  • refreshPage - you can cause a page refresh
  • isLoading - you can set the portal loading status externally


You can create your own event bus implementation like so:

//Facilitates communication between sibling components
export default class EventBus {
    static fireEvent(eventName, payload) {
        if (!window?.eventListeners) {
            window["eventListeners"] = {};
        }
        if (!window?.eventsPayload) {
            window["eventsPayload"] = {};
        }

        window.eventsPayload[eventName] = payload;

        if (window.eventListeners[eventName]) {
            window.eventListeners[eventName].forEach((listener) => {
                try {
                    listener(payload);
                } catch (error) {
                    console.error(error);
                }
            });
        }
    }

    static getEvent(eventName) {
        if (!window?.eventsPayload) {
            window["eventsPayload"] = {};
        }

        return window.eventsPayload[eventName] ?? null;
    }

    static addEventListener(eventName, listener) {
        if (!window?.eventListeners) {
            window["eventListeners"] = {};
        }

        if (!window?.eventListeners[eventName]) {
            window.eventListeners[eventName] = [];
        }
        window?.eventListeners[eventName].push(listener);
    }

    static removeEventListener(eventName, listener) {
        if (!window?.eventListeners) {
            window["eventListeners"] = {};
        }

        if (window?.eventListeners[eventName]) {
            const index = window?.eventListeners[eventName].indexOf(listener);
            if (index !== -1) {
                window.eventListeners[eventName].splice(index, 1);
            }
        }
    }
}

Then simply raise the correct event:

//This will cause a navigation to the index page
EventBus.fireEvent('elementClick', {
    detail: '#Index',
});