Backbone.js Routers confusion (pushState: true, tr

2019-05-06 16:07发布

I am using Backbone's router with pushState:true to handle my site's urls. Examples of URLs include:

Problem: When the user goes to http://domain.com/John/, the expected function photos is executed. However when the user goes to http://domain.com/John without the trailing slash, nothing happens; my guess is that the trailing 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);
});

2nd Attempt

Problem:: This time I removed the trailing backslash in root and http://domain.com/John now triggers the route. The problem this time comes when the user is at http://domain.com/John (which I believe is treated by the browser as a page named John), so when the link (with attribute data-toggle="tab") is clicked, the url is changed to http://domain.com/Johnphotos without the seperating /.

How should I solve this problem?

2条回答
We Are One
2楼-- · 2019-05-06 16:25

I think your 2nd attempt should work if you update backbone to the latest version. See this discussion:

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

The changes above were merged 8 days ago.

查看更多
Root(大扎)
3楼-- · 2019-05-06 16:32

While @shioyama's answer is correct, I often bypass this strangeness by using wildcard routes, where possible.

For example:

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

Of course, this is not a possibility for many apps, however, it's saved time for me in the past.

查看更多
登录 后发表回答