2012-09-20 41 views
0

我很困惑,爲什麼我向可觀察數組添加元素時未更新UI。我意識到我沒有對我的AJAX getJSON調用數據做任何事情,但是當我向它添加元素時不應該更新我的可觀察數組?它顯示「test1」正常,但不顯示「test2」。沒有PHP或JS錯誤,它只是不更新​​UI。使用jQuery getJSON敲除JS

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 

    }); 
}); 

回答

1

您應該將數據推到觀察的陣列(shedules)而不是AllSchedules變量。用這個替換你的代碼應該使它工作:

var model = new SchedulesViewModel() 
ko.applyBindings(model); 

$.getJSON("GetSchedules.php", function(data) {   
    model.schedules.push({downTime: "test2"}); 

}); 
+0

謝謝!我覺得很愚蠢。嘿 – Buchannon

0

因爲AllSchedules陣列是無法觀測陣列,將其更改爲observableArray

+0

你錯過了這條線嗎? self.schedules = ko.observableArray(AllSchedules); – Buchannon