Search code examples
durandal

Dynamically Adding / Removing Route in Durandal Router when application is loaded


I need help in dynamically adding/removing route in Durandal Router. What I want is after user is logged in then I would be able to add or remove specific route depending upon logged in user's type.

I tried to add/remove route from visibleRoutes/allRoutes array ... but get binding exception from knockout library...

I was hoping it would be common scenario... but still couldn't find any solution ... please help me in fixing this issue.

Thanks. Wasim

POST COMMENTS:

I tried this function to dynamically hide/show route... and similary tried to add/remove route from allRoutes[] ... but then get exception on knockout bidning

showHideRoute: function (url,show) {

        var routeFounded = false;
        var theRoute = null;
        $(allRoutes()).each(function (route) {

            if (url === this.url) {
                routeFounded = true;
                var rt = this;
                theRoute = rt;
                return false;
            }
        });

        if (routeFounded)
        {
            if (show)
            {
                visibleRoutes.push(theRoute);
            }
            else
            {
                visibleRoutes.remove(theRoute);
            }
        }
    }

Solution

  • I had a similar requirement. If I were you, I would take another approach. Rather than adding/removing routes when application loads - get the right routes to begin with per user type.

    Two options, (I use both) 1) have a json service provide the proper routes per user type, this approach would be good if you need to 'protect/obscure' routes... i.e. I don't want the route referenced on any client resource. 2) A simpler solution see Durandal.js: change navigation options per area You can have a settings property identify the user type.

    I hope this helps.