29

在 ExtJS 3.x 中,我能够使用 Store 的“字段”属性,但在 ExtJS 4 中,我似乎必须绝对使用模型。很好,但就我而言,它不是静态模型,我需要动态定义字段,有时还需要更改它们。

我可以重新创建一个模型,但我需要使用不同的名称,因为显然不可能修改现有模型,也不能删除它。如果我尝试使用同名的 Ext.regModel,ExtJS 会崩溃。

谢谢你的帮助!

4

3 回答 3

20

4.1 更新:

作为更新... 在 4.1 中,现在有一个静态方法setFields可用于定义模型原型字段。它在控制器的 init 方法中运行良好。

当我这样做时,我想在模型类中定义一些静态字段,然后更动态地设置一些。不幸的是,新setFields方法用参数替换了所有字段,但它很容易处理。

此示例使用 MVC 模式,其中我的模型和存储包含在控制器的model数组和store数组中(为我提供了下面使用的方便的 getter):

Ext.define('ST.controller.Main', {
    extend: 'Ext.app.Controller',

    models: ['User', 'Reference'],

    stores: ['CurrentUser', 'PermissionRef'],

    views: ['MainPanel'],

    init: function() {
        var me = this;

        me.getPermissionRefStore().on('load', function(store, records) {
            var model = me.getUserModel();
                // this returns the static fields already defined 
                // in my User model class
                fields = model.prototype.fields.getRange();

            // add the permission options (dynamic fields) to the static fields
            Ext.each(records, function(permission) {
                fields.push({name: permission.get('name'), type: 'bool'});
            });

            // 4.1 method to update the User model fields
            model.setFields(fields);

            // now load the current user (it will use the updated model)
            me.getCurrentUserStore().load();

        });

    }

});

User模型和商店的CurrentUser创建与常规的非动态模型完全相同,商店将包含在它们各自的控制器数组中,“用户”模型只是缺少如上所示添加的动态字段。

于 2012-05-14T17:53:48.347 回答
17

我也遇到了这个问题。我有一项服务,负责从服务器获取元数据并将模型和存储适应此元数据。

因此,我定义了一个空模型并将商店配置为使用此模型。

处理元数据时,我将新的/附加字段添加到模型的原型中(metaDataStore 是包含元数据的存储,模型是可以从模型管理器获得的模型):

var fields = [];
metaDataStore.each(function(item) {
    fields.push(Ext.create('Ext.data.Field', {
        name: item.get('field')
    }));
});
model.prototype.fields.removeAll();
model.prototype.fields.addAll(fields);

然后,当我使用此模型在商店上调用加载或创建新模型实例时,新字段将被正确处理。

于 2011-08-24T15:52:27.983 回答
3

这是一个非常简单的例子。只需使用普通的 Ext.data.Store 但不是模型,而是指定 fields 属性:

// you can specify a simple string ('totally')
// or an object with an Ext.data.Field ('dynamic')
var fields = ['totally', {name : 'dynamic', type : 'string'}];
var newStore = new MyApp.store.Object({
  fields : fields
  // other options like proxy, autoLoad...
});

不要指定模型属性 - 它似乎会覆盖字段属性。

我还想动态更改现有网格的列和内容:

// reconfigure the grid to use the new store and other columns
var newColumns = [
  {header: 'Totally', dataIndex: 'totally'},
  {header: 'Dynamic', dataIndex: 'dynamic'}
];
myGrid.reconfigure(newStore, newColumns);

来自关于Ext.data.Store的“字段”属性的 Ext JS 4 文档:

这可以用来代替指定模型配置。这些字段应该是一组 Ext.data.Field 配置对象。商店会自动创建一个包含这些字段的 Ext.data.Model。通常应避免使用此配置选项,它的存在是为了向后兼容。对于更复杂的事情,例如指定特定的 id 属性或关联,应为模型配置定义和指定 Ext.data.Model。

所以要小心 - Sencha 将来可能会删除它。

于 2011-06-26T22:14:56.697 回答