2011-10-22 92 views
1

我想创建一个可以重复使用的简单商店,只包含几年。在商店创建中静态定义商店中的数据

Ext.define('Workshop.store.YearsStore', 
{ 
    extend: 'Ext.data.Store', 
    fields: ['id', 'type'], 
    constructor: function(config) 
    { 
     var years = []; 
     for(var n=1972;n<=Ext.Date.format(new Date(), 'Y');n++) 
     { 
      years.push({id: n, type: n}); 
     } 
     config.data = years; 
     this.initConfig(config); 
     return this; 
    } 
}); 

这不起作用,我如何定义商店创建的静态数据集?

回答

1

几件事情需要纠正:

  1. 你并不需要调用initConfiginitConfig用于在类中的config属性中包含的属性中添加吸气剂&设置器。在这种情况下,您只需拨打callParent即可。它应该照顾你休息。
  2. config没有定义时,您忘记了照顾案件。 config可能为空,并且在某些情况下,您的行config.data将引发config is undefined
  3. 使用原生(new Date()).getFullYear()似乎更好?

以下是修改后的代码,link to demo

Ext.define('Workshop.store.YearsStore', { 
    extend: 'Ext.data.Store', 
    fields: ['id', 'type'], 
    startYear: 1972, 
    endYear: (new Date()).getFullYear(), 
    constructor: function(cfg) { 
     var me = this; 

     //We init the configurations first (to copy startYear and endYear) 
     Ext.apply(me, cfg || {}); 

     me.data = []; 
     //Then we push data 
     for(var n = me.startYear ; n <= me.endYear ; n++) { 
      me.data.push({id: n, type: n}); 
     } 

     //Then finally we callparent to init this store. 
     me.callParent([cfg]); 
    } 
});