Search code examples
backbone.js

How to use standard URL in Backbone.Router?


According to the Backbone.js page:

Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs (/page).

I tried to add this router rule:

routes: {
  'test': function() {
     alert('ok'); }
}

And called the Backbone.history.start({pushState: true, root: '/myroot/'}). I have a link in my page as:

<a href="test">test me</a>

I intercepted the link's click event with:

$('a[href=test]').click(function(e) {
  router.navigate('test');
  e.preventDefault(); });

When I click on the link, a request is not made, which I believe the interception was succeeded. But the event is not triggered.

So, please help me understand how this History API works. Or point out where I have done wrong.


Solution

  • You need to turn on pushState:

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

    Your link is going to force a full refresh from your server and your server must respond with the content of that url.

    You need to intercept that link's click and tell your router to navigate to the "test" route:

    myRouter.navigate("test");

    For more info on the HTML5 history api: http://diveintohtml5.info/history.html

    for some intro level info on using pushState with Backbone:

    http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-1-introducing-pushstate/

    http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-2-progressive-enhancement-with-backbone-js/

    And a video of a presentation I gave that covers all of this:

    http://lostechies.com/derickbailey/2011/10/06/seo-and-accessibility-with-html5-pushstate-part-3-the-video/

    Hope that helps.