开发者

How to connect Clojure functions to html page?

I am having some problems with a project and was hoping you could help.

I have some clojure functions like

(def player-grid {:width {} :height {}})

(defn contains-coord [grid x y]
  (if ((and (= ((grid :width) x) x) (= ((grid :height) y) y)))
    true
    false))

(defn add-to-grid [grid x y]
  (assoc grid :width (into (grid :width) {x x})
              :height (into (grid :height) {y y})))

and I also have a html page that has a 10X10 battleship game board made of checkboxes. I have tried to find a way to connect the two so that when I click on the board to put a ship the coordinates are sent to the clojure function.

Basically, I have开发者_开发百科 no idea how to put the two together to work as a whole.

I'd really appreciate some advice or example on this matter since I found nothing useful when using compojure and hiccup except for creating new html pages from scratch.


Whoa- You're trying to connect two things that aren't meant to connect together (but there's no way you could know that as a beginner.)

First, you need to decide where your clojure code should live- Should it live on a web server that is serving up these web pages, or should it live in the web browser on the computer that is being used to play battleship? Either possibility might make sense.

If you want to run your clojure code on the server, you'll have to write messages to the server when a user clicks on the grid. You'll have to link each grid square to some javascript code, which then sends a message to your server to a url with a name like "http://battleshipgame.com/game/3243/grid?x=3&y=7" which you would then handle with compojure (and the compojure route handler would then link to your function.) Doing this is called AJAX, and many people would use the jQuery functions "click" to connect the grid space to the javascript and "post" to send the message to the url.

If you want to run your clojure code on the client, then you can't do it, since there is no clojure interpreter running in the user's web browser... However, recently Rich Hickey released ClojureScript which can convert clojure code into javascript. Using ClojureScript you could do exactly what you want in the browser. Look at the twitter sample in the ClojureScript compiler to see how to do this: https://github.com/clojure/clojurescript/tree/master/samples/twitterbuzz

As you can see, this is all a bit involved and might require some dedication on your part to learn how to accomplish all this stuff- Good Luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜