从子Knockout ViewModel调用导航功能

时间:2012-06-01 11:12:02

标签: javascript asp.net-mvc-4 knockout.js asp.net-web-api single-page-application

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

两个视图模型:

  1. FatherViewModel;
  2. SonViewModel;
  3. FatherViewModel拥有所有导航方法, FatherViewModel有一个SonViewModel实例,

    问:如何从SonViewModel访问这些导航方法?

    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 = {...}
    
        //...
    }
    

1 个答案:

答案 0 :(得分: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();
    }

    //...
}