Skip to content

Instantly share code, notes, and snippets.

@djleonskennedy
Last active July 21, 2020 09:07
Show Gist options
  • Save djleonskennedy/8d4d530114f08d9c6313bd6cb9ef9490 to your computer and use it in GitHub Desktop.
Save djleonskennedy/8d4d530114f08d9c6313bd6cb9ef9490 to your computer and use it in GitHub Desktop.
// 'use strict'
let callback = null;
function observe(data) {
const subscribers = {};
return new Proxy(data, {
set(obj, key, value) {
obj[key] = value;
if (subscribers[key]) {
subscribers[key].forEach(callback => callback());
}
},
get(obj, key) {
if (callback) {
if (!subscribers[key]) subscribers[key] = [];
if (!subscribers[key].includes(callback)) {
subscribers[key].push(callback);
}
}
return obj[key];
}
});
}
function watcher(watchFunc) {
callback = watchFunc;
watchFunc();
callback = null;
}
// ----- App
const data = observe({
dinnerPrice: 100,
tip: 10,
total: 0,
});
watcher(() => {
data.total = data.dinnerPrice + data.tip;
});
watcher(() => {
document.getElementById('app').innerHTML = `
<table>
<tr>
<td>Dinner</td><td>${data.dinnerPrice} €</td>
<td>
<button value="incrementDinnerPrice">+</button>
<button value="decrementDinnerPrice">-</button>
</td>
</tr>
<tr>
<td>Tip</td><td>${data.tip} €</td>
<td>
<button value="incrementTip">+</button>
<button value="decrementTip">-</button>
</td>
</tr>
<tr>
<td>Total</td><td>${data.total} €</td>
<td></td>
</tr>
</table>
`;
});
const methods = {
'incrementDinnerPrice': () => data.dinnerPrice++,
'decrementDinnerPrice': () => data.dinnerPrice--,
'incrementTip': () => data.tip++,
'decrementTip': () => data.tip--,
};
document.getElementById('app').onclick = function (event) {
const method = methods[event.target.value];
if (method) method();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment