关于淘汰赛.js和范围的菜鸟问题

noob issue about knockout.js and scope

本文关键字:菜鸟 问题 范围 淘汰赛 js      更新时间:2023-09-26

遵循文档,尝试了我自己的文档并遇到了一些问题。

initializeViewModel = function(){
    var listing_model = {
        sale_rent: ko.observable( jQuery('#id_sale_rent')),
        property_type: ko.observable( jQuery('#id_property_type').val()),
        address: ko.observable( jQuery('#id_address')),
        is_condo: ko.computed(function(){
            return this.property_type() == 'condominium';
        }, this)
    };

    listing_model.district = ko.computed(function(){
        return this.district() || this.property_type();
    }, listing_model);
    return listing_model;
}

语句return this.property_type() == 'condominium';导致异常object <object> has no method property_type()。我认为这可能是一个范围界定问题,但this似乎在这里指的是正确的实例。有人可以指出我的问题吗?

最干净的解决方案是使用匿名函数(创建闭包)而不是普通对象:

initializeViewModel = function(){
    var listing_model = new function() {
        // Close-in a reference to this object
        var self = this;
        self.sale_rent = ko.observable( jQuery('#id_sale_rent') );
        self.property_type = ko.observable( jQuery('#id_property_type').val() );
        self.address = ko.observable( jQuery('#id_address') );
        self.is_condo = ko.computed(function() {
            return (self.property_type() == 'condominium');
        });
    }();
    // ...

否则,函数(定义计算)中的"this"是指您作为第二个参数传递给ko.computed()的任何内容 - "this"的值是执行"initializeViewModel"的当前上下文,因此如果您像往常一样调用该函数(即 initializeViewModel() ),"this"将只是对全局对象的引用,而不是对"listing_model"的引用(如预期/预期的那样)。

手册中

的示例与您的代码不同:您立即创建一个普通对象,而在手册中,所有内容都包装在一个函数中。使用"new"关键字调用该函数会创建一个新对象,并将上下文("this")设置为该对象。这就是他们的代码工作的原因。

好吧,this指的是匿名函数作用域,其次this.property_type()是一个函数调用,你不能为其分配变量。