How to use knockout.js data binding when ajax request periodically auto refreshes?

Viewed 20148

In my application I periodically makes ajax call once every 5 seconds to get new update from server.

My ajax data from server is JSON array that looks like: [ { "foo": "valx", "bar": "valy"

}, { "foo": "valw", "bar": "valz" } ]

My ajax code is:

(function update() {

    $.ajax({
        type : 'GET',
        url : url,
        data : {

        },
        dataType : "json",
        global : false,
        success : function(content, textStatus, jqXHR) {
        myViewModel = content;
        ko.applyBindings(myViewModel);

        },
        complete: function() {

         setTimeout(update, 5000);
          },

        error: function( xhr, textStatus ) {

            }
    });
    })();                       

My HTML is:

<tbody data-bind="foreach: myViewModel">
                        <tr>
                            <td data-bind="text: foo"></td>
                            <td data-bind="text: bar"></td>
                        </tr>
                    </tbody>

But this does not work and I get error after first ajax call: You cannot apply bindings multiple times to the same element.

1 Answers
Related