0

当触发 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 数组,它会在每个函数调用中更改它的数据。视图(表)未使用其数据进行更新。

4

1 回答 1

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);
            };
        });
于 2013-02-14T13:47:17.373 回答