How to use standard URL in Backbone.Router?

On the Backbone.js page:

Until recently, hash fragments (#page) were used to provide these permalinks, but with the advent of the history API, standard URLs (/ page) can now be used .

I tried to add this router rule:

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

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

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

I intercepted the link click event:

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

When I click on the link, the request is not created, and I believe that the interception was successful. But the event does not fire.

So, please help me understand how this History API works. Or indicate where I made a mistake.

+7
source share
3 answers

You need to enable pushState:

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

Your link will force you to completely upgrade your server, and your server should respond to the contents of this URL.

You need to intercept this link and tell the router to go to the "test" route:

myRouter.navigate("test");

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

for some intro level information on using pushState with the base:

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 the presentation video I gave covers all of this:

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

Hope this helps.

+12
source

You will need to add {trigger: true} to the navigation call to actually trigger routing events.

+1
source

To indicate that you want to use HTML5 pushState support in your application, use Backbone.history.start({pushState: true}) . If you want to use pushState , but for browsers that don't support it, use full-featured page updates instead, you can add {hashChange: false} to the parameters.

PS! If your application will not be sent from the root URL / your domain, be sure to tell History where the root really is, as an option (otherwise the navigation won 't work!):

 Backbone.history.start({pushState: true, root: "/public/search/"}) 
0
source

All Articles