title: JSF Best Practice: Custom Components and JavaScript
body: <p>I am developing a JSF Custom Component, using the information I found on the following book <a href="http://www.apress.com/9781430250104" rel="nofollow">Pro JSF and HTML5 by Apress</a>.</p>
  
  <p>So far, I successfully developed: </p>
  
  <ul>
  <li>the java class to obtain the data to be rendered in the component</li>
  <li>the java component class</li>
  <li>the java renderer class</li>
  <li>the taglib file</li>
  <li>an example page to render the taglib</li>
  </ul>
  
  <p>Everything is working fine, the component is successfully rendered.</p>
  
  <p>Now <em>I would like to add javascript events and behaviour to the rendered elements</em>, more specifically, the purpose of my custom component is to render a menu on a web page, and I would like to ad a dropdown effects to the menu entry. I know how to code the whole thing, in JavaScript, what I don't know is:</p>
  
  <p><strong>What is the best practice to add javascript events and behaviour to the element rendered within a custom component?</strong> </p>
  
  <p>Where should the JS files be placed? How do I bind the events to the elements? Is it done in the render class, or after, on the web pages?</p>
  
  <p>Thanks, I'm willing to provide more specific information about my code, if required.</p>
  
  <hr>
  
  <p>Java Component Class</p>
  
  <p><strong>Note:</strong> <em>The CosmoMenu class is just a bean. It basically stores a menu tree (a label, an id and a set of children, if any).</em></p>
  
  <pre><code>package components;
  
  import com.google.gson.Gson;
  import com.google.gson.JsonElement;
  import com.google.gson.JsonParser;
  import domain.CosmoMenu;
  import javax.faces.component.FacesComponent;
  import javax.faces.component.UIComponentBase;
  
  
  @FacesComponent(CosmoMenuComponent.COMPONENT_TYPE)
  public class CosmoMenuComponent extends UIComponentBase{
  
    /** Component family of {@link CosmoMenuComponent}.        */
    public static final String COMPONENT_FAMILY = "CosmoMenu";
  
    /** Component type of {@link CosmoMenuComponent}.          */ 
    public static final String COMPONENT_TYPE = "CosmoMenu";    
  
    @Override
    public String getFamily(){
        return CosmoMenuComponent.COMPONENT_FAMILY;
    }
  
  
    private CosmoMenu theMenu;    
  
    public CosmoMenu getMenu(){
  
        Gson gson = new Gson();
        JsonParser jsonParser = new JsonParser();
        CosmoMenuAPI myApi = new CosmoMenuAPI();
  
        String strMenu = myApi.getMenu();
        JsonElement jEl = jsonParser.parse(strMenu);
  
        theMenu = gson.fromJson(jEl, CosmoMenu.class);
        return theMenu;      
    }
  }
  </code></pre>