Routing in Backbone.js / Marionette.js - no hashtags, route list and sub-routers

五迷三道 提交于 2019-12-03 03:50:30

Answer for #1:

All the routes are registered in Backbone.history.handlers.

Answer for #2:

You can add a handler to every link in your site:

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 });
        }
    });
});

Of course make sure you use pushState:

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

That last snippet must be run after you have initialized all your routers.

Answer for #3:

This may work a little to split your routes:

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;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!