我的网站刚刚在Backbone.js中实现了pushstates,并且IE的整个网站都中断了。我该如何为IE创建一个后备?
我想要实现的目标
主要网址:http://mydomain.com/explore
另一个网址:'http://mydomain.com/explore/1234
该网站的主页为http://mydomain.com/explore
,触发路由器功能explore
。
当用户访问http://mydomain.com/explore/1234
时,Backbone的路由器将触发函数viewListing
,该函数与函数explore
相同,但也包含项ID 1234
的详细信息。
Backbone.js路由器
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'explore': 'explore',
'explore/:id': 'viewListing',
},
explore: function() {
this.listingList = new ListingCollection();
// More code here
},
viewListing: function(listing_id) {
this.featuredListingId = listing_id; // Sent along with fetch() in this.explore()
this.explore();
}
});
App = new AppRouter();
// Enable pushState for compatible browsers
var enablePushState = true;
// Disable for older browsers (IE8, IE9 etc)
var pushState = !!(enablePushState && window.history && window.history.pushState);
if(pushState) {
Backbone.history.start({
pushState: true,
root: '/'
})
} else {
Backbone.history.start({
pushState: false,
root: '/'
})
}
问题:正如您在上面的代码中所看到的,如果它是一个不兼容的浏览器,我尝试禁用pushState: false
的pushstates。
然而,要让IE访问通常适用于普通浏览器(http://mydomain.com/explore
)的内容,IE将需要转到http://mydomain.com/explore/#explore
这会让事情变得混乱!进一步访问http://mydomain.com/explore/1234
IE需要转到http://mydomain.com/explore/#explore/1234
如何解决这个问题?
答案 0 :(得分:2)
如果您不想要http://mydomain.com/explore/#explore
网址,则必须重定向到
http://mydomain.com/#explore
所以Backbone将从它开始。
if(!pushState && window.location.pathname != "/") {
window.location.replace("/#" + window.location.pathname)
}
UPD:将路径设置为哈希window.location.pathname.substr(1)
UPD2:如果您希望/explore/
成为骨干路由的根,那么您必须将其从路由中排除并设置为History.start({root: "/explore/"})
routes: {
'': 'explore',
':id': 'viewListing',
}