ObservableArray绑定无法更新

时间:2015-11-25 12:49:10

标签: javascript jquery knockout.js

修改: JSFiddle with comments

我正在使用knockoutjs开发我的第一个SPA。我的情况是:

  • 我有一个项目列表,用户可以从中选择项目
  • 选择项目后,用户可以对所选项目进行更改
  • 确认更改后,SPA会将更新的数据发送到Web api
  • 但是,显示所有条目的列表并不反映对项目所做的更新

我创建了一个简单的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>

我希望你能帮助我,我不想为了性能和速度而从服务器重新加载所有数据。

1 个答案:

答案 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")
}]);