How to access router states in any of the viewModels - Oracle JET

2.9k views Asked by At

I've defined root router in main.js and have the navigation code there itself. On of the the pages there is a list and I want to open view page from the selected list item. I'm able to get the data on the page by using $root.router.retreive() in the html page.

How do I get that value in it's corresponding viewModel?

navigation code:

self.gotoPage = function(data, event) 
{
   self.router.store(data.id);
   self.router.go(event.target.id);
};

Binding Code:

oj.Router.sync().then(
  function () {
    // bind your ViewModel for the content of the whole page body.
    ko.applyBindings(new RootViewModel(), document.getElementById('globalBody'));
  },
  function (error) {
    oj.Logger.error('Error in root start: ' + error.message);
  }
);
1

There are 1 answers

4
Debajyoti Das On BEST ANSWER

You can always use $module to access any variable defined in the active viewModel. Example: $module.router.retreive() to be used in the HTML binding.

If you are looking for the value in the ViewModel, you can extend router.moduleConfig and pass the context as moduleParams.

Or you can use ko.dataFor to pick up data from the binding context using HTML selectors.

As per comments...

setup: function(routerParent) {
    var router, latestState;
    if (routerParent == undefined) {
        router = oj.Router.rootInstance;
    } else {
        if (routerParent.getChildRouter(routerParent.currentState().id)) {
            routerParent.getChildRouter(routerParent.currentState().id).dispose();
        }
        router = routerParent.createChildRouter(routerParent.currentState().id);
    }
    router.configure(function(stateId) {
        if (stateId) {
            latestState = stateId;
            return new oj.RouterState(stateId);
        }
    });
    oj.Router.sync().then(function(value) {
        //console.info("Calling Router Sync: Result = " + value);
    }, function(reason) {
        console.info("Calling Router Sync: Result = " + reason);
    });
    return $.extend(router, { latestState: latestState });
},