Zhou Bontao (timen)
Email:[email protected]
Reprint Please specify the Source:http://blog.csdn.net/zhoubangtao/article/details/27707361
1. Introduction
The packet is primarily responsible for loading and saving all of your application's data, which contains 41 classes, but three of them are the most important--model,store and Ext.data.proxy.Proxy. These three classes are used in almost every application and have many satellite classes to support.
2. Model and Store
The core of the data package is Ext.data.Model. A model represents some type of data-such as an e-commerce possible users,products and orders model. In the simplest sense, a model is a collection of fields and data. Now look at the 4 main parts of a model class--field,proxy,association and validation.
Let's see how to create a model:
Ext.define (' User ', { extend: ' Ext.data.Model ', fields : [ {name: ' id ', type: ' int '}, {name: ' name ', Typ E: ' String '} });
The model is usually used in conjunction with the store, which is a collection of model instances. Creating a store and loading its data is simple:
Ext.create (' Ext.data.Store ', { model: ' User ', proxy: { type: ' Ajax ', URL: ' Users.json ', Reader: ' JSON ' }, autoload:true});
Let's configure an Ajax Proxy for our store to tell it to load the data URL and the reader that parses the data. In this example, our server returns JSON, so we need to set up a JSON reader to read the reply. Store automatically from Users.json. The Users.json URL should return a JSON string like the following:
{ success:true, users: [ {id:1, Name: ' Ed '}, {id:2, Name: ' Tommy '} ]}
3 Internal data
The store can also load data from within. Internally, the store converts each passed object into a model instance:
Ext.create (' Ext.data.Store ', { model: ' User ', data: [ {firstName: ' Ed ', lastName: ' Spencer '}, { FirstName: ' Tommy ', lastName: ' Maintz '}, {firstName: ' Aaron ', lastName: ' Conran '}, {firstName: ' Jamie ', last Name: ' Avins '} });
4. Sorting and Grouping
The store can perform sorting, filtering, and local grouping, as well as supporting remote sorting, filtering, and grouping:
Ext.create (' Ext.data.Store ', { model: ' User ', sorters: [' name ', ' ID '], filters: {Property : ' Name ', value : ' Ed ' }, GroupField: ' Age ', groupdir: ' DESC '});
In the store we just created, the data is sorted by name, then by ID, and filtered to only those users with name ' Ed ', and the data is grouped in descending order of age. You can easily change sorting, filtering, and grouping at any time via the store's API.
5. Agent (proxy)
The store uses proxy to control the loading and saving of model data. There are two types of proxy:client and server. The client example is the memory proxy that stores the data to the browser RAM and the local Storage proxy that uses the HTML5 native storage feature. The Server Proxy handles the data decoding of the remote service, which is an example of Ajax Proxy,jsonp Proxy and Rest Proxy.
A proxy can be defined directly in a model, for example:
Ext.define (' User ', { extend: ' Ext.data.Model ', fields : [' id ', ' name ', ' age ', ' gender '], proxy: { type : ' Rest ', URL: ' data/users ', reader: { type: ' json ', root: ' Users '}} };//Uses the User Model ' s proxyext.create (' Ext.data.Store ', { model: ' User '});
This has two advantages. First, each store that uses the user model will load the data it needs in the same way, thus avoiding the need to define a proxy for each store repeatedly. Second, we are able to load and save model data without using the store.
Data without a store://Gives us a reference to the user Classvar user = Ext.ModelMgr.getModel (' User '); var ed = ext.create (' User ', { name: ' Ed Spencer ', age:25});//We can save Ed directly without have to add him to a Store first is Cause we//configured a restproxy this would automatically send a POST request to the Url/usersed.save ({ success:func tion (ed) { Console.log ("Saved ed! He ID is "+ Ed.getid ());} ); /Load User 1 and do something with it (performs a GET request TO/USERS/1) User.load (1, { success:function (User) {
console.log ("Loaded User 1:" + user.get (' name '));} );
There are also proxy--localstorage and sessionstorage that use the new features of HTML5. Although older browsers do not support these new HTML5 APIs, they are so useful that a large number of applications will benefit from their presence.
6. Association
Model can be associated with the Associations API. Most say the application handles a variety of model, and the model is always associated. A blog app may have user, post, and comment Model. Each user creates multiple posts, and each post accepts multiple comment. Let's see how we use Association to write their models.
Ext.define (' User ', { extend: ' Ext.data.Model ', fields : [' id ', ' name '], proxy: { type: ' Rest ', URL: ' data/users ', reader: { type: ' json ', root: ' Users ' } , hasmany: ' Post '//Shorthand For {model: ' Post ', Name: ' Posts '}}); Ext.define (' Post ', { extend: ' Ext.data.Model ', fields : [' id ', ' user_id ', ' title ', ' Body '), proxy: { Type: ' Rest ', URL: ' data/posts ', reader: { type: ' json ', root: ' Posts ' } }, Belongsto: ' User ', hasmany: {model: ' Comment ', Name: ' Comments '}}); Ext.define (' Comment ', { extend: ' Ext.data.Model ', fields : [' id ', ' post_id ', ' name ', ' message '), Belongsto: ' Post '});
It's easy to express the relationship between the different model in your application. Each model can contain any number of associations with other model, and your model can be defined in any order. Once we have a model instance, we can access its associated data through it--for example, if you want to print all the comment of a given user's post to a log, we can do this:
Loads user with ID 1 and related posts and comments using user ' s Proxyuser.load (1, { success:function (User) { Console.log ("User:" + user.get (' name ')); User.posts (). each (function (POST) { Console.log ("Comments for post:" + post.get (' title ')); Post.comments (). each (function (comment) { console.log (comment.get (' message '));});});
Each of the Hasmany associations we created above will produce a new function and add it to the model. We define each user model Hasmany Post, which adds a posts () method to the user models. Calling User.posts () returns a store with the post model configured. Accordingly, the POST model will have a comments () method, because we have configured it with Hasmany Comment.
Association not only helps to load data, it also helps create new records:
User.posts (). Add ({ title: ' Ext JS 4.0 MVC Architecture ', body: ' it\ ' s a great idea to structure your Ext JS applic Ations using the built in MVC Architecture ... '}); user.posts (). sync ();
Here we instantiate a post, and its user_id field is automatically fu Cheng the user's ID. The call to sync () saves the new post--with a proxy configured for it, which is still an asynchronous operation, and if you want to be notified when the operation is complete, you can pass it a callback function.
The Belongsto association also generates a new method on the model to see how we use:
Get the user reference from the post ' s Belongsto associationpost.getuser (function (user) { console.log (' Just got the User reference from the post: ' + user.get (' name ')});//try to change the post ' s Userpost.setuser ({ callback:f Unction (product, operation) { if (operation.wassuccessful ()) { console.log (' post\ ' user was updated '); } else { console.log (' post\ ' user could not is updated ');} } );
The load function here (i.e. GetUser) is also asynchronous, and you can also pass in a callback function. The Setuser method simply updates the foreign key (Foreign_key, also the user_id here) to 100, and then saves the post model, and the callback function that is entered will be triggered when the save operation completes (either successfully or unsuccessfully).
7. Loading nested data
You might question why we pass a success function to User.load, but we don't have to do this when we access the user's post and comment! That's because the example above assumes that when a request to get a user is initiated, the server returns the user data and the post and comment data it says is associated. The framework automatically resolves nested data in a single request through the associated settings above. To avoid sending a request for a user data and then requesting all of his post data, and then comment the data for each post loader, we can directly get the server to return all of the above data:
{ success:true, users: [ { id:1, name: ' Ed ', age:25, Gender: ' Male ', posts: [ { ID : The title: ' All on the data in Ext JS 4 ', body: ' One areas that have seen the most improvement ... ' , comments: [ { id:123, name: ' S Jobs ', message: ' One more Thing ' } ] } ] } ]}
8. Verification
The data validation makes the EXT JS 4 model richer. To prove this, we are making further improvements based on the example above that explains the correlation. First add some validation to the user model:
Ext.define (' User ', { extend: ' Ext.data.Model ', fields : ..., validations: [ {type: ' Presence ', Name: ' Name '}, {type: ' length ', name: ' Name ', Min:5}, {type: ' format ', name: ' Age ', Matcher:/\d+/}, { Type: ' Inclusion ', Name: ' Gender ', list: [' Male ', ' female '}, {type: ' Exclusion ', Name: ' Name ', list: [' admin ']}
], proxy: ...});
Verify that the format definition and field are the same. In each of the above examples, we specify a field and a type for validation. The validation in the above example means that the Name field must be present and has at least 5 characters, the age field is a number, the gender field is either "male" or "female", and username can be any value other than "admin". Some validation also requires additional configuration, such as the Min and Max attributes required for length validation, the Matcher required for format validation, and so on. EXT JS 4 has 5 built-in authentication methods, and it's easy to add custom validation rules. Take a look at the built-in verification methods below:
- Presence: Make sure the field has a value. 0 is counted as a valid value, but an empty string does not count
- Length: Ensure that the string length is between min and Max. Both of these are optional.
- Format: Ensures that a string matches a regular expression. The above example means making sure that a field is made up of 4 digits followed by at least one character.
- Inclusion: Ensure that a value is in a specified collection (for example, make sure the gender is male or female)
- Exclusion: Ensure that a value is not in a specified collection (such as a blacklist username, like ' admin ')
Now that we have an understanding of what can not be verified, let's use it on a user instance. First create a user, then run the validation method, and note the error that occurred:
Now lets try to create a new user with as many validation errors as we canvar NewUser = ext.create (' user ', { name: ' admin ', age : ' Twenty-nine ', Gender: ' Not a valid gender '});//Run some validation on the new user we just created var errors = Newuser.validate (); Console.log (' is User valid? ', Errors.isvalid ()); Returns ' false ' as there were validation errorsconsole.log (' All Errors: ', errors.items); Returns the array of all errors found on this model instanceconsole.log (' Age errors: ', Errors.getbyfield (' age ')); Returns the errors for the age field
Here's the key function of validate (), which runs all the configured validations and then returns a Errors object. The Errors object contains a collection of any found errors, plus some handy methods, such as IsValid (), if there is no error on any field, it returns True, and the Getbyfield () method, which returns all errors that occur on a given field.
9. Summary
This chapter mainly describes the main functions of the data package of Ext JS 4, which is discussed in detail from model, Store, proxy, model, and validation. Through this study, you can have a preliminary understanding of the data manipulation and interaction of Ext JS 4.
10. References
- Http://dev.sencha.com/deploy/ext-4.1.0-gpl/docs/index.html#!/guide/data
Zhou Bontao (timen)
Email:[email protected]
Reprint Please specify the Source:http://blog.csdn.net/zhoubangtao/article/details/27707361