WinJS – how to cancel the navigation from a page ?

, , 3 Comments

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 :

  1. Detect the navigation
  2. Cancel or not the navigation
  3. 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.

[javascript]
WinJS.Navigation.addEventListener("beforenavigate", onbeforeNavigate);
[/javascript]

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 :

[javascript]
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));
}
[/javascript]

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 :
[javascript]
WinJS.Navigation.removeEventListener("beforenavigate", onbeforeNavigate);
[/javascript]

This is my first post on WinJS : let’s celebrate 🙂

 

3 Responses

  1. Milos

    08/05/2016 10 h 11 min

    I do not understand how to attach this event to my single page. For example:

    var myHomePage = WinJS.UI.Pages.define("/pages/home/home.html", { ready: }

    This is my page and I want to catch this event every time when someone wants to go to my page ?

Comments are closed.