【问题标题】:Backbone Router For Modals模态骨干路由器
【发布时间】:2012-09-09 06:10:55
【问题描述】:

我有一个非常基本的带有模式的 Backbone JS 应用程序。目前,我的路由器呈现的模态如下:

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: ->
    # ?

这很好用,但是我不清楚如何处理窗口历史记录和用户选择后退按钮(即如何在单击后退时拆除模式)。有人对最佳方法有任何想法吗?谢谢。

【问题讨论】:

    标签: backbone.js coffeescript


    【解决方案1】:

    您偶然发现了单页应用程序 (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 方法的“类”。以便应用负责清理。

    现在有时我在主应用程序中有模态或“子应用程序”。我使用了上述的变体,并在App 对象中添加了close 方法。但基本思想是将这些“子应用”添加为主应用的属性:

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

    现在,当通过单击后退按钮或应用程序的其他部分进行转换时 - 您必须调用 App-manager 来处理清理和转换。基本上就像在说:

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      相关资源
      最近更新 更多