本文介绍了如何在PrimeFaces中使用闭包在CommandButton上定义一个oncomplete事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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" />

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

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 () {
     ...
})

然而,完成不是DOM事件,基本上只有PrimeFaces知道它何时被调用。还有办法用正常JavaScript事件处理替换基于属性的脚本吗?

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?

推荐答案

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

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")) {
        // ...
    }
});

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

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")) {
        // ...
    }
});

或者,如果你将PrimeFaces与普通HTML / jQuery混合并希望申请两者:

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")) {
        // ...
    }
});

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

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.

这篇关于如何在PrimeFaces中使用闭包在CommandButton上定义一个oncomplete事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!