Grigoris
Grigoris

Reputation: 149

Knockout multiple view models - undefined

I am developing a UI that has multiple viewModels packed in a master view model. You can see the structure below:

function commonVM() {
   self = this;

   //initialize observable variables
   self.start_searching_visible = ko.observable(true); //start searching panel visible    
};

function searchCriteriaVM() {
   self = this;

   self.window_location = ko.observable("#/");
   self.company_search_criteria_visible = ko.observable(true);    
}

appViewModel = function () { 
   self = this;

   //False if the view has already been initialized
   isInitialized = false;
   self.commonViewModel = new commonVM();
   self.searchCriteriaViewModel = new searchCriteriaVM();     
   self.commonViewModel.start_searching_visible();     
}

var test = new appViewModel();
ko.applyBindings(test);

I am getting a searchCriteriaViewModel undefined error. Why am i getting this? Why can i not access this variable although i have initialized in the above statement?

Upvotes: 1

Views: 57

Answers (1)

Viktor Bahtev
Viktor Bahtev

Reputation: 4908

Use var when you decalre variable. When you miss the var keyword, the variables are declared as global. In your case self first refer to appViewModel but when you create commonVM, the self variable is assigned with different value and then it has a different meaning globally.

However you got so many other errors - not attaching start_searching_visible to this/self and it can not be accessed from instances, calling start_searching_visible from wrong view model etc..

function commonVM() {
    var self = this;

    //initialize observable variables
    self.start_searching_visible = ko.observable(true); //start searching panel visible    
};

function searchCriteriaVM() {
    var self = this;

    self.window_location = ko.observable("#/");
    self.company_search_criteria_visible = ko.observable(true);
}

appViewModel = function() {
    var self = this;

    //False if the view has already been initialized
    self.isInitialized = false;
    self.commonViewModel = new commonVM();
    self.searchCriteriaViewModel = new searchCriteriaVM();
    self.commonViewModel.start_searching_visible();
    // self.searchCriteriaViewModel.start_searching_visible();     
}

var test = new appViewModel();
ko.applyBindings(test);

I would recommend to complete some JavaScript (OOP) course/tutorial.

Upvotes: 1

Related Questions