KnockoutJS: Fine-Grained Reactivity with Observables and Computed
How KnockoutJS solves reactivity: observables as get/set functions, computed with automatic dependency tracking and targeted DOM updates instead of a global tree comparison.
Three functions are enough to keep an entire UI reactive in KnockoutJS: ko.observable, ko.observableArray and ko.computed. None of them takes a dependency list. Still, after the first run, Knockout knows which value is attached to which place in the DOM. It reads the dependencies from the actual program flow.
Editorial note (July 2026): This post explains KnockoutJS as a historical forerunner of today’s fine-grained reactivity. I am not recommending that you build a new frontend on Knockout in 2026. What has remained interesting is the mechanism: capturing dependencies on read and updating only the affected places.
Knockout declaratively couples the DOM to a ViewModel through bindings such as text, value, foreach and click. Here I look one level deeper: How does Knockout notice that something has changed, and how does it figure out which parts of the UI are affected? The core of this mechanism is called observables and computed.
An observable is a function – not a property#
The first mental leap you have to make with Knockout is this: in KnockoutJS, an observable is not a property but a function. More precisely, a function that is getter and setter at the same time. If I call it without an argument, I read the value. If I call it with an argument, I write the value – and Knockout notifies everyone interested in that value.
var name = ko.observable('Bob');
name(); // read -> 'Bob'
name('Mary'); // write -> sets the value and notifies subscribers
name(); // read -> 'Mary'
That is the whole trick. No Object.defineProperty, no proxy, no compiler magic. Just a function that remembers who read it and who wants to be notified. Writing is chainable, by the way, because the setter returns the ViewModel:
viewModel.name('Mary').age(50);
For lists, there is a matching variant. A ko.observableArray behaves like an observable on read – arr() returns the underlying array – but it also comes with mutation methods that trigger tracking:
var todos = ko.observableArray([]);
todos(); // read -> the current array
todos.push({ title: 'Buy milk' });
todos.remove(someItem);
todos.removeAll();
The first pitfall is already lurking here, and I will come back to it later: these push, remove and splice methods are Knockout’s own wrappers. They are what triggers a notification. If you write todos().push(x) instead, you bypass them on the raw array, and Knockout notices nothing of the change.
Computed derives – and automatically tracks what it reads#
Now comes the really interesting part. You rarely want to just store a value and output it again. Most of the time you need derived values: the total of a shopping cart, the full name from first and last name, the number of open tasks. That is what ko.computed is for.
var firstName = ko.observable('Mike');
var lastName = ko.observable('Bild');
var fullName = ko.computed(function () {
return firstName() + ' ' + lastName();
});
fullName(); // 'Mike Bild'
firstName('Michael');
fullName(); // 'Michael Bild'
And here something happens that I looked at twice myself when I first encountered Knockout, because it is the linchpin of the whole model. Nowhere did I tell Knockout that fullName depends on firstName and lastName. I declared no dependency list. Knockout figured that out by itself.
How? When the evaluator function runs for the first time, Knockout observes which observables are actually read. At that moment, firstName() and lastName() register themselves, so to speak: “This computed is reading me right now.” Knockout then registers a subscription. The dependency graph thus emerges at runtime, purely through execution – nothing is declared. This is the fine-grained, automatic dependency tracking that defines Knockout.
The evaluator does not run just once. It is executed once immediately on creation, and after that again every time one of the dependencies it read changes. The second part is important: on every re-evaluation, Knockout determines the dependencies afresh. That allows dynamic dependencies behind conditions:
var showFullName = ko.observable(true);
var displayName = ko.computed(function () {
if (showFullName()) {
return firstName() + ' ' + lastName();
}
return firstName();
});
As long as showFullName is true, displayName depends on three observables. If it is false, lastName() is no longer read at all – and Knockout automatically removes this dependency again on the next run. A change to lastName then no longer triggers a re-evaluation. That is exactly what “dynamic” means: the graph adapts to the actual control flow.
Drawn as a graph, this relationship looks like this:
graph LR A[firstName<br/>observable] --> C[fullName<br/>computed] B[lastName<br/>observable] --> C C --> D[text binding<br/>DOM]
The arrows mean “is read by and notifies.” If firstName changes, the notification travels along the edge to fullName, which recalculates, and from there on to the text binding in the DOM. Only this one path becomes active. Nothing else in the tree is touched.
For the toolbox, this small trio is enough for now:
ko.observable(value)– a single reactive value, read withobs(), written withobs(newValue).ko.observableArray([...])– a reactive list with mutation methods such aspush,removeandsplicethat notify bindings.ko.computed(fn)– a derived value that automatically tracks which observables it reads and recalculates when they change.
From the ViewModel into the DOM: the todos app#
So this does not stay abstract, here is a small todos application. It shows all three building blocks working together.
function TodoViewModel() {
var self = this;
self.todos = ko.observableArray([]);
self.newTodo = ko.observable('');
self.remaining = ko.computed(function () {
return self.todos().filter(function (t) {
return !t.done();
}).length;
});
self.addTodo = function () {
self.todos.push({
title: self.newTodo(),
done: ko.observable(false)
});
self.newTodo('');
};
}
ko.applyBindings(new TodoViewModel());
A few things here are built this way on purpose. self.todos is an observableArray, self.newTodo a simple observable for the input field. self.remaining is a computed that counts the tasks still open. It reads self.todos() and, per entry, t.done() – which means it depends both on the list and on every single done observable. If you add a todo or check one off, remaining recalculates by itself.
Notice that every single todo gets its own done: ko.observable(false). Only this way is the done status reactive per entry. A plain done: false would be a dead value with nothing to observe.
The view declaratively couples the ViewModel to the DOM. Here is the relevant excerpt:
<input data-bind="value: newTodo" />
<button data-bind="click: addTodo">Add</button>
<ul data-bind="foreach: todos">
<li data-bind="text: title"></li>
</ul>
<span data-bind="text: remaining"></span> remaining
ko.applyBindings activates these connections once at startup. From then on, everything runs through tracking: when the user types into the field, the value binding updates newTodo. A click on the button calls addTodo, which changes the list via push. This change notifies the foreach binding (new list entry) and the computed remaining (recalculation), which in turn updates the text binding in the <span>. Each of these updates hits exactly the place that is affected.
Why targeted tracking is a different model#
At this point, it pays to draw the distinction that gives the whole thing its shape. There is a second, very widespread approach to the same problem: Virtual DOM diffing, as you know it from React, for example. There, on every change you build a new virtual tree, compare it with the old one and apply the difference to the real DOM. The framework does not know up front which data change affects which place in the DOM – it computes the difference afterward.
Knockout goes the opposite way. Through fine-grained tracking, it knows exactly, per observable, which computed and which bindings depend on it. It does not have to compare anything. When a value changes, Knockout simply follows the registered edges of the dependency graph and updates only the DOM places attached to them. No tree comparison, no re-rendering of subtrees that have not changed at all.
The sequence of a single change looks like this:
sequenceDiagram participant U as User participant O as observable participant C as computed participant D as DOM binding U->>O: obs(newValue) O->>C: notify subscriber C->>C: re-evaluate C->>D: targeted text update
Both models have their place, and I do not want to declare either one the winner. But once you have understood the difference at this point, you also understand why the two worlds feel so different. Knockout’s approach is immediately comprehensible, because you can almost see the graph in the code. The price for that is discipline: you have to work consistently with observables, or the graph breaks at some point.
Pitfalls from practice#
It is exactly this discipline where the graph tends to break, and at three recurring places. All three have cost me hours in my own projects, because they fail silently.
The classic is forgotten parentheses. An observable is a function. If you use it without parentheses, you are working with the function itself instead of its value:
// wrong: todo.done is the function itself, so always truthy
if (todo.done) {
// this branch ALWAYS runs
}
// correct: todo.done() reads the value
if (todo.done()) {
// ...
}
The bug is treacherous because it throws no error. A function is truthy, so the condition simply always comes out the same. You then search for a long time in the wrong place. Reading always takes parentheses, without exception.
The second pitfall is the native array methods. I hinted at it above:
// wrong: mutates the raw array without notification
todos().push(newItem);
// correct: KO wrapper, notifies dependent bindings
todos.push(newItem);
todos() returns the underlying JavaScript array. Its native push does change the content, but Knockout learns nothing about it – the foreach binding stays as it was. The KO wrapper todos.push, on the other hand, triggers tracking. The only difference is the parentheses before .push, which once again makes the bug unpleasantly subtle.
The third concerns the this context in computed. If the evaluator wants to access the ViewModel, this really has to point to the ViewModel:
function ViewModel() {
this.price = ko.observable(10);
this.count = ko.observable(3);
// wrong: this does not reliably point to the ViewModel here
this.total = ko.computed(function () {
return this.price() * this.count(); // this.price is undefined
});
}
Knockout calls the evaluator in a different context, so this does not point to the instance. There are two established ways out. Either you pass the context as a second argument:
this.total = ko.computed(function () {
return this.price() * this.count();
}, this); // second argument binds this
Or you use the self pattern I already used in the todos example:
function ViewModel() {
var self = this;
self.price = ko.observable(10);
self.count = ko.observable(3);
self.total = ko.computed(function () {
return self.price() * self.count();
});
}
In my projects I prefer the self pattern, because it works across the board – in event handlers and callbacks too, not just in computed. One pattern for everything is easier to remember than a special rule for each case.
In passing, it is worth mentioning ko.pureComputed, which has been available since KO 3.2. It behaves like a normal computed but “sleeps” as long as nobody subscribes to it, which saves recalculations for pure derivations without side effects. For getting started, ko.computed is enough; as soon as you notice that a purely deriving computed recalculates unnecessarily often, pureComputed is the obvious improvement.
Conclusion#
Once you have understood the core of KnockoutJS, you are basically holding just three building blocks: observables as get/set functions, observableArrays for reactive lists and computed for derived values. The real elegance lies between these building blocks: in automatic dependency tracking. Knockout observes at runtime which observables a computed reads, builds a dependency graph from that and, on every change, updates only the affected places – determined afresh on every run, so that dynamic dependencies behind conditions are mapped cleanly too.
This model deliberately runs counter to Virtual DOM diffing: instead of comparing trees, Knockout follows the edges it registered itself while reading. That makes the behavior immediately comprehensible, but it demands discipline – parentheses for reading, KO wrappers for mutating lists, the right this context in computed. Once these three reflexes are internalized, working with Knockout becomes surprisingly calm. You describe what a value depends on, and the framework takes care of the rest. This clarity is exactly why I still consider Knockout’s reactivity model one of the best entry points for understanding what really happens behind reactive UIs.
Further reading#
Revised and translated from German with the help of AI.