Search code examples
javascriptbackbone.jsurl-routingrouter

Getting URL fragment instead of hash in Backbone.js


I have struggled with this for quite a long time. I'm using Backbone.js along with Require.js. I'm trying to tell Backbone to display a specific view according to the current URL (not hash). My code looks like this:

define(['jquery','underscore','backbone', 'views/manage_pages'], function($, _, Backbone,  ManagePages) {
  var AppRouter = Backbone.Router.extend({
    routes:{
      '/new_page': "showPageForm",
      '/edit_page': "showPageEditForm",
      '*actions': "showPageForm"
    },
  });
  var initialize = function(){
    appRouter = new AppRouter;
    appRouter.on("route:showPageForm", function(){
      console.log('hej');
    });
    appRouter.on("route:showPageEditForm", function(){
      console.log('ho');
    });
    var page_form = new ManagePages();
      Backbone.history.start();
    }
    return {
      initialize: initialize
    }
  });

So basically when the user goes to http://example.com/new_page it should log <code>hej</code> and when he goes to http://example.com/editpage it should log <code>ho</code>. I don't know how to accomplish this or even if it is possible. Can anyone help me?


Solution

  • You could use Backbone's support for HTML5 push-state, which uses the URL path by default (instead of the hash fragment). Just specify it as an option when calling history.start:

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

    (Note that if your application is located in a sub-path under the domain, then you can tell Backbone to use that as the root -- Backbone.history.start({pushState: true, root: "/myapproot/"}) -- although it looks like that's not a concern in your case.)