博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

前言: 

数据模型[Model]的主要职责是描述存储和管理应用程序的数据,堪称MVC应用程序的肌肉和组织,缺少了Model的应用程序只能是一具没多大实用价值的空壳。事实上,几乎当前所有的互联网应用程序都是以数据的传递和交互为主要目的。 

这篇文章的英文原址是http://docs.sencha.com/touch/2-0/#!/guide/models

原文标题是:Using Models(使用数据模型)。在官方文档目录中,它事实上的地位是MVC概述之后开篇三板斧之一,鉴于Sencha Touch MVC的特点,这三板斧的介绍顺序是倒过来的,先C控制器再V视图最后才是M数据模型,但是其重要性却不分先后。

Sencha Touch 交流QQ213119459欢迎您的加入。

 

 

Using Models in your Applications

在应用程序中使用数据模型


注:为方便起见,文中所有出现 Sencha Touch 的地方均以 ST 简写替代。

At its simplest a Model is just a set of fields and their data. We’re going to look at four of the principal parts of Ext.data.Model Fields, Proxies, Associations and Validations.

在最简单的情况下,一个数据模型只是一组字段和数据,我们来看一下Ext.data.Model的四个主要部分,Fields(字段), Proxies(代理), Associations(关联),Validations(验证)。

 


Let's look at how we create a model now:

来看一下如何创建一个数据模型:

Ext.define('User', {

    extend: 'Ext.data.Model',

    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.

通常store会使用proxy来处理model数据的加载和存储。Proxy有两种类型,客户端和服务端。客户端类型的例子里包含了浏览器内存存储和html5本地存储两种。服务端代理通过配置远程服务器来获取数据,例子包含了Ajax/JsonP/Rest的方式。

Proxies can be defined directly on a model, like so:

代理可以直接配置在数据模型上,比如这样:

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 Proxy(使用User数据模型代理)

Ext.create('Ext.data.Store', {

    model: 'User'

});

This helps in two ways. First, it's likely that every store that uses the User model will need to load its data the same way, so we avoid having to duplicate the proxy definition for each store. Second, we can now load and save model data without a store:

这么做有两个好处,首先每一个使用User数据模型的store都通过同样的方式加载数据,这样我们就无需把proxy的配置每个地方复制一遍了。第二我们可以在不需要store的情况下就加载和保存数据。

// Gives us a reference to the User class(实现对User类的引用)

var 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 this will automatically send a POST request 
// to the url /users 
//
我们可以直接保存Ed而无需把它加入到Store,因为我们已经配置了一个RestProxy 
//
它会自动发送一个Post请求到/users这个url

ed.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 1然后做点什么(发送一个Get请求到/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 don't support these new HTML5 APIs, they're so useful that a lot of applications will benefit enormously by using them.

另外一种proxy类型利用了html5的新能力——本地存储和会话存储。虽然老一些的浏览器不支持这些html5的API,但它们依然很有用,很多应用程序都可以通过使用它们获益。

Example of a Model that uses a Proxy directly(该链接是一个使用了代理的Model例子) 


Associations

关联

Models can be linked together with 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 like so:

数据模型可以通过Association API关联在一起。大部分应用程序都要处理很多不同的数据模型,数据模型之间几乎总是存在关联。一个博客应用程序可能会包含用户、发帖和评论等数据模型。每一个用户创建很多帖子,每个帖子又会收到很多评论。我们可以像下面这样来定义他们的关联。

Ext.define('User', {

    extend: 'Ext.data.Model',

    fields: ['id', 'name'],

    proxy: {

        type: 'rest',

        url : 'data/users',

        reader: {

            type: 'json',

            root: 'users'

        }

    }, 

    hasMany: 'Post' // 等价于 { 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 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 we have a model instance we can easily traverse the associated data. For example, to log all comments made on each post for a given user, do something like this:

在应用程序中描述不同数据模型之间的丰富关联是很容易的。每一个数据模型都可以包含无限多个关联关系,你的数据模型定义顺序也可以随意。我们得到一个数据模型的实例之后就可以轻松地把它跟它的相关数据贯穿起来。比如要列出给定用户每个帖子中的全部评论,我们可以这样做:

// Loads User with ID 1 and related posts and comments using User's Proxy 
//
使用User的代理来加载ID1的用户和他的相关帖子及评论

User.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 adds a new function to the Model. We declared that each User model hasMany Posts, which added the user.posts() function we 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 we set up.

上面例子中的每个hasMany关联都会自动创建一个新的方法。比如我们定义了“每个User数据模型都hasMany个post”,所以一个user.posts()的方法被自动创建出来。调用这个方法就会返回一个由post数据模型定义的Store,同理,由于我们定义了post数据模型hasMany个comment模型,所以也会得到一个post.comments()方法。

Associations aren't just helpful for loading data, they're useful for creating new records too:

关联不仅仅对加载数据有帮助,在创建新数据时依然很有用:

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();

 
Here we instantiate a new Post, which is automatically given the User id in the user_id field. Calling sync() saves the new Post via its configured proxy. This, again, is an asynchronous operation to which you can pass a callback if you want to be notified when the operation completed.

这里我们实例化一个新的post,它的user_id字段会自动被赋予给定user的id。调用sync()方法可以通过配置的代理来保存新post。这同样是一个异步的操作,如果你想得到操作结束的提示可以传一个callback函数进去。

The belongsTo association also generates new methods on the model. Here's how to use that:

belongsTo关联同样会产生数据模型的新方法,示例如下:

// get the user reference from the post's belongsTo association 
//
通过postbelongsTo关联获得对user的引用

post.getUser(function(user) {

    console.log('Just got the user reference from the post: ' + user.get('name'))

}); 

// try to change the post's user(尝试修改postuser

post.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 simply updates the foreign_key (user_id in this case) to 100 and saves the Post model. As usual, callbacks can be passed in that will be triggered when the save operation has completed, whether successfully or not.

getUser是一个异步方法,因此需要一个回调函数来获得返回的user实例。而setUser方法把外键(user_id)更改成为100并应用对post数据的更改。像往常一样,我们传入一个回调函数以确保保存操作结束的时候会被触发,不论是否成功(译者注:操作结束意味着网络层面数据交互的完成,而是否成功则代表逻辑层面更新数据的成败,千万不要混淆)。


Validations

验证

Sencha Touch 2 Models have rich support for validating their data. To demonstrate this we're going to build upon the example we created that illustrated associations. First, let's add some validations to the User model:

ST2的数据模型对数据验证有着丰富的支持。为了演示这些,我们继续在前面创建的例子基础之上进行扩展。首先给User数据模型加入一些验证:

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: ...

});

 
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, etc. There are five validations built into Sencha Touch 2, and adding custom rules is easy. First, let's look at the ones built right in:

验证功能遵循与field定义同样的格式。每一次我们只能定义一个字段的一种验证类型。例子当中的验证要求name字段是必须的并且最少5个字符,age字段必须是数字,gender字段要么是male要么是female,username不能为admin。某些验证还可能使用更多选项配置,比如字符长度可以有min和max属性,format可以是一个matcher等等。ST2内置有5种验证类型,想要增加自定义规则同样很简单,首先看一下内置的:

presence simply ensures that the field has a value. Zero counts as a valid value but empty strings do not.

Presence保证某个字段必须有一个值。如:0是一个有效地值,但空字符串则不行。

length ensures that a string is between a minimum and maximum length. Both constraints are optional.

Length确保字符串的长度在许可范围之内,不过这两个约束条件是可选的。

format ensures that a string matches a regular expression format. In the example above we ensure that the age field is four numbers followed by at least one letter.

Format确保字符串符合正则表达式的规定。例子当中我们要求age字段是至少4个数字并且后面跟着1个字母(莫非文档作者晕了头?没看出代码中是这么约束的呀)

inclusion ensures that a value is within a specific set of values (for example, ensuring gender is either male or female).

Inclusion保证其值必须是指定范围其中之一(比如性别要么是男要么是女)

exclusion ensures that a value is not one of the specific set of values (for example, blacklisting usernames like 'admin').

Exclusion保证值不能是指定范围的其中之一(比如username的黑名单就禁止admin)

Now that we have a grasp of what the different validations do, let's try using them against a User instance. We'll create a user 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 can 
//
故意新建一个有错误,铁定无法通过验证的用户

var 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 errors(有错误无法通过验证,因此当然会返回false

console.log('All Errors:', errors.items); //returns the array of all errors found on this model instance(返回数据模型实例中所有错误的数组) 

console.log('Age Errors:', errors.getByField('age')); //returns the errors for the age field(返回age字段的所有错误)

 
The key function here is validate(), which runs all of the configured validations and returns an Errors object. This simple object is just 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()方法,该方法会运行validation中配置的所有规则检查并返回错误对象。这个对象是一个由所有错误组成的数组组合,同时提供了一系列便捷的方法,比如isValid()在所有字段都没出现错误的时候就会返回true,而getByField()方法会返回指定字段的所有错误。

For a complete example that uses validations please seeAssociations and Validations

完整的验证实例请参见这里Associations and Validations