【问题标题】:Knockout not updating UI after ViewModel is updated更新 ViewModel 后淘汰赛不更新 UI
【发布时间】:2013-07-06 00:29:55
【问题描述】:

我有一个绑定到我的 UI 的 ViewModel

<div class="editor-label-medium-bold">
    <div data-bind="text: 'Cancellation Amount'"></div>
</div>
<div class="editor-field-short">
    <div id="CancellationAmount" data-bind="text: CancellationAmount"></div>
</div>

当调用 ko.applyBindings(xxx) 时,会显示 CancellationAmount 的值。到目前为止一切顺利。

我有一个 JQueryUI 日期选择器,当日期更改时,我会得到一个更新的取消金额数字。这会返回正确的值。

$.ajax({
    dataType: "json",
    method: "GET",
    url: '@Url.Action(MVC.XYZ.ActionNames.GetCancellationAmount, MVC.XYZ.Name)',
    data: { date: mdl.CancelDate(), policyid: '@ViewBag.PolicyID' }
})
.done(function (response) {
    mdl.CancellationAmount = ko.observable(response);
    $('#CancellationAmount').val(response);
})
.fail(function (response) {
    alert('fail');
});

“完成”回调中的两行都没有更新 UI。我用 Chrome 和控制台对此进行了测试,mdl.CancellationAmount() 返回正确的数字,但 UI 不会让步。

我即将取消绑定该字段并使用 JQuery 手动更新它,就像我在“完成”回调的第二行尝试一样。我认为因为该字段是绑定的,所以淘汰赛会阻止 JQuery(可能是其他任何东西......)对其进行更新。

我可能应该提到这行代码:

mdl.CancellationAmount = ko.observable(mdl.AnnualPremium());

在初始加载时,我的服务器模型为 CancellationAmount 发送 null,因此我将另一个值复制到它,这是一个正十进制数字,但我解开它,所以不要认为这是问题所在。这一行就在 ko.applyBindings(xxx) 之前

有没有人见过这个问题,或者知道如何解决这个问题?

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    您以错误的方式将数据分配给mdl.CancellationAmount。它已经是可观察到的,因此您应该使用 () 在 done 函数中赋值。重写你的回调如下:

    .done(function (response) {
        mdl.CancellationAmount(response);
    })
    

    【讨论】:

    • 非常感谢 Artem,这是最后一块拼图!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2013-08-30
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多