访问视图模型内部定义的方法时遇到问题。
以下是视图模型定义:
ProductMenu = function (name, subProductsMenu1, selectedMenu) {
name = ko.observable(name);
submenu = ko.observableArray(subProductsMenu1);
selectedProductName = ko.observable();
};
ProductSubMenu = function () {
submenuName = ko.observable();
submenu2 = ko.observableArray([]);
selectedSubMenuName = ko.observable();
};
ProductSubMenu2 = function () {
submenu2Name = ko.observable();
properties = ko.observableArray([]);
selectedSubMenu2Name = ko.observable();
};
Properties = function () {
productName = ko.observable();
shortDesc = ko.observable();
longDesc = ko.observable();
additionalDocs = ko.observableArray([]);
};
var MainViewModel = function () {
productModel = new ProductMenu();
subMenuModel = new ProductSubMenu();
submenu2Model = new ProductSubMenu2();
propertyModel = new Properties();
AllProductsModel = ko.observableArray([]);
ReturnToFamilyProduct = ko.observable(true);
ShowSubMenu = ko.observable(false);
showSubMenu2 = ko.observable(false);
ShowBackBtnOnSubMenuClick = ko.observable(false);
IfDocumentsPresent = ko.observable(true);
//to add product to products array
AddProducts = function (name, subProductsMenu1, selectedMenu) {
this.AllProductsModel.push(new ProductMenu(name, subProductsMenu1, selectedMenu));
};
};
在 $(document).ready 函数中,我试图访问视图模型方法,代码如下所示:
var VM;
$(document).ready(function () {
VM = new MainViewModel();
ko.applyBindings(VM);
FetchProductFamiliesForProductsKO();
});
function FetchProductFamiliesForProductsKO() {
$.getJSON(GetPath('/FetchProduct'), {}, function (data) {
for (var i = 0; i < data.length; i = i + 1) {
var family = data[i];
VM.AddProducts(family, null, family);
}
}).error(function () {
console.log("Error occured");
});enter code here
};
我在函数“FetchProductFamiliesForProductsKO”中收到错误:未捕获的类型错误:对象 [对象对象] 没有方法“添加产品”。
如何访问 MainViewModel 方法?视图模型定义是否正确?以及如何初始化 MainViewModel?
提前致谢。