From 9d6165d03be1d03ae530a151451be0cb8f1762d7 Mon Sep 17 00:00:00 2001 From: Kyle Dickerson Date: Thu, 12 Mar 2020 14:08:34 -0700 Subject: [PATCH] #3391 - Add History `trailingSlash` option always use trailing slash on root. --- backbone.js | 7 ++++--- test/router.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/backbone.js b/backbone.js index bc4f18f9a..35730a687 100644 --- a/backbone.js +++ b/backbone.js @@ -1851,6 +1851,7 @@ // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; + this._trailingSlash = this.options.trailingSlash || false; this._wantsHashChange = this.options.hashChange !== false; this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); this._useHashChange = this._wantsHashChange && this._hasHashChange; @@ -1993,10 +1994,10 @@ // Normalize the fragment. fragment = this.getFragment(fragment || ''); - // Don't include a trailing slash on the root. + // Strip trailing slash on the root unless _trailingSlash is true var rootPath = this.root; - if (fragment === '' || fragment.charAt(0) === '?') { - rootPath = rootPath.slice(0, -1) || '/'; + if (!this._trailingSlash && (fragment === '' || fragment.charAt(0) === '?')) { + rootPath = rootPath.slice(0, -1) || '/'; // rootPath must always have at least '/' } var url = rootPath + fragment; diff --git a/test/router.js b/test/router.js index c33901883..c60eb7418 100644 --- a/test/router.js +++ b/test/router.js @@ -807,6 +807,38 @@ Backbone.history.navigate('?x=1'); }); + QUnit.test('#3391 - Empty root normalizes to single slash.', function(assert) { + assert.expect(1); + Backbone.history.stop(); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(state, title, url) { + assert.strictEqual(url, '/'); + } + } + }); + location.replace('http://example.com/root/path'); + Backbone.history.start({pushState: true, hashChange: false, root: ''}); + Backbone.history.navigate(''); + }); + + QUnit.test('#3391 - Use trailing slash on root when trailingSlash is true.', function(assert) { + assert.expect(1); + Backbone.history.stop(); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(state, title, url) { + assert.strictEqual(url, '/root/'); + } + } + }); + location.replace('http://example.com/root/path'); + Backbone.history.start({pushState: true, hashChange: false, root: 'root', trailingSlash: true}); + Backbone.history.navigate(''); + }); + QUnit.test('#2765 - Fragment matching sans query/hash.', function(assert) { assert.expect(2); Backbone.history.stop();