这是我发现的一个小提琴,它有一种有趣的方法,看起来与您想要的相似。
http://jsfiddle.net/up8rB/
var items = [{
Id: 1,
Text: 'First item'
}, {
Id: 2,
Text: 'Second item'
}];
var observableItems = [
new ItemViewModel(1, "First item"),
new ItemViewModel(2, "Second item")
];
function ItemViewModel(id, text){
var self = this;
self.Id = ko.observable(id);
self.Text = ko.observable(text);
}
var viewModel = function (items) {
var self = this;
self.items = ko.observableArray(items);
self.selectedItemId = ko.observable();
self.item = ko.observable();
self.selectItem = function (item) {
for (var i = 0; i < self.items().length; i++) {
if (self.items()[i].Id() === self.selectedItemId()) {
self.item(self.items()[i]);
break;
}
}
};
};
ko.applyBindings(new viewModel(observableItems));