2013-07-29 32 views
0

我想在我的应用程序中使用Extjs 3编写的窗口上显示当前时间。时间应该每隔一秒更新,但我不知道如何执行此操作。这是我的代码: 任何人都可以帮助我吗?在extjs自动更新时间

function gettime(){ 
     var dt = new Date(); 
     dt = dt.format('h:i:s'); 
     return dt; 
    }; 

var clock = { layout:'form', frame:false, region:'center', height:100, width:400, 
items:[{id: 'currtime', xtype: 'displayfield',fieldLabel: 'Current Time' 
,value:gettime()}]}` 

回答

1

使用TaskManager或香草setInterval功能定期运行更新的代码。

编辑

例子:

// Keep a ref, in case you want to stop it later 
var task = Ext.TaskMgr.start({ 
    interval: 1000 
    ,run: function() { 
     Ext.getCmp('currtime').setValue(gettime()); 
    } 
}); 
+0

你能举个例子吗?我用setInterval但它没有工作! – MSH

+0

您可以在文档中找到示例:http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.util.TaskRunner http://www.w3schools.com/jsref/met_win_setinterval。 asp –

+0

@msh看我的编辑。 – rixo

0

如果你不需要它的每一秒,而是每一分钟,你可以这样做以下,你只会抢时间微小的变化:

(function startClock() { 
    var now = new Date(); 
    var sec = now.format('s'); 
    var runner = new Ext.util.TaskRunner(); 
    var task = function(dt) { 
     // start the interval 
     runner.start({ 
      run: function() { 
       Ext.getCmp('currtime').setValue(gettime()); 
      }, 
     interval: 60000 // 1 minute 
     }); 
    }; 

    Ext.getCmp('currtime').setValue(gettime()); // inital set time 
    Ext.defer(task, (60 - sec) * 1000, this, [now]); // get the time on next minute change 
})(); 
0

此代码可以帮助你,我用的ExtJS版本4.2.1

Ext.onReady(function() { 

var filterPanel = Ext.create('Ext.panel.Panel', { 
bodyPadding: 5, 
width: 200, 
title: 'Update Time in ExtJS', 
items: [{ 
    fieldLabel: 'Time', 
    id: 'txtTime', 
    name: 'txtTime', 
    xtype: 'textfield' 
    } 
], 
renderTo: Ext.getBody() 
}); 

Ext.TaskManager.start({ 
    run: function() { 
     Ext.getCmp('txtTime').setValue(Ext.Date.format(new Date(), 'H:i:s')); 
    }, 
    interval: 1000 
}); 

});