extjs-model讲解

来源:互联网 发布:无主之地2 mac汉化 编辑:程序博客网 时间:2024/05/22 17:29


分类: ExtJs 5448人阅读 评论(3) 收藏 举报
extjsjavascript

目录(?)[+]

1、Model的数据验证

这里借助官方的一个例子来说Model数据验证的基本用法

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('User', {  
  2.     extend: 'Ext.data.Model',  
  3.     fields: [  
  4.         { name: 'name',     type: 'string' },  
  5.         { name: 'age',      type: 'int' },  
  6.         { name: 'phone',    type: 'string' },  
  7.         { name: 'gender',   type: 'string' },  
  8.         { name: 'username', type: 'string' },  
  9.         { name: 'alive',    type: 'boolean', defaultValue: true }  
  10.     ],  
  11.   
  12.     validators: {  
  13.         age: 'presence',  
  14.         name: { type: 'length', min: 2 },  
  15.         gender: { type: 'inclusion', list: ['Male''Female'] },  
  16.         username: [  
  17.             { type: 'exclusion', list: ['Admin''Operator'] },  
  18.             { type: 'format', matcher: /([a-z]+)[0-9]{2,3}/i }  
  19.         ]  
  20.     }  
  21. });  
  22.   
  23. var instance = Ext.create('User', {  
  24.     name: 'Ed',  
  25.     gender: 'Male',  
  26.     username: 'edspencer'  
  27. });  
  28.   
  29. var validation = instance.getValidation();  
  30. console.log(validation);  
数据验证在validators属性中定义,数据验证的类型在Ext.data.validator下,Ext提供了8中验证。下面一一解释意思

age:'presence',字段后面直接写字符串表示这个类型的验证,类型查看的方法,打开这个类,在第一行就可以看到,如下

Ext.data.validator.Presencedata: validator.presence

validator.presence中的presence就是这个验证类的type,这种写法等同于{type:'presence'},presence类的意思是这个字段的值不能是null或undefined

name:使用的是长度验证,表示最小长度为2,验证类中各属性的配置,参见Ext官方API中这个类的config列表

gender:与name类似,表示这个字段只能是'Male',或者'Female'

username:的意思是不能包含Admin和Operator并且需满足后面的正则表达式。如果一个字段有多个验证的话可以参考username的形式。

下面我们自定义一个年龄的验证,首先值必须是数字,其次值需大于0小于160

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('Ext.data.validator.Age',{  
  2.     extend:'Ext.data.validator.Validator',  
  3.     alias: 'data.validator.age',  
  4.     type: 'age',  
  5.       
  6.     config:{  
  7.         message: 'Is in the wrong age',  
  8.         max:160 //默认最大年龄为160  
  9.     },  
  10.       
  11.     /** 
  12.      * 验证类中的核心方法 
  13.      * @param {Object} value 
  14.      * @return {Boolean} 返回true表示通过验证,否则返回message 
  15.      */  
  16.     validate:function(value){  
  17.         console.log(value);  
  18.         var result = Ext.isNumber(value);  
  19.         if(result){  
  20.             result = value>0 && value < this.getMax();  
  21.         }  
  22.           
  23.         return result ? result : this.getMessage();  
  24.     }  
  25. });  
用法如同Ext自带的验证类,需要注意的是这个类的定义需要在使用之前定义

2、Model转换的应用

如下面的转换,我们给电话号码前面加上+86

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('User', {  
  2.     extend: 'Ext.data.Model',  
  3.     fields: [  
  4.         { name: 'name',     type: 'string' },  
  5.         { name: 'age',      type: 'int' },  
  6.         { name: 'phone',    type: 'string', convert:function(value){  
  7.               
  8.             //如果值是字符串,并且没有以+86开头  
  9.             if(Ext.isString(value) && !Ext.String.startsWith(value,'+86')){  
  10.                 return '+86'+value;  
  11.             }  
  12.         }},  
  13.         { name: 'gender',   type: 'string' },  
  14.         { name: 'username', type: 'string' },  
  15.         { name: 'alive',    type: 'boolean', defaultValue: true }  
  16.     ]  
  17. });  
  18.   
  19. var user = Ext.create('User', {  
  20.     phone:'15938383838'  
  21. });  
  22.   
  23. //var validation = instance.getValidation();  
  24. console.log(user.get('phone'));  
上面的Model我们给phone加上了转换,那么在定义Model或者给phone赋值时,就会自动调用convert,检查phone是否是字符串、是否以+86开头,如果是字符串并且没有以+86开头则自动给phone加上+86

这个在0,1转true、false的时候用的比较多

3、Model之Ajax

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('User', {  
  2.     extend: 'Ext.data.Model',  
  3.     idProperty:'id',  
  4.     fields: ['id''name''email'],  
  5.   
  6.     proxy: {  
  7.         type: 'rest',  
  8.         api: {  
  9.             create: 'user/add',  
  10.             read: 'user/get'//在调用Model的静态方法load时,会默认去这里查数据  
  11.             update: 'user/update',  
  12.             destroy: 'user/del' //在调用Model的erase方法(Ext5.0以前的版本是destroy方法,意思就是根据ID删除Model)  
  13.         }  
  14.     }  
  15. });  
在调用save方法时,会自动判断Model的id属性是否有值如果有就使用update路径,如果没有就使用create路径,在5.0之前的版本save和update是一个方法,5.0的版本中其实save,update,delete用的都是save方法,这一点从源码中可以看出

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Destroys the model using the configured proxy. 
  3.  * @param {Object} options Options to pass to the proxy. Config object for {@link Ext.data.operation.Operation}. 
  4.  * @return {Ext.data.operation.Operation} The operation 
  5.  */  
  6. erase: function(options) {  
  7.     this.drop();  
  8.     return this.save(options);  
  9. },  
  10.   
  11. /** 
  12.  * Saves the model instance using the configured proxy. 
  13.  * @param {Object} [options] Options to pass to the proxy. Config object for {@link Ext.data.operation.Operation}. 
  14.  * @return {Ext.data.operation.Operation} The operation 
  15.  */  
  16. save: function(options) {  
  17.     options = Ext.apply({}, options);  
  18.       
  19.     var me = this,  
  20.         phantom = me.phantom,  
  21.         dropped = me.dropped,  
  22.         action = dropped ? 'destroy' : (phantom ? 'create' : 'update'),  
  23.         scope  = options.scope || me,  
  24.         callback = options.callback,  
  25.         proxy = me.getProxy(),  
  26.         operation;  
  27.           
  28.     options.records = [me];  
  29.     options.internalCallback = function(operation) {  
  30.         var args = [me, operation],  
  31.             success = operation.wasSuccessful();  
  32.         if (success) {  
  33.             Ext.callback(options.success, scope, args);  
  34.         } else {  
  35.             Ext.callback(options.failure, scope, args);  
  36.         }  
  37.         args.push(success);  
  38.         Ext.callback(callback, scope, args);  
  39.     };  
  40.     delete options.callback;  
  41.       
  42.     operation = proxy.createOperation(action, options);  
  43.   
  44.     // Not a phantom, then we must perform this operation on the remote datasource.  
  45.     // Record will be removed from the store in the callback upon a success response  
  46.     if (dropped && phantom) {  
  47.         // If it's a phantom, then call the callback directly with a dummy successful ResultSet  
  48.         operation.setResultSet(Ext.data.reader.Reader.prototype.nullResultSet);  
  49.         me.setErased();  
  50.         operation.setSuccessful(true);  
  51.     } else {  
  52.         operation.execute();  
  53.     }  
  54.     return operation;  
  55. },  

4、Model中的常用方法

Model中常用的方法在上面也提到了一些,下面介绍上面没有提到的

get(filedName):根据字段名获取字段的值,这个在上面用到过,这里重复强调一遍,这个是用的最多的方法之一

getId():获取Model的id,前提是要设置idProperty这个属性

getIdProperty:获取ID字段的值

isVaild():判断Model是否通过验证
set( fieldName, newValue, [options] ):为字段赋值,可以穿一个Object形式的参数如{name:'jaune',age:24}

分类: ExtJs 5448人阅读 评论(3) 收藏 举报
extjsjavascript

目录(?)[+]

1、Model的数据验证

这里借助官方的一个例子来说Model数据验证的基本用法

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('User', {  
  2.     extend: 'Ext.data.Model',  
  3.     fields: [  
  4.         { name: 'name',     type: 'string' },  
  5.         { name: 'age',      type: 'int' },  
  6.         { name: 'phone',    type: 'string' },  
  7.         { name: 'gender',   type: 'string' },  
  8.         { name: 'username', type: 'string' },  
  9.         { name: 'alive',    type: 'boolean', defaultValue: true }  
  10.     ],  
  11.   
  12.     validators: {  
  13.         age: 'presence',  
  14.         name: { type: 'length', min: 2 },  
  15.         gender: { type: 'inclusion', list: ['Male''Female'] },  
  16.         username: [  
  17.             { type: 'exclusion', list: ['Admin''Operator'] },  
  18.             { type: 'format', matcher: /([a-z]+)[0-9]{2,3}/i }  
  19.         ]  
  20.     }  
  21. });  
  22.   
  23. var instance = Ext.create('User', {  
  24.     name: 'Ed',  
  25.     gender: 'Male',  
  26.     username: 'edspencer'  
  27. });  
  28.   
  29. var validation = instance.getValidation();  
  30. console.log(validation);  
数据验证在validators属性中定义,数据验证的类型在Ext.data.validator下,Ext提供了8中验证。下面一一解释意思

age:'presence',字段后面直接写字符串表示这个类型的验证,类型查看的方法,打开这个类,在第一行就可以看到,如下

Ext.data.validator.Presencedata: validator.presence

validator.presence中的presence就是这个验证类的type,这种写法等同于{type:'presence'},presence类的意思是这个字段的值不能是null或undefined

name:使用的是长度验证,表示最小长度为2,验证类中各属性的配置,参见Ext官方API中这个类的config列表

gender:与name类似,表示这个字段只能是'Male',或者'Female'

username:的意思是不能包含Admin和Operator并且需满足后面的正则表达式。如果一个字段有多个验证的话可以参考username的形式。

下面我们自定义一个年龄的验证,首先值必须是数字,其次值需大于0小于160

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('Ext.data.validator.Age',{  
  2.     extend:'Ext.data.validator.Validator',  
  3.     alias: 'data.validator.age',  
  4.     type: 'age',  
  5.       
  6.     config:{  
  7.         message: 'Is in the wrong age',  
  8.         max:160 //默认最大年龄为160  
  9.     },  
  10.       
  11.     /** 
  12.      * 验证类中的核心方法 
  13.      * @param {Object} value 
  14.      * @return {Boolean} 返回true表示通过验证,否则返回message 
  15.      */  
  16.     validate:function(value){  
  17.         console.log(value);  
  18.         var result = Ext.isNumber(value);  
  19.         if(result){  
  20.             result = value>0 && value < this.getMax();  
  21.         }  
  22.           
  23.         return result ? result : this.getMessage();  
  24.     }  
  25. });  
用法如同Ext自带的验证类,需要注意的是这个类的定义需要在使用之前定义

2、Model转换的应用

如下面的转换,我们给电话号码前面加上+86

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('User', {  
  2.     extend: 'Ext.data.Model',  
  3.     fields: [  
  4.         { name: 'name',     type: 'string' },  
  5.         { name: 'age',      type: 'int' },  
  6.         { name: 'phone',    type: 'string', convert:function(value){  
  7.               
  8.             //如果值是字符串,并且没有以+86开头  
  9.             if(Ext.isString(value) && !Ext.String.startsWith(value,'+86')){  
  10.                 return '+86'+value;  
  11.             }  
  12.         }},  
  13.         { name: 'gender',   type: 'string' },  
  14.         { name: 'username', type: 'string' },  
  15.         { name: 'alive',    type: 'boolean', defaultValue: true }  
  16.     ]  
  17. });  
  18.   
  19. var user = Ext.create('User', {  
  20.     phone:'15938383838'  
  21. });  
  22.   
  23. //var validation = instance.getValidation();  
  24. console.log(user.get('phone'));  
上面的Model我们给phone加上了转换,那么在定义Model或者给phone赋值时,就会自动调用convert,检查phone是否是字符串、是否以+86开头,如果是字符串并且没有以+86开头则自动给phone加上+86

这个在0,1转true、false的时候用的比较多

3、Model之Ajax

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Ext.define('User', {  
  2.     extend: 'Ext.data.Model',  
  3.     idProperty:'id',  
  4.     fields: ['id''name''email'],  
  5.   
  6.     proxy: {  
  7.         type: 'rest',  
  8.         api: {  
  9.             create: 'user/add',  
  10.             read: 'user/get'//在调用Model的静态方法load时,会默认去这里查数据  
  11.             update: 'user/update',  
  12.             destroy: 'user/del' //在调用Model的erase方法(Ext5.0以前的版本是destroy方法,意思就是根据ID删除Model)  
  13.         }  
  14.     }  
  15. });  
在调用save方法时,会自动判断Model的id属性是否有值如果有就使用update路径,如果没有就使用create路径,在5.0之前的版本save和update是一个方法,5.0的版本中其实save,update,delete用的都是save方法,这一点从源码中可以看出

[javascript] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * Destroys the model using the configured proxy. 
  3.  * @param {Object} options Options to pass to the proxy. Config object for {@link Ext.data.operation.Operation}. 
  4.  * @return {Ext.data.operation.Operation} The operation 
  5.  */  
  6. erase: function(options) {  
  7.     this.drop();  
  8.     return this.save(options);  
  9. },  
  10.   
  11. /** 
  12.  * Saves the model instance using the configured proxy. 
  13.  * @param {Object} [options] Options to pass to the proxy. Config object for {@link Ext.data.operation.Operation}. 
  14.  * @return {Ext.data.operation.Operation} The operation 
  15.  */  
  16. save: function(options) {  
  17.     options = Ext.apply({}, options);  
  18.       
  19.     var me = this,  
  20.         phantom = me.phantom,  
  21.         dropped = me.dropped,  
  22.         action = dropped ? 'destroy' : (phantom ? 'create' : 'update'),  
  23.         scope  = options.scope || me,  
  24.         callback = options.callback,  
  25.         proxy = me.getProxy(),  
  26.         operation;  
  27.           
  28.     options.records = [me];  
  29.     options.internalCallback = function(operation) {  
  30.         var args = [me, operation],  
  31.             success = operation.wasSuccessful();  
  32.         if (success) {  
  33.             Ext.callback(options.success, scope, args);  
  34.         } else {  
  35.             Ext.callback(options.failure, scope, args);  
  36.         }  
  37.         args.push(success);  
  38.         Ext.callback(callback, scope, args);  
  39.     };  
  40.     delete options.callback;  
  41.       
  42.     operation = proxy.createOperation(action, options);  
  43.   
  44.     // Not a phantom, then we must perform this operation on the remote datasource.  
  45.     // Record will be removed from the store in the callback upon a success response  
  46.     if (dropped && phantom) {  
  47.         // If it's a phantom, then call the callback directly with a dummy successful ResultSet  
  48.         operation.setResultSet(Ext.data.reader.Reader.prototype.nullResultSet);  
  49.         me.setErased();  
  50.         operation.setSuccessful(true);  
  51.     } else {  
  52.         operation.execute();  
  53.     }  
  54.     return operation;  
  55. },  

4、Model中的常用方法

Model中常用的方法在上面也提到了一些,下面介绍上面没有提到的

get(filedName):根据字段名获取字段的值,这个在上面用到过,这里重复强调一遍,这个是用的最多的方法之一

getId():获取Model的id,前提是要设置idProperty这个属性

getIdProperty:获取ID字段的值

isVaild():判断Model是否通过验证
set( fieldName, newValue, [options] ):为字段赋值,可以穿一个Object形式的参数如{name:'jaune',age:24}

0 0