Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend protocol in ClojureScript to get value from native js object

I have a codebase that makes a heavy use of get and get-in for nested forms. I want to be able to use native javascript objects too, without (much) code rewrite.

js> cljs.user.o = {foo: 42}  // in js console

cljs.user> (get o "foo") ; => 42 ; in cljs console

Since I only query the forms, but don't modify them, I thought it would be enough to implement get (which get-in relies on). Here is my attempt,

(extend-protocol ILookup
  js/Object
    (-lookup [m k] (aget m k))
    (-lookup [m k not-found (or (aget m k) not-found)))

It seems to work, but it breaks a lot of things in a strange way.

like image 737
Adam Schmideg Avatar asked Jun 03 '13 10:06

Adam Schmideg


1 Answers

You're modifying the Object prototype, you don't want to do that, the following is better:

(extend-protocol ILookup
  object
  (-lookup [m k] (aget m k))
  (-lookup [m k not-found] (or (aget m k) not-found)))
like image 131
dnolen Avatar answered Dec 19 '22 09:12

dnolen