knockoutjs从根视图模型调用子视图模型中定义的函数

knockoutjs calling function which is defined in sub-viewModel from root-viewModel

本文关键字:视图 模型 定义 函数 调用 knockoutjs      更新时间:2023-09-26

我有一个结构为的单页应用程序

  • ViewModel RootVM(页眉、页脚、通用函数等):
    • SubModelA(第1页-模板)
    • SubModelB(第2页-模板)

我想从页头(ViewModel RootVM)调用在第2页(SubModelB)上定义的函数fnTest。如何从ViewModel和HTML中做到这一点?这可能吗?如果是,请帮我举个例子。我在这里有点迷路了。

我使用的是knockoutjsv2.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);

jsfiddle 的链接

这不起作用,因为fnTest()不是在"视图"中声明的,而是在其"数据"中声明。它使用:

self.views()[1].data.fnTest()

请参见此处:http://jsfiddle.net/LJBqp/