Ext JS的data包有41个类,最重要的就是Model,Store 和Ext.data.proxy.Proxy这三个了。
Ext JS 4 的数据包:
Ext.data.Model是数据包的核心。一个Model代表应用程序的一些类型的数据。比如,一个电子商务应用程序可能含有 User,Products 和Orders 这样的Model.最简单的Model就是一组字段和值。这里着重介绍Model的四个基本的组成部分-Fields,Proxies,Associations 和 validations.
来看看如何定义一个model 的简单示例:
Ext.define('User', { extend: 'Ext.data.Model', fields: [ { name: 'id', type: 'int' }, { name: 'name', type: 'string' } ] });
Ext.create('Ext.data.Store', { model: 'User', proxy: { type: 'ajax', url : 'users.json', reader: 'json' }, autoLoad: true });这里使用Ajax Proxy 作为Store的数据源,配置了url 和 Reader(用于解码数据)。
这个Store 自动通过url(user.json)从服务端加载model 为User 的数据,服务端返回的JSON数据应该是如下格式:
{ success: true, users: [ { id: 1, name: 'Ed' }, { id: 2, name: 'Tommy' } ] }
Stores 也可以内联的方式加载数据。Store 回把传入的数据转换成 model, 如:
Ext.create('Ext.data.Store', { model: 'User', data: [ { firstName: 'Ed', lastName: 'Spencer' }, { firstName: 'Tommy', lastName: 'Maintz' }, { firstName: 'Aaron', lastName: 'Conran' }, { firstName: 'Jamie', lastName: 'Avins' } ] });
类似远端服务器的排序,过滤和分组,Stores 也可以在本地客户端进行排序,过滤和分组。
Ext.create('Ext.data.Store', { model: 'User', sorters: ['name', 'id'], filters: { property: 'name', value : 'Ed' }, groupField: 'age', groupDir: 'DESC' });在这个例子中,这个store先用name排序,再用 id排序。 只包含name="Ed"的数据,用age栏位逆序排列。
代理可以直接定义在一个Model上, 像:
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 Ext.create('Ext.data.Store', { model: 'User' });这样做有两个好处:
首先是这样的写法保证了所有使用User 这个Model的Store 都以同样的方式加载数据,避免在每个Store中重复定义Proxy;
其次,这样写可以在不使用store的状况下,加载和保存Model 数据。如下例
// Gives us a reference to the User class 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')); } });
可以使用关联的API 建立Models之间的关系。大多数的应用程序都有很多模型,而且模型之间基本上都是有关联的。举博客程序这样的例子来说,每个用户可以发表多篇博文:
Ext.define('User', { extend: 'Ext.data.Model', fields: ['id', 'name'], proxy: { type: 'rest', url : 'data/users', reader: { type: 'json', root: 'users' } }, hasMany: 'Post' // shorthand for { 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' });定义完成之后,在模型实例中就很容易能得到这些关联数据:如
// Loads User with ID 1 and related posts and comments using User's Proxy 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')); }); }); } });
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();
// get the user reference from the post's belongsTo association post.getUser(function(user) { console.log('Just got the user reference from the post: ' + user.get('name')) }); // try to change the post's user 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'); } } });
{ success: true, users: [ { id: 1, name: 'Ed', age: 25, gender: 'male', posts: [ { id : 12, title: 'All about data in Ext JS 4', body : 'One areas that has seen the most improvement...', comments: [ { id: 123, name: 'S Jobs', message: 'One more thing' } ] } ] } ] }
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: ... });
// 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 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