ExtJS教程(5)---Ext.data.Model之高级应用

1、Model的数据验证

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

	Ext.define('User', {
	    extend: 'Ext.data.Model',
	    fields: [
	        { name: 'name',     type: 'string' },
	        { name: 'age',      type: 'int' },
	        { name: 'phone',    type: 'string' },
	        { name: 'gender',   type: 'string' },
	        { name: 'username', type: 'string' },
	        { name: 'alive',    type: 'boolean', defaultValue: true }
	    ],

	    validators: {
	        age: 'presence',
	        name: { type: 'length', min: 2 },
	        gender: { type: 'inclusion', list: ['Male', 'Female'] },
	        username: [
	            { type: 'exclusion', list: ['Admin', 'Operator'] },
	            { type: 'format', matcher: /([a-z]+)[0-9]{2,3}/i }
	        ]
	    }
	});

	var instance = Ext.create('User', {
	    name: 'Ed',
	    gender: 'Male',
	    username: 'edspencer'
	});

	var validation = instance.getValidation();
	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

	Ext.define('Ext.data.validator.Age',{
		extend:'Ext.data.validator.Validator',
		alias: 'data.validator.age',
    	type: 'age',

    	config:{
    		message: 'Is in the wrong age',
    		max:160 //默认最大年龄为160
    	},

    	/**
    	 * 验证类中的核心方法
    	 * @param {Object} value
    	 * @return {Boolean} 返回true表示通过验证,否则返回message
    	 */
    	validate:function(value){
    		console.log(value);
    		var result = Ext.isNumber(value);
    		if(result){
    			result = value>0 && value < this.getMax();
    		}

    		return result ? result : this.getMessage();
    	}
	});

用法如同Ext自带的验证类,需要注意的是这个类的定义需要在使用之前定义

2、Model转换的应用

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

	Ext.define('User', {
	    extend: 'Ext.data.Model',
	    fields: [
	        { name: 'name',     type: 'string' },
	        { name: 'age',      type: 'int' },
	        { name: 'phone',    type: 'string', convert:function(value){

	        	//如果值是字符串,并且没有以+86开头
	        	if(Ext.isString(value) && !Ext.String.startsWith(value,'+86')){
	        		return '+86'+value;
	        	}
	        }},
	        { name: 'gender',   type: 'string' },
	        { name: 'username', type: 'string' },
	        { name: 'alive',    type: 'boolean', defaultValue: true }
	    ]
	});

	var user = Ext.create('User', {
	    phone:'15938383838'
	});

	//var validation = instance.getValidation();
	console.log(user.get('phone'));

上面的Model我们给phone加上了转换,那么在定义Model或者给phone赋值时,就会自动调用convert,检查phone是否是字符串、是否以+86开头,如果是字符串并且没有以+86开头则自动给phone加上+86

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

3、Model之Ajax

	Ext.define('User', {
	    extend: 'Ext.data.Model',
	    idProperty:'id',
	    fields: ['id', 'name', 'email'],

	    proxy: {
	        type: 'rest',
	        api: {
			    create: 'user/add',
			    read: 'user/get', //在调用Model的静态方法load时,会默认去这里查数据
			    update: 'user/update',
			    destroy: 'user/del' //在调用Model的erase方法(Ext5.0以前的版本是destroy方法,意思就是根据ID删除Model)
			}
	    }
	});

在调用save方法时,会自动判断Model的id属性是否有值如果有就使用update路径,如果没有就使用create路径,在5.0之前的版本save和update是一个方法,5.0的版本中其实save,update,delete用的都是save方法,这一点从源码中可以看出

    /**
     * Destroys the model using the configured proxy.
     * @param {Object} options Options to pass to the proxy. Config object for {@link Ext.data.operation.Operation}.
     * @return {Ext.data.operation.Operation} The operation
     */
    erase: function(options) {
        this.drop();
        return this.save(options);
    },

    /**
     * Saves the model instance using the configured proxy.
     * @param {Object} [options] Options to pass to the proxy. Config object for {@link Ext.data.operation.Operation}.
     * @return {Ext.data.operation.Operation} The operation
     */
    save: function(options) {
        options = Ext.apply({}, options);

        var me = this,
            phantom = me.phantom,
            dropped = me.dropped,
            action = dropped ? 'destroy' : (phantom ? 'create' : 'update'),
            scope  = options.scope || me,
            callback = options.callback,
            proxy = me.getProxy(),
            operation;

        options.records = [me];
        options.internalCallback = function(operation) {
            var args = [me, operation],
                success = operation.wasSuccessful();
            if (success) {
                Ext.callback(options.success, scope, args);
            } else {
                Ext.callback(options.failure, scope, args);
            }
            args.push(success);
            Ext.callback(callback, scope, args);
        };
        delete options.callback;

        operation = proxy.createOperation(action, options);

        // Not a phantom, then we must perform this operation on the remote datasource.
        // Record will be removed from the store in the callback upon a success response
        if (dropped && phantom) {
            // If it's a phantom, then call the callback directly with a dummy successful ResultSet
            operation.setResultSet(Ext.data.reader.Reader.prototype.nullResultSet);
            me.setErased();
            operation.setSuccessful(true);
        } else {
            operation.execute();
        }
        return operation;
    },

4、Model中的常用方法

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

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

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

getIdProperty:获取ID字段的值

isVaild():判断Model是否通过验证

set( fieldName, newValue, [options] ):为字段赋值,可以穿一个Object形式的参数如{name:‘jaune‘,age:24}

ExtJS教程(5)---Ext.data.Model之高级应用

时间: 2024-07-30 22:02:33

ExtJS教程(5)---Ext.data.Model之高级应用的相关文章

[ExtJs] ExtJs4.2 数据模型Ext.data.Model学习

Model代表应用程序管理的一些对象.例如,我们可能会为 我们想在系统中建模的现实世界中的一些物体像使用者.产品和汽车等定义一个Model.这些Model在 Ext.ModelManager中注册,被Ext.data.Store使用, 而这些Ext.data.Store又被许多 Ext中许多与数据绑定的组件使用. 直接上代码: <%-- Created by IntelliJ IDEA. User: Administrator Date: 2015/12/13 0013 Time: 08:51

Extjs的form表单自动装载数据(通过Ext.data.Model的代理加载数据)

在做项目的时候遇到一个问题,以前双击grid页面一行数据的时候,会吧双击这一行的数据自动加载到双击的页面(Ext的弹出框),可以通过this.down(''form).getForm().loadRecord(record)来自动加载,可是现在有一个需求就是双击grid一行弹出一个新的浏览器页面(不是ext的弹出框,通过window.open()实现),只能把双击的id传到页面,再重新查数据手动赋值,如果一个页面字段很多,一个一个赋值是很辛苦的,所以就想能不能自动装载数据 通过长时间研究发现,t

ExtJS笔记 Ext.data.Model

A Model represents some object that your application manages. For example, one might define a Model for Users, Products, Cars, or any other real-world object that we want to model in the system. Models are registered via the model manager, and are us

ExtJS 4 【Ext.data.proxy.Ajax】

namespace ExtJSProject.WebApi.Models { [Serializable] [DataContract] public class Person { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } } }   namespace ExtJSProject.WebApi.Controllers { [RoutePrefix("api/Per

extjs4新特性Ext.data.model

在发布的ExtJS4版本中,在data包中新增加了一个类Model(模型类).这个类有点类似于ExtJS3.x中的record,但是新添加的Model的功能要比record类的功能强大的多,下面我们就是一起讨论一下.Model类的功能: (一).首先我们介绍一下Model类中比较常用的几个属性,如果我们想构建一个Model类,最主要的属性就是(Fields)属性,这个属性接受一个数组.用来设置Model中所包含的字段.定义的格式如下: Ext.regModel("Student",{

Extjs学习笔记——Ext.data.JsonStore使用说明

Ext.data.JsonStore继承于Ext.data.Store,使得从远程JSON数据创建stores更为方便的简单辅助类.JsonStore合成了Ext.data.HttpProxy与Ext.data.JsonReader两者.如果你需要其他类型的proxy或reader组合,那么你要创建以Ext.data.Store为基类的配置. 代码实例: var store = new Ext.data.JsonStore({ id:'id', url: 'get-images.php', ro

转: Ext.data.Store 修改Post请求

Extjs 4.0版本 var Store = Ext.create('Ext.data.Store', { pageSize: pageSize, model: 'Ext.data.Model名称', autoLoad: false, proxy: { type: 'ajax', url: '请求路径', //actionMethods: 'post', getMethod: function(){ return 'POST'; },//亮点,设置请求方式,默认为GET reader: { t

&#39;Ext.data.Store&#39; 中的 load

//产品store       window.product_store=Ext.create('Ext.data.Store',{  fields:[            'id',            'aid',            'webid',            'title',            'kindlist',            'attrid',            'ishidden',            'displayorder',     

ExtJS教程(3)--- Ext中类的使用

本章仅仅介绍Ext中类的基础知识,一些高级知识会在以后的章节中穿插介绍 注:由于截图上传较为麻烦,且图片占用篇幅较大,所以在以后的文章中如果不是特别必要,将不会插入很多图片,最终的执行结果请大家自行验证. 1.定义一个类 //使用Ext定义一个类 Ext.define('Person',{ name:'jaune', age:18 }); //创建一个类 var person = new Person(); console.log(person); 从打出来的结果中可以看出我们定义的属性已经出现