I'm using ClojureScript to retrieve battery levels with:

 navigator.battery.level

Which works fine when using the simple and whitespace optimization. But when using advanced optimization mode the above gets turned into:

navigator.hd.rd

And causes a TypeError as navigator.hd is undefined.

How can I fix this?

EDIT:

Fixed thanks to the answer below. Though in ClosureScript I would have to do some nasty, nested, agets... So I came up with this:

(defn jget [jobject & props]    
(loop [obj jobject 
       p (map name props)]
    (if (not (empty? p))            
        (let [prop (aget obj (first p))]
            (recur prop (rest p)))
    obj)))

then called it like so:

(jget js/navigator :battery :level)

If there are already tools out there for this could some one please let me know.

有帮助吗?

解决方案

The other solution is to write an externs file, which is a JavaScript file that contains references to all the objects and methods whose names you want to preserve. In this case, the JS file would look something like this:

//resources/externs/navigator.js
navigator = {}
navigator.battery = {}
navigator.battery.level = function(){};

And you'd refer to it in your ClojureScript complier options as:

:externs ["resources/externs/navigator.js"]

Like Sirko's proposed solution, this will prevent advanced-mode compilation from munging the navigator.battery.level name.

其他提示

Use

 navigator['battery']['level']

this will preserve the naming.

The closure compiler most often will rename variables of the dot notation (like navigator.battery), but retain those, he knows or that use bracket notation (like navigator['battery']).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top