访问视图模型中定义的方法时遇到问题。
以下是视图模型定义:
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”中收到错误:uncaught typeerror:object [object object]没有方法'AddProducts'。
如何访问MainViewModel方法? View模型定义是否正确?以及如何初始化MainViewModel?
提前致谢。
答案 0 :(得分:3)
这里的问题在于您定义ViewModel
的方式。您正在定义属性和函数,而不会将它们附加到创建对象的实例,这就是为什么JS
看不到函数AddProducts
。
您应该像这样定义ViewModel
:
function MainViewModel() {
self = this;
self.productModel = new ProductMenu();
self.subMenuModel = new ProductSubMenu();
self.submenu2Model = new ProductSubMenu2();
self.propertyModel = new Properties();
self.AllProductsModel = ko.observableArray([]);
self.ReturnToFamilyProduct = ko.observable(true);
self.ShowSubMenu = ko.observable(false);
self.showSubMenu2 = ko.observable(false);
self.ShowBackBtnOnSubMenuClick = ko.observable(false);
self.IfDocumentsPresent = ko.observable(true);
//to add product to products array
self.AddProducts = function (name, subProductsMenu1, selectedMenu) {
self.AllProductsModel.push(new ProductMenu(name, subProductsMenu1, selectedMenu));
};
}
注意变量self
,它引用您创建的对象的实例
请检查此演示并观看控制台没有错误 jsfiddle demo