Search code examples
jsf-2primefaces

primefaces keyup or other ajax event delay


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.


Solution

  • 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
    });