如何使用闭包在PrimeFaces中的CommandButton上定义一个oncomplete事件?

我正在使用一些JavaScript交互扩展PrimeFaces应用程序的一部分。 这一切都始于CommandButton ,它从bean获取一些数据并调用JavaScript。 目前,它看起来像这样:

 

当然,这是非常简单的基于function的编程。 没有上下文,没有闭包,没有OOP(如果我需要一些)。 我想将一个普通的JavaScript事件附加到CommandButton ,例如使用jQuery:

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

但是, complete不是DOM事件,基本上只有PrimeFaces知道它何时被调用。 是否还有一种方法可以将基于属性的脚本替换为“普通”JavaScript事件处理?

PrimeFaces使用jQuery来处理ajax请求。 因此,可以挂钩通用的$.ajaxComplete()处理程序。 源可用作第三个参数options属性:

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

或者,如果您使用的是PrimeFaces 4.0或更高版本,请在PrimeFaces特定的pfAjaxComplete事件上挂钩:

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

或者,如果您将PrimeFaces与“普通”HTML / jQuery混合,并希望同时适用于:

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

无论如何, $source因此表示触发了ajax动作的原始HTML DOM元素的jQuery对象,在这个特定示例的情况下是本身。 这使您可以通过例如检查元素的类将其进一步委托给期望的处理程序。

使用PrimeFaces 4.0, ajaxComplete被替换为pfAjaxComplete 。 有关详细信息,请参见问题5933 。

话虽这么说,我能够让它工作如下:

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