JSF PrimeFaces Ajax 变量重置



我想在我的JSF-Page中倒计时,我用Primefaces的<p:poll>解决了它。

我有以下来源:

JSF-Page:

<h:form>
    <h:outputText id="timeLeft" value="#{bean.secondsToGo}" />
    <p:poll interval="1" listener="#{bean.countdown}" stop="#{bean.secondsToGo<0}" update="timeLeft" />
</h:form>

BEAN(视图范围(:

private int secondsToGo;
public void setValues(){ //prerenderview-event )
    if(FacesContext.getCurrentInstance().isPostback()){
        System.out.println("POSTBACK RECOGNIZED");
        return; //ignore ajax-calls!
    }
    ...
    secondsToGo=74; //(the value depends from a GET-parameter
    System.out.println("INIT: " + secondsToGo);
}
public void countdown(){
    System.out.println("BEFORE: " + secondsToGo);
    secondsToGo--;
    System.out.println("AFTER: " + secondsToGo);
}

有趣或奇怪的是,当执行 ajax-call (p:poll( 时,secondsToGo 被重置为 0:

初始化:74//正确值

之前: 0

之后: -1

为什么?

你应该

对someMethodToSetTimeout_PrerenderView使用@PostConstruct注释,而不是prerenderview,因为"preRenderView事件在每个HTTP请求上被调用(是的,这也包括ajax请求!(",正如BalusC在when-to-use-prerenderview-vsus-postconstruct中所说的那样。

我还会将轮询的停止条件更改为stop="#{bean.secondsToGo == 0}",它使计数更加清晰。

编辑:

从我的角度来看,您所要做的就是:

    <h:form>
        <h:outputText id="timeLeft" value="#{bean.secondsToGo}" />
        <p:poll interval="1" listener="#{bean.countdown}" stop="#{bean.secondsToGo == 0}" update="timeLeft" />
    </h:form>

private int secondsToGo;
@PostConstruct
public void init(){
    secondsToGo = 10;
}
public void countdown(){
    secondsToGo--;
}

但是,如果您期望更多,请纠正我。

最新更新