這個問題的最簡單的方法,如果你不需要支持這種行爲對舊版瀏覽器,是使pushState的在你的骨幹路由器,這樣你就不會爲路由使用#
:
Backbone.history.state({pushState: true});
編輯:
的其他潛在解決方案,但它是一個有點亂,是做一些URL蠢事弄清楚應該是哈希後什麼,然後導航到該路線。
例如,假設您想瀏覽到:
http://webapp.com/abc/#page1
其中「第1頁」是它構成了主幹航線的片段。
如果您將用戶發送至http://webapp.com/abc/page1
。您可以檢測瀏覽器是否具有pushState。如果沒有,你可以用散列替換'root'後面的所有內容。下面是一些示例代碼,可能讓你在正確的軌道上,同時支持臺瀏覽器:
var _defaults = {
pushState: Modernizr.history,
silent: true,
root: '/'
};
var start = function(options) {
// Start the routing either with pushstate or without
options = _.extend(_.clone(this._defaults), options);
Backbone.history.start(options);
if (options.pushState) {
Backbone.history.loadUrl(Backbone.history.getFragment());
return;
}
this.degradeToNonHistoryURL();
};
/**
* For fragment URLs, we check if the actual request is for the root i.e '/',
* If it is, we can continue and Backbone will do the magic
* If it isn't we redirect to the root with the route as a fragment
* foo.com/bar/1 -> foo.com/#bar/1
*/
degradeToNonHistoryURL = function() {
var pathName = window.location.pathname;
// If the root is '/', length is one. If the root is 'foo', length is 5 (/foo/)
var rootLength = _getRoot().length;
var isRootRequest = pathName.length === rootLength;
if (!isRootRequest) {
var route = pathName.substr(rootLength);
window.location.href = _getRoot() + '#' + route + window.location.search;
return;
}
Backbone.history.loadUrl(Backbone.history.getFragment());
},
/**
* Get the effective root of the app. Normally it's '/', but if set to 'foo', we want
* to return '/foo/' so we can more easily determine if this is a root request or not.
* @returns {String} The effective root
*/
_getRoot = function() {
if (Backbone.history.options.root === '/') {
return '/';
}
return '/' + Backbone.history.options.root + '/';
},
訣竅這裏使pushState的網址您的規範網址,並始終將用戶引導至這些那些。一旦瀏覽器採用增加,理論上應該很容易將所有這些垃圾切除掉,而不必更新所有鏈接。
如果您向未登錄的用戶提供完整的URL路徑,這是如何工作的?網址的一部分根據url參數確定您要瀏覽哪個BB視圖? – bjm88 2014-10-17 20:02:47
這裏有一些文章解釋了爲什麼hash和hashbang標籤不理想。 http://danwebb.net/2011/5/28/it-is-about-the-hashbangs,http://artsy.github.io/blog/2012/06/25/replacing-hashbang-routes-with- pushState的/。 – bjm88 2014-10-23 17:39:16
這是一篇關於理解pushstate的文章,https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history – bjm88 2014-10-23 17:39:57