当在闭包函数内声明时,ko.computed无法访问observable

时间:2014-12-16 00:34:41

标签: knockout.js closures computed-observable

我创建了以下模型,但我不明白为什么pureComputed observable ApprovalIconCSS 无法从其函数上下文访问Approved()observable。

function KOViewModel() {
    var self = this;
    self.IsAdding = ko.observable(false);
    self.IsEnabled = ko.observable(true);
    self.ApprovalType = ko.observable(0);

    var RowControl = function() {
        return {
            Approved: ko.observable(null),
            ApproverNotes: ko.observable(''),
            ApprovalIconCSS: ko.pureComputed(function() {
                if (this.Approved() == 0)
                    return 'glyphicon glyphicon-remove-circle';
                if (this.Approved() == 1)
                    return 'glyphicon glyphicon-ok-circle';
                if (this.Approved() == 2)
                    return 'glyphicon glyphicon-time';
                return '';
            }, this)
        };
    };

    self.RowControls = ko.observableArray([RowControl()]);
}

欣赏是否有人可以解释为什么上下文无法访问。干杯!

1 个答案:

答案 0 :(得分:1)

您需要使用RowControls调用new,并且需要将属性附加到this函数的RowControl对象,而不是返回其他对象。

var RowControl = function() {
    this.Approved = ko.observable(null);
    this.ApproverNotes = ko.observable('');
    this.ApprovalIconCSS = ko.pureComputed(function() {
        if (this.Approved() == 0)
            return 'glyphicon glyphicon-remove-circle';
        if (this.Approved() == 1)
            return 'glyphicon glyphicon-ok-circle';
        if (this.Approved() == 2)
            return 'glyphicon glyphicon-time';
        return '';
    }, this)
};

self.RowControls = ko.observableArray([new RowControl()]);

返回文字对象的问题是使用ko.pureComputed对象调用this,如果返回其他对象,而不是向this添加属性,则{ {1}}对象,this的结果(即具有" Approved"属性的对象)是两个不同的对象。