Ext.TaskManager - 如何讓DataGrid AutoReload?

其實原本僅僅是想要做到讓DataGrid一段時間至Server取得最新的資料,但看一下DataGrid的method並沒提供這樣定時取資料的功能。至網上稍微研讀一下,發現Ext.TaskMsg可以解決我的問題。接下來讓我們看看怎麼用吧!

From ExtJS 4.0 Example: xml-grid.js
( Panel → Sotre → Model )

Ext.require([
    'Ext.data.*',
    'Ext.grid.*'
]);
 
Ext.onReady(function(){
    Ext.define('Book',{
        extend: 'Ext.data.Model',
        proxy: {
            type: 'ajax',
            reader: 'xml'
        },
        fields: [
            // set up the fields mapping into the xml doc
            // The first needs mapping, the others are very basic
            {name: 'Author', mapping: '@author.name'},
            'Title', 'Manufacturer', 'ProductGroup'
        ]
    });
 
    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        model: 'Book',
        autoLoad: true,
        autoSync: true,
        proxy: {
            // load using HTTP
            type: 'ajax',
            url: 'sheldon.xml',
            // the return will be XML, so lets set up a reader
            reader: {
                type: 'xml',
                // records will have an "Item" tag
                record: 'Item',
                idProperty: 'ASIN',
                totalRecords: '@total'
            }
        }
    });
 
    // create the grid
    Ext.create('Ext.grid.Panel', {
        store: store,
        columns: [
            {text: "Author", flex: 1, dataIndex: 'Author'},
            {text: "Title", width: 180, dataIndex: 'Title'},
            {text: "Manufacturer", width: 115, dataIndex: 'Manufacturer'},
            {text: "Product Group", width: 100, dataIndex: 'ProductGroup'}
        ],
        renderTo:'example-grid',
        width: 540,
        height: 200
    });
});
在Ext.onReady內使用ExtTaskManager。首先設定interval並於run中將去reload store,最後丟入Ext.TaskManager中就可以了。
(在Docs中是Ext.TaskMgr,但正確為Ext.TaskManager)
var task = {
	run : function() {
		store.reload();
	},
	interval : 5000 // 5 seconds
};
Ext.TaskManager.start(task);
如果要重新設定interval,可以透過
Ext.TaskManager.stop(task);
再重新產生task即可,要停止所有task呼叫stopAll即可。