使用defprotocol创建javascript对象

时间:2015-05-11 21:21:15

标签: clojurescript

鉴于我已经定义了协议

(defprotocol SubscriptionListener
  (onConnection [cid] "")
  (onUpdate [cid data] ""))

我正在与一个库进行交互,其中带有此接口的javascript对象传递如下

(js/somelib.connect url listener)

是否有一种使用定义的协议创建javascript对象的简单方法?

我试过reify协议:

(js/somelib.connection "localhost" (reify SubscriptionListener
                                      (onConnection [cid] (println cid))
                                      (onUpdate [cid data] (println data))))

但是,这并没有提供与外部库兼容的对象。

由于

1 个答案:

答案 0 :(得分:1)

这里存在概念上的不匹配。 js库已经预期了一个已定义的行为,但你想自己从cljs定义它。听众应该是一个有两种方法的js对象,onConnectiononUpdate?然后你需要在你的SubscriptionListener cljs和js中的常规对象之间有一些翻译:

(defprotocol SubscriptionListener
  (on-connection [o cid])
  (on-update     [o cid data]))

(defn translator
  "Translates a cljs object that follows SubscriptionListener 
   into a js object that has the right mehods"
  [o]
  #js {:onConnection (fn [cid]      (on-connection o cid))
       :onUpdate     (fn [cid data] (on-update o cid data))})

(js/somelib.connection "localhost"
                        (translator (reify SubscriptionListener
                                      (on-connection [_ cid] (println cid))
                                      (on-update     [_ cid data] (println data))))

请注意SubscriptionListener中的函数将符合协议的对象作为其第一个参数。如果cid是服务器为您提供的某个ID,并且您尝试拨打(on-connection cid),则会获得Method on-connection not defined for integers

相关问题