Skip to content

Instantly share code, notes, and snippets.

@michaelcpuckett
Created November 26, 2014 20:34
Show Gist options
  • Save michaelcpuckett/72c4ee5159bbd3d752ec to your computer and use it in GitHub Desktop.
Save michaelcpuckett/72c4ee5159bbd3d752ec to your computer and use it in GitHub Desktop.
Two-way Data-binding
<!doctype html>
<html>
<head>
<title>Object.observe</title>
<style>*{box-sizing:border-box;}input{width:100%;}</style>
</head>
<body>
<h1 data-bind="foo"></h1>
<input data-bind="foo">
<script>
(function () {
'use strict';
// TODO better fallback
if (!Object.observe) {
alert('This page requires a modern browser that supports Object.observe, such as Google Chrome.')
return;
}
// basically $scope
var data = {};
function handleInputChange (ev) {
var el = ev.target,
key = el.getAttribute('data-bind'),
value = el.value;
if (key) {
data[key] = value;
}
}
function getBoundEls (key) {
return [].slice.call(document.querySelectorAll('[data-bind="' + key + '"]'));
}
function handleDataChange (changes) {
changes.forEach(function (change) {
getBoundEls(change.name).forEach(function (el) {
el.value = data[change.name];
el.innerHTML = data[change.name];
});
});
}
document.addEventListener('keyup', handleInputChange);
Object.observe(data, handleDataChange);
data.foo = "Hello world!";
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment