Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a oncomplete event on a CommandButton in PrimeFaces with a closure?

I'm extending a part of a PrimeFaces application with some JavaScript interactivity. It all starts with CommandButton which gets some data from the bean and calls then JavaScript. Currently, it looks something like this:

<p:commandButton actionListener="#{myBean.doSomething}"
                                 oncomplete="doSomethingSimple()"
                                 value="Do something" />

Naturally, this is very simple function-based programming. There is no context, no closures, no OOP (if I needed some). I'd like to attach a normal JavaScript event to the CommandButton, e.g. like this with jQuery:

$('.myCommandButton').on('complete', function () {
     ...
})

However, complete is not a DOM event and basically, only PrimeFaces knows when it's to be called. Is there still a way to replace attribute-based scripting with a "normal" JavaScript event handling?

like image 480
Nikolai Prokoschenko Avatar asked Sep 21 '13 20:09

Nikolai Prokoschenko


1 Answers

PrimeFaces uses under the covers jQuery to deal with ajax requests. So, could just hook on the generic $.ajaxComplete() handler. The source is available as property of 3rd argument options:

$(document).ajaxComplete(function(event, xhr, options) {
    var $source = $("[id='" + options.source + "']");

    if ($source.hasClass("myCommandButton")) {
        // ...
    }
});

Or, if you're using PrimeFaces 4.0 or newer, hook on PrimeFaces-specific pfAjaxComplete event:

$(document).on("pfAjaxComplete", function(event, xhr, options) {
    var $source = $("[id='" + options.source + "']");

    if ($source.hasClass("myCommandButton")) {
        // ...
    }
});

Or, if you're mixing PrimeFaces with "plain" HTML/jQuery and would like to apply on both:

$(document).on("ajaxComplete pfAjaxComplete", function(event, xhr, options) {
    var $source = $("[id='" + options.source + "']");

    if ($source.hasClass("myCommandButton")) {
        // ...
    }
});

Regardless of the way, the $source represents thus the jQuery object of the original HTML DOM element on which the ajax action was been triggered, which is in case of this particular example the <p:commandButton> itself. This offers you the possibility to delegate it further to the desired handler by e.g. examining element's class.

like image 110
BalusC Avatar answered Sep 29 '22 17:09

BalusC