Given the following HTML/JS (http://jsfiddle.net/mgs_jsfiddle/gUhm2/)
<div data-bind="foreach: users">
<p data-bind="click: $root.onClick">
<span data-bind="text: id"></span>
<span data-bind="text: firstName"></span>
<span data-bind="text: $root.isSelected($data)"></span>
</p>
</div>
$(function() {
function ViewModel() {
var self = this;
self.users = [
{ id: 1, firstName: "Bob" },
{ id: 2, firstName: "David" },
{ id: 3, firstName: "Walter" }
];
self.selectedId = ko.observable(1);
self.isSelected = function(user) {
return user.id === self.selectedId() ? "YES" : "NO";
};
self.onClick = function(user) {
self.selectedId(user.id);
}
};
ko.applyBindings(new ViewModel());
});
A list is shown. By clicking a row, the row's id is stored into selectedId
.
I do not understand, why the function isSelected
is re-evaluated, when the selectedId
is changed. After all, this is no computed. Why is it re-evaluated anyway?
That happens because
isSelected()
method accessesselectedId
property (which isobservable
). Consider this:HTML
JS
Fiddle.
As you see, the only difference between those functions is that the first one does check the value of a model property defined as
ko.observable
. So each timeself.selectedId
is changed, this function is notified about it (which effectively means its rerun).Note that if you drop the corresponding
data-bind
part, this method won't be run in the view initialization phase, thus failing to register as a proper observer.The second method, though invoked in the initialization phase too, doesn't attempt to check
selectedId
value - so it's not registered as this value's observer, and it's not invoked subsequently.