USEPA / useeio-widgets

Creative Commons Zero v1.0 Universal
3 stars 14 forks source link

Trigger event when hiddenhash changes #33

Open localsite opened 3 years ago

localsite commented 3 years ago

Goal: To allow each widget to "listen" for changes to the hiddenhash independently. This will allow us to avoid hardcoding config script for each widget. Config script would be more prone to break as the widget's internal code is modified.

Question: How should we independently watch for changes to the hiddenhash object? The following works well for listening for URL hash changes:

// In localsite.js
$(window).on('hashchange', function() { 
  triggerHashChangeEvent();
});

var triggerHashChangeEvent = function () {
    // Create a new event
    var event = new CustomEvent('hashChangeEvent');
    // Dispatch the event
    document.dispatchEvent(event);
};

// In index.html or JQuery widget .js file
// This eventListener also allows map to remove selected shapes when backing up.
document.addEventListener('hashChangeEvent', function (elem) {
    console.log("local page detects hashChangeEvent");
    refreshWidgetsLocal();
}, false);

Like the hash change trigger, we need to only fire 1 event when multiple values are updated in the hiddenhash object.

Since there does not seem to be an efficient way to watch an object, perhaps we should instead save the hiddenhash as an object string within a hidden div element. We could then watch the DOM for changes to a hidden div with id="hiddenhash".

Each widget would check if a div with id="hiddenhash" already existed before adding to the DOM. The hidden div could be appending at the start of the body tag.

What do you think?

TheTisiboth commented 3 years ago

I am currently looking for some information about the subject. I found this library, that allow to use Observable on Objects : https://www.npmjs.com/package/object-observer There is also Redux, which helps storing global state of an application : https://redux.js.org/tutorials/essentials/part-1-overview-concepts#why-should-i-use-redux Maybe it can help I keep looking for a satisfactory tool