0

Given I've defined a protocol

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

And I am interacting with a library in which a javascript object with this interface is passed in as follows

(js/somelib.connect url listener)

Is there an easy way to create a javascript object using the defined protocol?

I have tried to reify the protocol:

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

However this does not give an object that is compatible with external libraries.

Thanks

1 Answer 1

1

There is a conceptual mismatch here. The js library already expects a defined behavior but you want to define it yourself from cljs. Should the listener be a js object with 2 methods, onConnection and onUpdate? Then you need some translator between your SubscriptionListener in cljs and a regular object in 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))))

Notice that the functions in SubscriptionListener take the object that complies with the protocol as their first argument. If cid is some id given to you by the server and you tried to call (on-connection cid) you would get Method on-connection not defined for integers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.