Skip to content

Instantly share code, notes, and snippets.

@danielsz
Last active July 15, 2016 15:13
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save danielsz/8086074 to your computer and use it in GitHub Desktop.
Save danielsz/8086074 to your computer and use it in GitHub Desktop.
PushState (via Html5History from google closure) with secretary, a client-side routing library for clojurescript. Allows to map absolute urls with routes without the hash-bang hackery.
(def history (Html5History.))
(.setUseFragment history false)
(.setPathPrefix history "")
(.setEnabled history true)
(let [navigation (listen history EventType/NAVIGATE)]
(go
(while true
(let [token (.-token (<! navigation))]
(secretary/dispatch! token)))))
(events/listen js/document "click" (fn [e]
(let [path (.getPath (.parse Uri (.-href (.-target e))))
title (.-title (.-target e))]
(when (secretary/any-matches? path)
(. history (setToken path title))
(.preventDefault e)))))
@xavi
Copy link

xavi commented Feb 14, 2014

I understand that the first listen is from Google Closure, but... where is the second one, events/listen, coming from?

@danielsz
Copy link
Author

Sorry about that.

(require' [goog.events :as events]

(defn listen [el type]
  (let [out (chan)]
    (events/listen el type
      (fn [e] (put! out e)))
    out))

@rafd
Copy link

rafd commented Oct 2, 2014

Thanks for this.

In my case, I had spans within my a tags, and the path would not be found, because (-target e) was the span. I fixed this my search up the DOM from the clicked element for an href:

 (let [href ((fn [e]
                   (if-let [href (.-href e)]
                      href
                      (when-let [parent (.-parentNode e)]
                         (recur parent)))) (.-target e))] 
    ...)

@venantius
Copy link

Since this seems like the sort of thing that almost any ClojureScript app is going to have to wrestle with, I've put together a small library that encapsulates this pattern here for easy consumption: https://github.com/venantius/accountant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment