public class JSObject
- Object
- 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; }); `````
Constructors
public JSObject(JavascriptContext context, String expr) | Constructor for a JSObject. |
Methods
Inherited methods
Constructor details
JSObject
public JSObject(JavascriptContext context, String expr)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
contextJavascriptContext- The javascript context in which this object is being created.
exprString- A javascript expression that resolves to a Javascript Object.
Method details
get
public Object get(String key)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
getString
public String getString(String key)Parameters
keyString- The name of the property in the object to retrieve. Value of this property must be a string.
Returns
getInt
public int getInt(String key)Parameters
keyString- The name of the property in the object to retrieve. Value of this property must be an integer.
Returns
getDouble
public double getDouble(String key)Parameters
keyString- The name of the property in the object to retrieve. Value of this property must be a number.
Returns
getBoolean
public boolean getBoolean(String key)Parameters
keyString- The name of the property in the object to retrieve. Value of this property must be a boolean.
Returns
getObject
public JSObject getObject(String key)Parameters
keyString- The name of the property in the object to retrieve. Value of this property must be a Javascript object or function.
Returns
get
public Object get(int index)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
indexint- The index of the entry within the array to return.
Returns
getString
public String getString(int index)Parameters
indexint- The index within an Array object whose value to retrieve.
Returns
getInt
public int getInt(int index)Parameters
indexint- The index within the Array object whose value to retrieve.
Returns
getDouble
public double getDouble(int index)Parameters
indexint- The index within the Array object whose value to retrieve.
Returns
getBoolean
public boolean getBoolean(int index)Parameters
indexint- The index within the Array object whose value to retrieve.
Returns
getObject
public JSObject getObject(int index)Parameters
indexint- The index within the Array object whose value to retrieve.
Returns
set
public void set(String key, Object js, boolean async)this[key] = js;.Parameters
keyString- The name of the property to set on the current object.
jsObject- 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.
asyncboolean- If this flag is set, then the call will be asynchronous (will not wait for command to complete before continuing execution).
set
public void set(String key, Object js)this[key] = value;.Parameters
keyString- The name of the property.
jsObject- A value for the property. This may be a primitive type, a JSObject, or a JSFunction.
setInt
public void setInt(String key, int value, boolean async)this[key] = value;.Parameters
keyString- The property name to set.
valueint- The value to assign to the property.
asyncboolean- True if you want this call to be asynchronous.
setInt
public void setInt(String key, int value)this[key] = value;.Parameters
keyString- The name of the property to set.
valueint- The integer value of to set.
setDouble
public void setDouble(String key, double value, boolean async)this[key] = value;.Parameters
keyString- The name of the property to set
valuedouble- The value to set.
asyncboolean- True if you want this call to be asynchronous.
setDouble
public void setDouble(String key, double value)this[key] = value;.Parameters
keyString- The name of the property to set
valuedouble- The value to set.
setBoolean
public void setBoolean(String key, boolean value, boolean async)this[key] = value;.Parameters
keyString- The name of the property to set
valueboolean- The value to set.
asyncboolean- True if you want this call to be asynchronous.
setBoolean
public void setBoolean(String key, boolean value)this[key] = value;.Parameters
keyString- The name of the property to set
valueboolean- The value to set.
set
public void set(int index, Object js, boolean async)this[index] = js;.Parameters
indexint- The index to set.
jsObject- The object to set. This may be a primitive type, a String, a JSObject, or a JSFunction.
asyncboolean- True to make this call asynchronously.
set
public void set(int index, Object js)this[index] = js;.Parameters
indexint- The index to set.
jsObject- 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)this[index] = value;.Parameters
indexint- The index within this array to set.
valueint- The value to set.
asyncboolean- True to make this call asynchronous.
setInt
public void setInt(int index, int value)this[index] = value;.Parameters
indexint- The index within this array to set.
valueint- The value to set.
setDouble
public void setDouble(int index, double value, boolean async)this[index] = value;.Parameters
indexint- The index within this array to set.
valuedouble- The value to set.
asyncboolean- True to make this call asynchronous.
setDouble
public void setDouble(int index, double value)this[index] = value;.Parameters
indexint- The index within this array to set.
valuedouble- The value to set.
setBoolean
public void setBoolean(int index, boolean value, boolean async)this[index] = value;.Parameters
indexint- The index within this array to set.
valueboolean- The value to set.
asyncboolean- True to make this call asynchronous.
setBoolean
public void setBoolean(int index, boolean value)this[index] = value;.Parameters
indexint- The index within this array to set.
valueboolean- The value to set.
toJSPointer
public String toJSPointer()call
public Object call(String key, Object[] params)Parameters
keyString- The name of the method to call.
paramsObject[]- Array of parameters to pass to the method. These will be
converted to corresponding Javascript types according to the translation
table specified in
Object)
Returns
JavascriptContext#get(String)callAsync
public void callAsync(String key, Object[] params, Callback callback)Parameters
keyString- The name of the method to call.
paramsObject[]- Array of parameters to pass to the method. These will be
converted to corresponding Javascript types according to the translation
table specified in
Object) callbackCallback- Callback to be called when the method call is completed.
callAsync
public void callAsync(String key, Object[] params, SuccessCallback callback)Parameters
keyString- The name of the method to call.
paramsObject[]- Array of parameters to pass to the method. These will be
converted to corresponding Javascript types according to the translation
table specified in
Object) callbackSuccessCallback- Callback to be called when the method call is completed.
call
public Object call(String key)Parameters
keyString- The name of the method.
Returns
callAsync
public void callAsync(String key, Callback callback)Parameters
keyString- The name of the method.
callbackCallback- Callback to be called with the return value.
callAsync
public void callAsync(String key, SuccessCallback callback)Parameters
keyString- The name of the method.
callbackSuccessCallback- Callback to be called with the return value.
callInt
public int callInt(String key)Parameters
keyString- The name of the method.
Returns
callIntAsync
public void callIntAsync(String key, Callback<Integer> callback)Parameters
keyString- The name of the method.
callbackCallback<Integer>- Callback to handle the return value.
callIntAsync
public void callIntAsync(String key, SuccessCallback<Integer> callback)Parameters
keyString- The name of the method.
callbackSuccessCallback<Integer>- Callback to handle the return value.
callDouble
public double callDouble(String key)Parameters
keyString- The name of the method.
Returns
callDoubleAsync
public void callDoubleAsync(String key, Callback<Double> callback)Parameters
keyString- The name of the method.
callbackCallback<Double>- Callback to handle the return value.
callDoubleAsync
public void callDoubleAsync(String key, SuccessCallback<Double> callback)Parameters
keyString- The name of the method.
callbackSuccessCallback<Double>- Callback to handle the return value.
callString
public String callString(String key)Parameters
keyString- The name of the method.
Returns
callStringAsync
public void callStringAsync(String key, Callback<String> callback)Parameters
keyString- The name of the method.
callbackCallback<String>- Callback to handle the return value.
callStringAsync
public void callStringAsync(String key, SuccessCallback<String> callback)Parameters
keyString- The name of the method.
callbackSuccessCallback<String>- Callback to handle the return value.
callObject
public JSObject callObject(String key)Parameters
keyString- The name of the method.
Returns
callObjectAsync
public void callObjectAsync(String key, Callback<JSObject> callback)Parameters
keyString- The name of the method.
callbackCallback<JSObject>- Callback to handle the return value.
callObjectAsync
public void callObjectAsync(String key, SuccessCallback<JSObject> callback)Parameters
keyString- The name of the method.
callbackSuccessCallback<JSObject>- Callback to handle the return value.
call
public Object call(Object... params)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
paramsObject...- The parameters to pass to the function. These will be converted to the appropriate Javascript type.
Returns
callAsync
public void callAsync(Object[] params, Callback callback)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
paramsObject[]- The parameters to pass to the function. These will be converted to the appropriate Javascript type.
callbackCallback- The result of the javascript function call converted to the appropriate Java type and passed to the callback.
callAsync
public void callAsync(Object[] params, SuccessCallback callback)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
paramsObject[]- The parameters to pass to the function. These will be converted to the appropriate Javascript type.
callbackSuccessCallback- The result of the javascript function call converted to the appropriate Java type and passed to the callback.
toString
public String toString()callString("toString")