繁体   English   中英

Ext.data.Store、Javascript Arrays 和 Ext.grid.ColumnModel

[英]Ext.data.Store, Javascript Arrays and Ext.grid.ColumnModel

我正在使用 Ext.data.Store 调用 PHP 脚本,该脚本返回 JSON 响应,其中包含有关将在查询中使用的字段的一些元数据(唯一名称、表、字段和用户友好的标题)。 然后我遍历每个 Ext.data.Record 对象,将我需要的数据放入一个数组( this_column ),将该数组推到另一个数组( columns )的末尾,并最终将其传递给 Ext.grid.ColumnModel object。

我遇到的问题是 - 无论我正在测试哪个查询(我有很多,大小和复杂性各不相同),列数组始终按预期工作,直到columns[15] columns[16] ,从该点和之前的所有索引都填充了columns[15]的值。 这种行为一直持续到循环到达 Ext.data.Store object 的末尾,此时整个 arrays 包含相同的值。

这是一些代码:

columns = [];
this_column = [];

var MetaData = Ext.data.Record.create([
    {name: 'id'},
    {name: 'table'},
    {name: 'field'},
    {name: 'title'}
]);
// Query the server for metadata for the query we're about to run
metaDataStore = new Ext.data.Store({
    autoLoad: true,
    reader: new Ext.data.JsonReader({
        totalProperty: 'results',
        root: 'fields',
        id: 'id'
    }, MetaData),
    proxy: new Ext.data.HttpProxy({
        url: 'index.php/' + type + '/' + slug
    }),
    listeners: {
        'load': function () {
            metaDataStore.each(function(r) {
                this_column['id'] = r.data['id'];
                this_column['header'] = r.data['title'];
                this_column['sortable'] = true;
                this_column['dataIndex'] = r.data['table'] + '.' + r.data['field'];
                // This display valid information, through the entire process
                console.info(this_column['id'] + ' : ' + this_column['header'] + ' : ' + this_column['sortable'] + ' : ' + this_column['dataIndex']);
                columns.push(this_column);
            });

            // This goes nuts at columns[15]
            console.info(columns);

            gridColModel = new Ext.grid.ColumnModel({
                columns: columns
            });

因为您首先在全局上下文中使用变量this_column (在您的示例顶部),所以它变成了一个全局变量 您应该将每个列定义实例化为 object 文字(为了便于阅读,拆分为多行)。

metaDataStore.each(function(r) {
  columns.push({
    id: r.data['id'],
    header: r.data['title'],
    sortable: true,
    dataIndex: r.data['table'] + '.' + r.data['field']
  });
});

或者如果你真的想使用一个变量,你可以这样做以确保它是一个局部变量

metaDataStore.each(function(r) {
    var this_column = {};
    ...

好的,由于 this_column 数组在每次运行时都正确响应,但列数组没有,我认为这一定是 push() 的问题。

在玩了一会儿之后,我改变了代码以在循环的每次迭代中重置 this_column 数组 - 似乎已经解决了这个问题......

metaDataStore.each(function(r) {
    this_column = [];
    this_column['id'] = r.data['id'];
    this_column['header'] = r.data['title'];
    this_column['sortable'] = true;
    this_column['dataIndex'] = r.data['table'] + '.' + r.data['field'];
    columns.push(this_column);
});

我看到您已经找到了一些可行的方法,但只是为将来提供一些建议:如果您直接使用 json 存储和列 model 而不是手动执行中间步骤,这会容易得多。

我不确定您使用的是网格还是数据视图,但它们的概念几乎相同。 如果您必须进行一些数据自定义,但不是在此处手动进行,您实际上可以在 prepareData 回调 function 中进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM