primefaces keyup or other ajax event delay
If using Primefaces 5.x, there's a delay
attribute in the p:ajax
tag for this purpose. So it's done like this:
<p:inputText...>
<p:ajax event="keyup" delay="1000" listener="#{someBean.doSomething}"
update="somefield" process="@this" />
</p:inputText>
If not, you could achieve it using f:ajax
instead of p:ajax
(yes, it works with p:inputText
, too). f:ajax
has added support for queue control starting from JSF 2.2. So the code looks like:
<p:inputText...>
<f:ajax event="keyup" delay="1000" listener="#{someBean.doSomething}"
render="somefield" execute="@this" />
</p:inputText>
See also:
- Primefaces 5.0
p:ajax
javadoc - JSF 2.2 docs for
f:ajax
You cannot use the Primefaces Ajax Component, if you chose the jquery/javascript solution. You would have to implement your own javascript function (with ajax/xmlHttpRequest
support) and trigger that function after half a second.
But there is another solution, a workaround: you could use an autocomplete component and use 3 helpful attributes: valueChangeListener(A method expression that refers to a method for
handling a valuchangeevent
- you use that instead of completeMethod
because you don't need the returning suggestions), queryDelay (Delay to wait in milliseconds before sending
each query to the server
) and minQueryLength (Number of characters to be typed before starting
to query
- if you don't want to start the ajax request after just one character typed).
I hope you will find this solution quiet interesting...Please see the autocomplete component in action here( http://www.primefaces.org/showcase-labs/ui/autocompleteHome.jsf ) and you can find out more by reading the Primefaces User Guide for 3.0.M4.
Why don't you use PrimeFaces' RemoteCommand component?
It gives you a global Javascript function, that you can call from wherever whenever you want. And it lets you call the managed-bean method and it has the update
attribute for partial update.
<p:inputText id="input" />
<h:form>
<p:remoteCommand name="sendAjaxical" update="somefield" action="#{someBean.doSomething}"/>
</h:form>
Register event handler, I borrowed the following from the same answer you posted:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
jQuery("#input").keyup(function() {
delay(function() { sendAjaxical(); }, 2000); //sendAjaxical is the name of remote-command
});