Integrate JavaScript in JSF composite component, the clean way

I’d say that what you’ve there is the best you can get, provided that you’re absolutely positive that the HTML element’s nature is so unique that you absolutely need to select it by an ID, every time again.

If the HTML representation is not that unique (I can imagine that a Facelets template or include file might contain application-wide unique HTML elements like header, menu, footer, etc, but a composite component which can be reused multiple times in a single view? I can’t for life imagine that), then you could also consider using an unique classname and hook initialization on it.

E.g. /resources/composites/yourComposite.xhtml

<cc:implementation>
    <h:outputScript library="composites" name="yourComposite.js" target="head" />
    <div id="#{cc.clientId}" class="your-composite">
        ...
    </div>
</cc:implementation>

with in the /resources/composites/yourComposite.js (assuming that you’re using jQuery)

var $yourComposites = $(".your-composite");
// ...

You can if necessary extract the autogenerated HTML element ID for each of them in a jQuery.each():

$yourComposites.each(function(index, yourComposite) {
    var id = yourComposite.id;
    // ...
});

Leave a Comment