2013-04-10 30 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