在Backbone中的视图中调用路由

6
我知道有很多关于使用Backbone.js组织应用程序的教程/信息。我正在逐步创建一个,借助这些教程。我似乎无法理解路由器的概念。好吧,我知道路由器是起点(并告诉应用程序的状态),最好避免在那里放置更多的逻辑。
我有一个路由器。我的应用程序首先会加载页眉、页脚和页面的主要部分。在主要部分中,首先,我应该登录用户。要加载登录页面,我会做如下操作:
       var AppRouter = Backbone.Router.extend({
            initialize : function() {
            var headerView = new HeaderView({el:$('#header')});
            headerView.render;

            var footerView = new FooterView({el:$('#footer')});
            footerView.render;

            var loginView = new LoginView({el:$('#login')});
            loginView.render;
        },
        routes : {
            "inbox" : "inbox",
            "sentbox : "sentbox"
        },
        inbox : function() {
            // ...
        },
        sentbox : function() {
            // ...
        }
    });
    app = new AppRouter();
    Backbone.history.start();

成功登录后,邮件页面将被加载。MailView有一些事件来显示收件箱、已发送等。

     events: {
        "click .inbox": "showInbox",
        "click .sentbox": "showSentbox",
      },
       showInbox : function() {
            // app.route() or app.inbox() - ?
      }

此时,我希望路由器分别显示../#inbox../#sentbox。我在想是否应该调用路由器的某个方法来在地址栏中显示它们。我感到困惑的原因是因为有人说使用一个路由器比使用多个更好。如果这样做,我的AppRouter将会更加复杂。另一个问题是,如果用户直接输入地址,我应该加载那个页面。我认为需要把逻辑放在AppRouter里面。
请告诉我正确的方法。先谢谢!
3个回答

12

请查看Router.navigate() (http://documentcloud.github.com/backbone/#Router-navigate)。

通常我会在我的App对象中保存一个Router的实例变量,例如:

var App = {
  Views: {},
  Routers: {},
  Models: {},
  data: {}

  initialize: function() {
    this.data.mainRouter = new App.Routers.MainRouter();
  }
};

App.MainRouter的定义如下:

App.Routers.MainRouter = Backbone.Router.extend({

   routes: {
     'route1' : 'route1handler',
     'route2/:param' : 'route2handler'
   },

   ... 
});

在我的视图内,如果我想导航到新路由,则调用:

App.data.mainRouter.navigate('route2/param1');

7
请注意,如果您的路由器无法从视图中访问,您也可以调用Backbone.history.navigate - jgillich
3
只会改变网址的哈希值,不会触发路由处理函数的方法。 - Animal Rights
4
要触发路由处理程序,你需要将{trigger: true}作为第二个参数添加。 - juanra

7

您只需通过以下方式将浏览器发送到适当的路由:

location.href = "#/the_route_you_want";
Backbone.history 中的监听器会捕获 hashChange 事件,并显示相应的视图。

这可以通过 HTML 非常简单地实现:

<a href="#/the_route_you_want">The Route You Want</a>

For further reading.


谢谢您快速的回复。我实际上并没有使用<a>标签。其次,如果用户在地址栏中输入该网址会发生什么? - boburShox

1
如果您希望调用路由函数,将触发器选项设置为true:
app.navigate("help/troubleshooting", {trigger: true});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接