简体   繁体   English

Backbone.js路由器混乱(pushState:true,斜杠结尾)

[英]Backbone.js Routers confusion (pushState: true, trailing slash)

I am using Backbone's router with pushState:true to handle my site's urls. 我正在使用带有pushState:true Backbone路由器来处理我网站的网址。 Examples of URLs include: URL的示例包括:

Problem : When the user goes to http://domain.com/John/ , the expected function photos is executed. 问题 :当用户转到http://domain.com/John/时 ,将执行预期的功能photos However when the user goes to http://domain.com/John without the trailing slash, nothing happens; 但是,当用户不带斜杠转到http://domain.com/John时 ,什么也没有发生。 my guess is that the trailing backslash defined in root prevented this. 我的猜测是, root定义的尾部反斜杠阻止了此操作。

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 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. 问题::这次我删除了root的尾部反斜杠,并且http://domain.com/John现在触发了路由。 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 / . 这次的问题是当用户位于http://domain.com/John (我认为浏览器将其视为名为John的页面)时出现的,因此当链接(具有属性data-toggle="tab" )时出现单击后,URL将更改为http://domain.com/Johnphotos,而不会使用/分隔。

How should I solve this problem? 我应该如何解决这个问题?

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 https://github.com/documentcloud/backbone/pull/1505

The changes above were merged 8 days ago. 以上更改已在8天前合并。

While @shioyama's answer is correct, I often bypass this strangeness by using wildcard routes, where possible. 尽管@shioyama的答案是正确的,但我经常在可能的情况下使用通配符路由来绕过这种奇怪的情况。

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. 当然,对于许多应用程序来说这是不可能的,但是,这过去为我节省了时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM