Question

I'm Building a Single Page Application using ASP.NET MVC, Knockout, nav.js...etc.,

Two View Model:

  1. FatherViewModel;
  2. SonViewModel;

FatherViewModel has All the Navigation methods, FatherViewModel has an instance of SonViewModel,

Q: How to access those Navigation methods from the 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 = {...}

    //...
}
Was it helpful?

Solution

In order to access the father's methods from the son viewmodel, you need to pass a reference of the father to the son, like so:

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();
    }

    //...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top