Ext obj.ucountry is null

此问题出现在BasicForm调用load()方法进行数据回填且配置了BasicForm的reader时。extjs-logo
默认情况下,BasicForm调用load()方法向服务器请求数据用于数据回填(多数用于编辑数据),如要编辑一人员信息(user),其要求服务器返回的JSON格式如下:

{
    success: true,
    data: {
        uname: "neeke",
        uage: "21",
        ublog: "http://www.ineeke.com"
    }
}

当FormPanel中有一下ComboBox(name属性为ucountry)用于显示此人所属国家时(country),ComboBox所需要服务器端提供的是要显示的国家的cid(依具体数据库表结构而定),ComboBox得到ID后会自动的从其store中找出所匹配的国家名cname并呈现出来。而服务器端返回的JSON则是:

{
    success: true,
    data: {
        uname: "neeke",
        uage: "21",
        ublog: "http://www.ineeke.com",
	ucountry: {
		cid: 86,
		cname: '中国'
	}
    }
}

这样的数据ComboBox是不认识的,即便将CombobBox的name属性设为“ucountry.cid”也没用。此时就需要自己为BasicForm写reader进行映射。

reader: new Ext.data.JsonReader({
 
	root: 'data',
	successProperty: 'success',
	fields: [
		{name: 'ucountry', mapping: 'ucountry.cid'},
		{name: 'uname'},
		{name: 'uage'},
		{name: 'ublog'}
		]
})

当创建了自己的reader后,BasicForm要求服务器返回的数据又变了:

{
    success: true,
    data: [{
        uname: "neeke",
        uage: "21",
        ublog: "http://www.ineeke.com",
	ucountry: {
		cid: 86,
		cname: '中国'
	}
    }]
}

data需要变为数组,当user的ucountry不为空那么这样是不会存在任何问题的,反之Ext就会报obj.ucountry is null错误,这个错误很容易理解。问题出在Ext.data.JsonReader的getJsonAccessor()方法上,源码如下:

getJsonAccessor: function(){
	var re = /[\[\.]/;
	return function(expr) {
		try {
			return(re.test(expr)) ?
			new Function("obj", "return obj." + expr) :
			function(obj){
				return obj[expr];
			};
		} catch(e){}
		return Ext.emptyFn;
	};
}()

从源码可以看出,虽然在从第四行起加了try catch,可是在其第六行所返回的function中没有对obj.expr进行校验便返回了,所以映射时就会出现obj.null.cid,自然就报错了。我的解决方法就是复写getJsonAccessor()给它也加上try catch。

Ext.override(Ext.data.JsonReader,{
 
getJsonAccessor: function(){
    var re = /[\[\.]/;
    return function(expr) {
        try {
            return(re.test(expr)) ?
            new Function("obj", " try{return obj." + expr + "}catch(e){}") :
            function(obj){
                return obj[expr];
            };
        } catch(e){}
        return Ext.emptyFn;
    };
}()
})

可以说上面这段代码之前的一堆都是废话,就最后这段代码才是正解,不过对于我来说还是得搞清楚问题原由。


除非另有声明,本站遵循【署名-非商业性使用-相同方式共享 3.0 共享协议】授权。

转载原创文章请注明,转载自:Neeke[http://www.ineeke.com]

本文链接: http://www.ineeke.com/archives/ext-obj-ucountry-is-null/

2009年12月11日 | 归档于 ExtJS | 没有评论
标签: ,
本文目前尚无任何评论.

发表评论

XHTML: 您可以使用这些标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
n:-zy n:-zr n:-zan n:-xf n:-wx n:-tz n:-tt n:-ts n:-sy n:-st n:-ss n:-sk n:-qd n:-pz n:-lh n:-kun n:-ku n:-hx n:-hd n:-gt n:-gg n:-bz

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!