0

来自我的 viewModel 的 JS:

 self.newInterests = ko.observableArray();

 self.saveNewInterest = function () {
    // construct data and send to server
    var payload = {
        // data defined here
    };
    var appendInterest = function(newInterest) {
        self.newInterests().push(newInterest);
    };
    interestservice().addInterest(payload, appendInterest);
    self.closeModal();
 };

兴趣服务.add兴趣:

var addInterest = function (payload, callback) {
    loadAnimate();
    var options = {
        url: apiEndpoint + 'interest',
        type: 'POST',
        dataType: 'json',
        data: payload,
        xhrFields: {
            withCredentials: true
        }
    };
    return $.ajax(options)
        .done(function (response) {
            toastr.success("Interest Added", "Success");
            callback(response);
        })
        .fail(function (msg) {
            toastr.error("Could not add interest.", "Error");
        }).complete(function () {
            loadComplete();
        });
};

在我看来:

<h3 data-bind="text: newInterests().length"></h3>
<div data-bind="foreach: newInterests()">
    <p>new interest!</p>
</div>

如果我用数据初始化 newInterests() 数组,它会显示在 DOM 中。如果我调试,我会看到来自服务器的数据被添加到数组中,但由于某种原因视图的绑定没有被更新。知道发生了什么吗?

4

1 回答 1

2

从 newInterests 中删除 () ,它将正确更新。

<h3 data-bind="text: newInterests().length"></h3>
<div data-bind="foreach: newInterests">
    <p>new interest!</p>
</div>

此外,当您推送一个值时,您不需要先获取它 -

var appendInterest = function(newInterest) {
    self.newInterests.push(newInterest);
};
于 2013-09-22T04:30:33.193 回答