6

I am trying to run ClojureScript on node.js

app1.js target code: working:

var rx = require("./lib/rx/rx.node.js");
var moment = require("./lib/moment/moment.js");

var timeStream = new rx.Observable.interval(300)
    .subscribe(function(index)
     {
        console.log(moment().format("dddd, MMMM Do YYYY, h:mm:ss a"));
    });

core.cljs my try so far:

(ns rxcljs.core
  (:use [cljs.nodejs :only [require]])
)

(def rx (require "./lib/rx/rx.node.js"))
(def moment (require "./lib/moment/moment.js")) 

(-> rx
   (.Observable)
   (.interval 300)
   (.subscribe #(->> (->(moment) 
                        (.format "dddd, MMMM Do YYYY, h:mm:ss a" )
                      )
                     (.log js/console)
                 )
    )
)

app.js the actual compile output: not working

.....
.....
cljs.nodejs = {};
cljs.nodejs.require = require;
cljs.nodejs.process = process;
cljs.core.string_print = cljs.nodejs.require.call(null, "util").print;
var rxcljs = {core:{}};
rxcljs.core.rx = cljs.nodejs.require.call(null, "./lib/rx/rx.node.js");
rxcljs.core.moment = cljs.nodejs.require.call(null, "./lib/moment/moment.js");
rxcljs.core.rx.Observable().interval(300).subscribe(function() {
  return console.log(rxcljs.core.moment.call(null).format("dddd, MMMM Do YYYY, h:mm:ss a"))
});

The error:

/...../rxcljs/app.js:12726
rxcljs.core.rx.Observable().interval(300).subscribe(function() {
                            ^
TypeError: Cannot call method 'interval' of undefined

Please advice.


Answer EDIT

Thanks to Michal:

(ns rxcljs.core
  (:use [cljs.nodejs :only [require]])
)
(def log #(.log js/console %))

(def rx (require "./lib/rx/rx.node.js"))
(def moment (require "./lib/moment/moment.js"))

(-> rx .-Observable
   (.interval 300)
   (.subscribe #(->> (-> (moment) 
                         (.format "dddd, MMMM Do YYYY, h:mm:ss a")
                     )
                     (log) 
                )    
   )
)

rx interval working properly, moment format output is still weired though.

4

1 回答 1

4

(.Observable rx) is always a method call in ClojureScript; for property access, you must use (.-Observable rx) or perhaps (aget rx "Observable").1

With this in mind, your timeStream definition could be rewritten in ClojureScript like so:

(def time-stream
  (.. rx
      -Observable            ;; property access
      (interval 300)         ;; method call
      (subscribe (fn [index] ...))))

You could also use js/rxcljs.core.rx.Observable if you find this prettier (the js magic namespace causes the literal JavaScript identifier given as the name part of the symbol to be used in the compiled output; in particular, this means you need to supply the namespace prefix yourself, as shown here).


1 Note that in Clojure, (.foo x) might be a method call or a property access depending on the x, so that's a difference between dialects.

于 2013-07-04T16:20:13.663 回答