Skip to content

Instantly share code, notes, and snippets.

@abp
Forked from bodil/README.md
Created July 31, 2013 11:51
Show Gist options
  • Save abp/6121338 to your computer and use it in GitHub Desktop.
Save abp/6121338 to your computer and use it in GitHub Desktop.

core.async example thing

To run:

  • checkout https://github.com/clojure/core.async and install it using lein install
  • make a project directory for this code
  • put omgcoreasync.cljs in a src subdirectory, project.clj and index.html in the root
  • go lein cljsbuild once to build
  • load index.html in a browser and watch it go
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>core.async demo</title>
<meta name="viewport" content="width=device-width">
<script src="js/main.js"></script>
</head>
<body>
<h1>horse_ebooks knows what you did</h1>
</body>
</html>
(ns omgcoreasync
(:require-macros [cljs.core.async.macros :refer [go alt!]])
(:require [cljs.core.async :as async]))
(def counter (atom 0))
(defn parse-data [data]
(let [data (js->clj data)
children ((data "data") "children")]
(map (fn [child] ((child "data") "title")) children)))
(defn jsonp-get [url]
(let [callback-name (str "mycallback" (swap! counter inc))
channel (async/chan)]
(aset js/window callback-name
(fn [data]
(async/put! channel data)))
(let [script (.createElement js/document "script")]
(aset script "src" (str url "?jsonp=" callback-name))
(.appendChild document/head script))
channel))
(go
(let [c (jsonp-get "http://www.reddit.com/r/clojure.json")
d (jsonp-get "http://www.reddit.com/r/dogfort.json")
h (jsonp-get "http://www.reddit.com/r/haskell.json")]
(while true
(alt!
[c d h] ([val ch] (.write js/document (str (parse-data val)) ch))))))
(defproject omgcoreasync "0.1.0-SNAPSHOT"
:dependencies [[core.async "0.1.0-SNAPSHOT"]]
:plugins [[lein-cljsbuild "0.3.2"]]
:cljsbuild {:builds
[{:source-paths ["src"],
:compiler
{:output-to "js/main.js",
:output-dir "js",
:optimizations :simple,
:jar true}}]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment