Created
November 26, 2014 20:34
-
-
Save michaelcpuckett/72c4ee5159bbd3d752ec to your computer and use it in GitHub Desktop.
Two-way Data-binding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!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