javascriptjqueryjsfjquery-eventsunobtrusive-javascript

Unobtrusive javascript with jsf components ... how?


I have some jsf 'commandLinks' on my page. For these commandLinks, there is onClick event. Currently I have written onclick functions directly as the onclick attribute of these commandLinks.

As it is a commandLink, it will create html anchor tag and also have some jsf JavaScript attached to it for form submissions. When I write my JavaScript directly in onclick attribute, the jsf will take care of that JavaScript while inserting it's own. But when the same event handler if I attach through jQuery, the it wouldn't recognize and submit the form before executing the event handler.

Is there any proper solution to this problem?


Solution

  • You need to let your jQuery function do the same as JSF is doing under the covers: wrapping the custom onclick function specified in the onclick attribute in another function which executes the standard JSF job of submitting the form depending on the outcome of the custom onclick function.

    Here's a kickoff example assuming that all those link elements have a class of link and that your custom onclick function is yourCustomFunction().

    $(".link").each(function(i, element) {
        var originalJsfOnclick = element.onclick; // Grab the JSF-generated onclick function.
        element.onclick = null; // Reset it.
    
        $(element).click(function(event) {
            if (yourCustomFunction()) { // First call your function.
                originalJsfOnclick.call(element, event); // If it returns true, then execute the JSF-generated onclick.
            }
        });
    });
    
    function yourCustomFunction() {
        // ...
    }