Home
Categories
Dictionary
Download
Project Details
Changes Log
FAQ
License

Javascript external functions



Javascript scripts are available through the JSScriptWrapper wrapper.

It is possible to implement Javascript functions by methods provided by other scripts. This can be useful if you want to easily interoperate with other scripts.

For example in the following script the doSomething(int) method can be provided by another script (which can even not be a Javascript script):
      myScript: function() {
        value = doSomething(10);
        return value;
      }      

Adding external functions

To add external functions, you must use the JSScriptable.addExternalFunction(CachedMethodKey, String, ScriptWrapper) method to allow one method from another ScriptWrapper to be used in your Javascript scripts. The API for this method is the following:
class JSScriptable
Method Summary
Modifier and Type Method and Description
boolean addExternalFunction(CachedMethodKey key, String methodName, ScriptWrapper wrapper)
Add a method existing in another ScriptWrapper as a function available in the Javascript script. Return true if the function could be found

Parameters
key - the key of the method in the other script
methodName - the function key as used in the Javascript script
wrapper - the ScriptWrapper

Limitation

For the moment only functions with one argument at most are supported.

Example

For example, suppose that we have a Groovy ScriptWrapper for the following script interface:
      public interface ScriptGroovy {
        public int computeValue(int value);
      }      
And we want to use this method to implement the doSomething function in the Javascript script. We could have the following basic AbstractJSScriptable:
      public class MyScriptable extends AbstractJSScriptable {
      };
Now we could create the groovy wrapper:
      ScriptWrapper<GroovyScript> groovyWrapper = new GroovyScriptWrapper<GroovyScript>(){
      };   
      CachedMethodKey key = new CachedMethodKey("computeValue", Integer.class);
      
      JSScriptWrapper<Script> wrapper = new JSScriptWrapper<Script>(){
      };
      MyScriptable scriptable = new MyScriptable();
      
      scriptable.addExternalFunction(key, "doSomething", groovyWrapper);
      wrapper.setScriptable(scriptable);
The following script will call the computeValue(int value) method in the Groovy script:
      myScript: function() {
        value = doSomething(10);
        return value;
      }      

See also


Categories: impls

Copyright 2019-2020 Herve Girod. All Rights Reserved. Documentation and source under the BSD licence