Skip to content

Instantly share code, notes, and snippets.

@theikkila
Created October 15, 2018 19:00
Show Gist options
  • Save theikkila/6b4ce36fa9a097100cdd3ee7cd984584 to your computer and use it in GitHub Desktop.
Save theikkila/6b4ce36fa9a097100cdd3ee7cd984584 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>state-management-by-perkele</title>
</head>
<body>
<button id="click">c++</button>
<div id="state">
</div>
<div id="history">
</div>
</body>
<script type="text/javascript">
var State = function(initialState) {
this.subscribers = [];
this.s = initialState;
this.subscribe = function(cb) {
this.subscribers.push(cb);
cb(this.s);
};
this.mutate = function(f) {
this.s = Object.assign(this.s, f(this.s));
this.subscribers.forEach(subscriber => {
subscriber(Object.assign({}, this.s));
})
};
return this;
}
var k = new State({a: 1, b: 1, c: 0});
// Timer based mutates
setInterval(() => {
k.mutate((state) => {
return {a: state.a+1}
})
}, 10000)
setInterval(() => {
k.mutate((state) => {
return {b: state.b+1}
})
}, 5000)
k.subscribe((state) => {
document.getElementById('state').innerHTML = "<pre>"+JSON.stringify(state, null, 2)+"</pre";
});
// Click handler
document.getElementById('click').addEventListener('click', () => {
k.mutate((state) => ({c: state.c+1}))
})
// History rollback
// This is additional and only for showing how to save and "revert" previous state
var hist = [];
k.subscribe((state) => {
hist.push(state);
var node = document.createElement("li");
if (hist.length <= 1) return;
node.innerHTML = JSON.stringify(state) + "<button onclick='revertState("+(hist.length-1)+")'>Revert</button>";
document.getElementById('history').appendChild(node);
});
function revertState(hist_id) {
k.mutate((state) => {
return Object.assign(hist[hist_id])
})
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment