1
我有结构的单页应用:knockoutjs调用函数在子视图模型从根视图模型定义
- 视图模型-RootVM(页面页眉,页脚,常用功能,...):
- SubModelA(第1页 - 模板)
- SubModelB(第2页 - 模板)
我想调用从页头(ViewModel-RootVM)在页面2(SubModelB)上定义的函数fnTest。我怎么能从ViewModel和HTML做到这一点?这甚至有可能吗?如果是这样,请以示例帮助我。我有点迷失在这里。
我使用knockoutjs V2.2.1和jQuery v1.9.1的
视图模型(你可以看到的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);
juhuhu,你只要让我很快乐。谢谢! – grajsek