Is there a way to communicate information between page and masterPage code?

Question:
Is there a way to communicate information between page and masterPage code ?

Product:
Velo

What are you trying to achieve:
Here is my problem,

In the masterPage I have a widget that displays information about users’s current favorite store. If no store is selected the widget turns into a button “select a store”

One of my pages, I got a button “set as favorite” and “clear favorite store” that either changed the favorite store or cleared the selection.

How do I make the event on the page notify the widget in the Masterpage that the location has been cleared or change?

What have you already tried:
He a few (bad) idea I got:

  • Use local storage to communicate between contexts: you need to pull the information every 250ms to make it look realtime. This is not suitable for large datastructure
  • Use realtime API: seems a bit silly to use the backend in order to send a notification from the user to the user. This is suitable for large datastructure but overly complex to set in place.

I think you can write the code inside page code. But if that won’t work you can try this:

export a function in masterPage.js file import this function in your page code and call this function with any data you need. In this way you can communicate between masterPage.js and current page code.

But as I said accessing widgets or any other element in master sections is possible also with page code.

No I don’t want to interact on my page’s element from the masterPage code. I prefer to separate the concern of each “page”

I endup using the import to expose an Observer pattern so that the page can be notify when something changes.

Here a code snippet for anyone looking for an answer

/** MasterPage code*/

/**
 * @callback LocatorListennerCallback
 * @param {"restaurantClicked" | "restaurantLoaded"} eventId
 * @param {object} data
 */

/** @type {LocatorListennerCallback}*/
let eventListenner = null;

/**
 * @param {LocatorListennerCallback} listenner
 */
export function registerEventListenner(listenner) {
    eventListenner = listenner;
}

/**
 * Emits an event so that page can react to event
 * @type LocatorListennerCallback
 */
function emitEvent(eventId, data) {
  if(state.eventListenner) eventListenner(eventId, data);
}

On the page code you simply import the registering function and react to changes

/** Page code*/
import {registerEventListenner} from './masterPage.js';

registerEventListenner((eventId, payload) => {
  if(eventId === "restaurantClicked") selectedRestaurantId = payload;
  else if(eventId === "restaurantLoaded") restaurantsRequest = payload;
});