【问题标题】:Knockout JS with jQuery getJSON使用 jQuery getJSON 淘汰 JS
【发布时间】:2012-09-20 23:38:44
【问题描述】:

我很困惑为什么当我将元素添加到可观察数组时我的 UI 没有更新。我意识到我没有对我的 AJAX getJSON 调用数据做任何事情,但是当我向其中添加元素时,淘汰赛不应该更新我的可观察数组吗?它显示“test1”很好但不是“test2”。没有 PHP 或 JS 错误,它根本不会更新 UI。

HTML:

<div class="allScheduleWrap" data-bind="foreach: schedules">
    <div class="schedule">
        <div class="downTime" data-bind="text:downTime"></div>
    </div>
</div>

JS:

$(document).ready(function() {
    var AllSchedules = [];
    AllSchedules.push({downTime: "test1"});

    function SchedulesViewModel() {
        var self = this;
        self.schedules = ko.observableArray(AllSchedules);
    }

    ko.applyBindings(new SchedulesViewModel());

    $.getJSON("GetSchedules.php", function(data) {          
        AllSchedules.push({downTime: "test2"}); //does NOT update the UI

    });
});

【问题讨论】:

    标签: php jquery ajax knockout.js


    【解决方案1】:

    您应该将数据推送到可观察数组(shedules)而不是 AllSchedules 变量。用这个替换你的代码应该使它工作:

    var model = new SchedulesViewModel()
    ko.applyBindings(model);
    
    $.getJSON("GetSchedules.php", function(data) {          
        model.schedules.push({downTime: "test2"}); 
    
    });
    

    【讨论】:

      【解决方案2】:

      因为AllSchedules数组不是observable数组,所以改为observableArray

      【讨论】:

      • 你错过了这条线吗? self.schedules = ko.observableArray(AllSchedules);
      猜你喜欢
      • 2013-04-09
      • 2013-02-09
      • 2012-10-03
      • 2012-10-18
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      相关资源
      最近更新 更多