LoginSignup
5
5

More than 5 years have passed since last update.

js->cljが効かない。なぜ?

Posted at

ClojureScriptの標準にある関数js->cljはJavaScriptのオブジェクトをClojureScriptのマップに変換したりするものですが、効かないときがあります。

sample.cljs
(ns sample.core
  (:require [lt.objs.editor :as editor]
            [lt.objs.editor.pool :as pool]))

(def cm (editor/->cm-ed (pool/last-active)))
(def cursor (.getCursor cm))

(js->clj cursor)

上のようにカーソルをjs->cljで変換しようとしてもうまくいかず
(assoc (js->clj cursor) :a :b)なんてすると
Error: No protocol method IAssociative.-assoc defined for type object: [object Object]と怒られます。

この原因は
https://github.com/clojure/clojurescript/blob/master/src/cljs/cljs/core.cljs
js->cljを見るとわかりますがcondの中の
(identical? (type x) js/Object)の条件が厳しいのが原因です。

代わりに

sample2.cljs
(ns sample.core
  (:require [lt.objs.editor :as editor]
            [lt.objs.editor.pool :as pool]
            [lt.util.cljs :as c]))

(def cm (editor/->cm-ed (pool/last-active)))
(def cursor (.getCursor cm))

(c/js->clj cursor)

のようにlt.util.cljs/js->cljを使うと変換できたりします。

https://github.com/LightTable/LightTable/blob/master/src/lt/util/cljs.cljs を見ると条件が

                  (or force-obj
                      (identical? x (js/Object x))
                      (identical? (type x) js/Object)
                      (identical? (type x) js/global.Object))

になっています。

js->cljのオプションには:keywordize-keysがありますが、lt.util.cljsの方には追加で:force-objオプションもあります。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5