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

前言:

 

数据模型[Model]就像模具,它保证了经它手产出的数据都具有一样的格式,但是数据模型本身并不能直接为view的展示提供内容,因为它并不是数据实体,真正存储数据实体的是Store,而Store的获取与保存由需要借助Proxy的力量,所以学习Sencha TouchModel,就必须熟练掌握StoreProxy。由于两篇文章都比较短且关系紧密,所以我把它们合并成一篇来发布。

 

两文章的英文原址是

http://docs.sencha.com/touch/2-0/#!/guide/stores

http://docs.sencha.com/touch/2-0/#!/guide/proxies

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


 

Using Stores

使用数据存储


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


Models are typically used with a Store, which is basically a collection of model instances. Setting up 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

});


We configured our store to use an Ajax Proxy, providing the name of the URL from which to load data the Reader used to decode the data. In this case our server is returning JSON, so we've set up a Json Reader to read the response. The store auto-loads a set of User model instances from the URL users.json. The users.json URL should return a JSON string that looks something like this:

我们定义这个数据存储(store)使用Ajax作为数据代理(proxy),并指定了提供数据的Url和用来解码数据的阅读器(reader)。本例当中我们的服务器返回的是JSON格式,所以我们使用Json Reader去读取和解析数据。这个数据存储会通过访问users.json路径来自动加载一系列使用User数据模型的实例。Users.json这个url应当返回一个JSON字符串,比如下面这样:

{

    success: true,

    users: [

        { id: 1, name: 'Ed' },

        { id: 2, name: 'Tommy' }

    ]

}


For a live demo, see the Simple Store example.

这里有一个简单鲜活的例子, Simple Store,我把代码直接抠过来了

Ext.define('User', {

    extend: 'Ext.data.Model',

    fields: [

        {name: 'id', type: 'int'},

        {name: 'name', type: 'string'}

    ]

});

 

var userStore;

Ext.require('Ext.data.Store');

Ext.onReady(function() {

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

        model: 'User',

        autoLoad: true,

 

        proxy: {

            type: 'ajax',

            url: 'data/users.json',

            reader: {

                type: 'json',

                root: 'users',

                successProperty: 'success'

            }

        }

    });

});

 


Inline data

内联数据


Stores can also load data inline. Internally, Store converts each of the objects we pass in as data into Model instances:

数据存储也可以通过内联(内嵌)的方式加载数据。数据存储内部会把传入的每一个对象转成数据模型的实例:

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

    model: 'User',

    data: [

        { firstName: 'Ed',    lastName: 'Spencer' },

        { firstName: 'Tommy', lastName: 'Maintz' },

        { firstName: 'Aaron', lastName: 'Conran' },

        { firstName: 'Jamie', lastName: 'Avins' }

    ]

});


Inline Data example惯例我把代码直接抠过来方便看

Ext.define('User', {

    extend: 'Ext.data.Model',

    fields: ['firstName', 'lastName']

});

 

var userStore;

Ext.require('Ext.data.Store');

Ext.onReady(function() {

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

        model: 'User',

        data: [

            {firstName: 'Ed',    lastName: 'Spencer'},

            {firstName: 'Tommy', lastName: 'Maintz'},

            {firstName: 'Aaron', lastName: 'Conran'},

            {firstName: 'Jamie', lastName: 'Avins'}

        ]

    });

});

 


Sorting and Grouping

排序和分组


Stores are able to perform sorting, filtering, and grouping locally, as well as to support 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 will be sorted first by name then id; it will be filtered to only include users with the name Ed, and the data will be grouped by age in descending order. It's easy to change the sorting, filtering, and grouping at any time through the Store API. For a live demo, see the Sorting Grouping Filtering Store example.

在刚才创建的数据存储里,数据将会按照先nameid的顺序进行排序,他还会筛选出仅仅满足name等于Edusers,同时数据会按照年龄分组进行降序排列。在任何时候通过Storeapi来改变排序、筛选和分组都是很容易的,这里有个例子Sorting Grouping Filtering Store。(下面就是代码,免得你自己去翻了)

Ext.define('User', {

    extend: 'Ext.data.Model',

    fields: [

        { name: 'id', type: 'int' },

        { name: 'name', type: 'string' },

        { name: 'age', type: 'int' },

        { name: 'bob', type: 'int' }

    ]

});

 

var userStore;

Ext.require('Ext.data.Store');

Ext.onReady(function() {

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

        model: 'User',

        autoLoad: true,

 

        sorters: ['name', 'id'], // sort first by name, then by id

        filters: {

            // filter the data to only include users with the name 'Ed'

            property: 'name',

            value: 'Ed'

        },

        groupField: 'age',

        groupDir: 'DESC',

 

        proxy: {

            type: 'ajax',

            url: 'data/users.json',

            reader: {

                type: 'json',

                root: 'users',

                successProperty: 'success'

            }

        }

    });

});

 

Using Proxies

使用数据代理

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


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.

数据存储通过代理来处理Model数据的加载和保存。代理有两种方式,本地代理和服务端代理。例子里的客户端代理包含了浏览器内存和html5的本地存储两种介质。服务端代理通过远程服务器实现数据的处理,包含AjaxJsonPRest方式。


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

代理可以直接定义在数据模型里,就像这样:

Ext.define('User', {

    extend: 'Ext.data.Model',

 

    config: {

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

        proxy: {

            type: 'rest',

            url : '/data/users.json',

            reader: {

                type: 'json',

                root: 'users'

            }

        }

    }

});

 

// Uses the User Model's Proxy

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里都拷贝一遍了,第二我们现在可以不通过store就实现加载和保存model数据了。


// 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.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 don't support these new HTML5 APIs, they're so useful that a lot of applications will benefit enormously by using them.

我们还有利用了html5新特性备受内地存储和会话存储的proxy。虽然比较老一些的浏览器不支持这些html5api,但仍会有很多应用程序会从中受益。