How can I generate a unique JavaScript variable name from a JSF clientId?

439 views Asked by At

I want to define a JavaScript function for every instance of a JSF composite component.

For this, inside the component, I'm trying something like:

<h:outputScript>
function myFunction_#{component.clientId}(day) {
   //do my instance specific stuff
}
</h:outputScript>

Specifically I am trying to use this function in a RichFaces calendar like this:

<rich:calendar id="calendar" ... dayClassFunction="myFunction_#{component.clientId}">

But the clientId doesn't necessarily only contain characters which are valid in JavaScript variable names.

Is there a way to calculate an md5 hash or something similarly pseudo-unique from the clientId (or something else!) inside a JSF EL expression?

I need it instance-specific because the return value relies on the instance values and the dayClassFunction attribute doesn't accept a function that takes the clientId itself or something likewise specific as an argument.

3

There are 3 answers

1
ChristopherS On BEST ANSWER

I've done it before like this:

window['#{cc.clientId}'] = {
    myFunction1 : function() { ... },
    myFunction2 : function() { ... }
};

then simply call it where you need it with

dayClassFunction="window['#{cc.clientId}'].myFunction1()"

This way everything is scoped to your component. Eventually you can add some prefix to the client id to never get into conflict with other variable names on the window scope.

Can't think of any character, which is allowed in a client id, that would break the javascript.

1
wrschneider On

Assuming it's the separator (:) that's the issue you could use fn:replace:

function myFunction_#{fn:replace(component.clientId, ':', '_')}
0
Aaron Digulla On

When calling your function, JSF will assign this to be the instance-specific JS object which JSF uses to implement the client side. You may be able to get the information you need from that.