如何在其自己的验证扩展器中调用可观察的 属性?

How do I call an observable property within its own validation extender?

我正在尝试使用 ASP MVC4 中的淘汰框架创建一个国家/地区下拉列表。验证要求相当简单——在验证控件之前必须选择一个国家/地区。视图模型中的相关代码如下:

function viewModel(model) {
    var _self = this;

    // Various guff
    _self.ConfirmationOption = ko.observable(model.ConfirmationOption).extend({ required: { message: _self.mdata.requiredMessage } }); //mdata is part of the guff

    _self.CountryOfPractice = ko.observable(model.CountryOfPractice).extend({
        required: {
            message: "You must select a country",
            onlyIf: function () { return (_self.ConfirmationOption() === '4' && (_self.CountryOfPractice() === null || _self.CountryOfPractice() === undefined)); }
        }
    });

    // Assorted other guff
}

当我尝试 运行 时,Firebug 告诉我在尝试解析时发生错误,显示:

TypeError: _self.CountryOfPractice() is not a function.

我对 knockout 的有限理解是声明为 ko.observable 的属性严格来说不是 JS 属性,必须作为函数访问才能获得它们的当前值。在大多数其他代码区域,这通常工作正常。我尝试访问验证器扩展中的值的原因是为了确保已做出选择。

我可以在调试器中看到 CountryOfPractice 还不是 _self 的一部分,所以我可以看出错误是如何发生的。我尝试将测试分解到另一个事先声明的函数中,但该函数随后失败,因为它还没有看到 CountryOfPractice(),如果我将它放在这个方法之后,它会失败,因为 CountryOfPractice() 的扩展器还没有还看到我的验证方法...

我需要使用什么模式才能使该功能正常工作?

解决方案是在新的一行调用扩展函数 - 谁能解释为什么?

_self.CountryOfPractice = ko.observable(model.CountryOfPractice);

_self.CountryOfPractice.extend({
    required: {
        message: "You must select a country",
        onlyIf: function () { return (_self.ConfirmationOption() === '4' && (_self.CountryOfPractice() === null || _self.CountryOfPractice() === undefined)); }
    }