knockout.js和observable不更新,即使断点一步

时间:2013-11-18 04:29:31

标签: knockout.js

我有一个问题,即observable没有更新,即使我单步执行,即使我尝试手动更新它,它仍然保留相同的旧值。如果self.divisionId发生更改,则会运行计算的可观察self.divisionBracketsself.divisionBracketId(divisionBrackets[0].Id)运行并且具有与之前不同的值,但是当我退出时,self.divisionBracketId仍然具有相同的值?日志记录之前和之后显示相同的值,即使它使用不同的更新。

您可以查看链接here

 function Brackets() {

        var self = this;

        self.loaded = ko.observable(false);
        self.divisionId = ko.observable();
        self.divisionBracketId = ko.observable();
        self.divisions = ko.observableArray([]);
        self.brackets = [];

        self.divisionBrackets = ko.computed(function () {
            var divisionId = self.divisionId();
        self.divisionBracketId(null);

        var divisionBrackets = ko.utils.arrayFilter(self.brackets, function(bracket) {
            return bracket.DivisionId == divisionId;
        });

        console.log("Division Brackets Count: " + divisionBrackets.length);

        if (divisionBrackets.length > 0) {
            console.log("Selected Division Bracket ID: " + divisionBrackets[0].Id);
            console.log("Before Update: " + self.divisionBracketId());
            self.divisionBracketId(divisionBrackets[0].Id);
            console.log("After Update: " + self.divisionBracketId());
        }

        return divisionBrackets;
        });

        self.search = function() {
            self.loaded(true);
            resize();
        };

        self.divisionBracketId.subscribe(function(_) {
            app.showProgress();
        });

        self.init = function (options) {

            self.divisions(options.divisions);
            self.brackets = options.brackets;

            app.applyBindings();
        };

    };

2 个答案:

答案 0 :(得分:0)

为了使计算的observable更新,必须在函数内的某处读取另一个observable。如果是,则计算的observable将依赖于该observable。

虽然您在过滤器函数中读取了divisionId,但无法保证该函数被调用。在初始化时,它永远不会因为self.brackets最初是一个空数组。

要解决此问题,只需读取过滤器功能之外的ID即可。然后,计算将在divisionId更改时随时更新。另外,考虑使brackets也可观察,如果该数组发生变化,它仍会更新。

self.divisionBrackets = ko.computed(function () {
    self.divisionBracketId(null);
    var divisionId = self.divisionId(); 
    var divisionBrackets = ko.utils.arrayFilter(self.brackets, function(bracket) {
        return bracket.DivisionId == divisionId;
    });

    if(divisionBrackets.length > 0)
        self.divisionBracketId(divisionBrackets[0].Id);

    return divisionBrackets;
});

答案 1 :(得分:0)

我通过像杰夫所说的订阅来修复它。

self.divisionBrackets = ko.computed(function () {
            var divisionId = self.divisionId();

            return ko.utils.arrayFilter(self.brackets, function(bracket) {
                return bracket.DivisionId == divisionId;
            });
        });

        self.divisionBrackets.subscribe(function (divisionBrackets) {
            if (divisionBrackets.length > 0) {
                self.divisionBracketId(divisionBrackets[0].Id);
            }
        });