Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind method call in JavaScript script in Java Scripting

Suppose I have a Javascript file

function js_main(args){
     /* some code */
     var x = api_method1(some_argument);
     /* some code */
}

And I try to run it with javax.scripting the usual way

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.eval(...);

Now the I'd like to handle the call to api_method1 in Javascript with my Java class. I'd like to have some kind of mapping/binding of calls i.e. each time the script calls api_method1(arg) a method

public Object api_method1(Object arg){ ... }

(placed in the same class as the engine) would be called.

Can I achieve this?

like image 788
emesx Avatar asked Jun 20 '12 18:06

emesx


People also ask

What is Bind method in JavaScript?

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

What is Bind method in JavaScript w3schools?

JavaScript Function bind() With the bind() method, an object can borrow a method from another object. The example below creates 2 objects (person and member).

Does bind call function?

The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.

Should you use BIND in JavaScript?

. bind() is used when you need to pass a callback (e.g. some sort of function reference), but you want the caller to call your function with a specific this value.


1 Answers

  1. use engine.createBindings() to make a Bindings object;
  2. put an object exposing your method into the bindings with some name:

    Bindings b = engine.createBindings(); b.put("api", yourApiObject); engine.setBindings(b, ScriptContext.ENGINE_SCOPE); 
  3. Then in JavaScript there'll be a global "api" object you can call:

    api.method1( "foo", 14, "whatever" ); 

The facility is easy to use, but be careful with what you pass back and forth; it doesn't do that much to convert JavaScript types to Java types.

like image 186
Pointy Avatar answered Sep 29 '22 03:09

Pointy