【问题标题】:knockoutjs calling function which is defined in sub-viewModel from root-viewModel从 root-viewModel 的 sub-viewModel 中定义的 knockoutjs 调用函数
【发布时间】:2013-07-24 18:48:57
【问题描述】:

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

  • ViewModel-RootVM(页眉、页脚、常用功能...):
    • SubModelA(第 1 页 - 模板)
    • SubModelB(第 2 页 - 模板)

我想从页眉 (ViewModel-RootVM) 调用在第 2 页 (SubModelB) 上定义的函数 fnTest。如何从 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);

link to jsfiddle

【问题讨论】:

    标签: javascript knockout.js root subview


    【解决方案1】:

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

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

    请看这里:http://jsfiddle.net/LJBqp/

    【讨论】:

    • juhuhu,你让我很开心。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2015-03-04
    • 2011-05-30
    • 1970-01-01
    相关资源
    最近更新 更多