简体   繁体   中英

Knockoutjs does not update View

I use knockoutjs to update my Html view when an Javascript (Signalr) function is fired. But the view does not update when producthub.client.showOnlineUser is called. When i apply the binding everytime the table has same content multiple times. How can i just update the view in 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 is an JSON-Array which changes it's data on each function call. The view (table) is not updated with it's data.

try not to call model every time just update it with function

  $(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);
            };
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM