Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

Integrate JavaScript in JSF composite component, the clean way

In JSF, what would be the "right" and "clean" way to integrate JavaScript i.e. into a composite-compenent? I am a fan of Unobtrusive JavaScript, and separating HTML from JS from CSS. What would be a good way to have as little quirks as possible? This is what I like the best so far:

<composite:interface>
  // ...
</composite:interface>

<composite:implementation>
  // ...
  <script> initSomething('#{cc.clientId}'); </script>
</composite:implementation>    

What I don't like is, to use language A to generate language B. Basically the same goes for event handlers and stuff. My favorite would be to attach those handlers via <insert favorite DOM JavaScript library here>. Is this possible? How do you do this kind of integration?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    // ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...