const createGlobalReactive = (id = "", prefix = "gr-") => {
if(id[0] == "#")id = id.replace('#','');
const _root = id ? document.getElementById(id) : document;
if(!_root)throw new Error(`The id '${id}' you give to the globalReactive app is invalid as it can't find the root element!`);
const nodes = {_root};
_root.querySelectorAll('*').forEach(n => {
n.classList.forEach(c =>{
if (c.startsWith(prefix)) {
const key = c.replace(prefix,'');
if(nodes[key]){
nodes[key].push(n);
}else{
nodes[key] = [n];
}
}
})
if(n.id.startsWith(prefix))nodes[n.id.replace(prefix,'')] = n;
})
const effects = [];
const data = {};
const getData = (key) => data[key];
const setData = (key, value) => {
if(data[key] == value)return;
data[key] = value;
reactTo(key);
}
const useData = (key, initValue) => {
data[key] = initValue;
return [() => getData(key), (value) => setData(key,value)];
}
const func = (fn) => {fn(setData,{...data},nodes,id)};
const useEffect = (fn, deps) => {
if(!Array.isArray(deps))throw new Error('Effect dependencies are mandatory and have to be in an array!');
effects.push({fn, deps});
document.addEventListener('DOMContentLoaded', ()=>{
func(fn);
});
}
const reactTo = (key) => {
effects.forEach(ef => {
const {fn, deps} = ef;
if(!key || deps.includes(key)){
func(fn);
}
})
}
return { useData, getData, setData, useEffect, reactTo, nodes, id };
}
留言
發佈留言