Universal Navigation module

I’m trying to build a universal navigation module in JS, so I can define two main navigation functions:

Navigation.js

function goBack(){
    router.goBack();
}
module.exports = {goBack:goBack}

Page.js

Navigation = require('Modules/Navigation');

module.exports={goBack:Navigation.goBack()}

The problem I’m getting is that I get a router is not defined. How can I solve this?

Thanks

Funny that I couldn’t find the forum thread where I replied with a solution to this exact challenge earlier.

Anyway, what you want to do is explicitly pass the router to your module. Via a dedicated function.

In your Navigation.js:

var router;
function init(r) {
    router = r;
}
function goBack(){
    router.goBack();
}
module.exports = {
    init: init,
    goBack: goBack
};

in your MainView.js or whatever else is your top-level viewmodel, on the master page where you have <Router ux:Name="router" /> in UX - so that the JS viewmodel has access to UX nodes by their ux:Names:

var Navigation = require('Modules/Navigation');
Navigation.init(router);

And finally on your Page.js:

var Navigation = require('Modules/Navigation');
module.exports = {
    goBack: Navigation.goBack
};

Note that you only want to set the router once, otherwise all hell will break loose.

Hope this helps!

All that said, our suggestion for the right way to solve multi-level navigation is shown in Navigation example. Please do take a look at that and consider if you really need an abstraction for this, because in our experience you probably don’t.

I tried building a push function, couldn’t get it to work. Is there a way to do that?
My goal is to simply reduce the amount of code in the js file for each page.

Thanks

Sorry, that last question is not clear. Please show some code in a new forum post, since the original challenge in this one has been thoroughly answered.