1

I have a Durandal app that allows the user to update various bits of profile information. For some bits of data, the user must click "save" to indicate they want to save their changes.

In the event that the user attempts to navigate away from the current view with unsaved changes, we want to intercept the navigation and popup a modal saying "you have unsaved changes--do you want to save them before leaving this view?"

However, in reviewing Durandal Router plugin documentation, I haven't been able to determine how to intercept navigation requests in my viewmodel. I think I want to listen for the router:route:activating event. But:

  1. I'm not sure where and how to setup the listener for this.
  2. I don't know how to cancel the navigation (so I can instead pop up my modal) in my event handler.
Josh
  • 7,232
  • 8
  • 48
  • 75
  • Handle the browser events directly if talking about arbitrary link clicks or other UA navigation such and changing the URL. The stock Durandal router does not encompass "before navigation" behavior. – user2864740 Feb 05 '14 at 22:35
  • In a user point of view, that's the most annoying thing that a website can make. Sorry. – Filipe YaBa Polido Feb 06 '14 at 01:21

2 Answers2

2

You can do this in canDeactivate event that durandal has.

var canDeactivate = function () {
// Check if your data has unsaved changes with logic in hasChanges() method
if (hasChanges()) {
            var msg = 'Do you want to leave and cancel?';
            return app.showMessage('Message', 'Confirm Title', ['Yes', 'No'])
                .then(function (selectedOption) {
                    if (selectedOption === 'Yes') {
                       // Cancel your changes here
                    }
                    return selectedOption;
                });
        }
        return true;
};

This will cancel the navigation based on the user's selected option.

Sarcastic
  • 677
  • 5
  • 14
0

Just add a canDeactivate method to your VM; look at flickr.js in the Starter Kit example, which does almost exactly what you want.

ebohlman
  • 14,795
  • 5
  • 33
  • 35