Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Простой пример observable
<input type="text" id="a-text">
+
<input type="text" id="b-text">
=
<input type="text" id="c-text" readonly>
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
You can’t perform that action at this time.