landland
landland

Reputation: 2147

Backbone router, pushstate, and relative urls

I'm making my first backbone app. I have pushstate enabled. In the router I have two routes.

    'link1(/)' : 'link1Route',              
    'link2(/)' : 'link2Route'

On my link1 page, I have a link pointing to link 2 like so:

    <a href="link2">Link2</a>

I click on the link, the router takes over and I go to link2Route as expected. However, if I hover over the link, the status bar indicates that the link is at domain.com/link1/link2 rather than domain.com/link2. This is correct given the relative url structure on the link1 page. Unfortunately, if a user decides to open the link in a new window or tab, backbone's router will not take effect. This is expected since opening in a new window or tab results in a new page load from the server. The problem of course, is that domain.com/link1/link2 does not exist.

What are some ways of dealing with this situation? Thanks.

Upvotes: 1

Views: 1672

Answers (2)

David Sulc
David Sulc

Reputation: 25994

As mateusmaso indicated, you need to change your link target to "/link2" (i.e. including the "/").

In addition, when implementing pushState, don't forget you need your server to respond with content if a user requests the "domain.com/link2" URL. The response can be index.html if you wish, but the server must return a page for that URL.

If you return index.html for all your Backbone-related URLs, when your Backbone app gets started the route-handling code will get fired and the proper data will be displayed.

If you want to learn more about routing and how to manage it properly without needing to pass trigger: true when calling navigate, check out pages 32-46 of this free sample pdf: http://samples.leanpub.com/marionette-gentle-introduction-sample.pdf (full disclosure, I'm the book author)

Upvotes: 2

Mauvis Ledford
Mauvis Ledford

Reputation: 42354

You must serve the correct index.html at the server level — since this is before the JavaScript even loads on the page.

http://readystate4.com/2012/05/17/nginx-and-apache-rewrite-to-support-html5-pushstate/

Upvotes: 0

Related Questions