Skip to content

Instantly share code, notes, and snippets.

@fielding
Created October 30, 2019 02:50
Show Gist options
  • Save fielding/cb1ca31cc4c5f559483cd38ac483c800 to your computer and use it in GitHub Desktop.
Save fielding/cb1ca31cc4c5f559483cd38ac483c800 to your computer and use it in GitHub Desktop.
blah
// this is @Lukeed's 'sublet' with some small changes to allow for automatic dependency tracking as well as
// explicit registering of change effects
// prob should use a weakMap for these
const reactionsMap = {};
const contextMap = {};
let ctx;
export const setContext = id => {
ctx = id;
}
export const clearContext = el => {
//console.log('mapping', ctx, ' to ', el);
contextMap[ctx] = el;
ctx = null;
return el;
};
function handler(key, shim, obj) {
Object.defineProperty(shim, key, {
enumerable: true,
get: function() {
if (contextMap[ctx] === undefined) return obj[key];
if (!reactionsMap[key]) {
reactionsMap[key] = [contextMap[ctx]];
}
const hasComponent = reactionsMap[key].find(c => c._id === contextMap[ctx]._id);
if (!hasComponent) {
reactionsMap[key].push(contextMap[ctx]);
}
return obj[key];
},
set: function(v) {
console.log('set');
if (obj[key] !== v) {
obj[key] = v;
reactionsMap[key].forEach(c => {
if (c.update !== undefined) c.update();
});
}
return v;
},
});
}
export function Store(obj) {
var k, shim={};
if (Array.isArray(obj)) {
shim = obj;
} else {
for (k in obj) {
handler(k, shim, obj);
}
}
return shim;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment