给定以下 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());
});
显示一个列表。通过单击一行,该行的 id 存储到selectedId
.
我不明白,为什么在更改isSelected
时重新评估功能。selectedId
毕竟,这不是计算出来的。为什么还要重新评估?