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?

Answers:

Answer

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.

Answer

With PrimeFaces 4.0, ajaxComplete was replaced with pfAjaxComplete. See Issue 5933 for more details.

That being said, I was able to get it to work as follows:

$(document).on('pfAjaxComplete', function() {
    foo.bar()
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.