我使用Extjs4和MVC。我想动态更改我的模型的字段... 像添加可变数量的字段......有什么建议?
答案 0 :(得分:12)
您可以使用API中显示为here的model.setFields(fieldsArray)
函数。此方法使用您在参数中包含的任何新字段替换模型上的所有现有字段。没有静态getFields
方法来捕获现有字段,以免覆盖它们,但很容易使用model.prototype.fields
来获取它们。
我最近这样做是为了在加载用户之前将动态权限设置字段附加到“用户”模型。这是一个例子:
Ext.define('myApp.controller.Main', {
extend: 'Ext.app.Controller',
models: [
'User',
],
stores: [
'CurrentUser', // <-- this is not autoLoad: true
'PermissionRef', // <-- this is autoLoad: true
],
views: ['MainPanel'],
init: function() {
var me = this;
// when the PermissionRef store loads
// use the data to update the user model
me.getPermissionRefStore().on('load', function(store, records) {
var userModel = me.getUserModel(),
fields = userModel.prototype.fields.getRange();
// ^^^ this prototype function gets the original fields
// defined in myApp.model.User
// add the new permission fields to the fields array
Ext.each(records, function(permission) {
fields.push({
name: permission.get('name'),
type: 'bool'
});
});
// update the user model with ALL the fields
userModel.setFields(fields);
// NOW load the current user with the permission data
// (defined in a Java session attribute for me)
me.getCurrentUserStore().load();
});
}
});