我正在使用knockoutjs开发我的第一个SPA。我的情况是:
我创建了一个简单的fiddle.js(see here)。它显示我的问题比1000字更好。为简单起见,我省略了分页逻辑,但由于各种原因,我的列表中的observable需要计算。
VIEWMODE。
var ViewModel = function() {
var self = this;
self.selectedItem = ko.observable();
self.items = ko.observableArray([
{
name: "Item A",
price: "12.99"
},
{
name: "Item B",
price: "13.99"
},
{
name: "Item C",
price: "90.99"
}]);
self.paginated = ko.computed(function() {
// This is where I do some pagination and filtering to the content
// It's left out here for simplicity. The binding for the list needs
// to be a computed though.
return self.items();
});
self.selectItem = function(item) {
self.selectedItem(item);
};
self.save = function(item) {
// Sending data to web api...
// After the saving, the displaying list does not update to reflect the changes
// I have made. However, switching entries and checking the changed item shows
// that my changes have been saved and are stored in the observable.
}
};
ko.applyBindings(new ViewModel());
查看
<!-- ko foreach: paginated -->
<a href="#" data-bind="text: name, click: $parent.selectItem"></a><br />
<!-- /ko -->
<br />
<br />
<div data-bind="visible: selectedItem">
<!-- ko with: selectedItem -->
<form>
<input type="text" data-bind="value: name" />
<input type="text" data-bind="value: price" />
<br />
<button type="button" data-bind="click: $parent.save">Save</button>
</form>
<!-- /ko -->
</div>
我希望你能帮助我,我不想为了性能和速度而从服务器重新加载所有数据。
答案 0 :(得分:2)
您必须在数组的可观察属性中创建对象的属性,以反映对UI的更改。
self.items = ko.observableArray([
{
name: ko.observable("Item A"),
price: ko.observable("12.99")
},
{
name: ko.observable("Item B"),
price: ko.observable("13.99")
},
{
name: ko.observable("Item C"),
price: ko.observable("90.99")
}]);