Search code examples
backbone.jsmarionettepushstate

Marionette PushState URL Handeling - How to do it?


I have been unable to find any articles on Backbone.Marionette using pushstate withOUT Node.js, or grunt, or require where a serious discussion is made about URL handeling. A user should be able to send a link to an internal page to her grandmother and have the link work, for example. The pushstate functionality seems uniquely ill-suited to the real world. Can someone comment and perhaps provide some links to serious articles on the subject?


Solution

  • Generally speaking, there's really just 2 things you need to do...

    1. Tell Backbone to use pushstate by calling Backbone.history.start({ pushState: true });. You may also need to add something like root: 'myApp' to that parameter if your Marionette app is served from http://example.com/myApp instead of directly on http://example.com.
    2. Configure your web server so that no matter what URL the user requests, the same content (your Marionette app) is returned (without doing a redirect).

    The catch is that #2 is implemented differently depending on what type of web server you are using. And you haven't told us what stack you're on. In ASP.NET, for example, this can be handled by setting up a 'catch all' route by adding something like this to your RouteConfig.cs file:

            // all requests (except those explicitly handled by another route)
            // go to HomeController.Index and then the Backbone router examines
            // the URL client-side to determine client-side what to do
            routes.MapRoute(
                name: "Default",
                url: "{*clientRoute}", // this is wildcard which captures the entire URL
                defaults: new { controller = "Home", action = "Index" }
            );
    

    Other web server stacks will have different ways of achieving the same type of thing.