2013-02-14 149 views
0

我使用knockoutjs來更新我的Html視圖時,一個Javascript(信號)函數被激發。但是當調用producthub.client.showOnlineUser時,視圖不會更新。當我每次應用綁定時,表格都有多次相同的內容。我該如何更新knockoutjs中的視圖?Knockoutjs不更新查看

HTML:

<table id="usersTable"> 
    <thead> 
     <tr> 
      <th>Name</th> 
      <th>Mail</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: seats"> 
     <tr> 
      <td data-bind="text: NameFirst"></td> 
      <td data-bind="text: Mail"></td> 
     </tr> 
    </tbody> 
</table> 

的Javascript:

$(document).ready(function() { 
    var applied = false; 
    var model; 
    producthub.client.showOnlineUser = function (userOnlineOnUrl, msg1) { 
     function ReservationsViewModel() { 
      var self = this; 
      self.seats = ko.observableArray(userOnlineOnUrl); 
     } 

     model = new ReservationsViewModel(); 
     if (!applied) { 
      ko.applyBindings(model); 
      applied = true; 
     } 

    }; 
}); 

userOnlineOnUrl是JSON-數組,它改變了每個函數調用它的數據。視圖(表格)不隨其數據更新。

回答

1

儘量不要打電話模型每次只是功能更新

$(document).ready(function() { 
      var applied = false; 
      var model; 
      function ReservationsViewModel() { 
        var self = this; 
        self.seats = ko.observableArray(); 
       } 
      model = new ReservationsViewModel(); 
      ko.applyBindings(model); 
      applied = true; 

      producthub.client.showOnlineUser = function (userOnlineOnUrl, msg1) {     
       model = new ReservationsViewModel(); 
       //remove the previous data in array 
       model.seats.removeAll(); 
       //Add new data to array 
       model.seats(userOnlineOnUrl); 

       $('#onlineUsers').append(msg1); 
      }; 
     });