How I'll create a model from json file? (ExtJS)

ⅰ亾dé卋堺 提交于 2019-12-12 16:06:57

问题


This the model that I want to create using json file

Ext.define('Users', {
    extend: 'Ext.data.Model',
    fields: [{name: 'user_id',  type: 'int'},
    {name: 'user_name',  type: 'string'}]
});

What do I have to do in order to automatically create this model, based on the content of a json response from the server?


回答1:


In order to have the model created automatically, you need to include the metaData field with your Json data. metaData can be used to describe all of the fields for the Model.

In the ExtJS 4.1 documentation - Ext.data.reader.Json has a section called Response MetaData which describes basic use of this feature.




回答2:


You should be able to pull down some json with fields and or some format that can be transformed into that format pretty easily.

  1. Make call to service to get model's fields. Might need to define some chain that first calls model service and performs subsequent steps after.

  2. Build model's field array w/ fields results from #1. May need to transform data based on response in #1.

    var fields = response.fields;

  3. Define model based on fields in Store's constructor

    var store = Ext.create('Ext.data.Store', {
        constructor: function () {
            var model = Ext.define("Users", {
                extend: "Ext.data.Model",
                fields: fields
            });
            this.model = model.$className;
            this.callParent(arguments);
        }
    });
    



回答3:


I only use the jsonp, which loads an json file and parses it automatically, don't know if Ext.Ajax does this, too.

But you would do something like this:

definition.json:

{
  "name": "User",
  "fields": [
    { "name": "user_id"  , "type": "int"    },
    { "name": "user_name", "type": "string" }
  ]
}

load it:

Ext.Ajax.request({
  url    : "..../definition.json"
  success: function( res ) {
    Ext.define( res.name, {
      extend: 'Ext.data.Model',
      fields: res.fields
    }, function() {
      Ext.create( 'somestore', { model: res.name });
    });
  }
});


来源:https://stackoverflow.com/questions/11016701/how-ill-create-a-model-from-json-file-extjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!