Class JSObject
A Java Wrapper around a Javascript object. In Javascript there are only a few different types: Number, String, Boolean, Null, Undefined, and Object.
NOTE: The com.codename1.javascript package is now deprecated. The preferred method of
Java/Javascript interop is to use BrowserComponent#execute(java.lang.String), com.codename1.util.SuccessCallback),
BrowserComponent#executeAndWait(java.lang.String), etc.. as these work asynchronously (except in the XXXAndWait() variants, which
use invokeAndBlock() to make the calls synchronously.
Arrays and functions are objects also.
A JSObject is associated with a particular JavascriptContext and it is backed
by a Javascript object inside the javascript context. This object acts as a
proxy to call methods and access properties of the actual javascript object.
All return values for Javascript calls in the JavascriptContext will be
converted to the appropriate Java type. Javascript objects will automatically
be wrapped in a JSObject proxy.
Getting and Setting Properties
JSObject provides #get(String) and Object) methods to get and set properties on the
object. E.g.
java obj.set("name", "Steve"); obj.set("age", 12); String name = (String)obj.get("name"); // Steve Double age = (Double)obj.get("age"); // 12.0
Typed Getters
The return value of #get(String) will be one of Double, String, Boolean, or JSObject
depending on the type of Javascript value that is being returned. #get(String) requires
you to cast the return value to the correct type, which is a bit a pain. Luckily,
JSObject provides a set of typed getter methods that will automatically cast to
particular types:
getInt()Returns int
getString()Returns String
getDouble()Returns double
getObject()Returns JSObject
getBoolean()Returns boolean
Indexed Properties
JSObject can wrap Javascript arrays also. You can retrieve the indexed
properties of the array using indexed versions of #get(int) and Object) (i.e. they
take an int as their first parameter instead of a String). There are also
typed versions of the indexed #get(int) method to allow directly returning
values of the correct type without having to type cast
Example, looping through array
JSObject allows you to call Javascript object methods on the wrapped
Javascript object via the its `Object[])` method. It takes the name of the
method (i.e. property name that stores the function), and an array of
parameters to pass to the method.
`````java JSObject document = (JSObject)context.get("document"); // Call document.writeln("Hello world"); document.call("writeln", new Object[]{"Hello world"}); `````
Calling Wrapped Functions
Since, in Javascript, functions are objects, it is possible to wrap a function
with a JSObject object also. You can then call the function using the alternate
version of the `Object[])` method.
`````java JSObject window = (JSObject)context.get("window"); // reference to the window object so that we can pass it as the context // of the function call. JSObject myfunc = (JSObject)context.get("function(a,b){ return a+b}"); Double result = (Double)myfunc.call(window, new Object[]{new Integer(1), new Integer(2)}); `````
Calling Java Methods from Javascript
The `JSFunction` interface allows you to implement functions in Java that can
be called from Javascript. You can assign any `JSFunction` object to be a member
method of an existing JSObject via the `Object) JSObject.set()` method. Then the function
can be called from javascript just like any other Javascript method. `JSFunction`
methods are called asynchronously from Javascript to prevent deadlocks. If you
require a return value to Javascript, you can do that by passing a callback
function which is called by the JSFunction with some parameters.
The following example, adds a camera object to the Javascript environment
that has a capture() method, which can be used to capture images using the
device's camera:
`````java // Create a new Javascript object "camera" final JSObject camera = (JSObject)ctx.get("{}"); // Create a capture() method on the camera object // as a JSFunction callback. camera.set("capture", new JSFunction(){ public void apply(JSObject self, final Object[] args) { Display.getInstance().capturePhoto(new ActionListener(){ public void actionPerformed(ActionEvent evt) { String imagePath = (String)evt.getSource(); // Get the callback function that was provided // from javascript JSObject callback = (JSObject)args[0]; ctx.call( callback, // The function camera, // The "this" object new Object[]{"file://"+imagePath} // Parameters ); } }); } }); // Add the camera object to the top-level window object ctx.set("window.camera", camera); `````
We can then capture photos directly from Javascript using a function similar to the following:
`````java camera.capture(function(url){ if ( url == null ){ // No image was captured return; } // Fetch the preview tag. var image = document.getElementById('preview-image'); // Set the preview URL to the image that was taken. image.src = url; }); `````
-
Constructor Summary
ConstructorsConstructorDescriptionJSObject(JavascriptContext context, String expr) Constructor for a JSObject. -
Method Summary
Modifier and TypeMethodDescriptionCalls the object as a function statically.Calls a method on the underlying Javascript object synchronously with no arguments.Calls a method on the underlying Javascript object.voidCalls the object as a function statically.voidcallAsync(Object[] params, SuccessCallback callback) Calls the object as a function statically.voidCalls a method on the underlying Javascript object asynchronously with no arguments.voidcallAsync(String key, SuccessCallback callback) Calls a method on the underlying Javascript object asynchronously with no arguments.voidCalls a method on the underlying Javascript object asynchronously.voidcallAsync(String key, Object[] params, SuccessCallback callback) Calls a method on the underlying Javascript object asynchronously.doublecallDouble(String key) Calls a method on the underlying Javascript object that returns a double.voidcallDoubleAsync(String key, Callback<Double> callback) Calls a method on the underlying Javascript object that returns a double.voidcallDoubleAsync(String key, SuccessCallback<Double> callback) Calls a method on the underlying Javascript object that returns a double.intCalls a method on the underlying Javascript object that returns an int.voidcallIntAsync(String key, Callback<Integer> callback) Calls a method on the underlying Javascript object that returns an int.voidcallIntAsync(String key, SuccessCallback<Integer> callback) Calls a method on the underlying Javascript object that returns an int.callObject(String key) Calls a method on the underlying Javascript object that returns a Javascript object.voidcallObjectAsync(String key, Callback<JSObject> callback) Calls a method on the underlying Javascript object that returns a Javascript object.voidcallObjectAsync(String key, SuccessCallback<JSObject> callback) Calls a method on the underlying Javascript object that returns a Javascript object.callString(String key) Calls a method on the underlying Javascript object that returns a String.voidcallStringAsync(String key, Callback<String> callback) Calls a method on the underlying Javascript object that returns a String.voidcallStringAsync(String key, SuccessCallback<String> callback) Calls a method on the underlying Javascript object that returns a String.get(int index) This method is useful only for JSObjects that encapsulate Javascript arrays.Returns a member variable of the Javascript object.booleangetBoolean(int index) Wrapper for get(int) for indexed boolean values.booleangetBoolean(String key) Wrapper around get() to return a boolean.doublegetDouble(int index) Wrapper for get(int) for indexed double values.doubleWrapper around get() to return a double.intgetInt(int index) Wrapper for get(int) for indexed int values.intWrapper around get() to return an intgetObject(int index) Wrapper for get(int) for indexed object values.Wrapper around the get() method to return a JSObject.getString(int index) Wrapper for get(int) for indexed string values.Wrapper around get() to return a String.voidSets an indexed value on this object synchronously (assuming this object is a Javascript array).voidSets an indexed value on this object (assuming this object is a Javascript array).voidSets a property on this object.voidSets a property on the underlying Javascript object.voidsetBoolean(int index, boolean value) Sets an indexed value on this array to a boolean synchronously.voidsetBoolean(int index, boolean value, boolean async) Sets an indexed value on this array to a boolean.voidsetBoolean(String key, boolean value) Sets a property on this object to a boolean value synchronously.voidsetBoolean(String key, boolean value, boolean async) Sets a property on this object to a boolean value.voidsetDouble(int index, double value) Sets an indexed value on this array to a double synchronously.voidsetDouble(int index, double value, boolean async) Sets an indexed value on this array to a double.voidSets a property on this object to a double value synchronously.voidSets a property on this object to a double value.voidsetInt(int index, int value) Sets an indexed value on this array to an integer synchronously.voidsetInt(int index, int value, boolean async) Sets an indexed value on this array to an integer.voidSets a property on this object to an integer value synchronously.voidSets a property on this object to an integer value.Returns a Javascript variable name for the underlying Javascript object.toString()Returns the toString from the JavaScript object effectively the equivalent ofcallString("toString")
-
Constructor Details
-
JSObject
Constructor for a JSObject.
Example
java // Create a JavascriptContext for a browser component JavascriptContext ctx = new JavascriptContext(browserComponent); // Get reference to the window object JSObject window = new JSObject(ctx, "window"); // This is equivalent to window = (JSObject)ctx.get("window");Parameters
-
context: The javascript context in which this object is being created. -
expr: A javascript expression that resolves to a Javascript Object.
-
-
-
Method Details
-
get
Returns a member variable of the Javascript object.
E.g., suppose you have a Javascript object myCar whose JSON representation is
{ make : 'Ford', model : 'Escort', 'year' : 1989}Then the JSObject proxy for this object could call:
String model = (String)myCar.get("model");And this would return "Ford".
Example
`````java JSObject document = (JSObject)ctx.get("document"); // Get document title String title = document.get("title"); // Since the "title" property is a string, get() returns a String. // We could equivalently use title = document.getString("title"); // Get a grandchild property Double titleLength = (Double)document.get("title.length"); // Since length is an integer, it is probably easier to use getInt() int titleLengthInt = document.getInt("title.length"); // Get a child object JSObject body = (JSObject)document.get("body"); // Since "body" is a Javascript object, it is probably easier to use // getObject() JSObject body2 = document.getObject("body"); // Get a method as a function object JSObject open = (JSObject) document.get("open"); // Call the open() method, with document as "this" open.call(document, new Object[]{}); // Takes no parameters // Equivalently we could have called open via the document object document.call("open", new Object[]{});``
#### Parameters - `key`: The name of the property to retrieve on this object. #### Returns- Returns:
- The value of the property specified converted to the appropriate Java value. See @ref JavascriptContext.get() for a table of the Javascript to Java type conversions.
-
getString
-
getInt
Wrapper around get() to return an int
Parameters
key: @param key The name of the property in the object to retrieve. Value of this property must be an integer.
Returns
The property value as an integer.
-
getDouble
Wrapper around get() to return a double.
Parameters
key: @param key The name of the property in the object to retrieve. Value of this property must be a number.
Returns
The property value as a double.
-
getBoolean
Wrapper around get() to return a boolean.
Parameters
key: @param key The name of the property in the object to retrieve. Value of this property must be a boolean.
Returns
The property value as a boolean.
-
getObject
-
get
This method is useful only for JSObjects that encapsulate Javascript arrays. It provides a method to get indexed properties of the array. E.g. to retrieve the 5th element of the wrapped array, you could use this method.
Example `````java JSObject colors = ctx.get("['red','green','blue']"); String red = (String)colors.get(0); String green = (String)colors.get(1); String blue = (String)colors.get(2);``
It may be more convenient to use the typed wrapper methods so that you don't have to typecast the values. E.g. `````java String red = colors.getString(0); String green = colors.getString(1); String blue = colors.getString(2);``Example, looping through array
java JSObject colors = ctx.get("['red','green','blue']"); int len = colors.getInt("length"); for ( int i=0; i< len; i++ ){ System.out.println("Color "+i+" is "+colors.getString(i)); }Parameters
index: The index of the entry within the array to return.
Returns
The value of the specified indexed element.
-
getString
Wrapper for get(int) for indexed string values.
Parameters
index: The index within an Array object whose value to retrieve.
Returns
The value of the indexed element. Must be a String.
-
getInt
public int getInt(int index) Wrapper for get(int) for indexed int values.
Parameters
index: The index within the Array object whose value to retrieve.
Returns
The value of the indexed element. Must be an integer.
-
getDouble
public double getDouble(int index) Wrapper for get(int) for indexed double values.
Parameters
index: The index within the Array object whose value to retrieve.
Returns
The value of the indexed element. Must be a number.
-
getBoolean
public boolean getBoolean(int index) Wrapper for get(int) for indexed boolean values.
Parameters
index: The index within the Array object whose value to retrieve.
Returns
The value of the indexed element. Must be a boolean.
-
getObject
Wrapper for get(int) for indexed object values.
Parameters
index: The index within the Array object whose value to retrieve.
Returns
- Returns:
- The value of the indexed element. Must be an Object. (e.g. can be Object, Function, Array, or any other type of Javascript object).
-
set
Sets a property on the underlying Javascript object. Equivalent of
this[key] = js;.Parameters
-
key: The name of the property to set on the current object. -
js: @param js The value of the property. This value should be provided as a Java value and it will be converted to the appropriate Javascript value. See @ref JavascriptContext.set() for a conversion table of the Java to Javascript type conversions. -
async: If this flag is set, then the call will be asynchronous (will not wait for command to complete before continuing execution).
-
-
set
Sets a property on this object. This call is synchronous. Equivalent of
this[key] = value;.Parameters
-
key: The name of the property. -
js: A value for the property. This may be a primitive type, a JSObject, or a JSFunction.
See also
- #set(java.lang.String, java.lang.Object, boolean)
-
-
setInt
Sets a property on this object to an integer value. Equivalent of
this[key] = value;.Parameters
-
key: The property name to set. -
value: The value to assign to the property. -
async: True if you want this call to be asynchronous.
-
-
setInt
Sets a property on this object to an integer value synchronously. Equivalent of
this[key] = value;.Parameters
-
key: The name of the property to set. -
value: The integer value of to set.
-
-
setDouble
Sets a property on this object to a double value. Equivalent of
this[key] = value;.Parameters
-
key: The name of the property to set -
value: The value to set. -
async: True if you want this call to be asynchronous.
-
-
setDouble
Sets a property on this object to a double value synchronously. Equivalent of
this[key] = value;.Parameters
-
key: The name of the property to set -
value: The value to set.
-
-
setBoolean
Sets a property on this object to a boolean value. Equivalent of
this[key] = value;.Parameters
-
key: The name of the property to set -
value: The value to set. -
async: True if you want this call to be asynchronous.
-
-
setBoolean
Sets a property on this object to a boolean value synchronously. Equivalent of
this[key] = value;.Parameters
-
key: The name of the property to set -
value: The value to set.
-
-
set
Sets an indexed value on this object (assuming this object is a Javascript array). Equivalent of
this[index] = js;.Parameters
-
index: The index to set. -
js: The object to set. This may be a primitive type, a String, a JSObject, or a JSFunction. -
async: True to make this call asynchronously.
-
-
set
Sets an indexed value on this object synchronously (assuming this object is a Javascript array). Equivalent of
this[index] = js;.Parameters
-
index: The index to set. -
js: The object to set. This may be a primitive type, a String, a JSObject, or a JSFunction.
-
-
setInt
public void setInt(int index, int value, boolean async) Sets an indexed value on this array to an integer. Assumes this object is a Javascript array. Equivalent of
this[index] = value;.Parameters
-
index: The index within this array to set. -
value: The value to set. -
async: True to make this call asynchronous.
-
-
setInt
public void setInt(int index, int value) Sets an indexed value on this array to an integer synchronously. Assumes this object is a Javascript array. Equivalent of
this[index] = value;.Parameters
-
index: The index within this array to set. -
value: The value to set.
-
-
setDouble
public void setDouble(int index, double value, boolean async) Sets an indexed value on this array to a double. Assumes this object is a Javascript array. Equivalent of
this[index] = value;.Parameters
-
index: The index within this array to set. -
value: The value to set. -
async: True to make this call asynchronous.
-
-
setDouble
public void setDouble(int index, double value) Sets an indexed value on this array to a double synchronously. Assumes this object is a Javascript array. Equivalent of
this[index] = value;.Parameters
-
index: The index within this array to set. -
value: The value to set.
-
-
setBoolean
public void setBoolean(int index, boolean value, boolean async) Sets an indexed value on this array to a boolean. Assumes this object is a Javascript array. Equivalent of
this[index] = value;.Parameters
-
index: The index within this array to set. -
value: The value to set. -
async: True to make this call asynchronous.
-
-
setBoolean
public void setBoolean(int index, boolean value) Sets an indexed value on this array to a boolean synchronously. Assumes this object is a Javascript array. Equivalent of
this[index] = value;.Parameters
-
index: The index within this array to set. -
value: The value to set.
-
-
toJSPointer
Returns a Javascript variable name for the underlying Javascript object. This refers to the object inside the JavascriptContext's lookup table. -
call
Calls a method on the underlying Javascript object.
Parameters
-
key: The name of the method to call. -
params: @param params Array of parameters to pass to the method. These will be converted to corresponding Javascript types according to the translation table specified inObject)
Returns
- Returns:
- The result of calling the method. Javascript return values will
be converted to corresponding Java types according to the rules described
in
JavascriptContext#get(String)
-
-
callAsync
Calls a method on the underlying Javascript object asynchronously.
Parameters
-
key: The name of the method to call. -
params: @param params Array of parameters to pass to the method. These will be converted to corresponding Javascript types according to the translation table specified inObject) -
callback: Callback to be called when the method call is completed.
-
-
callAsync
Calls a method on the underlying Javascript object asynchronously.
Parameters
-
key: The name of the method to call. -
params: @param params Array of parameters to pass to the method. These will be converted to corresponding Javascript types according to the translation table specified inObject) -
callback: Callback to be called when the method call is completed.
-
-
call
-
callAsync
-
callAsync
Calls a method on the underlying Javascript object asynchronously with no arguments.
Parameters
-
key: The name of the method. -
callback: Callback to be called with the return value.
-
-
callInt
Calls a method on the underlying Javascript object that returns an int. Called synchronously with no arguments.
Parameters
key: The name of the method.
Returns
The return value of the method.
-
callIntAsync
Calls a method on the underlying Javascript object that returns an int. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callIntAsync
Calls a method on the underlying Javascript object that returns an int. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callDouble
Calls a method on the underlying Javascript object that returns a double. Called synchronously with no arguments.
Parameters
key: The name of the method.
Returns
The return value of the method.
-
callDoubleAsync
Calls a method on the underlying Javascript object that returns a double. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callDoubleAsync
Calls a method on the underlying Javascript object that returns a double. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callString
-
callStringAsync
Calls a method on the underlying Javascript object that returns a String. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callStringAsync
Calls a method on the underlying Javascript object that returns a String. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callObject
-
callObjectAsync
Calls a method on the underlying Javascript object that returns a Javascript object. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
callObjectAsync
Calls a method on the underlying Javascript object that returns a Javascript object. Call is asynchronous. Return value or error is passed to the provided callback.
Parameters
-
key: The name of the method. -
callback: Callback to handle the return value.
-
-
call
Calls the object as a function statically. In this case "this" will be window.
E.g.
java JSObject alert = (JSObject)ctx.get("window.alert"); alert.call(new Object[]{"An alert message"});The above gets a reference to the alert() function (remember functions are objects in Javascript). Then it calls it via Java, passing it a single string parameter. This is equivalent to the following Javasript:
java alert("An alert message");Parameters
params: @param params The parameters to pass to the function. These will be converted to the appropriate Javascript type.
Returns
- Returns:
- The result of the javascript function call converted to the appropriate Java type.
-
callAsync
Calls the object as a function statically. The call is made asynchronously In this case "this" will be window.
E.g.
java JSObject alert = (JSObject)ctx.get("window.alert"); alert.call(new Object[]{"An alert message"});The above gets a reference to the alert() function (remember functions are objects in Javascript). Then it calls it via Java, passing it a single string parameter. This is equivalent to the following Javasript:
java alert("An alert message");Parameters
-
params: @param params The parameters to pass to the function. These will be converted to the appropriate Javascript type. -
callback: @param callback The result of the javascript function call converted to the appropriate Java type and passed to the callback.
-
-
callAsync
Calls the object as a function statically. The call is made asynchronously In this case "this" will be window.
E.g.
java JSObject alert = (JSObject)ctx.get("window.alert"); alert.call(new Object[]{"An alert message"});The above gets a reference to the alert() function (remember functions are objects in Javascript). Then it calls it via Java, passing it a single string parameter. This is equivalent to the following Javasript:
java alert("An alert message");Parameters
-
params: @param params The parameters to pass to the function. These will be converted to the appropriate Javascript type. -
callback: @param callback The result of the javascript function call converted to the appropriate Java type and passed to the callback.
-
-
toString
-