Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

primefaces keyup or other ajax event delay

Tags:

I have something like:

<p:inputText...>     <p:ajax event="keyup" update="somefield" listener="#{someBean.doSomething}"/> </p:inputText> 

But I don't want to do an Ajax request on every keypress, I would like to do the request a half second after the user stops writing.

I have seen this problem solved in jQuery in another question: How to delay the .keyup() handler until the user stops typing?

I would like to know if it's possible to do this on primefaces or how adapt the solution from the jQuery question.
I'm using PrimeFaces 3.0.M4.
Thank you in advance.

like image 381
Roteke Avatar asked Dec 06 '11 14:12

Roteke


2 Answers

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
like image 88
Xtreme Biker Avatar answered Sep 21 '22 09:09

Xtreme Biker


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 }); 
like image 33
Bhesh Gurung Avatar answered Sep 21 '22 09:09

Bhesh Gurung