Skip to content

Commit

Permalink
CLJS-26: Added this-as macro and extend-object fn to provide standard…
Browse files Browse the repository at this point in the history
… ways to reference this
  • Loading branch information
fogus committed Sep 30, 2011
1 parent 2647fd5 commit 09ff093
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/clj/cljs/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -643,3 +643,9 @@
ret# ~expr]
(prn (str "Elapsed time: " (- (.getTime (js/Date.) ()) start#) " msecs"))
ret#))

(defmacro this-as
"Defines a scope where JavaScript's implit this is bound to the name provided."
[name & body]
`(let [~name (~'js* "this")]
~@body))
11 changes: 11 additions & 0 deletions src/cljs/cljs/core.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -3265,3 +3265,14 @@ reduces them without incurring seq initialization"
(defn prefers
"Given a multimethod, returns a map of preferred value -> set of other values"
[multifn] (-prefers multifn))

(defn extend-object
"Takes a JavaScript object and a map of names to functions and
attaches said functions as methods on the object. Any references to
JavaScript's implict this (via the this-as macro) will resolve to the
object that the function is attached."
[obj fn-map]
(doseq [[key-name f] fn-map]
(let [str-name (name key-name)]
(js* "~{obj}[~{str-name}] = ~{f}")))
obj)

1 comment on commit 09ff093

@swannodette
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this-as is a bit of an awkward name. "bind-this", "bind"?

Please sign in to comment.