检查未保存的更改在Backbone.js的切换视图时 [英] Checking for unsaved changes when switching views in backbone.js

查看:134
本文介绍了检查未保存的更改在Backbone.js的切换视图时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Javascript和Backbone.js的,所以希望我在这里简单的东西。我与一些样本code,我发现这是应该允许用户导航离开到另一个页面之前检查未保存的更改试验。我创建了一个在这里的jsfiddle:

I am new to Javascript and backbone.js, so hopefully I am missing something simple here. I am experimenting with some sample code I found which is supposed to check for unsaved changes before allowing a user to navigate away to another page. I have created a JSfiddle here:

http://jsfiddle.net/U43T5/4/

在code赞同这样的hashchange事件:

The code subscribes to the hashchange event like this:

$(window).on("hashchange", router.hashChange);

以及 router.hashChange 函数检查脏标志,以确定是否允许导航,就像这样:

And the router.hashChange function checks a "dirty" flag to determine whether or not to allow the navigation, like this:

hashChange: function (evt) {
    if (this.cancelNavigate) { // cancel out if just reverting the URL
        evt.stopImmediatePropagation();
        this.cancelNavigate = false;
        return;
    }
    if (this.view && this.view.dirty) {
        var dialog = confirm("You have unsaved changes. To stay on the page, press cancel. To discard changes and leave the page, press OK");
        if (dialog == true) return;
        else {
            evt.stopImmediatePropagation();
            this.cancelNavigate = true;
            window.location.href = evt.originalEvent.oldURL;
        }
    }
},

问题是,code未工作,因为 this.view 未定义,所以第二个如果从未进入过的块。

The problem is that the code is not working because this.view is undefined, so the 2nd if block is never entered.

我想示例程序从页面导航离开(在我的示例程序,我已经设置 this.view.dirty 永远是前总是要求确认真正,这就是为什么它应该总是要求确认)。或者,如果有更好的办法,我愿意接受的替代品。

I would like the sample program to always ask for confirmation before navigating away from the page (in my sample program, I have set this.view.dirty to always be true, which is why it should always ask for confirmation). Or if there is a better approach, I am open to alternatives.

推荐答案

的主要问题是中的方法本的背景下,这个对应的窗口对象并不会在路由器。因此,它始终保持未定义,因为你是在路由器上定义视图。声明结合的方法,以路由器内部的上下文初始化方法。

The main issue is the this context in the methods , this corresponds to the Window Object and not the Router. So it always remains undefined as you are defining view on the router. Declare a initialize method which binds the context inside the methods to router.

 initialize: function() {
        _.bindAll(this, 'loadView', 'hashChange');
    },

检查小提琴

Check Fiddle

这篇关于检查未保存的更改在Backbone.js的切换视图时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆