Skip to content

Instantly share code, notes, and snippets.

@zhenyanghua
Last active February 16, 2017 19:48
Show Gist options
  • Save zhenyanghua/72112f53d95f370c8e0dcd067b17bcc6 to your computer and use it in GitHub Desktop.
Save zhenyanghua/72112f53d95f370c8e0dcd067b17bcc6 to your computer and use it in GitHub Desktop.
ES6 Naive Data Binding
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test</title>
<link rel="stylesheet" href="">
<style>
body { background-color: rice; }
ul {
border: 2px dotted black;
}
</style>
</head>
<body>
<ul id="list"></ul>
<script src="main.js"></script>
</body>
</html>
HTMLElement.prototype.bindData = function(data, templateFn){
if (templateFn) {
this.innerHTML = templateFn(data);
} else {
this.innerHTML = JSON.stringify(data);
}
};
let proxy = (scope, fn) => {
let p = new Proxy(scope, {
set: (obj, k, v) => {
obj[k] = v;
fn(scope);
}
});
return p;
};
// Model
const data = {
flights: [
{ "label": "UN407", "value": 3407 },
{ "label": "SW102", "value": 2102 },
{ "label": "AA377", "value": 1377 }
]
};
const scope = Object.assign({}, data);
// View
const listElm = document.getElementById('list');
let syncList = scope => scope.flights.map(x => `<li>${x.label}</li>`).join('');
// Controller
let f = proxy(scope, (scope) => listElm.bindData(scope, syncList));
f.flights = f.flights;
setInterval(() => {
f.flights = f.flights.filter(x => x.value < 2000);
}, 2000);
setTimeout(() => {
setInterval(() => {
f.flights = data.flights;
}, 2000);
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment