followed the docs, tried my own and bump into some problem.
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;
}
The statement return this.property_type() == 'condominium'; causes an exception object <object> has no method property_type(). I think this might be a scoping issue, but this seems to be referring to the right instance here. Can someone please point out my problem?
The cleanest solution is to use an anonymous function (to create a closure) rather than a plain object:
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.