25 Mar 2017

Passing Values to JavaScript from Managed Bean

In this simple post I am going to consider a common use case when we need to invoke a JS function from a managed bean method and this function consumes some value provided by a managed bean. Let's have a look at what options we have to pass this value from a Java bean to a JS function.

The easiest and the most obvious option is to pass the value as a parameter of the JS function:

JavaScript function:
        function alertParamValue(paramValue)
        {
          alert(paramValue);
        }

Managed bean method:
  private void renderScript(String script)  {
    FacesContext fctx = FacesContext.getCurrentInstance();
    ExtendedRenderKitService erks = null;
    erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
    erks.addScript(fctx, script);
  }

  public void paramButtonListener(ActionEvent actionEvent) {
    StringBuilder script = new StringBuilder();
    script.append("alertParamValue('came from managed bean');");
    renderScript(script.toString());   
  }

However, sometimes it might happen that passing a parameter to a JS function is not the best option due to complicated implementation of the function and it would require much effort to pass parameter's value to the exact place in the code where this value is used. In this case the JS function may refer to a "helper" JS function returning parameter's value. And this JS function is going to be rendered dynamically in a managed bean:

Java Script function:
        function alertFunctionValue()
        {
          alert(renderedFunction());
        }

Managed bean method:
public void functionButtonListener(ActionEvent actionEvent) {
 StringBuilder script = new StringBuilder();    
 script.append("function renderedFunction() {return 'came from managed bean'}");
 script.append("alertFunctionValue();");
 renderScript(script.toString());
}

Another solution for this case could be implemented by means of JavaScript variables:

Java Script function:
        var varValue;

        function alertVarValue()
        {
          alert(varValue);
        }

Managed bean method:
  public void varButtonListener(ActionEvent actionEvent)  {
    StringBuilder script = new StringBuilder();
    script.append("varValue = 'came from managed bean';");
    script.append("alertVarValue();");
    renderScript(script.toString());
  }

The sample application for this post is available here. It requires JDeveloper 12.1.3.

That's it!

No comments:

Post a comment

Post Comment