Last active
December 21, 2015 06:19
-
-
Save fredyr/6263249 to your computer and use it in GitHub Desktop.
FRP version of swannodette's examples on CSP and core.async.
http://swannodette.github.io/2013/07/12/communicating-sequential-processes/
This file contains 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
;; Mouse move handler | |
(let [el "#only-mouse" | |
ch (Bacon.fromEventTarget js/window "mousemove")] | |
(-> ch | |
(.map (ƒ [e] (str (.-offsetX e) ", " (.-offsetY e)))) | |
(.onValue (js/$ el) "text"))) | |
(defn location [ch] | |
(.map ch (ƒ [[tag e]] | |
[tag {:x (.-offsetX e) :y (.-offsetY e)}]))) | |
;; Independent timer events merged into a stream | |
(let [el "#processes" | |
ch (Bacon.mergeAll | |
(Bacon.interval 250 1) | |
(Bacon.interval 1000 2) | |
(Bacon.interval 1500 3))] | |
(-> ch | |
(.map (ƒ [p] (str "<div class='proc-" p "'>Process " p "</div>"))) | |
(.slidingWindow 10) | |
(.onValue (js/$ el) "html"))) | |
;; Maintain source name in the events | |
(defn tagged-event [target evt-name] | |
(-> (Bacon.fromEventTarget target evt-name) | |
(.map (ƒ [e] [evt-name e])))) | |
(defn set-html! [el val] | |
(.html (js/$ el) val)) | |
;; Mouse move & keyboard handler | |
(let [ch (.merge (location (tagged-event js/window "mousemove")) | |
(tagged-event js/window "keyup"))] | |
(.onValue ch (ƒ [[tag e]] | |
(case tag | |
"mousemove" (set-html! "#mouse" (str (:x e) ", " (:y e))) | |
"keyup" (set-html! "#key" (str (.-keyCode e))))))) | |
;; Simplest auto complete | |
(def base-url | |
"http://en.wikipedia.org/w/api.php?action=opensearch&callback=?&search=") | |
(let [search (ƒ [q] (.then (js/$.getJSON (str base-url q)) | |
(ƒ [data] (aget data "1")))) | |
ch (-> (.asEventStream (js/$ "#input-field") "keyup") | |
(.throttle 250) | |
(.map (ƒ [e] (.val (js/$ (.-target e))))) | |
(.flatMapLatest (ƒ [q] (Bacon.fromPromise (search q)))))] | |
(.onValue ch (js/$ "#search") "text")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment