javascript ajax请求定期自动刷新时如何使用knockout.js数据绑定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20483599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:36:08  来源:igfitidea点击:

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

javascriptjqueryajaxknockout.js

提问by rjc

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

在我的应用程序中,我每隔 5 秒定期调用一次 ajax 以从服务器获取新更新。

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

我来自服务器的 ajax 数据是 JSON 数组,看起来像: [ { "foo": "valx", "bar": "valy"

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

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

My ajax code is:

我的ajax代码是:

(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:

我的 HTML 是:

<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.

但这不起作用,并且在第一次 ajax 调用后出现错误:您不能多次将绑定应用到同一个元素。

回答by Justin Helgerson

You're close. You only call applyBindingsonce. Instead what you should be doing is setting an observableproperty on your view model.

你很接近。你只调用applyBindings一次。相反,您应该做的是observable在您的视图模型上设置一个属性。

Here is how you would setup your view model:

以下是设置视图模型的方法:

function ViewModel() {
    var self = this;

    self.data = ko.observableArray();
};

var viewModel = new ViewModel();

ko.applyBindings(viewModel);

Then when you have new data (e.g. in your ajaxcall):

然后当您有新数据时(例如在您的ajax通话中):

$.ajax({
    success : function(content, textStatus, jqXHR) {
        viewModel.data(content);
    }
});

Note: You could set the data a few different ways. If you want your timed event outside the view model then you can use the view model instance (in my example, viewModel) to access the properties and update them. You could place the timed event within your view model if you want and then just call self.data(content)(or something similar).

注意:您可以通过几种不同的方式设置数据。如果您希望在视图模型之外设置定时事件,那么您可以使用视图模型实例(在我的示例中viewModel)来访问属性并更新它们。如果需要,您可以将定时事件放置在您的视图模型中,然后只需调用self.data(content)(或类似的东西)。