SB2055
SB2055

Reputation: 12872

Durandal - how to "protect" a route?

In my shell.js, I have some options in the UI that a user can select before navigating to the child.js vm. The child.js vm requires this option data to be provided.

If I navigate to #/child directly, currently I get some errors because this data has not been provided. This is the expected behavior... though I'd like to somehow protect the child.js view from being accessed directly.

The ideal scenario is that if a user refreshes the page on the child view or navigates directly to it (could be captured by checking to see if the required option data exists), I push them to another view via a different route. I should only be able to access the child vm if the required option data is there.

I tried doing this:

var vm = {
    activate: activate
};

function activate() {
   alert("ACTIVATED");
    if (<check for data exists>) {
        vm.data = ko.mapping.fromJS(<data>, mapping);
    } else {
        toastr.error("session data lost");
        router.navigateTo("#/getdata");
    }
};

return vm;

however I can see the entire page load and code above activate run before the new view is loaded from router.navigateTo when the data is not there.

How can I either totally exit the vm at either router.navigateTo above (and prevent any further execution), or somehow protect the route from even loading the vm if certain data is unavailable (preferred)?

Upvotes: 0

Views: 1103

Answers (2)

RainerAtSpirit
RainerAtSpirit

Reputation: 3723

You should look into router.guardRoute as described at http://durandaljs.com/documentation/Router/. Make sure that you're running Durandal 1.2 router.guardRoute is not being called

Updated router link for Durandal 2.0. based on comment:

http://durandaljs.com/documentation/Using-The-Router/

Upvotes: 1

yeraycaballero
yeraycaballero

Reputation: 1603

It looks, you could use canActivate hook method. This method is called before calling activate. You could stop the transition returning false from this method.

  vm = {
     canDeactivate : function(data) {
       if (! data.foo) return false;
     }
  }

Upvotes: 0

Related Questions