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?
fullName
is coded as a computed. Wouldn't the result be the same, if it had been coded as a normal function? – Kopans