Guards are methods that are run before the page navigation takes place and
that can stop the navigation from displaying a certain page.
Use the property guard: someMethod
to apply the guard. The method
takes 3 parameters: page, route, and callback. If the callback is called
the navigation takes place - otherwise it is stopped.
Use cases are login, validating steps in state machines, etc.
The reason the guard takes a callback as the third argument is simply because the guard might be asynchronous,
e.g., accessing a webserver for login details or asking if a valid shopping cart exists, etc.
You are not logged in. Check the checkbox and try again.
<div data-bind="page: {id: 'admin', guard: isLoggedIn}" class="well"> This page is only accessible if the user is logged in. <a href="#!/navigation/guards" data-bind="click: logout">Logout</a> </div> <div data-bind="page: {id: 'login'}" class="well"> <p class="alert alert-error">You are not logged in. Check the checkbox and try again.</p> <form> <label class="checkbox">Login <input type="checkbox" data-bind="checked: loggedIn"/> </label> </form> </div>where
loggedIn: ko.observable(false), isLoggedIn: function(page, route, callback) { if(viewModel.loggedIn()) { callback(); } else { window.location.href = "login"; } },