Knockout doesn't support atomic updates, but provides a workaround. If you want to
simultaneously update two reactive variable you have to track all reactive variables that
depend on them and add .extend({throttle:delay})
to each. delay
is an interval in ms to await all dependencies to be updated.
I can't say that such approach to handle atomic updates is best, because if
delay
is too small you lose atomically and if it is too high you
may get a visible delay in the user interface.
Move over it breaks composability because it violates locality of change: to make an atomic update on some variables we have to alter all its dependants (which may be spread all over the code) and not to forget to alter its future dependants.
HTML
JS
var model = new ViewModel();
ko.applyBindings(model);
function ViewModel() {
this.alice = ko.observable(10);
this.bob = ko.observable(15);
this.parcel = ko.observable("2");
this.history = ko.observableArray([]);
ko.computed(function(){
this.history.push(JSON.stringify({
Alice: this.alice() + "$",
Bob: this.bob() + "$",
sum: (this.alice() + this.bob()) + "$"
}));
}, this).extend({ throttle: 50 });
this.update = function() {
this.alice(this.alice() - parseInt(this.parcel()));
this.bob(this.bob() + parseInt(this.parcel()));
}
}