From 736e4b4514be4cb1c0e9b9deedccc573f89629c9 Mon Sep 17 00:00:00 2001 From: Emil Bay Date: Fri, 19 May 2017 14:56:45 +0200 Subject: [PATCH] Add hook for replaceState (#494) * Add hook for replaceState * Clarify why replaceState is dangerous --- README.md | 1 + index.js | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c0a24da..5fa7bd3 100644 --- a/README.md +++ b/README.md @@ -262,6 +262,7 @@ Choo fires messages when certain events happen: The `render` event should be emitted (`emitter.emit('render')`) whenever you want the app to re-render the DOM - it won't happen on its own except when you navigate between routes. The `pushState` can be emitted to navigate between routes: `emitted.emit('pushState', '/some/route')`. +You can emit `replaceState` which will overwrite the current entry in the browser history, but be very careful as this removes the option of navigating back! Note `render` will only have an effect once the `DOMContentLoaded` event has been fired. diff --git a/index.js b/index.js index f91fa0e..591c2dc 100644 --- a/index.js +++ b/index.js @@ -55,13 +55,16 @@ function Choo (opts) { bus.emit('pushState') }) - bus.prependListener('pushState', function (href) { - if (href) window.history.pushState({}, null, href) + bus.prependListener('pushState', updateHistory.bind(null, 'push')) + bus.prependListener('replaceState', updateHistory.bind(null, 'replace')) + + function updateHistory (mode) { + if (href) window.history[mode + 'State']({}, null, href) bus.emit('render') setTimeout(function () { scrollIntoView() }, 0) - }) + } if (opts.href !== false) { nanohref(function (location) {