我有一个简单的Backbone
应用程序。我试图理解启动 Backbone.History
对象时传递 pusState: true
所产生的差异。
JavaScript
var r = new (Backbone.Router.extend({
routes: {
"users": "allUsers",
"users/new": "createUser"
},
allUsers: function () {
v.render("showing all users");
},
createUser: function () {
v.render("showing form for creating new user");
}
}));
Backbone.history.start({ pushState: true });
Q1。当我传递 pushState: true
并打开 localhost:3000/#/users/
时,此网址会自动重定向到 localhost:3000/users
为什么会发生这种重定向?
第二季度。当我不通过 pushState: true
时,不会发生重定向。
localhost:3000/#/users/
工作正常,但 localhost:3000/users
不起作用?
在history.start方法中传递这个值有什么重要性以及为什么它很重要。
最佳答案
启动 Backbone.history
时包含 pushState
选项会告知 Backbone 使用 HTML5 历史记录 API。基本上,此 API 允许您更改地址栏中的 URL,而无需重新加载页面 ( see more about it here )。如果没有 pushState
,Backbone 将使用哈希值 (#
) 来更改 URL,因此无需重新加载页面。
When I pass
pushState: true
and I open localhost:3000/#/users/, this url automatically redirects to localhost:3000/users Why does this redirect happen ?
由于您启用了历史 API,Backbone 将选择使用实际路由 (localhost:3000/users
),而不是散列路由 (localhost:3000/#/users/
)。但是,它仍然可以理解散列路由,因此它将它们重定向到实际路由。这样,如果您在现有应用程序中启用了 pushState
,则任何添加了哈希路由书签的用户仍然可以使用该书签。 (当然,任何新书签都会有正确的路线)。
When I do not pass pushState: true then redirect does not happen. localhost:3000/#/users/ works fine but localhost:3000/users does not work ?
回答问题2:当pushState
未启用时,Backbone将仅使用散列路由。因此 localhost:3000/#/users/不会重定向,因为它是“正确”的路由:它将显示内容。根据您设置服务器的方式,localhost:3000/users
将是
- 加载您的应用,但不显示任何内容(或默认内容)
- 加载
/users
资源,或者 - 给您一个 404 错误。
关于javascript - Backbone History Start方法中HTML5的pushState有什么用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30897419/