-
Notifications
You must be signed in to change notification settings - Fork 0
History
The file src/lib/cljs/one/browser/history.cljs
contains the one.browser.history
namespace which implements basic support for working with the browser's history.
Traditional web applications allow users to navigate between pages by clicking on hyperlinks, using the browser's navigation buttons and entering URLs in the address bar. Single-page JavaScript applications do not have pages, and yet browsers still allow all of these forms of navigation. Providing support for this type of navigation can help make an application feel more familiar.
Google Closure supports working with history and responding to navigation events generated by the browser. The one.browser.history
namespace provides a very simple wrapper around this functionality.
The sample application has two main views: the form where a user may enter their name and a greeting view where a greeting message is displayed. In the sample application, when the form is displayed, the #form
document location fragment is added to the end of the URL.
http://localhost:8080/development#form
When the greeting page is displayed the #greeting
document page fragment is added to the end of the URL.
http://localhost:8080/development#greeting
History changes are reflected in this document location fragment. As changes are made to the history, these fragments (also known as tokens) are stored internally in a stack.
Users may navigate this stack by clicking the "Back" or "Forward" button or by entering a URL in the address bar which contains a document location fragment.
To work with history from ClojureScript, you must first create a history object. This must be done before the host page has finished loading. The history object is initialized with a function that will be called every time the history is changed.
(use '[one.browser.history :only (history set-token)])
(use '[one.sample.history :only (nav-handler)])
(history nav-handler)
nav-handler
is a function defined in the one.sample.history
namespace of the sample application. It fires the token it receives when a navigation event occurs. Valid tokens for this application are :form
and :greeting
which correspond to events which move the application to the :form
or :greeting
state.
(defn nav-handler [{:keys [token navigation?]}]
(when navigation?
(dispatch/fire token)))
The history may be modified from ClojureScript with the set-token
function.
(set-token :something)
When the user navigates by clicking the "Back" button, or entering a URL with a document location fragment, the nav-handler
function will be called, passing a map with :token
, :type
and :navigation?
keys. An application is free to respond to these events in any way.