標籤:
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.
模型表示你的app管理的對象。例如Users, Products, Cars等模型類,或其它你想在app中模型化的真實世界的對象。模型通過model manager註冊,被stores使用,stores被Ext中大量資料繫結組件使用。
Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:
模型被定義為一些欄位的集合,並可能包含一些模型相關的任意方法、屬性。例如:
Ext.define(‘User‘, { extend: ‘Ext.data.Model‘, fields: [ {name: ‘name‘, type: ‘string‘}, {name: ‘age‘, type: ‘int‘, convert: null}, {name: ‘phone‘, type: ‘string‘}, {name: ‘alive‘, type: ‘boolean‘, defaultValue: true, convert: null} ], changeName: function() { var oldName = this.get(‘name‘), newName = oldName + " The Barbarian"; this.set(‘name‘, newName); }});
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,其它的函數和屬性會被複製到新模型的prototype。
A Model definition always has an identifying field which should yield a unique key for each instance. By default, a field named "id" will be created with a mapping of "id". This happens because of the default idProperty provided in Model definitions.
模型定義總是具有一個識別欄位--做為每個執行個體的唯一鍵。預設的,一個命名為”id“的欄位會自動對應到”id“屬性,這功能是由模型預設的idProperty提供的。
To alter which field is the identifying field, use the idProperty config.
要改變做為識別欄位的欄位,使用 idProperty 配置。
If the Model should not have any identifying field (for example if you are defining ab abstract base class for your application models), configure the {@liknkidProperty} as null.
如果模型不應該包含任何識別欄位(例如你正在定義一個app中使用的抽象基類),則將{@liknkidProperty} 配置為 null。
By default, the built in numeric and boolean field types have a 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讀取器有更好的表現,可以把預設的轉換方法置空,這些轉換方法會把原生屬性直接複製到屬性的值中。(註:這樣做的前提是要保證reander讀到的資料值都是正確的,不需要轉換)
Now we can create instances of our User model and call any model logic we defined:
現在我們可以建立User模型的執行個體,並且調用我們定義的任何模型邏輯:
var user = Ext.create(‘User‘, { id : ‘ABCD12345‘, 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). Validations are easy to add to models:
模型是內建支援校正器的,它會執行Ext.data.validations中的校正器方法,校正器是很容易添加到模型中的。
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. 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.data.association.HasOne、blongsTo、hasMany建立起和其他模型的關係。例如,寫一個部落格管理系統,這個系統要處理使用者、文章和內容,這些模型有下面這些關係:
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. Let‘s see how this works:
建立Rest Proxy,Rest Proxy會從RESTful後端載入和儲存資料。請看看是它如何工作的:
var user = Ext.create(‘User‘, {name: ‘Ed Spencer‘, email: ‘[email protected]‘});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. 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). We configure any Proxy on any Model and always follow this API - see Ext.data.proxy.Proxy for a full list.
新的模型對象調用save方法會使RestProxy把模型資料儲存到伺服器上。 RestProxy根據模型是否有id來判斷模型是否已經儲存,據此採取合適的操作,如果要儲存資料,RestProxy會發送post請求到配置的url。請根據API在模型上配置Proxy-請看Ext.data.proxy.Proxy中關於Proxy的完整列表。
Loading data via the Proxy is equally easy:
通過Proxy載入資料是很容易的
//get a reference to the User model classvar User = Ext.ModelManager.getModel(‘User‘);//Uses the configured RestProxy to make a GET request to /users/123User.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 iduser.save({ success: function() { console.log(‘The User was updated‘); }});//tells the Proxy to destroy the Model. Performs a DELETE request to /users/123user.destroy({ success: function() { console.log(‘The User was destroyed!‘); }});
Usage in Stores 在Store中使用
It is very common to want to load a set of Model instances to be displayed and manipulated in the UI. We do this by creating a Store:
在UI中顯示和控制一組模型對象是經常需要的,
var store = Ext.create(‘Ext.data.Store‘, { model: ‘User‘});//uses the Proxy we set up on Model to load the Store datastore.load();
A Store is just a collection of Model instances - usually loaded from a server somewhere. Store can also maintain a set of added, updated and removed Model instances to be synchronized with the server via the Proxy. See the Store docs for more information on Stores.
store是模型對象的集合,通常這些模型對象是從伺服器某個地方載入的。Store通過Proxy和服務進行通過操作,比如添加,比如更新,比如刪除。請查閱Store瞭解更多關於Store的資訊。
ExtJS筆記 Ext.data.Model