Skip to content

Instantly share code, notes, and snippets.

@Jesseyx
Created October 20, 2016 09:50
Show Gist options
  • Select an option

  • Save Jesseyx/758635f0ffdca782914c7df7bfc71336 to your computer and use it in GitHub Desktop.

Select an option

Save Jesseyx/758635f0ffdca782914c7df7bfc71336 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getset</title>
</head>
<body>
<div id="test">
<p>{{msg}}</p>
<p>{{msg}}</p>
<p>{{msg}}</p>
<p>{{what}}</p>
<p>{{hey}}</p>
</div>
<script>
var bindingMark = 'data-vm-binding';
function VM(id, initData) {
var self = this,
el = self.el = document.getElementById(id),
data = self.data = {}, // the external interface
bindings = {}, // the internal copy
content = el.innerHTML.replace(/\{\{(.*)\}\}/g, markToken);
el.innerHTML = content;
for (var variable in bindings) {
bind(variable);
}
if (initData) {
for (variable in initData) {
data[variable] = initData[variable];
}
}
function markToken(match, variable) {
bindings[variable] = {};
return '<span ' + bindingMark + '="' + variable + '"></span>';
}
function bind(variable) {
bindings[variable].el = el.querySelectorAll('[' + bindingMark + '="' + variable + '"]');
[].forEach.call(bindings[variable].el, function (e) {
e.removeAttribute(bindingMark);
});
Object.defineProperty(data, variable, {
set: function (newValue) {
[].forEach.call(bindings[variable].el, function (e) {
bindings[variable].value = e.textContent = newValue;
});
},
get: function () {
return bindings[variable].value;
},
});
}
}
var data = {
msg: 'Hello',
};
var app = new VM('test', data);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment