Skip to content

Instantly share code, notes, and snippets.

@zachallaun zachallaun/gist:7610122
Last active Dec 29, 2015

Embed
What would you like to do?

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