amaik
amaik

Reputation: 162

KnockoutJs Computed - 'Is not a function'

Essentially i've got the following code-snippet in JS :

var pgViewModel = { 
    inited : false,
    username : ko.observable("", {persist: "login.username"}),
    password : ko.observable("", {persist: "login.password"}),
    vehicles : ko.observableArray(),    
    selectedVehicle : ko.observable(null, {persist: "login.vehicle"}),
    tirepressure : ko.computed(function(){
        var selecV = this.selectedVehicle();
        return selecV.tirepressure_vl + '/' + selecV.tirepressure_vr + '/'     +          selecV.tirepressure_hl + '/' + slecV.tirepressure_hr + 'bar';
    },this),

Whilst trying to load the page i get the error : 'this.selectedVehicle() is not a function'. Occurs this problem because the pgViewModel is not ready when the function is parsed? Is there a possible solution. I'm sorry but i don't understand the problem here in every detail. thanks.

Upvotes: 0

Views: 1740

Answers (2)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

Problem you're getting is related to context and this value at invocation time. It is highly recommended to avoid direct this usage in knockout view models. Instead create additional self field which will be initialized on object creation.

var self = this;
...
tirepressure : ko.computed(function(){
        var selecV = self.selectedVehicle();

Seems like you've messed up something with your ViewModel without full code there is no way to find root cause. I've updated it a bit and everything seems working fine:

function pgViewModel() {
    var self = this;    
    self.inited = false;
    self.username = ko.observable("", {persist: "login.username"});
    self.password = ko.observable("", {persist: "login.password"});
    self.vehicles = ko.observableArray();
    self.selectedVehicle = ko.observable(null, { persist: "login.vehicle"});
    self.tirepressure = ko.computed(function() {
        var selecV = self.selectedVehicle();
        return selecV.tirepressure_vl + '/' + selecV.tirepressure_vr + '/' + selecV.tirepressure_hl + '/' + slecV.tirepressure_hr + 'bar';
    }, self);
};

ko.applyBindings(new pgViewModel()); 

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82241

You have type,It should be:

 this.selectedVehicle()//not this.selecttedVehicle()

Upvotes: 0

Related Questions