Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Last active December 29, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachallaun/7610122 to your computer and use it in GitHub Desktop.
Save zachallaun/7610122 to your computer and use it in GitHub Desktop.

cljs/js interop

Node.js require

var request = require('request');
(ns ...
  (:require [cljs.nodejs :as nodejs]))

(def request (nodejs/require "request"))

Constructors

new Date();
(js/Date.)

Method invocation

JSON.parse("[1, 2, 3]")
(.parse js/JSON "[1, 2, 3]")

Property lookup

[1, 2, 3].length
(.-length (array 1 2 3))

clj->js, js->clj

(clj->js {:a 1 :b 2}) ;; JS object {a: 1, b: 2}

(let [o (clj->js {:a 1 :b 2})]
  (js->clj o) ;; {"a" 1 "b" 2}
  (js->clj o :keywordize-keys true)) ;; {:a 1 :b 2}

Working with JS data

(array 1 2 3 4) ;; JS array [1, 2, 3, 4]

(js-obj "a" 1 "b" 2) ;; JS object {a: 1, b: 2}

(js-keys (js-obj "a" 1 "b" 2)) ;; JS array ["a", "b"]

(let [a (array "foo" "bar" "baz")]
  (aget a 0) ;; "foo"
  (aset a 2 "buzz")) ;; a is now ["foo", "bar", "buzz"]

(let [o (js-obj "somekey" (array "foo" "bar" "baz"))]
  (aget o "somekey" 0) ;; "foo", nested lookup
  (aset o "somekey" 2 "buzz")) ;; o is now {somekey: ["foo", "bar", "buzz"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment