Last active
July 15, 2016 15:13
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))))) |
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))
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))]
...)
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
I understand that the first
listen
is from Google Closure, but... where is the second one,events/listen
, coming from?