1

My project.clj is as follows :

(defproject cljsbuild-example-simple "0.3.2"
  :description "A simple example of how to use lein-cljsbuild"
  :source-paths ["src-clj"]
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [compojure "1.0.4"]
                 [hiccup "1.0.0"]]
  :plugins [[lein-cljsbuild "0.3.2"]
            [lein-ring "0.7.0"]]
  :cljsbuild {
    :builds [{:source-paths ["src-cljs"]
              :compiler {:output-to "resources/public/js/main.js"
                         :libs ["src-js/jsfuncs.js"]
                         :optimizations :whitespace
                         :pretty-print true}}]}
  :ring {:handler example.routes/app})

jsfuncs.js contains the following code :

function calculate(a,b,c) {
    d = (a+b) * c;
    return d;
}

How do I invoke this js function from within the clojurescript files? I tried to invoke this function via :

(js/calculate 4 5 6)

But this did not work. Thanks.

1 Answer 1

4

The main problem is the Google Closure Compiler needs to read the JavaScript and be able to understand it. Normal JS code lacks some hints (JSDoc tags) and namespaces that are necessary for the compiler.

The JSDoc tags are kind of optional (they help the compiler catch extra errors and optimize code better) but the namespace parts need to be added. So this would be:

goog.provide('jsfuncs');

/**
 * @param {number} a
 * @param {number} b
 * @param {number} c
 * @return {number}
 */
jsfuncs.calculate = function(a, b, c) {
  d = (a+b) * c;
  return d;
};

The other method is to give the Closure Compiler an extern file that describes the JS code. I'm not 100% certain how to do this but there is some pretty good documentation from Google. There are also some large extern files on the project's homepage that cover jQuery, Angular, and other common libraries.

After doing one of these methods you can call calculate with this:

(ns some.namespace
   (:require [jsfuncs :as jsf]))

(console/log (jsf/calculate 1 2 3))
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.