我正在开发一个在主视图模型中打包多个viewModel的UI。您可以看到以下结构:
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);
我收到了searchCriteriaViewModel未定义错误。我为什么要这个?为什么我不能访问这个变量,虽然我已经在上面的陈述中初始化了?
答案 0 :(得分:1)
在变量decalre时使用var
。当您错过var
关键字时,变量将被声明为全局变量。在您的情况下self
首先引用appViewModel
,但是当您创建commonVM
时,self
变量会被赋予不同的值,然后它在全局中具有不同的含义。
但是你有很多其他错误 - 没有将start_searching_visible
附加到此/ self,并且无法从实例访问它,从错误的视图模型调用start_searching_visible
等。
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);
我建议完成一些JavaScript(OOP)课程/教程。