Saturday, June 2, 2012

Passing arguments to a JavaScript function

In this tutorial, we will see how to call a JavaScript  function and pass arguments to it. Since the JavaScript functions in ADF Faces RC cannot take a second argument in a call from af:clientListener, the parameters
need to be passed differently. Here client attributes come to the rescue. Using the af:clientAttribute element, the existing properties of a component can be extended by custom properties - like the  product name  in the following code sample:

<af:table id="t1" value="#{bindings.ProductsBase1.collectionModel}" var="row"
                      rows="#{bindings.ProductsBase1.rangeSize}" rowSelection="single"
                      ... >
       <af:column sortProperty="#{bindings.ProductsBase1.hints.ProductName.name}"
                         headerText="#{bindings.ProductsBase1.hints.ProductName.label}" id="c2">
            <af:outputText value="#{row.ProductName}" id="ot2">
                  <af:clientAttribute name="productName" value="#{row.ProductName}"/>
                   <af:clientListener method="sampleMethod" type="click"/>

             </af:outputText>
      </af:column>
</af:table>
The JavaScript function looks as follows:
function sampleMethod(evt) {
    productName = evt.getSource().getProperty("productName");
    alert('Selected product: '+productName);
the function reads the product name value from the outputText component, which is passed as the source of the JavaScript event. Once the information is available in the JavaScript function, developers can use it as they please.
This function can be put in a JavaScript file and included as a resource by the code below:
<af:resource type="javascript" source="/resources/js/script.js"/>
You can download this sample from the link below: (it uses the FOD demo schema which you can find it here)
PassingParamsToJSFunction.rar (66ko)