Backbone.js Router Confusion (pushState: true, trailing slash)

I am using Backbone router with pushState:true to process the URLs of my site. Sample URLs:

Problem . When the user goes to http://domain.com/John/ , the expected photos function is executed. However, when a user navigates to http://domain.com/John without a trailing slash, nothing happens; I assume that the backslash defined in root prevented this.

router

 var AppRouter = Backbone.Router.extend({ routes: { '': 'photos', 'photos': 'photos' }, viewing_username: $('#viewing_username').val(), // eg: 'John' photos: function() { console.log('photos'); } }); var app = new AppRouter(); Backbone.history.start({ pushState: true, root: '/' + app.viewing_username + '/' }); 

JQuery

 $('a[data-toggle="tab"]').on('click', function(e) { app.navigate(e.target.getAttribute('href'), true); }); 

Second attempt

Problem :: This time I removed the backslash in root and http://domain.com/John now starts the route. The problem this time occurs when the user is at http://domain.com/John (which, as it seems to me, is viewed by the browser as a page with the name John ), so when the link is clicked (with the data-toggle="tab" attribute) URL changed to http://domain.com/Johnphotos without sharing / .

How do I solve this problem?

+4
source share
2 answers

I think your second attempt should work if you upgrade the base station to the latest version. See discussion:

https://github.com/documentcloud/backbone/pull/1505

The above changes were merged 8 days ago.

+2
source

While @shioyama's answer is correct, I will often get around this weirdness using possible wildcard routes where possible.

For instance:

 routes: 'dashboard(/*subroute)': 'index' 

Of course, this is not an opportunity for many applications, but in the past I have succeeded.

0
source

All Articles