Skip to content

Instantly share code, notes, and snippets.

@junwatu
Last active August 29, 2015 13:57
Show Gist options
  • Save junwatu/9738796 to your computer and use it in GitHub Desktop.
Save junwatu/9738796 to your computer and use it in GitHub Desktop.
Object.observer binding example
Just a raw and dull Object.observe() example, test on Google Chrome Version 35.0.1897.2 dev aura
0. Enable flags "Enable Experimental JavaScript" on Google Chrome.
1. Make HTML file to load JS file
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Object.observe()</title>
</head>
<body>
<div>
<h3>Object.observe()</h3>
<input type="text" id="input">
<input type="text" id="input2">
</div>
<script src="js/app.js"></script>
</body>
</html>
2. Main JavaScript File
/* app.js */
/* JS */
var inputData = document.getElementById('input');
var inputData2 = document.getElementById('input2');
var oModel = {
data: ''
};
Object.observe(oModel, changeHandler);
// add event listeners for input data
init(inputData);
init(inputData2);
function init(o) {
o.addEventListener('keydown', onInputChange);
o.addEventListener('keyup', onInputChange);
o.addEventListener('change', onInputChange);
o.addEventListener('blur', onInputChange);
o.addEventListener('focus', onInputChange);
}
function onInputChange(event) {
oModel.data = document.getElementById(event.target.id).value;
}
function changeHandler(changes) {
changes.forEach(function(change) {
console.log(change);
console.log('type:' + change.type, 'value:' + change.object[change.name], 'oldValue:' + change.oldValue);
});
inputData2.value = oModel.data;
inputData.value = oModel.data;
}
3. Type anything in input text (id is input or input2).
4. Test from console dev tools
> oModel.data = "Inggih Sam!";
LINK RESOURCES:
- http://updates.html5rocks.com/2012/11/Respond-to-change-with-Object-observe
- http://amasad.me/2014/03/16/why-im-excited-about-objectobserve/
- https://github.com/rwaldron/fact/blob/master/src/fact.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment