Created
January 24, 2016 15:56
-
-
Save monochromer/2ad547595abe2d76d979 to your computer and use it in GitHub Desktop.
Простой пример observable
This file contains hidden or 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
| <input type="text" id="a-text"> | |
| + | |
| <input type="text" id="b-text"> | |
| = | |
| <input type="text" id="c-text" readonly> |
This file contains hidden or 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
| function observable(value) { | |
| var listeners = []; | |
| function notify(newValue) { | |
| listeners.forEach(function(listener){ listener(newValue); }); | |
| } | |
| function accessor(newValue) { | |
| if (arguments.length && newValue !== value) { | |
| value = newValue; | |
| notify(newValue); | |
| } | |
| return value; | |
| } | |
| accessor.subscribe = function(listener) { listeners.push(listener); }; | |
| return accessor; | |
| } | |
| function computed(calculation, dependencies) { | |
| var value = observable(calculation()); | |
| function listener(v) {value(calculation()); } | |
| dependencies.forEach(function(dependency) { | |
| dependency.subscribe(listener); | |
| }); | |
| function getter() { return value(); } | |
| getter.subscribe = value.subscribe; | |
| return getter; | |
| } | |
| function bindValue(input, observable) { | |
| var initial = observable(); | |
| input.value = initial; | |
| observable.subscribe(function(){ input.value = observable(); }); | |
| input.addEventListener('input', function() { | |
| observable(input.value); | |
| }); | |
| } | |
| var aText = document.getElementById('a-text'); | |
| var bText = document.getElementById('b-text'); | |
| var cText = document.getElementById('c-text'); | |
| var a = observable("Hello, "), b = observable("World!"); | |
| var c = computed(function(){ return a() + b(); }, [a, b]); | |
| bindValue(aText, a); | |
| bindValue(bText, b); | |
| bindValue(cText, c); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment