Search code examples
javascriptknockout.jsdurandal

Durandal routing IF statement


I have a click binding on a button in my shell.js file. The click takes you back

function goBack() {
return router.navigateBack();
}

I have one particular route(reportForm) that I do not want it to copy this exact behaviour. I'm trying to introduce a confirmation message before going back.

    function goBack() {

        if (router.routes[7].moduleId === "viewmodels/reportForm") {
            return router.navigateBack();
        } else {
            return app.showMessage(strings.logoutWarning, strings.logout, [strings.no, strings.yes])
                .then(function (answer) {
                    if (answer === strings.yes) {
                        return router.navigateBack();
                    }
                })
        }
    }

Looks like it does not know its current route. I need to find out my current position and see if this matches. Its currently checking if that exists which it does so always returns the same statement. If somebody with Durandal experience could help me achieve what I am trying to do above I will be very grateful.

Here is my Durandal router map(its reportForm that I want to show this message):

function activate() {
    router.map([
        { route: '', title: 'Welcome', moduleId: 'viewmodels/login', nav: true },
        { route: 'home', moduleId: 'viewmodels/home', nav: true },
        { route: 'log', moduleId: 'viewmodels/log', nav: true },
        { route: 'locationSelect', moduleId: 'viewmodels/locationSelect', nav: true },
        { route: 'history', moduleId: 'viewmodels/history', nav: true },
        { route: 'helpText', moduleId: 'viewmodels/helpText', nav: true },
        { route: 'scheduled', moduleId: 'viewmodels/scheduled', nav: true },
        { route: 'reportForm/:formId(/:templateId)', moduleId: 'viewmodels/reportForm', nav: true }
    ]).buildNavigationModel();

    return router.activate();
}

Solution

  • You can check the router.activeInstruction().params[0] value which gives you the route you are about to navigate to. In your canDeactivate (or any other place you are handling this) life-cycle callback, you can put your logic to show a confirmation message to the user and then navigate accordingly. Here's what you can try out -

    function goBack() {    
            if (router.activeInstruction().params[0] !== null && typeof(router.activeInstruction().params[0]) !== "undefined" && router.activeInstruction().params[0].indexOf("reportForm") >= 0) {
                return router.navigateBack();
            } else {
                return app.showMessage(strings.logoutWarning, strings.logout, [strings.no, strings.yes])
                    .then(function (answer) {
                        if (answer === strings.yes) {
                            return router.navigateBack();
                        }
                    })
            }
        }
    

    Hope this helps.