拦截路线导航并询问用户“您确定要离开此页吗?”

时间:2014-02-05 22:27:32

标签: knockout.js durandal durandal-2.0 durandal-navigation

我有一个Durandal应用程序,允许用户更新各种配置文件信息。对于某些数据位,用户必须单击“保存”以表示他们想要保存更改。

如果用户尝试使用未保存的更改导航离开当前视图,我们希望拦截导航并弹出一个模式,说“您有未保存的更改 - 是否要在离开此视图之前保存它们? “

但是,在审核Durandal Router plugin documentation时,我无法确定如何拦截视图模型中的导航请求。我想我想听the router:route:activating event。但是:

  1. 我不确定在何处以及如何为此设置侦听器。
  2. 我不知道如何在我的事件处理程序中取消导航(所以我可以改为弹出我的模态)。

2 个答案:

答案 0 :(得分:2)

您可以在durandal拥有的canDeactivate事件中执行此操作。

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;
};

这将取消基于用户所选选项的导航。

答案 1 :(得分:0)

只需向VM添加canDeactivate方法即可;在Starter Kit示例中查看flickr.js,它几​​乎完全符合您的要求。