Wicket倒数计时器不会自我更新 [英] Wicket countdown timer will not self-update

查看:207
本文介绍了Wicket倒数计时器不会自我更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Wicket中实现一个倒数计时器。我有一个时钟类:

I would like to implement a countdown timer in Wicket. I have a clock class:

public class Clock extends Label{
    private static int time;
    public Clock(int mytime,String id,String message){
    super(id,message);
        time=mytime;
        this.setDefaultModelObject(message);
    }

    public int getTimeLeft(){
        return time;
    }

    public void decrement(){
        time--;
    }
}

在这里我尝试每秒更新一次:

and here I attempt to update it every second:

clock.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)){
    protected void onTimer(AjaxRequestTarget target){
        clock.decrement();
        target.addComponent(clock);
    }           
});

这不起作用,因为 onTimer 是一个 final 方法,因此无法覆盖。什么是正确的方法?

This doesn't work because onTimer is a final method and therefore cannot be overridden. What is the correct approach?

推荐答案

这里有两个问题。


  1. 生成的标签标记中出现 time 的位置?该模型只包含消息,所以即使时间被更改,它也不会有任何区别。

  2. 正如您所提到的, onTimer()是最终的,即使它不是,也不能保证它每秒都会被精确调用。

  1. Where does time appear in the generated label markup? The model simply contains the message so even if time is changed, it won't make any difference.
  2. As you mentioned, onTimer() is final, and even if it wasn't, there's no guarantee that it would be invoked precisely every second.

因此,Wicket中的解决方案是将其颠倒过来,而不是将数据推送到输出中,让框架将其拉入。这就是您需要做的事情。

So the solution, as so often in Wicket is to turn it upside down, instead of pushing data into your output, let the framework pull it in. This is what you need to do.


  1. 你不需要一个单独的 Clock 类,只使用一个普通的标签没有覆盖任何内容。

  2. 创建 IModel< String> 存储的子类时钟应该为零的时间戳。

  3. 使模型的 getObject()方法返回包含差异的字符串在时钟的零时间和当前时间之间。

  4. 设置此实例作为标签的模型并添加aj ax计时器行为也是如此。

  5. 完成。

  1. You don't need a separate Clock class, use just a plain Label with nothing overridden.
  2. Create an IModel<String> subclass that stores the timestamp when the clock should be at zero.
  3. Make the getObject() method of the model return a string that contains the difference between the clock's zero time and the current time.
  4. Set an instance of this as the model of your Label and add the ajax timer behaviour too.
  5. Done.

您的模型将是这样的:

public class ClockModel implements IModel<String> {
    private long zeroTime;

    public ClockModel( int timeInSecs ) {
        this.zeroTime = System.currentTimeMillis() + (timeInSecs * 1000 );
    }

    public String getObject() {
        return String.valueOf( ( zeroTime - System.currentTimeMillis() ) / 1000 );
    }

}

您可以猜测其余部分。

You can probably guess the rest.

更新:还有一件事,有点显而易见但值得一提:在现实世界的应用程序中,请确保检查剩余时间不是负面的。

Update: just one more thing, kind of obvious but may be worth mentioning: in a real world application make sure you check that time left isn't negative.

这篇关于Wicket倒数计时器不会自我更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆