2013-04-10 32 views
1

我試圖使用AJAX JSON請求自動刷新頁面上顯示的數據與服務器的最新值。試圖從knockoutjs自動刷新JSON

這裏是我的javascript:

function ExampleViewModel() { 
    var self = this; 
    self.ExampleData = ko.observableArray([]); 

    $.getJSON("/JSONExample", function (allData) { 
     var mappeddata = $.map(allData, function (item){ 
      return new DataItem(item) 
     }); 
     self.ExampleData(mappeddata); 
    }) 

    window.setTimeout(ExampleViewModel, 5000); 
} 

function DataItem(data) { 
    //console.log(data); 
    this.Name = ko.observable(data.Name); 
    this.Price = ko.observable(data.Price); 
} 

ko.applyBindings(new ExampleViewModel()); 

這是我的HTML:

<div id="knockout"> 
    <table> 
     <thead> 
      <tr> 
       <th>Name</th><th>Price</th> 
      </tr> 
     </thead> 
     <tbody data-bind="foreach: ExampleData"> 
      <tr> 
       <td data-bind="text: Name"></td> 
       <td data-bind="text: Price"></td> 
      </tr>  
     </tbody> 
    </table> 
</div> 

它正確地拉動了JSON並正確顯示在第一次迭代。輸出看起來是這樣的:

Name  Price 
Item1  $150.00 
Item2  $20.00 
Item3  $99.99 

在隨後的迭代,它拉的JSON,如果我更改服務器上的數據(比如,如果我更改項目1的價格$ 200.00),它得到的最新數據在JSON中。但是,UI不刷新 - 它只是顯示初始數據,直到我刷新整個頁面。

我相信我誤解了一些關於knockout綁定是如何工作的,或者我的方法對於我正在嘗試做的事情完全沒有辦法。

回答

4

結帳demo

你必須保持ExampleViewModel的實例,並使用該實例的一切。

function getRandomData() { 
    return [{ 
     "Name": "Apple", 
     "Price": (Math.random()*10)+1}, 
    { 
     "Name": "Orange", 
     "Price":(Math.random()*10)+1}, 
    { 
     "Name": "Banana", 
     "Price": (Math.random()*10)+1}, 
    { 
     "Name": "Melon", 
     "Price": (Math.random()*10)+1}]; 
} 

function ExampleViewModel() { 
    var self = this; 
    self.ExampleData = ko.observableArray([]);  
    self.update = function() { 
      $.ajax("/echo/json/", { 
      data: { 
       json: ko.toJSON(getRandomData()) 
      }, 
      type: "POST", 
      dataType: 'json', 
      success: function(allData) {   
       var mappeddata = $.map(allData, function (item){ 
        return new DataItem(item) 
       }); 
       self.ExampleData(mappeddata); 
      } 
     }); 
    } 
} 

function DataItem(data) { 
    //console.log(data); 
    this.Name = ko.observable(data.Name); 
    this.Price = ko.observable(data.Price); 
} 

var exampleViewModel = new ExampleViewModel(); 
window.setInterval(exampleViewModel.update,1000); 
ko.applyBindings(exampleViewModel); 

另外注意的直接使用的setTimeout &間隔的回調函數內這個關鍵字的。改用'self'。結帳this problem part

+0

啊現在我明白我做錯了什麼。這工作就像一個魅力,謝謝! – Eric 2013-04-10 20:38:37