From 4049279269ede7cdc4887ffc41a4ba78f878af2f Mon Sep 17 00:00:00 2001 From: Samy Pesse Date: Mon, 3 Oct 2016 15:48:28 +0200 Subject: Emit current location when listening --- packages/gitbook-core/src/actions/navigation.js | 42 +++++++++++++++++++------ 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/packages/gitbook-core/src/actions/navigation.js b/packages/gitbook-core/src/actions/navigation.js index bb58595..bcb4619 100644 --- a/packages/gitbook-core/src/actions/navigation.js +++ b/packages/gitbook-core/src/actions/navigation.js @@ -14,16 +14,35 @@ const SUPPORTED = ( */ function activate() { return (dispatch, getState) => { - const listener = (location) => { - const { listeners } = getState().navigation; - location = Location.fromNative(location); + dispatch({ + type: ACTION_TYPES.NAVIGATION_ACTIVATE, + listener: () => dispatch(emit()) + }); - listeners.forEach(handler => { - handler(location, dispatch, getState); - }); - }; + // Trigger for existing listeners + dispatch(emit()); + }; +} - dispatch({ type: ACTION_TYPES.NAVIGATION_ACTIVATE, listener }); +/** + * Emit current location + * @param {List|Array} to? + */ +function emit(to) { + return (dispatch, getState) => { + const { listeners, history } = getState().navigation; + + if (!history) { + return; + } + + const location = Location.fromNative(history.location); + + to = to || listeners; + + to.forEach(handler => { + handler(location, dispatch, getState); + }); }; } @@ -87,7 +106,12 @@ function redirect(uri) { * @return {Action} action */ function listen(listener) { - return { type: ACTION_TYPES.NAVIGATION_LISTEN, listener }; + return (dispatch, getState) => { + dispatch({ type: ACTION_TYPES.NAVIGATION_LISTEN, listener }); + + // Trigger for existing listeners + dispatch(emit([ listener ])); + }; } /** -- cgit v1.1