Skip to content

Instantly share code, notes, and snippets.

@smelukov smelukov/mvvm.html
Last active Nov 23, 2018

What would you like to do?
Very simple MVVM (dynamic data binding) on JS
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<link href="" rel="stylesheet">
<div class="container">
<form role="form">
<div class="checkbox">
<input type="checkbox" checked id="bindingEnabled"> Динамическое связывание
<div class="form-group">
<label for="firstName">Имя</label>
<input type="text" class="form-control" id="firstName" data-bind="firstName">
<div class="form-group">
<label for="lastName">Фамилия</label>
<input type="text" class="form-control" id="lastName" data-bind="lastName">
<div class="form-group">
<label for="old">Возраст</label>
<input type="text" class="form-control" id="old" data-bind="old">
<div class="form-group">
<label for="town">Город</label>
<input type="text" class="form-control" id="town" data-bind="town">
<div class="jumbotron">
<p>Меня зовут <span data-bind="firstName"></span> <span data-bind="lastName"></span>.</p>
<p>Мне <span data-bind="old"></span> лет и я живу в городе <span data-bind="town"></span>.</p>
<script src="script.js"></script>
var bindMap = {},
scope = {},
bindedEls = document.querySelectorAll('*[data-bind]');
for (var i = 0; i < bindedEls.length; i++) {
var el = bindedEls[i],
bindTo = el.dataset.bind;
if (!bindMap[bindTo]) {
bindMap[bindTo] = [];
function bindValue(bindingName, value) {
scope[bindingName] = value;
function syncBindings() {
for (var bindTo in scope) {
var value = scope[bindTo];
bindMap[bindTo].forEach(function(el) {
if (el.tagName === 'INPUT') {
el.value = value;
} else {
el.innerText = value;
delete scope[bindTo];
document.addEventListener('keyup', function(e) {
var target =,
bindTo = target.dataset.bind;
if (bindTo && bindMap[bindTo]) {
bindValue(bindTo, target.value);
if (bindingEnabled.checked) {
}, true);
bindingEnabled.addEventListener('change', function() {
if (bindingEnabled.checked) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.