0

我正在使用 ASP.NET MVC、Knockout、nav.js 等构建单页应用程序,

两个视图模型:

  1. 父视图模型;
  2. 子视图模型;

FatherViewModel 拥有所有 Navigation 方法,FatherViewModel 拥有 SonViewModel 的实例,

问:如何从 SonViewModel 访问那些 Navigation 方法?

FatherViewModel = function () {
    var self = this;
    var dataSource = {...}

    self.sonViewModel = new SonViewModel();

    self.nav = new NavHistory({
        params: {...},
        onNavigate: function (navEntry) {...}
    }).initialize({ linkToUrl: true });
    //navigation methods:
    self.gotoHomePage = function (){...}
}
SonViewModel = function () {
    var self = this;
    var dataSource = {...}

    //...
}
4

1 回答 1

0

为了从儿子视图模型访问父亲的方法,您需要将父亲的引用传递给儿子,如下所示:

FatherViewModel = function () {
    var self = this;
    var dataSource = {...}

    self.sonViewModel = new SonViewModel(self);

    self.nav = new NavHistory({
        params: {...},
        onNavigate: function (navEntry) {...}
    }).initialize({ linkToUrl: true });
    //navigation methods:
    self.gotoHomePage = function (){...}
}
SonViewModel = function (father) {
    var self = this;
    self.father = father;
    var dataSource = {...}

    function gotoHomePage() {
        self.father.gotoHomePage();
    }

    //...
}
于 2012-06-01T12:51:33.653 回答