Created
August 14, 2016 06:08
-
-
Save yuizho/de319d72d3a8e0c5fe9b0e67f2bee139 to your computer and use it in GitHub Desktop.
binding.html
This file contains 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 lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
<script> | |
function ViewModel() { | |
this.email = observable(); | |
} | |
function observable() { | |
var value; | |
var subscribers = []; | |
var observable = function(newValue) { | |
if (typeof(newValue) === 'undeinded') { | |
// getter | |
return value; | |
} else { | |
// setter | |
value = newValue | |
observable.valueChanged(); | |
} | |
}; | |
observable.valueChanged = function() { | |
subscribers.forEach(function(subscriber) { | |
subscriber(value); | |
}); | |
} | |
observable.addSubscriber = function(subscriber) { | |
subscribers.push(subscriber); | |
} | |
return observable; | |
} | |
function bindViewModel(viewModel) { | |
var props = Object.getOwnPropertyNames(viewModel); | |
props.forEach(function(prop) { | |
var views = document.querySelectorAll('[data-bind=' + prop + ']'), | |
prop = viewModel[prop], | |
i; | |
// viewModel -> view | |
for (i = 0; i < views.length; i++) { | |
prop.addSubscriber((function(view) { | |
return function(newValue) { | |
if (view.tagName === 'INPUT' ) { | |
view.value = newValue; | |
} else { | |
view.innerText = newValue; | |
} | |
}; | |
})(views[i])); | |
} | |
// View -> viewModel | |
for (i = 0; i < views.length; i++) { | |
views[i].addEventListener('keyup', function(e) { | |
prop(e.target.value); | |
}); | |
} | |
}); | |
} | |
document.addEventListener('DOMContentLoaded', function() { | |
var viewModel = new ViewModel(); | |
bindViewModel(viewModel); | |
viewModel.email("hamada.syougo`mountposition.co.jp"); | |
}); | |
</script> | |
</head> | |
<body> | |
<input type="text" data-bind="email"> | |
<p data-bind="email"></p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment