使用ExtJS 4的动态模型

Tig*_*eow 28 extjs extjs4

使用ExtJS 3.x,我能够使用商店的"fields"属性,但在ExtJS 4中我似乎必须绝对使用模型.这很好,但就我而言,它不是一个静态模型,我需要动态定义字段,有时需要更改它们.

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

谢谢你的帮助!

Aci*_*ier 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();

        });

    }

});
Run Code Online (Sandbox Code Playgroud)

User模型和CurrentUser存储被创建酷似常规的非动态模型,并存储将被并包括在它们各自的控制器的阵列,该"用户"模型被简单地丢失如上所示其中添加动态字段.


fro*_*row 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);
Run Code Online (Sandbox Code Playgroud)

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