在Backbone.js/Marionette.js中路由 - 没有主题标签,路由列表和子路由器

m_v*_*eek 4 routes backbone.js marionette

我在Backbone.js/Marionette.js中有三个关于路由的问题:

  • 1)如何获取应用程序路由器已注册的所有路由的列表?

例如,对于Express.js(在Node.js中),它将是app.routes.

我正在尝试使用Backbone.js/Marionette.js做同样的事情,但找不到任何执行此操作的属性或方法.

  • 2)我想清理我的URL并删除它们前面的#"#标签,我知道它们会触发路由器,所以我怎么能设法做到这一点?

我发现以下脚本是Backbone路由器的原型,但它更像是一个黑客而不是一个稳定的解决方案:没有哈希URL的简单骨干路由

  • 3)Backbone.js/Marionette.js中是否可以有子路由器?

我所说的子路由器是一个只处理网址的一部分的路由器,例如:

var AppRouter = Backbone.Router.extend({
    routes: {
        'articles' : 'MyArticleRouter'
    }
});

var MyArticleRouter = Backbone.Router.extend({
    routes: {
        'science' : 'someMethod',
        'literrature' : 'someOtherMethod'
    }
});
Run Code Online (Sandbox Code Playgroud)

这将通过让我在类别特定的子路由器中定义AppRouter中的主要路由和所有子路由(在第二个斜杠"/"之后的部分)来对我的URL进行更多分类.

因此对于以下URL:"hostname/articles/science",路由过程看起来像这样:

  • 1)将"/ articles/science"传递给AppRouter
  • 2)AppRouter拆分URI并采用"/ articles"部分
  • 3)AppRouter找到已注册的"/ articles"路由
  • 4)AppRouter识别出MyArticleRouter绑定到该URI元素
  • 5)AppRouter将路由转发到该路由器,并仅将"/ science"元素作为路由传递
  • 6)MyArticleRouter将"/ science"路由到someMethod()并运行它

先感谢您 !

Jul*_*dez 8

回答#1:

所有路线都已注册Backbone.history.handlers.

回答#2:

您可以为站点中的每个链接添加处理程序:

var application = new Backbone.Marionette.Application();

application.addInitializer(function(options) {
    // Add class to target a browser, not as standalone app.
    if(window.navigator.standalone != true) {
        $('body').addClass('no-standalone');
    }

    // Prevent internal links from causing a page refresh.
    $(document).on('click', 'a', function(event) {
        var fragment = Backbone.history.getFragment($(this).attr('href'));
        var matched = _.any(Backbone.history.handlers, function(handler) {
            return handler.route.test(fragment);
        });
        if (matched) {
            event.preventDefault();
            Backbone.history.navigate(fragment, { trigger: true });
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

当然请确保使用pushState:

    if (!Backbone.history.started) {
        Backbone.history.start({ pushState: true });
    }
Run Code Online (Sandbox Code Playgroud)

在初始化所有路由器之后必须运行最后一个片段.

回答#3:

这可能有点分裂您的路线:

define([
    'backbone',
    'underscore',
    'routers/dashboard',
    'routers/anotherroute1',
    'routers/anotherroute2'
],

function(Backbone, _, DashboardRouter, AnotherRoute1, AnotherRoute2) {
    'use strict';

    var application = new Backbone.Marionette.Application();

    application.addInitializer(function () {

        _.each([DashboardRouter, AnotherRoute1, AnotherRoute2], function(router) {
            new router();
        });

        if (!Backbone.history.started) {
            Backbone.history.start({ pushState: true });
        }
    });

    return application;
});
Run Code Online (Sandbox Code Playgroud)