第八天(Using Models)

来源:互联网 发布:上海达内java培优班 编辑:程序博客网 时间:2024/05/21 14:02

原文地址:http://docs-origin.sencha.com/touch/2.2.0/#!/guide/models


Using Models

使用模型

Contents

  1. Using Proxies
  2. Associations
  3. Validations

At its simplest, a Model is only a set of fields and their data. In this guide we are going to look at four of the principal parts of Ext.data.Model — Fields,Proxies, Associations and Validations.

最简单情形下,一个模型是一系列字段和数据。在本章中,我们会看下Ext.data.Model的最重要部分中的4个 ——字段、代理、关系和验证。

The following code sample illustrates the creation of a model:

下面的代码简明的说明了如何创建一个模型:

Ext.define('User', {    extend: 'Ext.data.Model',    config: {        fields: [            { name: 'id', type: 'int' },            { name: 'name', type: 'string' }        ]    }});

Using Proxies

使用代理

Proxies are used by stores to handle the loading and saving of model data. There are two types of proxy: client and server. Examples of client proxies include Memory for storing data in the browser's memory and Local Storage which uses the HTML 5 local storage feature when available. Server proxies handle the marshaling of data to some remote server, and examples include Ajax, JsonP, and Rest.

代理是被数据存储用来处理加载、保存模型的数据的。有两种类型的代理:客户端和服务端。客户端代理的例子包括用浏览器的内存保存数据和用html5的本地存储。服务端代理将组织好的数据交给远程服务器,例子包括Ajax、JsonP和Rest。

Proxies can be defined directly on a model, as shown in the following code sample:

代理可以直接在模型中声明,如下面代码所示:

Ext.define('User', {    extend: 'Ext.data.Model',    config: {        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 way of defining models provides two benefits. First, since it is likely that every store that uses the User model will need to load its data the same way, we avoid duplicating the proxy definition for each store. Second, we can load and save model data without calling a store:

这种定义模型的方式有两种好处。第一,由于使用User模型的每一个数据存储都需要以同样的方式加载数据,我们可以避免为每一个数据存储重复定义代理。其次,我们可以不调用数据存储的情况下加载并保存模型数据:

// 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 having to add him to a Store first because we// configured a RestProxy which will automatically send a POST request to the url /usersed.save({    success: function(ed) {        console.log("Saved Ed! His 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 proxies that take advantage of the new capabilities of HTML5 - LocalStorage and SessionStorage. Although older browsers do not support these new HTML5 APIs, these are so useful that a lot of applications will benefit enormously by using them.

也有代理采用了html5新功能的优势——本地存储和回话存储。尽管老的浏览器不支持html5的这些新的api,但是应用使用这些新api依旧收益良多。

Example of a Model that uses a Proxy directly    直接使用代理的模型例子。

Associations

关系

Models can be linked together using the Associations API. Most applications deal with many different models, and the models are almost always related. A blog authoring application might have models for User, Post, and Comment. Each user creates posts and each post receives comments. We can express those relationships as shown in the following example:

模型间可以通过关系api关联在一起。大部分应用都包含很多模型,并且这些模型几乎总是有关联的。一个博客应用可能包含用户、博客、评论模型。每一个用户创建博客,每一篇博客都可以接受评论。我们可以像下面这样表示它们之间的关系:

Ext.define('User', {    extend: 'Ext.data.Model',    config: {        fields: ['id', 'name'],        proxy: {            type: 'rest',            url : 'data/users',            reader: {                type: 'json',                root: 'users'            }        },        hasMany: 'Post' // shorthand for { model: 'Post', name: 'posts' }    }});Ext.define('Comment', {    extend: 'Ext.data.Model',    config: {        fields: ['id', 'post_id', 'name', 'message'],        belongsTo: 'Post'    }});Ext.define('Post', {    extend: 'Ext.data.Model',    config: {        fields: ['id', 'user_id', 'title', 'body'],        proxy: {            type: 'rest',            url : 'data/posts',            reader: {                type: 'json',                root: 'posts'            }        },        belongsTo: 'User',        hasMany: { model: 'Comment', name: 'comments' }    }});

As illustrated by this example, it is easy to express rich relationships between different models in your application. Each model can have any number of associations with other models, and your models can be defined in any order. Once you have a model instance, you can easily traverse the associated data. For example, to log all comments made on each post for a given user, use code as in the following example:

如例子所说明的样,在你的application中表达丰富的关系是简单的。每一个模型都可以与其它模型拥有任意数量的关系,而且你的模型可以以任意顺序定义。一旦你有一个模型的实例,你很容易遍历关联的数据。例如,打印出一个给定用户对每一篇博客的所有评论,代码如下:

// 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 automatically adds a new function to the Model. We declared that each User model hasMany Posts, which added the user.posts() function used in the snippet above. Calling user.posts() returns a Store configured with the Post model. In turn, the Post model gets a comments() function because of the hasMany Comments association that we have set up.

上面我们添加的每一个hasMany关系,框架都会自动为该模型添加一个新的方法。我们声明每一个用户模型有多篇博客这样一个hasMany关系,会自动添加user.posts()方法,如下面的代码片段所示。调用user.posts()方法会返回博客模型的一个数据存储。相应的,博客模型会有一个comments()方法,因为我们也为它配置了一个针对Comments的hasMany关系。

Associations are not only helpful for loading data, they can also be used for creating new records:

关系不仅在加载数据时很有用,在创建新记录时也很有用:

user.posts().add({    title: 'Ext JS 4.0 MVC Architecture',    body: 'It\'s a great Idea to structure your Ext JS Applications using the built in MVC Architecture...'});user.posts().sync();

In this example we instantiated a new Post, then called sync() to save the new Post via its configured proxy. This is an asynchronous operation to which you can pass a callback, if you want to be notified when the operation completes.

在这个例子中,我们实例化了一个新的Post,然后调用sync()通过配置的代理保存这个新的Post。这是一个异步的操作,如果你想在操作完成后得到一个通知,那么你亦可以传递一个回调函数。

The belongsTo association also generates new methods on the model. The following example shows how to use that functionality:

belongsTo关系也会为模型生成新的方法。下面的例子展示了如何使用该功能:

// 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(100, {    callback: function(product, operation) {        if (operation.wasSuccessful()) {            console.log('Post\'s user was updated');        } else {            console.log('Post\'s user could not be updated');        }    }});

Once more, the loading function (getUser) is asynchronous and requires a callback function to get at the user instance. The setUser method then updates the foreign_key (user_id in this case) to 100 and saves the Post model. As usual, you can pass in callbacks that will be triggered when the save operation has completed, whether successfully or not.

同样的,加载方法(getUser)也是异步的,并且在用户需要获取得到的user实例时需要提供一个回调函数。setUser方法更新外键(这个例子中是user_id)为100并保存Post模型。通常,你可以传入一个回调函数,在保存操作结束后触发,无论成功与否。

Validations

验证

Models have rich support for validating their data. To demonstrate this, we build upon the previous example that illustrated associations. First, let us add some validations to the User model:

模型还支持对数据的验证。为了说明该功能,我们在上一个说明关系的例子上进行构建。首先,先向用户模型添加一些验证:

Ext.define('User', {    extend: 'Ext.data.Model',    config: {        fields: [            // ...        ],        validations: [            { type: 'presence',  field: 'name' },            { type: 'length',    field: 'name', min: 5 },            { type: 'format',    field: 'age', matcher: /\d+/ },            { type: 'inclusion', field: 'gender', list: ['male', 'female'] },            { type: 'exclusion', field: 'name', list: ['admin'] }        ],        proxy: [            // ...        ]    }});

Validations follow the same format as field definitions. In each case, we specify a field and a type of validation. The validations in our example are expecting the name field to be present and to be at least five characters in length, the age field to be a number, the gender field to be either "male" or "female", and the username to be anything but "admin". Some validations take additional optional configuration - for example the length validation can take min and max properties, format can take a matcher, and so on. There are five validations built into Sencha Touch, and adding custom rules is easy.

验证的格式与字段定义的格式一致。在每种情况下,我们指定了一个字段和一个验证类型。我们例子中的验证想达到的目的是:那么

字段必须填写并且至少5个字符的长度,age字段是数字类型,gender字段只能是male或者female,username字段是除admin之外的。某些验证需要添加额外的配置——例如长度验证可以用min和max属性,格式化可以用正则表达式等等。st中有5种内置的验证类型,添加自己的规则是很容易的。

The following validation are built in:

下面5中验证是内置的:

  • presence ensures that the field has a value. Zero counts as a valid value but empty strings do not.   非空——保证字段一定有值。0是一个合法值但是空字符串是非法的
  • length ensures that a string has a lenght that is between a minimum and a maximum value. Both constraints are optional.   长度——保证字段的长度在最小和最大之间。最小最大长度都是可选的。
  • format ensures that a string matches a regular expression format. In the example above we ensure that the age field is a number.  格式化——保证字符串匹配给定的格式。在例子中,我们保证age字段是数字类型
  • inclusion ensures that a value is within a specific set of values (for example, we ensure that gender is either male or female).    包含——保证字段的值是给定一系列值中的一个(例如,我们保证gender字段一定是male或者female)。
  • exclusion ensures that a value is none of the specific set of values (for example, we could be blacklisting usernames like 'admin').     不包含——保证字段的值不在给定的值中(例如,我们排除username像admin这样的)。

Now that we have an understanding of the different validations, let us use them to validate a User instance. In the following example, we create a user instance and run the validations against it, noting any failures:

现在,我们对不同的验证有了一个大致的了解,让我们使用它们来验证一个User实例。在下面的例子中,我们创建了一个user实例,并对它进行了验证,没有任何失败:

// 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 createdvar 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

The key function here is validate(), which runs all of the configured validations and returns an Errors object. This simple object is a collection of any errors that were found, plus some convenience methods such as isValid(), which returns true if there were no errors on any field, and getByField(), which returns all errors for a given field.

关键的方法是validate,该方法会调用所有的验证配置并返回一个错误对象。这个对象是发现的验证错误的集合及一些很方便的方法如isValid方法、getByField方法,isValid方法在没有任何验证错误的时候会返回true,getByField方法返回给定字段上的所有错误。

For a complete example that uses validations please see Associations and Validations

查看Associations and Validations查看关于验证的完整例子。


原创粉丝点击