A Model represents some object that your application manages.(模型代表了你的应用程序中要管理的一些对象) For example, one might define a Model for Users, Products, Cars, or any other real-world object that we want to model in the system.(例如,程序可能会定义用户、产品、汽车或者其他真实世界中我们想要在系统中模拟的模型) Models are registered via the model manager, and are used by stores, which are in turn used by many of the data-bound components in Ext.(模型通过模型管理器注册,在stores中使用,在Ext中模型被很多数据绑定组件使用。)

Models are defined as a set of fields and any arbitrary methods and properties relevant to the model.(模型定义了一系列的属性和任意的方法、模型的相关的属性) For example:(例如)

  1. Ext.define('User', { 
  2.  
  3.     extend: 'Ext.data.Model'
  4.  
  5.     fields: [ 
  6.  
  7.         {name: 'name',  type: 'string'}, 
  8.  
  9.         {name: 'age',   type: 'int', convert: null}, 
  10.  
  11.         {name: 'phone', type: 'string'}, 
  12.  
  13.         {name: 'alive', type: 'boolean', defaultValue: true, convert: null
  14.  
  15.     ], 
  16.  
  17.     changeName: function() { 
  18.  
  19.         var oldName = this.get('name'), 
  20.  
  21.             newName = oldName + " The Barbarian"
  22.  
  23.   
  24.  
  25.         this.set('name', newName); 
  26.  
  27.     } 
  28.  
  29. }); 

The fields array is turned into a MixedCollection automatically by the ModelManager, and all other functions and properties are copied to the new Model's prototype.( ModelManager自动把属性数组转换为MixedCollection,其他的方法和属性都复制到新的模型的属性。)

By default, the built in numeric and boolean field types have a (@link Ext.data.Field.convert} function which coerces string values in raw data into the field's type.(默认,数值和布尔属性类型有一个内置的函数,它会强迫字符串数值转换为属性的类型。) For better performance with Json or Array readers if you are in control of the data fed into this Model, you can null out the default convert function which will cause the raw property to be copied directly into the Field's value.(把数据填充到模型中,为了让Json或者是Array读取器有更好的表现,可以把默认的转换方法置空,这些转换方法会把原生属性直接复制到属性的值中。)

Now we can create instances of our User model and call any model logic we defined:(现在创建用户模型的实例,调用所有定义的模型逻辑)

var user = Ext.create('User', {
    name : 'Conan',
    age  : 24,
    phone: '555-555-5555'
});
 
user.changeName();
user.get('name'); //returns "Conan The Barbarian"

Validations

Models have built-in support for validations, which are executed against the validator functions in Ext.data.validations (see all validation functions).(模型是内置支持校验器的,它会执行Ext.data.validations中的校验器方法) Validations are easy to add to models:(校验器是很容易添加到模型中的)

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'name',     type: 'string'},
        {name: 'age',      type: 'int'},
        {name: 'phone',    type: 'string'},
        {name: 'gender',   type: 'string'},
        {name: 'username', type: 'string'},
        {name: 'alive',    type: 'boolean', defaultValue: true}
    ],
 
    validations: [
        {type: 'presence',  field: 'age'},
        {type: 'length',    field: 'name',     min: 2},
        {type: 'inclusion', field: 'gender',   list: ['Male', 'Female']},
        {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']},
        {type: 'format',    field: 'username', matcher: /([a-z]+)[0-9]{2,3}/}
    ]
});

 

The validations can be run by simply calling the validate function, which returns a Ext.data.Errors object:(简单地调用validate方法就会进行校验,它返回Ext.data.Errors对象)

var instance = Ext.create('User', {
    name: 'Ed',
    gender: 'Male',
    username: 'edspencer'
});
var errors = instance.validate();
Associations(关联)

Models can have associations with other Models via Ext.data.association.HasOne, belongsTo and hasMany associations.(模型通过Ext.data.association.HasOneblongsTohasMany建立起和其他模型的关系) For example, let's say we're writing a blog administration application which deals with Users, Posts and Comments.(例如,写一个博客管理系统,这个系统要处理用户、帖子和内容) We can express the relationships between these models like this:(这些模型有下面这些关系:)

Ext.define('Post', {
    extend: 'Ext.data.Model',
    fields: ['id', 'user_id'],
 
    belongsTo: 'User',
    hasMany  : {model: 'Comment', name: 'comments'}
});
 
Ext.define('Comment', {
    extend: 'Ext.data.Model',
    fields: ['id', 'user_id', 'post_id'],
 
    belongsTo: 'Post'
});
 
Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id'],
 
    hasMany: [
        'Post',
        {model: 'Comment', name: 'comments'}
    ]
});

 

 

See the docs for Ext.data.association.HasOne, Ext.data.association.BelongsTo and Ext.data.association.HasMany for details on the usage and configuration of associations. (请查阅文档查看这些关系的用法和配置详细内容)Note that associations can also be specified like this:(这些关系也可以像下面这样指定:)

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id'],
 
    associations: [
        {type: 'hasMany', model: 'Post',    name: 'posts'},
        {type: 'hasMany', model: 'Comment', name: 'comments'}
    ]
});

 

Using a Proxy(使用代理)

Models are great for representing types of data and relationships, but sooner or later we're going to want to load or save that data somewhere.(模型可以很清楚表示出数据和关系的类型,但是使用模型的目的是用来加载和保存数据。) All loading and saving of data is handled via a Proxy, which can be set directly on the Model:(所有数据的加载和保存都是使用Proxy来处理,Proxy可以在模型中直接设置。)

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'email'],
 
    proxy: {
        type: 'rest',
        url : '/users'
    }
});

Here we've set up a Rest Proxy, which knows how to load and save data to and from a RESTful backend.(建立Rest ProxyRest Proxy会从RESTful后端加载和保存数据) Let's see how this works:(请看看是它如何工作的)

var user = Ext.create('User', {name: 'Ed Spencer', email: 'ed@sencha.com'});
 
user.save(); //POST /users

 

Calling save on the new Model instance tells the configured RestProxy that we wish to persist this Model's data onto our server. (新的模型对象调用save方法会是RestProxy把模型数据保持到服务器上)RestProxy figures out that this Model hasn't been saved before because it doesn't have an id, and performs the appropriate action - in this case issuing a POST request to the url we configured (/users).( RestProxy根据模型是否有id来判断模型是否已经保存,据此采取合适的操作,如果要保存数据,RestProxy会发送post请求到配置的url) We configure any Proxy on any Model and always follow this API - see Ext.data.proxy.Proxy for a full list.(请根据API在模型上配置Proxy-请看Ext.data.proxy.Proxy中关于Proxy的完整列表。)

Loading data via the Proxy is equally easy:(通过Proxy加载数据是很容易的)

//get a reference to the User model class
var User = Ext.ModelManager.getModel('User');
 
//Uses the configured RestProxy to make a GET request to /users/123
User.load(123, {
    success: function(user) {
        console.log(user.getId()); //logs 123
    }
});

 

Models can also be updated and destroyed easily:(模型也是很容易更新和销魂的)

//the user Model we loaded in the last snippet:
user.set('name', 'Edward Spencer');
 
//tells the Proxy to save the Model. In this case it will perform a PUT request to /users/123 as this Model already has an id
user.save({
    success: function() {
        console.log('The User was updated');
    }
});
 
//tells the Proxy to destroy the Model. Performs a DELETE request to /users/123
user.destroy({
    success: function() {
        console.log('The User was destroyed!');
    }
});

 

Usage in Stores(Stores的用法)

It is very common to want to load a set of Model instances to be displayed and manipulated in the UI.(在UI中显示和控制一组模型对象是经常需要的) We do this by creating a Store:(创建Store可以做到)

var store = Ext.create('Ext.data.Store', {
    model: 'User'
});
 
//uses the Proxy we set up on Model to load the Store data
store.load();

 

A Store is just a collection of Model instances - usually loaded from a server somewhere. (store是模型对象的集合,通常这些模型对象是从服务器某个地方加载的)Store can also maintain a set of added, updated and removed Model instances to be synchronized with the server via the Proxy. (Store通过Proxy和服务进行通过操作,比如添加,比如更新,比如删除。)See the Store docs for more information on Stores.(请查阅Store了解更多关于Store的信息。)

--------------------------------------------------------------------------------------

Number/String id, [Object config] )STATIC

Asynchronously loads a model instance by id. Sample usage:(通过id异步加载model的实例,示例用法:)

  1. Ext.define('MyApp.User', { 
  2.     extend: 'Ext.data.Model'
  3.     fields: [ 
  4.         {name: 'id', type: 'int'}, 
  5.         {name: 'name', type: 'string'
  6.     ] 
  7. }); 
  8.  
  9. MyApp.User.load(10, { 
  10.     scope: this
  11.     failure: function(record, operation) { 
  12.         //do something if the load failed 
  13.     }, 
  14.     success: function(record, operation) { 
  15.         //do something if the load succeeded 
  16.     }, 
  17.     callback: function(record, operation) { 
  18.         //do something whether the load succeeded or failed 
  19.     } 
  20. }); 

Parameters

  • id : Number/String

    The id of the model to load(要加载的模型的id)

  • config : Object (optional)

    config object containing success, failure and callback functions, plus optional scope(配置对象包括了success,failure,callback函数,还有可选的范围)