ExtJS4 自定義 TreeComboBox

鄧學彬發表於2012-05-15

今天在弄這個自定義TreeComboBox的時候走了不少彎路,在"Ext技術交流群"的網友"java-青島-小花園"指教下才修改好,十分感謝.

為了使自己印象深刻,特把結果發到這裡來存檔,以後隨時看一下.

問題分析
最早程式碼如下,例項化一次倒也沒有什麼問題,例項化多次後就出問題了

Ext.define('keel.TreeComboBox',{
	extend : 'Ext.form.field.ComboBox',
	treeObj : new Ext.tree.Panel({.....})//關鍵處
});

解決問題
在網友"java-青島-小花園"提示後,修改如下,主要是把new Ext.tree.Panel放到了initComponent裡面

Ext.define('keel.TreeComboBox',{
	extend : 'Ext.form.field.ComboBox',
	treeObj : null,//修改處
	initComponent : function(){
		this.treeObj=new Ext.tree.Panel({.....});//修改處
	});
});

最後執行效果

完整程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TreeComboBox</title>
<link rel="stylesheet" type="text/css" href="ext4/resources/css/ext-all.css" />
<script type="text/javascript" charset="utf-8" src="ext4/ext-all.js"></script>
<script language="JavaScript" type="text/javascript">
Ext.require(['*']);
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
//自定義下拉樹
Ext.define('keel.TreeComboBox',{
	extend : 'Ext.form.field.ComboBox',
	alias: 'widget.keeltreecombo',
	store : {fields:[],data:[[]]},
	editable : false,
	allowBlank:false,
	listConfig : {resizable:false,minWidth:200,maxWidth:450},
	_idValue : null,
	_txtValue : null,
	callback : Ext.emptyFn,
	treeObj : null,
	initComponent : function(){
		this.treeObj=new Ext.tree.Panel({
			border : false,
			autoScroll : true,
			rootVisible: false,
			renderTo:this.treeRenderId,
			root: {text: 'root',draggable: false,expanded: true,
				children:[{ text:'一級節點',expanded: true,
					children:[{ text:'二級節點1',leaf:true},{ text:'二級節點2',leaf:true}]}
				]}
		});		
		this.treeRenderId = Ext.id();
		this.tpl = "<tpl><div id='"+this.treeRenderId+"'></div></tpl>";		
		this.callParent(arguments);
		this.on({
			'expand' : function(){
			    if(!this.treeObj.rendered&&this.treeObj&&!this.readOnly){
			        Ext.defer(function(){
		        		this.treeObj.render(this.treeRenderId);
		        	},100,this);
			    }
		}
	});
		this.treeObj.on('itemclick',function(view,rec){
			if(rec){
				this.setValue(this._txtValue = rec.get('text'));                
				this.collapse();//關閉tree
			}
		},this);
	},
});

//例項化下拉樹
var xltree1=new keel.TreeComboBox({
    fieldLabel : '下拉樹1',
    name:'xltree1111',
    allowBlank:true
}); 
var xltree2=new keel.TreeComboBox({
    fieldLabel : '下拉樹2',
    name:'xltree2222',
    allowBlank:true
});


Ext.create('Ext.form.Panel', {
    renderTo: Ext.getBody(),
    width: 500,
    bodyPadding: 10,
    title: 'TreeComboBox',
    items: [xltree1, xltree2]
});

</script>
</body>
</html>

相關文章