From 09ff093dc86b455e3090ce3612c5e01f3b5bada6 Mon Sep 17 00:00:00 2001 From: fogus Date: Fri, 30 Sep 2011 14:37:58 -0400 Subject: [PATCH] CLJS-26: Added this-as macro and extend-object fn to provide standard ways to reference this --- src/clj/cljs/core.clj | 6 ++++++ src/cljs/cljs/core.cljs | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/clj/cljs/core.clj b/src/clj/cljs/core.clj index 6c3221be53..5448654fd0 100644 --- a/src/clj/cljs/core.clj +++ b/src/clj/cljs/core.clj @@ -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)) diff --git a/src/cljs/cljs/core.cljs b/src/cljs/cljs/core.cljs index aedfe0067f..9efefd2cb5 100644 --- a/src/cljs/cljs/core.cljs +++ b/src/cljs/cljs/core.cljs @@ -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)