0

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

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似乎在这里指的是正确的实例。有人可以指出我的问题吗?

4

2 回答 2

2

The cleanest solution is to use an anonymous function (to create a closure) rather than a plain object:

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

    // ...

Otherwise, "this" inside the function (that defines the computed) refers to whatever you're passing as the second parameter to ko.computed() - the value of the "this" there is the current context that "initializeViewModel" is executed in, so if you're calling that function as usual (i.e. initializeViewModel()), "this" will just be a reference to the global object and not to "listing_model" (as expected/intended).

The example in the manual differs from you're code: you're creating a plain object right away while in the manual everything is wrapped in a function. Calling that function with the "new" keyword creates a new object and sets the context ("this") to this object. That's why their code works.

于 2012-05-04T17:48:39.617 回答
0

好吧,this指的是匿名函数范围,其次this.property_type()是函数调用,您不能为其分配变量。

于 2012-05-04T17:32:07.227 回答