可以使用计算的 observable 来完成,如下所示(小提琴:http: //jsfiddle.net/MA8Mu/2/):
html:
showFullNotes: <input type="checkbox" data-bind="checked:showFullNotes" /><br />
<table>
<tbody data-bind="foreach:customers">
<tr>
<td>
<span data-bind="text:actualNotes"></span>
</td>
</tr>
</tbody>
</table>
js:
var Customer = function(notes, parent ){
var self = this;
self.notes = ko.observable(notes);
self.actualNotes = ko.computed(function() {
if (parent.showFullNotes()){
return self.notes();
} else {
return self.notes().substring(0,5) + "...";
}
}, self);
}
var VM = function(){
var self = this;
self.showFullNotes = ko.observable(false);
self.customers = ko.observableArray(
[new Customer("123456789", self),
new Customer("abcderfgh", self)]
);
}
var vm = new VM();
ko.applyBindings(vm);