0

我需要在 ajax 请求(异步 ajax 请求)之后更新计算的 observable 中的 observable 值(过滤器),但是当我在计算中更新 observable 时,计算的 observable(filterChanged)依赖于这个 observable(过滤器),在计算中发生了无限循环?

如何在计算的可观察对象中更新依赖的可观察对象?

function vm(){
    var self = this;
    self.filter = ko.observable();
    self.isOpenFilter = ko.observable(false);

    self.result = ko.obseravableArray([]);

    self.filterChanged = ko.computed(function(){
            var data = {filter:self.filter(),isOpen:self.isOpenFilter()}


        $.ajax("/service",data,function(response){
            self.result(ko.mappings.fromJS(response.results);
            self.filter(response.filter);   // infinite loop
                    self.isOpenFilter(response.isOpen);
        });
    });
}
4

1 回答 1

1

I'm not sure why you're using ko.computed. Something like this makes more sense:

function vm() {
    var self = this;
    self.filter = ko.observable("default filter");
    self.result = ko.observableArray([]);

    self.updateFilter = function() {
        var filter = self.filter();

        $.ajax("/service",
               {filter:filter},
               function(response){
                   self.result(ko.mappings.fromJS(response.results));
                   self.filter(response.filter);
               });
    };
}

If you call updateFilter to get an update from the server, it will change the filter computed property and if your View is bound to that property it should update automatically.

For an example, see this jsfiddle.

于 2013-04-17T08:34:17.370 回答