2012-09-09 140 views
2

我有一个非常基本的Backbone JS应用程序,它具有模态。目前,我的路由器提出了模态如下:Modals的骨干路由器

class App.Routers.Router extends Backbone.Router 
    routes: 
    "modal" : "modal" 

    modal: -> 
    view = new App.Views.Modal.New() 
    $('#shared').html(view.el) 
    view.render() 
    view.show() 
    return 

class App.Views.Sessions.New extends Backbone.View 
    template: Handlebars.templates["backbone/templates/modals"] 

    initialize: (options) -> 
    super(options) 

    render: -> 
    $(@el).html(@template()) 
    $('.modal', @el).modal() 
    $('.modal', @el).on 'hidden', @cleanup 
    return @ 

    show: -> 
    $('.modal', @el).modal('show') 

    hide: -> 
    $('.modal', @el).modal('hide') 

    cleanup: -> 
    # ? 

这工作得很好,但我不清楚如何处理窗口的历史和选择后退按钮用户(即如何我拆毁模态上单击后退)。有没有人对最佳方法有任何想法?谢谢。

回答

4

你已经偶然发现了单页面应用程序(SPA)的一个有趣问题。是的,它可能会有点棘手,但简单的软件工程原理/设计可以在这里帮助。我已通过以下方式处理清理:

有一个单独的类/对象负责管理各个“应用程序的各个部分”之间的视图转换。例如,在我的应用我有这样的事情:

var App = {}; 

//when showing a specific app: 

App.showView = function(appToShow){ 
if(this.currentApp) 
    currentApp.close(); 

this.currentApp = appToShow; 
//render appToShow; 
} 

appToShow是一个“阶级”有方法create/renderclose。因此,该应用程序负责清理。

现在有时我在主应用程序中有模态或“子应用程序”。我已经使用了上述的一个变体,并将close方法添加到App对象。但是,其基本思想是这些“子应用”添加为主要应用的特性:通过单击后退按钮或应用程序的不同部分转换时

//when creating modal: 
App.addModal = function(modal){ 
this.currentApp.modal = modal; 
} 

现在 - 你必须于App调用 - 管理清理和过渡。这基本上就像在说:

App.closeModal = function(modal){ 
if(this.currentApp.modal) 
    this.currentApp.modal.close(); 
} 

根据您的路由器是如何组织的,你应该能够决定是否完全或只是莫代尔/子应用程序关闭整个应用程序。基本上你的“应用管理器”是一个单独的对象,只负责处理视图之间的转换,不必是Backbone.View - 单独的对象可以正常工作。你甚至可以通过创建和事件聚合器来监听使用Backbone事件的事件。 Derick Bailey撰写了一篇优秀的博客文章,详述了相同的内容:http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/