const store = {};
const subscribers = {}
const nameWarning = (value, nameType) => {
if (typeof value !== 'string') {
console.warn(`${value} is not a valid ${nameType}`);
return;
}
}
const subscriptions = stateName => {
if (subscribers[stateName] === undefined) {
return;
}
Object.entries(subscribers[stateName]).forEach(([ref, callback]) => {
// stateName, value, ref
const value = state.get(stateName);
const parsed = () => JSON.parse(value);
callback({
stateName,
value,
parsed,
ref
})
});
}
const state = {
get(stateName, parse) {
nameWarning(stateName);
const value = store[stateName];
return parse ? JSON.parse(value) : value;
},
/**
*
* @param {string} stateName - The name of the state to set
* @param {*} value - The value of the state to store
* @param {Boolean} allowReferences - Allows objects and functions to be stored as references.
*/
set(stateName, value, allowReferences) {
nameWarning(stateName, 'stateName');
if (typeof value === 'function' && allowReferences) {
console.warn(`${stateName} is not a valid value. A value cannot be a function`);
return;
}
const resolvedValue = typeof value === 'object' && value !== null && !allowReferences ? JSON.stringify(value) : value;
store[stateName] = resolvedValue;
subscriptions(stateName);
},
subscribe(stateName, ref, callback) {
nameWarning(ref, 'ref');
if (subscribers[stateName] === undefined) {
subscribers[stateName] = {};
}
if (subscribers[stateName][ref] !== undefined) {
console.warn(`There is already a subscriber using ref ${ref} subscribed to ${stateName}`);
return;
}
subscribers[stateName][ref] = callback;
},
unsubscribe(stateName, ref) {
if(subscribers[stateName] === undefined){
console.warn(`State ${stateName} does not exist`);
return;
}
if(subscribers[stateName][ref] ===...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.