Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a JavaScript function from managed bean

Is there a way to call (execute) a JavaScript function from managed bean in JSF?

If that's relevant, I'm also using PrimeFaces.

like image 394
Maddy Avatar asked Apr 15 '11 09:04

Maddy


2 Answers

PrimeFaces 6.2+

Use PrimeFaces#executeScript():

public void submit() {
    // ...
    PrimeFaces.current().executeScript("alert('peek-a-boo');");
}

NOTE: works only when submit() is invoked by Ajax.

PrimeFaces 6.2-

Use RequestContext#execute():

public void submit() {
    // ...
    RequestContext.getCurrentInstance().execute("alert('peek-a-boo');");
}

NOTE: works only when submit() is invoked by Ajax.

JSF 2.3+

Use PartialViewContext#getEvalScripts():

public void submit() {
    // ...
    FacesContext.getCurrentInstance().getPartialViewContext().getEvalScripts().add("alert('peek-a-boo');");
}

NOTE: works only when submit() is invoked by Ajax.

OmniFaces

Use Ajax#oncomplete().

public void submit() {
    // ...
    Ajax.oncomplete("alert('peek-a-boo');");
}

NOTE: works only when submit() is invoked by Ajax.

JSF 2.2-

Best what you can do is to set the desired script as a bean property and conditionally render a <h:outputScript> component when the bean property is not empty.

<h:commandButton ... action="#{bean.submit}" />
<h:outputScript rendered="#{not empty bean.script}">#{bean.script}</h:outputScript>
public void submit() {
    // ...
    script = "alert('peek-a-boo');";
}

In case you're submitting the form by Ajax, don't forget to wrap the <h:outputScript> in another component and ajax-update it instead. See also Ajax update/render does not work on a component which has rendered attribute.

<h:commandButton ... action="#{bean.submit}">
    <f:ajax execute="@form" render="script" />
</h:commandButton>
<h:panelGroup id="script">
    <h:outputScript rendered="#{not empty bean.script}">#{bean.script}</h:outputScript>
</h:panelGroup>
like image 133
BalusC Avatar answered Nov 13 '22 12:11

BalusC


Depending on which version of Primefaces you're on you can use RequestContext.execute("{js here}");

From the Primefaces 3.4 documentation:

RequestContext provides a way to execute javascript when the ajax request completes, this approach is easier compared to passing callback params and execute conditional javascript. Example below hides the dialog when ajax request completes;

Code

public void save() {
  RequestContext requestContext = RequestContext.getCurrentInstance();  
  requestContext.execute("dialog.hide()");
}
like image 38
mbeedub Avatar answered Nov 13 '22 12:11

mbeedub