Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save akirattii/6972c78d3854ac1a789c64e5d126d7fe to your computer and use it in GitHub Desktop.
Save akirattii/6972c78d3854ac1a789c64e5d126d7fe to your computer and use it in GitHub Desktop.
js getters and setters achieves observer pattern instead of Object.observe()
<button>test</button>
<div id="hoge"></div>
<script type="text/javascript">
var hoge = document.querySelector("#hoge");
var obj = {
set name(val) {
obj._name = val;
hoge.innerText = val; // change `hoge` pane's text
},
get name() {
return obj._name;
}
};
document.querySelector("button").onclick = function(e) {
// On modifyed `obj`, div's text will also
// be changed as if `Object.observe()` used.
// js getter & setter is alternative way of `Object.observe()`.
obj.name = new Date().getTime();
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment