Dirty State Factory

December 15, 2024

Files

js/
  factories/
    dirty-state-factory.js
  uis/
    dirty-states.js
index.js

Source Code

index.js

{
	urls: [
      "js/factories/dirty-state-factory.js",
  ],
},
{
	urls: [
      "js/uis/dirty-states.js",
  ],
},

js/uis/dirty-states.js

let pageStateActivities = DirtyStateFactory({
    'default': () => {
        // todo, e.g. refresh list
    },
});

js/factories/dirty-state-factory.js

function DirtyStateFactory(stateHandlerMap={}) {

    // # self
    let SELF = {
        Update,
        SetDirty,
    };

    let local = {
        stateHandlers: {},
    };

    // # function

    function SetDirty(stateKeys, dirtyState=true) {
        for (let key of stateKeys) {
            if (typeof(local.stateHandlers[key]) == 'undefined') continue;

            local.stateHandlers[key].isDirty = dirtyState;
        }
    }

    function Update() {
        for (let key in local.stateHandlers) {
            let handler = local.stateHandlers[key];
            if (!handler.isDirty) return;
            
            handler.callback();
            handler.isDirty = false;
        }
    }

    // # init
    {
        for (let key in stateHandlerMap) {
            local.stateHandlers[key] = {
                isDirty: true,
                callback: stateHandlerMap[key],
            }
        }
    }

    return SELF;
}

Comments

Thank You

for your visit