Skip to content

Instantly share code, notes, and snippets.

@vdt
Forked from potch/proxies_are_magic.html
Created December 10, 2013 04:52
Show Gist options
  • Select an option

  • Save vdt/7885885 to your computer and use it in GitHub Desktop.

Select an option

Save vdt/7885885 to your computer and use it in GitHub Desktop.
<!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