skip to Main Content

I want this function to run not with the onClick event but when something is stored in the Session Storage. The eventListener did not work.


function mobileHandler(event) {
    event.preventDefault();

    // Get the selectedNodes array from sessionStorage
    const selectedNodes = JSON.parse(sessionStorage.getItem('selectedNodes'));

    // If no selectedNodes, return early
    if (!selectedNodes) return;

    // Loop through each selected node and add it to the chart

    selectedNodes.forEach((nodeData) => {
      console.log('Adding node:', nodeData);
      addNodeData(nodeData);
    });

    // Clear the selectedNodes from sessionStorage
    sessionStorage.removeItem('selectedNodes');
  }

2

Answers


  1. You could try registering the event listener with a third param (T/F) denoting whether the event is captured or not.

    addEventListener(type, listener, useCapture)

    Additionally, could you provide an example of using selectedNodes prior to storage in sessionStorage?

    Login or Signup to reply.
  2. There is this storage event, but there is catch. The event is being only dispatched, when other pages on the domain using storage change something. There is no event dispatched for change being made by the same page, that owns the storage.

    You can create your own "event dispatch", by implementing some function to set/get items from the sessionStorage, something like this:

    function setItemToSessionStorage(key, item) {
      // dispatch event
      const event = new Event("session-storage-changed")
      window.dispatchEvent(event)
    
      // or call some handler
      onSessionStorageChanged()
    
      // set the item
      sessionStorage.set(key, item)
    }
    
    // you can later add event listener for the event
    window.addEventListener("session-storage-changed", () => {/* handle */})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search