Question

How can i access get method in this script:

(function( global ){

    var Result;

    (Result = function( val ) {
        this.tpl = val || '' ;
    }).prototype = {

        get: function ()
        {
            return 'text' ;
        }

    };

    global.Result = Result ;

} ( window ) ) ;

I tried in this way:

Create Window class and Result interface:

public interface Result{ public String get(); }

public class Window { public Result Result;   }

Call js function:

public void call() {

    Context context = Context.enter();

    ScriptableObject scope = context.initStandardObjects();

    FileReader fileReader = new FileReader("file.js");

    Object window = Context.javaToJS(new Window(), scope);

    scope.put("window", scope, window);

    context.evaluateReader(scope, fileReader, "test", 1, null);

    context.evaluateString(scope, "Result = window.Result;", "test", 2, null);

    context.evaluateString(scope, "result = Result.get();", "test", 3, null);
    Object result = scope.get("result", scope);
    System.out.println("\n" + Context.toString(result));
    context.exit();

}

but I can't get the return result from get function:

Was it helpful?

Solution

It worked for me:

public class Result extends ScriptableObject{

    @Override
    public String getClassName() {
        // TODO Auto-generated method stub
        return "Result";
    } 
}

public class Window extends ScriptableObject { 
    private Result Result;   

    public Result getResult() {
        return Result;
    }

    @Override
    public String getClassName() {
        return "Window";
    }
}

public void call() {

    Context context = Context.enter();

    ScriptableObject scope = context.initStandardObjects();

    FileReader fileReader = new FileReader("file.js");

    Window window = new Window();

    scope.put("window", scope, window);

    scope.put("window.Result", window.getResult());

    context.evaluateReader(scope, fileReader, "test", 1, null);

    context.evaluateString(scope, "Result = window.Result;", "test", 1, null);

    context.evaluateString(scope, "var myResult = new Result();", "test", 1, null);

    context.evaluateString(scope, "r = myResult.get();", "test", 1, null);
    Object result = scope.get("r", scope);
    System.out.println("\n" + Context.toString(result));
    context.exit();

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top