Knockoutjs不会更新View

时间:2013-02-14 13:38:10

标签: javascript html knockout.js signalr

当触发Javascript(Signalr)函数时,我使用knockoutjs来更新我的Html视图。但是在调用producthub.client.showOnlineUser时视图不会更新。每当表格具有多次相同的内容时,我都会应用绑定。我怎样才能更新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 个答案:

答案 0 :(得分: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);
            };
        });