Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

commented Mar 13, 2014

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Sep 14, 2015

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
You can’t perform that action at this time.