From the translator: Your attention is invited to the second article from the series “Waiting for Ext JS 4”. In the previous article , the Ext JS developers talked about the new class system.The data package is responsible for receiving, decoding, and using information in your application. It is one of those parts of the library that had the most improvements and additions.
The package has been completely rewritten for the fourth branch of the framework, but the overall concept has not changed since the previous versions. Today we will learn more about this technology and look at its capabilities.
')
What's new
The data package in Ext JS 4 consists of 43 classes, but three of them are especially important in comparison with the others - these are
Model (Model),
Storage (Store) and
Proxy (Proxy). They are used in almost every application with satellite classes.

Models and Storages
The basic element of the package is the Ext.data.Model class, which is responsible for working with the model. A model is a set of certain data in an application — for example, in an electronic store there may be models for Users (Users), Products (Products) and Orders (Orders).
In the most simplified version, the Model is a set of fields and their values. Anyone who worked with Ext JS 3 probably used the Ext.data.Record class, the predecessor of Ext.data.Model. Let's see how we create the model now:
Ext.regModel('User', { fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'} ] });
Typically, Models are used in conjunction with Storages — sets of Model instances. Declaring the Storage and loading data into it is simple:
new Ext.data.Store({ model: 'User', proxy: { type: 'ajax', url : 'users.json', reader: 'json' }, autoLoad: true });
That's all that should be done in order to download a set of instances of the Users model from the 'users.json' address. We set up our Storage using AjaxProxy to read the data at the specified address and the Ext.data.Reader class for transcoding data. In our case, the server returns a response in the JSON format, so we prepared the JsonReader to read the response.
With the help of Storage you can sort, filter and group data both locally and remotely. In the fourth version of Ext JS, there is no separate GroupingStore class, since the standard Storage is suitable for multiple sorting, filtering and grouping of records:
new Ext.data.Store({ model: 'User', sorters: ['name', 'id'], filters: { property: 'name', value : 'Ed' }, groupers: { property : 'age', direction: 'ASC' } });
In the Storage we just created, the data will be sorted first by name (name field), and then by id field; the records will be filtered so that only Users with the name 'Ed' would remain and are grouped by age (the age field). If required, you can easily change the sorting, filtering or grouping options at any time using the Store API.
Proxy
Above, we saw how the Repository uses Proxy to load data and how Proxy can be configured to use Reader classes to parse the server’s response. Compared with the third version, there is one structural change in Ext JS 4: The storage no longer contains references to the Reader and Writer classes, which are transferred to Proxy. This approach provides us with an incredible advantage - the Proxy can now be specified directly in the Model:
Ext.regModel('User', { fields: ['id', 'name', 'age'], proxy: { type: 'rest', url : '/users', reader: { type: 'json', root: 'users' } } }); // new Ext.data.Store({ model: 'User' });
We have double winnings: firstly, it is very likely that every Vault that works with the Users model equally loads data - accordingly, we will not have to duplicate the Proxy descriptions for the Vaults. Secondly, we can now load and save an instance of a model without a repository:
// (User) var User = Ext.getModel('User'); var ed = new User({ name: 'Ed Spencer', age : 25 }); // , // - RestProxy, // POST /users ed.save({ success: function(ed) { console.log("Saved Ed! His ID is "+ ed.getId()); } }); // 123 - ( GET- /users/123) User.load(123, { success: function(user) { console.log("Loaded user 123: " + user.get('name')); } });
We also bring to your attention several new Proxy types that use the features of HTML 5 - LocalStorageProxy and SessionStorageProxy. Although older browsers do not support the HTML 5 innovations, new Proxies are so useful that many applications will benefit from their use. Even if we do not have a Proxy that meets your requirements, then you can simply create your own.
Connections
Proxy is not the only new feature added to Models. You can now define relationships between Models using the new Associations API. Most applications work with a serious number of different Models, and Models are usually interconnected at the level of applied logic. A blog platform can have models for Users (Users), Posts (Posts) and Comments (Comments). Each User publishes Records, and Record receives Comments. We can describe the relationships between the models as follows:
Ext.regModel('User', { fields: ['id', 'name'], hasMany: 'Posts' }); Ext.regModel('Post', { fields: ['id', 'user_id', 'title', 'body'], belongsTo: 'User', hasMany: 'Comments' }); Ext.regModel('Comment', { fields: ['id', 'post_id', 'name', 'message'], belongsTo: 'Post' });
The task of describing relationships between different models is not too complicated. Each model can contain descriptions of any number of links with other models, and the models themselves can be declared in any order. After receiving an instance of the model, we can track the associated data - for example, if we want to receive a log of all Comments to the Records that a certain User left, then we can use the following construction:
// ID 123 User User.load(123, { 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 many-to-one relationships (hasMany) turns into a new function that is added to the Model. We indicate that each User has many Records. This relationship is described in the user.posts () function, which we met in the previous code snippet. Calling this function will return the Vault configured to work with the Records model. In turn, the Records model has a comments () function, because a many-to-one relationship with the Comments model is set.
Perhaps you were surprised by the fact that we set the 'success' handler to call User.load, but do not do this while accessing the User’s posts and comments. It is believed that all data is loaded asynchronously from a remote server. This fact implies the use of special success-handlers that are automatically called at the time of the final and successful data loading - as a function described above.
Loading related data
The library can automatically recognize and process related data in one request, based on the relationships described between the models. Instead of first requesting data for the User, then about the Record, and another request for each Comment, we can return all the necessary information in one server response:
{ id: 1 name: 'Ed', posts: [ { id : 12, title: 'All about data in Ext JS 4', body : 'One of the areas that has seen the most improvement in Ext JS 4...', comments: [ { id: 123, name: 'S Jobs', message: 'One more thing' } ] } ] }
You can easily configure the Proxy model to receive data from any source, and Reader-classes will help to cope with the most intricate response formats. Starting with Ext JS 3, Models and Storages are widely used by components inside the framework, especially Tables (Grids), Trees (Tress) and Forms.
Demonstration of opportunities
We have prepared for you a small
online demonstration . This application uses the same Models that were described in the article, but the code processes the test data. You can also
download a demo with one archive and experiment on your own. The library itself is now in beta status, so errors can sometimes occur, but in general the data processing package is fairly stable.
To find out more news from the world of Sencha Touch and Ext JS, I suggest you
subscribe to our monthly newsletter , which usually contains articles that you will not find anywhere else (even in our blog).