From 4e0fe376cfafb5419e0f4e5684d35873322abeac Mon Sep 17 00:00:00 2001 From: Tom Coleman Date: Wed, 17 Sep 2014 11:36:31 +1000 Subject: [PATCH] Allow replaceState via `Location.replaceState` #4 --- examples/historyState/historyState.js | 6 ++++-- lib/location.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/examples/historyState/historyState.js b/examples/historyState/historyState.js index 04b2816..b98cded 100644 --- a/examples/historyState/historyState.js +++ b/examples/historyState/historyState.js @@ -9,11 +9,13 @@ if (Meteor.isClient) { Template.hello.events({ 'submit #push': function(e, t) { e.preventDefault(); - Iron.Location.go('/' + Random.id(), {historyState: t.$('input').val()}); + var state = $(e.target).find('input').val(); + Iron.Location.go('/' + Random.id(), {historyState: state}); }, 'submit #replace': function(e, t) { e.preventDefault(); - console.log("Can't do this yet"); + var state = $(e.target).find('input').val(); + Iron.Location.replaceState(state); } }) } diff --git a/lib/location.js b/lib/location.js index 048afc4..a1ea6e6 100644 --- a/lib/location.js +++ b/lib/location.js @@ -121,6 +121,21 @@ var onClickHandler = function (e) { throw err; } }; + +var replaceState = function(historyState) { + // XXX: should we throw / warn / do nothing here? + if (isUsingHashPaths()) + throw new Error("Can't replaceState when using hash paths"); + + var state = current; + if (EJSON.equals(state.options.historyState, historyState)) + return; + + state.options.historyState = historyState; + history.replaceState(historyState, null, state.url); + dep.changed(); +} + /*****************************************************************************/ /* Location API */ /*****************************************************************************/ @@ -228,6 +243,13 @@ Location.go = function (url, options) { return go(url, options); }; +/** + * Update the history.state for the given location + */ +Location.replaceState = function(historyState) { + return replaceState(historyState); +} + /** * Automatically start Iron.Location */