Countdown to Ext JS 4: Anatomy of a Model

56 篇文章 0 订阅
27 篇文章 0 订阅

If you follow Ext JS, chances are you already know that we have a brand new data package for Ext JS 4. The new data package builds on the principles of the one in Ext JS 3 while adding a huge number of new capabilities. We recently introduced the new data package on our blog, and today we’re going to take a deeper look at the new Model class.

A Model represents almost any type of persistable data in an application. For example, an e-commerce application might have models for User, Product, Order and so on. Each model contains a set of fields as well as functions that enable the application to operate on its data—for example an Order model might have a ‘shipToCustomer’ function that kicks off the shipping process.

Ext JS 3.x and before had a class called Record, which was very similar to the new Model class. The difference is that whereas Record was only fields and functions, Model is much more powerful. Today, we’re going to look at four of the principal parts of Model—Fields, Proxies, Associations and Validations.

Ext.data.Model in Ext JS 4

Fields

Every model consists of one or more fields. At its simplest, a field is just a name: ‘id’, ‘email’ and ‘phone’ could all be fields on a User model. Fields can also do a lot more. They can have a type (int, float, string or auto) and even conversion functions that modify their values when set. For example, if we record our user’s height, we can have a function that converts it from inches to centimeters.

Here’s how we would set up a simple User model with three fields. For the first field, we will specify type ‘int’—e.g. it should be an integer. For the second field, we won’t specify a type, which means it will use the ‘auto’ type by default. The auto type will accept anything passed to it. For the third field, we’ll specify type ‘int’ and also provide a conversion function that takes a number of inches and converts it to centimeters:

 
Ext.regModel('User', {
    fields: [
        {name: 'id', type: 'int'},
        'name',
        {
            name: 'height',
            type: 'int',
            convert: function(inches) {
                return Math.round(inches * 2.54);
            }
        }
    ]
});
 

It’s easy to create a new User instance now and see how our field definitions affect the data we pass into them:

 
var abe = new User({
    id: 123,
    name: 'Abe Elias',
    height: 76
});
 
console.log(abe.get('id')); //logs 123 (a JavaScript Number object)
console.log(abe.get('name')); //logs 'Abe Elias' (A JavaScript String object)
console.log(abe.get('height')); //logs 193 (inches converted to centimeters)
 

Using simple instances of Models is very easy, but usually an application needs to load and save data. For this, we turn to Proxy.

Proxy

In Ext JS 4, a Proxy is responsible for loading and saving data from some source. This can be over AJAX, using HTML5 localStorage or even simply keeping data in memory. Ext JS 4 comes with a set of Proxies built in by default, but it’s easy to create your own. Let’s see how we might set up a Proxy for our User Model:

 
Ext.regModel('User', {
    fields: ['id', 'name', 'email'],
 
    proxy: {
        type: 'rest',
        url : '/users',
        reader: 'json'
    }
});
 

Defining Proxies directly on a Model is a new approach in version 4—its main benefit is that we can easily load and save Model data without creating a Store, as we did in Ext JS 3.

Above we set up the User Model to use a RestProxy. This Proxy uses AJAX calls to load and save its data from a server. It’s smart enough that it knows how to build RESTful urls automatically given a base url (‘/users’ in this case). We also set up our Proxy with a JsonReader—this takes the server response and decodes it into User Model instances. In this case, we know that our server will respond with JSON, so a JsonReader makes sense.

Let’s load up a User model now:

 
//GET /users/123
User.load(123, {
    success: function(user) {
        console.log(user.get('name'));
    }
});
 

The code above loads data from the URL /users/123, which was constructed from the ID we passed to User.load. It then uses the JsonReader to decode the response into a User object. Our server sends back a response like this, which would make the code above log “Aaron Conran”:

 
//response from GET /users/123
{
    "id": 123,
    "name": "Aaron Conran",
    "email": "aaron@sencha.com"
}
 

Easy enough, but let’s take it to the next level with associations.

Associations

We usually have many Models in an application, but none of them exist in a vacuum. There are relationships between models—each User in our system makes Orders, and each Order is composed of Order Items. Ext JS 4 gives us the ability to represent these relationships on the client side with a simple and intuitive Associations API. Let’s see how we’d set those three Models up:

 
//each User hasMany Orders
Ext.regModel('User', {
    fields: ['id', 'name', 'email'],
    proxy : {
        type: 'rest',
        url : '/users',
        reader: 'json'
    },
 
    hasMany: 'Orders'
});
 
//each Order belongsTo a User, and hasMany OrderItems
Ext.regModel('Order', {
    fields: ['id', 'user_id', 'status'],
    belongsTo: 'User',
    hasMany: 'OrderItems'
});
 
//each OrderItem belongsTo an Order
Ext.regModel('OrderItem', {
    fields: ['id', 'order_id', 'name', 'description', 'price', 'quantity'],
    belongsTo: 'Order'
});
 

Now that our application knows about its Models and their associations, let’s put them to use. Expanding on the example from the Proxy section above, let’s make our server response look like this:

 
{
    "id": 123,
    "name": "Aaron Conran",
    "email": "aaron@sencha.com",
    "orders": [
        {
            "id": 1,
            "status": "shipped",
            "orderItems": [
                {
                    "id": 2,
                    "name": "Sencha Touch",
                    "description": "The first HTML5 mobile framework",
                    "price": 0,
                    "quantity": 1
                }
            ]
        }
    ]
}
 

When we load our User data now, the associated Orders and OrderItems are loaded along with it, enabling us to interact with them in our code:

 
User.load(123, {
    success: function(user) {
        console.log(user.get('name')); //"Aaron Conran"
        console.log(user.orders().getCount()); //"1" -- there is only 1 order in the response above
 
        //we can iterate over the orders easily using the Associations API
        user.orders().each(function(order) {
            console.log(order.get('status')); //"shipped"
 
            //we can even iterate over each Order's OrderItems:
            order.orderItems().each(function(orderItem) {
                console.log(orderItem.get('title')); //"Sencha Touch"
            });
        });
    }
});
 

The Associations API is one of the most powerful new capabilities of Ext JS 4, and because the data package is shared with Sencha Touch, you can get a sneak peek at it by downloading Sencha Touch today or checking out the HasMany and BelongsTo API docs.

Validations

The last new feature we’re going to look at today is Validation. In Ext JS 3, the only place that validations could be performed was inside a form. In all of the examples above, we were manipulating data without a form, so we need to be able to validate at the Model level. Thankfully, Ext JS 4 has support for just that—let’s take a look:

 
Ext.regModel('User', {
    fields: ['id', 'name', 'email', 'height'],
 
    validations: [
        {type: 'presence', field: 'id'},
        {type: 'length', field: 'name', min: 2},
        {type: 'format', field: 'email', matcher: /[a-z]@[a-z].com/}
    ]
});
 

We set up three simple validations on our User model. First, we say that the ‘id’ field must be present, then we say that the ‘name’ field must be at least 2 characters long, and finally we use a very simple regular expression to match the format of the ‘email’ field.

We can use these validations to ensure that the data in our model is correct. Here we create a new User without a valid name and missing an ID, and ask it to validate itself:

 
var ed = new User({
    email: "ed@sencha.com"
});
 
var validation = ed.validate();
 
console.log(validation.isValid()); //false
 
//we can easily output or manipulate any validation errors
validation.each(function(error) {
    console.log(error.field + " " + error.message);
});
 
//in this case, the output looks like this:
"id must be present"
"name is the wrong length"
 

Find out more

We’ve looked at the four cornerstones of the new Model class—Fields, Proxies, Associations and Validations. Mastering these four concepts will enable you to create advanced applications using Ext JS 4 and Sencha Touch. To find out more about the data package, check out our recent blog postand browse through the extensive data package documentation in the Sencha Touch docs.

From:http://www.sencha.com/blog/ext-js-4-anatomy-of-a-model

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值