invalidator
Advanced tools
Comparing version 1.0.0 to 1.0.1
@@ -8,9 +8,11 @@ /** @type {BroadcastChannel | null} */ | ||
/** @type {Map<string, Array<()=>any>>} */ | ||
/** @type {Map<string, ()=>any>} */ | ||
const cb_map = new Map(); | ||
/** @type {Map<string, Array<string>>} */ | ||
const cb_ids = new Map(); | ||
/** @param {string} key */ | ||
function invalidate(key) { | ||
const callbacks = cb_map.get(key); | ||
//Dispatch a message to all other tabs, if possible | ||
if (bc) { | ||
@@ -20,4 +22,8 @@ bc.postMessage(key); | ||
const callback_ids = cb_ids.get(key) ?? []; | ||
const callbacks = callback_ids.map((id) => cb_map.get(id)); | ||
if (callbacks) { | ||
for (const cb of callbacks) { | ||
if (cb === undefined) continue; | ||
cb(); | ||
@@ -29,31 +35,39 @@ } | ||
function depends(key, cb) { | ||
const new_cb_array = cb_map.get(key) ?? []; | ||
new_cb_array.push(cb); | ||
cb_map.set(key, new_cb_array); | ||
const id = | ||
Math.random().toString(36).substring(2, 15) + | ||
Math.random().toString(36).substring(2, 15); | ||
//Add the id to the list of ids for this key | ||
const cb_ids_array = cb_ids.get(key) ?? []; | ||
cb_ids_array.push(id); | ||
cb_ids.set(key, cb_ids_array); | ||
function handle_message(e) { | ||
if (e.data === key) { | ||
cb(); | ||
} | ||
} | ||
cb_map.set(id, cb); | ||
if (bc) { | ||
bc.addEventListener("message", handle_message); | ||
//Listen for messages from other tabs | ||
/** @param {MessageEvent<string>} e */ | ||
function handle_message(e) { | ||
if (e.data === key) { | ||
cb(); | ||
} | ||
} | ||
if (bc) { | ||
bc.addEventListener("message", handle_message); | ||
} | ||
return () => { | ||
const cb_array = cb_map.get(key)?.filter((cb) => cb !== undefined) ?? []; | ||
if (cb_array.length === 0) { | ||
cb_map.delete(key); | ||
return; | ||
//remove the event listener | ||
if (bc) { | ||
bc.removeEventListener("message", handle_message); | ||
} | ||
cb_map.set(key, cb_array); | ||
//remove the id from the list of ids for this key | ||
let ids = cb_ids.get(id) ?? []; | ||
ids = ids.filter((i) => i !== id); | ||
cb_ids.set(id, ids); | ||
if(bc) { | ||
bc.removeEventListener("message", handle_message); | ||
} | ||
//remove the callback from the map | ||
cb_map.delete(id); | ||
}; | ||
@@ -60,0 +74,0 @@ } |
@@ -5,3 +5,3 @@ { | ||
"version": "1.0.0", | ||
"version": "1.0.1", | ||
"type": "module", | ||
@@ -8,0 +8,0 @@ "files": [ |
3398
63