【问题标题】:Why is this knockout array not updating in the DOM?为什么这个淘汰赛数组没有在 DOM 中更新?
【发布时间】:2013-09-22 12:37:34
【问题描述】:

来自我的 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();
 };

interestservice.addInterest:

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 中。如果我调试,我会看到来自服务器的数据被添加到数组中,但由于某种原因视图的绑定没有被更新。知道发生了什么吗?

【问题讨论】:

    标签: knockout.js knockout-2.0


    【解决方案1】:

    从 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);
    };
    

    【讨论】:

    • 完美。这些括号杀死了我!感谢您的帮助
    • 有一些规则——在视图中,Knockout 已经为你解包了 observable(只要它是函数链上的最后一个)——即。 this().you().hey 当你想传递对象时使用 parans,当你想传递值时使用 ()。祝你好运
    猜你喜欢
    • 2017-05-11
    • 2013-05-01
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多