更新在计算的observable中依赖observable

时间:2013-04-17 08:25:34

标签: javascript knockout.js

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

如何在计算的observable中更新depended 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);
        });
    });
}

1 个答案:

答案 0 :(得分:1)

我不确定你为什么要使用ko.computed。这样的事情更有意义:

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

如果您致电updateFilter以从服务器获取更新,它将更改filter计算属性,如果您的View绑定到该属性,则应自动更新。

有关示例,请参阅this jsfiddle