Skip to content

Instantly share code, notes, and snippets.

/history.cljs Secret

Created February 13, 2017 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/e9e4c1c1c3d40afaf49cf6be154ae87a to your computer and use it in GitHub Desktop.
Save anonymous/e9e4c1c1c3d40afaf49cf6be154ae87a to your computer and use it in GitHub Desktop.
Example of using HTML5History
(ns relocate.history
"Working with Html5History features"
(:require [goog.events :as events]
[re-frame.core :as re-frame])
(:import goog.history.Html5History
[goog.History EventType]))
(declare use-fragment)
(goog-define use-fragment false)
(def token-transformer
"goog.history.Html5History default behavior is that setToken
replaces pathname of current location, but keeps search query as is.
This transformer treats tokens as \"pathAndAfter\"; hence they may also include
query string with hash and a query string is replaced when a new history state
is pushed."
(reify
Object
(retrieveToken [_ prefix location]
(str (.. location -pathname (substr (.-length prefix)))
(.-search location)
(.-hash location)))
(createUrl [_ token prefix location] (str prefix token))))
(defonce page-history (Html5History. js/undefined token-transformer))
(doto page-history
(.setUseFragment use-fragment)
(.setPathPrefix "")
(.setEnabled true))
(defonce ^:dynamic *page-navigate-listener* nil)
(defn init-history!
"Listen for navigate event listeners to dispatch events."
[]
(when *page-navigate-listener*
(events/unlistenByKey *page-navigate-listener*))
(set! *page-navigate-listener*
(events/listen page-history
EventType.NAVIGATE
#(re-frame/dispatch [::navigate
(.getToken page-history)]))))
(defn push-state
"Handler to add a new window.history entry with state and href attributes."
[page [_ uri]]
(.setToken page-history uri)
page)
(defn replace-state
"Handler to update the current window.history entry with state."
[page [_ href]]
(.replaceToken page-history href)
page)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment