我有一个单页应用程序,其结构:
- ViewModel-RootVM(页眉、页脚、常用功能……):
- SubModelA(第 1 页 - 模板)
- SubModelB(第 2 页 - 模板)
我想调用一个函数 fnTest,它是在页眉 (ViewModel-RootVM) 的第 2 页 (SubModelB) 上定义的。我如何从 ViewModel 和 HTML 中做到这一点?这可能吗?如果是这样,请帮我举个例子。我在这里有点迷失。
我正在使用 knockoutjs v2.2.1 和 jQuery v1.9.1
ViewModel(您可以在 jsfiddle 中查看其余代码,链接如下)
var View = function(title, templateName, data) {
var self = this;
self.title = title;
self.templateName = templateName;
self.data = data;
self.myPostProcessingLogic = function(element1, index1, data1) {
console.log('post processing');
};
};
var SubModelA = function(root) {
var self = this;
self.items = ko.observableArray([
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" }
]);
};
var SubModelB = function(root) {
var self = this;
self.firstName = ko.observable("Bob");
self.lastName = ko.observable("Smith");
self.fnTest = function() {
alert('calling function from subModelB');
};
self.fnSubModelB = function() {
root.allert('calling function allert from root');
};
};
var ViewModel = function() {
var self = this;
self.views = ko.observableArray([
new View("one", "oneTmpl", new SubModelA(self)),
new View("two", "twoTmpl", new SubModelB(self))
]);
// default open page 'two'
self.selectedView = ko.observable(self.views()[1]);
self.allert = function() {
alert('alert from rootVM');
};
self.allert2 = function() {
// how can I call function 'fnTest' which is defined in SubModelB
self.views()[1].fnTest(); // this is not working
};
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
最佳答案
这不起作用,因为 fnTest() 不是在“ View ”中声明的,而是在其“数据”中声明的。它的工作原理是:
self.views()[1].data.fnTest()
关于javascript - knockoutjs 从 root-viewModel 调用子 viewModel 中定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17831617/