Model定义的两种方式

第一种


第二种


如何实例化?

首先我们尝试最基本的方式 new

var user = new User({username:'somnus',password:'123456'});
console.info(user.get('password'));//123456
然后用create方式

var user = Ext.create('User'{username:'somnus',password:'123456'});
console.info(user.get('password'));//123456

extjs4还给model单独提供了一种对象创建方式

如何远程加载数据到model

Ext.regModel('User', {
	fields : [
		{name : 'name',type : 'string'},
		{name : 'id',type : 'int'}
	],
	proxy : {
		type : 'ajax',
		url : 'userServer.jsp'
	}
});
var user = Ext.ModelManager.getModel('User');
user.load(1,{
	success:function(rec){
		console.log(rec.get('username'));
	}
});

如何校验model中的数据

这里不得不提下我在密码那里新增了一个长度验证,那如何自定义呢?且看

//自定义数值范围验证
Ext.apply(Ext.data.validations,{
	number : function(config, value){
		if (value === undefined){
	           return false;
	    }
        var min    = config.min;
        var max    = config.max;
        
	    if ((min && value < min) || (max && value > max)){
	    		this.numberMessage = this.numberMessage+"它应该在["+min+"-"+max+"]";
	           return false;
	    } else{
	           return true;
	    }
	},
	numberMessage : '数值范围错误。'
});


Model之间是如何关联的

我们在hibernate中已经认识到,对象之间是可以关联的,extjs在这里也实现了

Ext.regModel('User', {
	fields : ['name','id'],
	hasMany : {
		model : 'Product',
		name : 'getProducts',
		autoLoad : false
	},
	proxy : {
		type : 'ajax',
		url : 'userServer.jsp'
	}
});
Ext.regModel('Product', {
	fields : ['id','title','user_id'],
	proxy : {
		type : 'ajax',
		url : 'ProductServer.jsp',
		reader : {
			type : 'json',
			root : 'products'
		}
	}
});
var user = Ext.ModelManager.getModel('User');
// 读取id为1的User实例
user.load(1, {
	success : function(rec) {
		// 获取user_id为1的产品Store
		var products = rec.getProducts();
		// 加载user_id为1的产品数据
		products.load({
			callback : function(records, operation, success) {
				Ext.each(records,function(record){
					console.info(record.get('title'));
				})
			}
		});
	}
});

Extjs4还提供了一种配置方式

Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id'],
    associations: [
        {type: 'hasMany', model: 'Product', name: 'getProducts'}
    ]
});

上面我给的例子是一对多,一对一肯定也是存在的,翻看api

hasOne
belongsTo

相关文章:

  • 2021-12-07
  • 2022-02-09
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
  • 2021-05-30
猜你喜欢
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2021-10-13
  • 2022-12-23
  • 2022-01-22
相关资源
相似解决方案