-
-
Save vdt/7885885 to your computer and use it in GitHub Desktop.
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> | |
| <meta charset="utf-8"> | |
| <title>Why can't I have Proxy yet??</title> | |
| </head> | |
| <body> | |
| <div id="item"> | |
| <h1 class="name">name goes here</h1> | |
| <dl> | |
| <dt>Age:</dt> | |
| <dd class="age">age goes here</dd> | |
| </dl> | |
| </div> | |
| <script> | |
| // data binding in 12 lines. | |
| function bind(o, el, map) { | |
| function set(o, prop, value) { | |
| o[prop] = value; | |
| if (prop in map) { | |
| map[prop](el, value); | |
| } | |
| } | |
| for (prop in o) { | |
| set(o, prop, o[prop]); | |
| } | |
| return new Proxy(o, { set: set }); | |
| } | |
| </script> | |
| <script> | |
| // Make an object. | |
| var obj = { | |
| name: 'Bob', | |
| age: 12, | |
| color: 'red' | |
| }; | |
| // Bind our object to the DOM. | |
| obj = bind(obj, document.querySelector('#item'), { | |
| 'name': function(el, v) { | |
| el.querySelector('.name').textContent = v; | |
| }, | |
| 'age': function(el, v) { | |
| el.querySelector('.age').textContent = v; | |
| }, | |
| 'color': function(el, v) { | |
| el.style.background = v; | |
| } | |
| }); | |
| // These assignments update the DOM! | |
| obj.name = 'Steve'; | |
| obj.age = 13; | |
| obj.color = 'orange'; | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment