Did you use the WinJS navigation framework ? If not, you should really take a look at it because it’s can be really useful and powerful !
Today I needed to cancel the navigation from a page based on the current state of the page. It could be useful to zoom out of a semantic zoom instead of navigating back when the user tap the little arrow (windows phone habit
).
I was wondering how I would be able to code this and it turned out that this is pretty easy.
Th is done in several steps :
- Detect the navigation
- Cancel or not the navigation
- If not canceled, perform some clean-up code
Detect the navigation
Detecting that the user request a navigation is easy as an event subscription.
The subscription is done on the “onBeforeNavigate” event of the Navigation object.
I usually do it on the ready method which is called whenever a user navigates to the page.
WinJS.Navigation.addEventListener("beforenavigate", onbeforeNavigate);
Cancel or not the navigation
In the onBeforeNavigate method, you can set a promise which will tell the navigation system if the navigation must be canceled.
This is done using the provided event param ‘setPromise’ method. Here is an example :
function onbeforeNavigate(eventObject) {
//cancel the navigation
eventObject.detail.setPromise(WinJS.Promise.wrap(true));
//let the navigation proceed (this is the default behavior)
eventObject.detail.setPromise(WinJS.Promise.wrap(false));
}
If not canceled, perform some clean-up code
When the navigation must be proceed, you have to remove your subscription to the event because it would be raised on each navigation. Simple as this code :
WinJS.Navigation.removeEventListener("beforenavigate", onbeforeNavigate);
This is my first post on WinJS : let’s celebrate

