---
title: "Ext实用例子"
author: "jungh"
date: "2010-12-15T15:38:52Z"
tags: ["C", "C#", "C++", "EXT", "UI"]
categories: ["Web前端"]
slug: "ext"
draft: false
lastmod: "2010-12-15T15:38:52Z"
id: 842964
url: "https://jungh.iteye.com/blog/842964"
---

总结自己的代码 可能以后会用到 记录一下 方便以后查阅

 1：所以显示window 的所需的代码

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. MyExt.Utils.myWindow = Ext.extend(Ext.Window, {
02. shadow:**false**,
03. closeAction:'hide',
04. layout:'fit',
05. closable:**true**,
06. resizable:**false**,
07. modal:**true**,
08. constrain:**true**,
09. listeners:{
10. hide:function(w){
11. **if**(w.items){
12. w.items.each(function(f){
13. **if**(f.getXType()=="form"){
14. f.form.reset();
15. }
16. });
17. }
18. }
19. },
20. initComponent: function(config){
21. Ext.apply(**this**,config);
22. MyExt.Utils.myWindow.superclass.initComponent.call(**this**);
23. }
24. });

```
MyExt.Utils.myWindow = Ext.extend(Ext.Window, {  
     shadow:false,
      closeAction:'hide',
     layout:'fit',
     closable:true,
     resizable:false, 
     modal:true,
     constrain:true,
      listeners:{
     	hide:function(w){
      	      if(w.items){
        		w.items.each(function(f){
        		 	if(f.getXType()=="form"){
          				 f.form.reset();
        		 	}
           		});
      	    }
     	}
     }, 
      initComponent: function(config){ 
      Ext.apply(this,config);
    MyExt.Utils.myWindow.superclass.initComponent.call(this);   
    }   
   });
```

   使用例子：

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

1. var win = **new** MyExt.Utils.myWindow({
2. height:600
3. ,width:650
4. ,items:\[form]
5. })

```
   		var win = new MyExt.Utils.myWindow({
   			height:600
   			,width:650
   			,items:[form]
   		})
```

 

2:jsonStore

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. MyExt.Utils.myJsonStore = Ext.extend(Ext.data.JsonStore, {
02. constructor: function(config){
03. var cfg = {
04. totalProperty: "totalCount",//总数
05. root: "items",//grid的数据
06. autoLoad:**false**, //是否自动加载
07. autoDestroy:**true**, //自动销毁
08. idProperty: 'id' //一个数据对象的参数名，它包含了一条记录的标识符。 默认为 id
09. };
10. //把cfg对象的所有属性覆盖到congfig对象里面
11. //如果congfig对象已经存在cfg的属性 则不覆盖
12. Ext.applyIf(config,cfg);
13. MyExt.Utils.myJsonStore.superclass.constructor.call(**this**,config);
14. }
15. });

```
MyExt.Utils.myJsonStore = Ext.extend(Ext.data.JsonStore, {
    constructor: function(config){
    	var cfg = {
    		  totalProperty: "totalCount",//总数 
			  root: "items",//grid的数据
			  autoLoad:false, //是否自动加载
			  autoDestroy:true, //自动销毁
			  idProperty: 'id' //一个数据对象的参数名，它包含了一条记录的标识符。 默认为 id 
			  	
    	};
    	//把cfg对象的所有属性覆盖到congfig对象里面
    	//如果congfig对象已经存在cfg的属性 则不覆盖
        Ext.applyIf(config,cfg);
        MyExt.Utils.myJsonStore.superclass.constructor.call(this,config);
    }
});
```

 

  使用例子：

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. store = **new** MyExt.Utils.myJsonStore({
02. url:"....action",
03. fields:[
04. {"name":"yyshd","type":"string","mapping":"yyshd"},
05. {"name":"hm","type":"string","mapping":"hm"},
06. {"name":"sf","type":"string","mapping":"sf"},
07. {"name":"ds","type":"string","mapping":"ds"},
08. {"name":"yysid","type":"int","mapping":"yysid"},
09. {"name":"qy","type":"int","mapping":"qy"}
10. ]
11. });

```
store = new MyExt.Utils.myJsonStore({
				        url:"....action",
				        fields:[
					        		{"name":"yyshd","type":"string","mapping":"yyshd"},
					        		{"name":"hm","type":"string","mapping":"hm"},
					        		{"name":"sf","type":"string","mapping":"sf"},
					        		{"name":"ds","type":"string","mapping":"ds"},
					        		{"name":"yysid","type":"int","mapping":"yysid"},
					        		{"name":"qy","type":"int","mapping":"qy"}
				        	    ]
				    }); 
```

 

3:行提示

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. function showGjToolTip(\_grid){
02. var \_store = \_grid.getStore();
03. var view = \_grid.getView();
04. \_grid.tip = **new** Ext.ToolTip ({
05. target:view.mainBody,
06. delegate:'.x-grid3-row',
07. trackMouse :**true**,
08. width:230,
09. autoHide:**true**,
10. title:"告警信息",
11. dismissDelay:5000,  //默认5秒后提示框消失
12. frame:**true**,
13. renderTo:document.body,
14. bodyStyle:"color:red",//字体颜色
15. //floating:{shadow:false,shim:true,useDisplay:true,constrain:false},
16. listeners:{
17. beforeshow:function updateTipBody(tip){
18. var rowIndex = view.findRowIndex(tip.triggerElement);
19. **if**(\_store.getAt(rowIndex).get("sfgj")==0){
20. **return** **false**;
21. tip.destroy();
22. }**else**{
23. tip.body.dom.innerHTML=\_store.getAt(rowIndex).get("gjxx");
24. }
25. }
26. }
27. })
28. }

```
function showGjToolTip(_grid){
	 			var _store = _grid.getStore();
 				var view = _grid.getView();
 		 		_grid.tip = new Ext.ToolTip ({
					target:view.mainBody,
					delegate:'.x-grid3-row',
					trackMouse :true,
					width:230,
					autoHide:true, 
					title:"告警信息",
					dismissDelay:5000,  //默认5秒后提示框消失
					frame:true,
					renderTo:document.body,
					bodyStyle:"color:red",//字体颜色
					//floating:{shadow:false,shim:true,useDisplay:true,constrain:false},
					listeners:{
						beforeshow:function updateTipBody(tip){
							var rowIndex = view.findRowIndex(tip.triggerElement);
							if(_store.getAt(rowIndex).get("sfgj")==0){
								return false;
								tip.destroy(); 
							}else{
								tip.body.dom.innerHTML=_store.getAt(rowIndex).get("gjxx");
							}
						}
					}
	})
}
```

 

4:获得一个不带复选框的树的所有子节点的id

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

1. function getTreeChildIds(node){
2. var r = \[];
3. var f = function(){
4. r.push(**this**.id);
5. };
6. node.cascade(f);
7. **return** r;
8. }

```
            function getTreeChildIds(node){
			        var r = [];
			        var f = function(){
			                r.push(this.id);
			        };
			        node.cascade(f);
              	    return r;
            }
```

 

  调用例子

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

1. var rootNode = tree.getRootNode();   //获取主节点
2. var result = getTreeChildIds(rootNode );
3. alert(result );

```
      var rootNode = tree.getRootNode();   //获取主节点
                   var result = getTreeChildIds(rootNode );
                  alert(result ); 
```

 

 

5：对Ext中DateField字段的扩展 （转自： [http://gaoliujie.iteye.com/blog/703839](http://gaoliujie.iteye.com/blog/703839) ）

  Ext中的DateField字段默认显示格式为'm/d/Y'，不太符合中国的使用习惯，以'-'号隔开，或直接显示'xxxx年x月x日'的格    式，并且在同一个软件系统中，通常情况会希望日期的显示格式都相同，不要在每个页面中单独设置显示样式。

另外，由于后台传输到前台的格式一般都是java中的Date类型，直接传输到前台会因为Ext中的时区设置问题造成转换错。

基于以上原因，扩展Ext中的DateField字段类型，代码如下所示： 

 

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. justgin.bap.DateFieldEx = Ext.extend(Ext.form.DateField,{
02. format:"Y-m-d",
03. initComponent: function() {
04. **this**.hideTrigger = **this**.readOnly;
05. justgin.bap.DateFieldEx.superclass.initComponent.call(**this**);
06. },
07. setValue:function(value){
08. var date = **this**.formatDate2(value);
09. justgin.bap.DateFieldEx.superclass.setValue.call(**this**, date);
10. },
11. // private ,ext自己有个formatDate方法，因此这里用formatDate2
12. formatDate2 : function(date){
13. //CST时间和UTC时差转换
14. var dateStr=date.toString();
15. var position=dateStr.indexOf("UTC");
16. **if**(position!=-1){
17. **return** Ext.util.Format.date(date, **this**.format);
18. }**else**{
19. var vdate=**new** Date(date); //后台默认为格林尼治时间，该方法会默认把后台时间认为是北京时间，北京时间比格林尼治时间多14小时。
20. //找出当地时间偏移值的毫秒数
21. var localOffset=vdate.getTimezoneOffset()\*60000;
22. var utcOffset= vdate.getTime() + localOffset;
23. timezone=utcOffset-6\*3600000;//
24. var lastDate=**new** Date(timezone);
25. **return** Ext.util.Format.date(lastDate, **this**.format);
26. }
27. }
28. });

```
justgin.bap.DateFieldEx = Ext.extend(Ext.form.DateField,{
	format:"Y-m-d",
	
	initComponent: function() {
		this.hideTrigger = this.readOnly;
		justgin.bap.DateFieldEx.superclass.initComponent.call(this);
	},
	
	setValue:function(value){
		var date = this.formatDate2(value);
		justgin.bap.DateFieldEx.superclass.setValue.call(this, date);
	},
	
	// private ,ext自己有个formatDate方法，因此这里用formatDate2
    formatDate2 : function(date){
        //CST时间和UTC时差转换
        var dateStr=date.toString();
        var position=dateStr.indexOf("UTC");
        if(position!=-1){
        	return Ext.util.Format.date(date, this.format);
        }else{
        	var vdate=new Date(date); //后台默认为格林尼治时间，该方法会默认把后台时间认为是北京时间，北京时间比格林尼治时间多14小时。
	        //找出当地时间偏移值的毫秒数
	        var localOffset=vdate.getTimezoneOffset()*60000; 
	        var utcOffset= vdate.getTime() + localOffset;
	        timezone=utcOffset-6*3600000;//
	        var lastDate=new Date(timezone);     
	    	return Ext.util.Format.date(lastDate, this.format); 
        }
    }
});
```

 

6：对Ext中CheckBox的扩展 （转自：[http://gaoliujie.iteye.com/blog/703833](http://gaoliujie.iteye.com/blog/703833) ）

 使用Ext中的Checkbox时，经常需要随form一起提交，但Checkbox设置的默认的提交值为"on"或""，后台代码中需要对字段的提交进行判断后取值，不符合我们通常的使用习惯，即直接将提交的值转换为对应的boolean类型，为此，特进行扩展和封装，以满足通过的使用方式，代码如下：

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. justgin.bap.CheckboxEx = Ext.extend(Ext.form.Checkbox, {
02. trueValue: **true**,
03. falseValue: **false**,
04. hiddenField: {value:''},
05. onRender : function(ct, position){
06. justgin.bap.CheckboxEx.superclass.onRender.call(**this**, ct, position);
07. var hidden = **this**.el.insertSibling({tag:'input', type:'hidden', name: **this**.name}, 'before', **true**);
08. hidden.value = **this**.hiddenField.value;
09. **this**.hiddenField = hidden;
10. **this**.el.dom.removeAttribute('name');
11. **this**.on('check', **this**.onCheck);
12. },
13. setValue : function(v){
14. var me = **this**;
15. justgin.bap.CheckboxEx.superclass.setValue.call(**this**, v);
16. **this**.hiddenField.value = **this**.checked?me.trueValue:me.falseValue;
17. },
18. getValue : function(v){
19. **return** **this**.hiddenField.value;
20. },
21. onDestroy : function(){
22. Ext.destroy(**this**.wrap);
23. justgin.bap.CheckboxEx.superclass.onDestroy.call(**this**);
24. },
25. onCheck : function(me, checked){
26. **this**.hiddenField.value = checked?me.trueValue:me.falseValue;
27. }
28. );

```
	justgin.bap.CheckboxEx = Ext.extend(Ext.form.Checkbox, {
		trueValue: true,
		falseValue: false,
		hiddenField: {value:''},
		
		onRender : function(ct, position){
	    	justgin.bap.CheckboxEx.superclass.onRender.call(this, ct, position);
	    	var hidden = this.el.insertSibling({tag:'input', type:'hidden', name: this.name}, 'before', true);
	    	hidden.value = this.hiddenField.value;
	    	this.hiddenField = hidden;
	    	this.el.dom.removeAttribute('name');
	    	this.on('check', this.onCheck);
	    },
	    
	    setValue : function(v){
	    	var me = this;    	
	    	justgin.bap.CheckboxEx.superclass.setValue.call(this, v);
	    	this.hiddenField.value = this.checked?me.trueValue:me.falseValue;
	    },
	   
	    getValue : function(v){
	    	return this.hiddenField.value;
	    },
	   
	    onDestroy : function(){
	        Ext.destroy(this.wrap);
	        justgin.bap.CheckboxEx.superclass.onDestroy.call(this);
	    },
	
		onCheck : function(me, checked){
	        this.hiddenField.value = checked?me.trueValue:me.falseValue;
	    }

});
```

 

扩展两个属性trueValue和falseValue，可提供使用者指定选中或取消时提交的值，默认为true和false。

重写字段的onRender方法，在render时，移除用来展示的html的input元素的名称，插入一个的同名hidden元素，保存要提交的值，不改变使用方式的前提下，能保证from在提交时，将插入的新元素提交，确保了设置的值会提交到后台。

重写setValue和getValue方法，保证了存取值时数据的同步。

常用的Ext创建对象的方式有两种：new justgin.bap.CheckboxEx()和Ext.create({xtype: 'checkbox'})，要想使用户在使用第二种方式时创建一个自己扩展的对象，可以在类的声明后加入一句对象类型的注册语句即可  

Ext.reg('checkbox', justgin.bap.CheckboxEx);

 

 

 7:grid 上移 下移

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. Ext.apply(Ext.grid.GridPanel.prototype, {
02. moveUp : function() {
03. var d = **this**.getStore();
04. var c = **this**.getColumnModel();
05. var r = **this**.getSelectionModel().getSelections();
06. var idx;
07. **if** (r.length == 0) {
08. Ext.Msg.alert('提示', '请选择记录进行操作！');
09. **return**;
10. }
11. **if** (r.length == d.getCount())
12. **return**;
13. **if** (d.indexOf(r\[0]) == 0)
14. **return**;
15. **for** (var i = 0; i &lt; r.length; i++) {
16. idx = d.indexOf(r\[i]) - 1;
17. d.remove(r\[i]);
18. d.insert(idx, r\[i]);
19. }
20. **this**.getSelectionModel().selectRow(idx);
21. **this**.reconfigure(d, c);
22. },
23. moveDown : function() {
24. var d = **this**.getStore();
25. var c = **this**.getColumnModel();
26. var r = **this**.getSelectionModel().getSelections();
27. var idx;
28. var idx;
29. var len = r.length;
30. **if** (len == 0) {
31. Ext.Msg.alert('提示', '请选择记录进行操作！');
32. **return**;
33. }
34. **if** (len == d.getCount())
35. **return**;
36. **if** (d.indexOf(r\[len - 1]) == d.getCount() - 1)
37. **return**;
38. **for** (var i = 0; i &lt; len; i++) {
39. idx = d.indexOf(r\[len - i - 1]) + 1;
40. d.remove(r\[len - i - 1]);
41. d.insert(idx, r\[len - i - 1]);
42. }
43. **this**.getSelectionModel().selectRow(idx);
44. **this**.reconfigure(d, c);
45. }
46. );

```
    		Ext.apply(Ext.grid.GridPanel.prototype, {
    			moveUp : function() {
					var d = this.getStore();
					var c = this.getColumnModel();
					var r = this.getSelectionModel().getSelections();
					var idx;
					if (r.length == 0) {
						Ext.Msg.alert('提示', '请选择记录进行操作！');
						return;
					}
					if (r.length == d.getCount())
						return;
					if (d.indexOf(r[0]) == 0)
						return;
					for (var i = 0; i < r.length; i++) {
						idx = d.indexOf(r[i]) - 1;
						d.remove(r[i]);
						d.insert(idx, r[i]);
					}
					this.getSelectionModel().selectRow(idx);
					this.reconfigure(d, c);
				},
				moveDown : function() {
					var d = this.getStore();
					var c = this.getColumnModel();
					var r = this.getSelectionModel().getSelections();
					var idx;
					var idx;
					var len = r.length;
					if (len == 0) {
						Ext.Msg.alert('提示', '请选择记录进行操作！');
						return;
					}
					if (len == d.getCount())
						return;
					if (d.indexOf(r[len - 1]) == d.getCount() - 1)
						return;
					for (var i = 0; i < len; i++) {
						idx = d.indexOf(r[len - i - 1]) + 1;
						d.remove(r[len - i - 1]);
						d.insert(idx, r[len - i - 1]);
					}
					this.getSelectionModel().selectRow(idx);
					this.reconfigure(d, c);
				}
			});
```

 

    8：自定义事件  来自我的ext群：23334375中的中国加油所写

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. &lt;script type="text/javascript"&gt;
02. Ext.onReady(function(){
03. Ext.ExtendPanel= Ext.extend(Ext.Panel,{
04. initComponent:function(){
05. Ext.ExtendPanel.superclass.initComponent.call(**this**);
06. **this**.addEvents("click");
07. },
08. onRender: function(ct, position){
09. Ext.ExtendPanel.superclass.onRender.apply(**this**, arguments);
10. var c = **this**.body;
11. c.on("click", **this**.onClick, **this**);
12. },
13. onClick:function(e){
14. **this**.fireEvent("click", e);
15. }
16. });
17. var ep=**new** Ext.ExtendPanel({
18. renderTo:'panel',
19. width:500,
20. height:500,
21. html:'点击试试',
22. listeners:{
23. click:function(e){
24. alert("被点击了!"+e.getTarget());
25. }
26. }
27. });
28. });
29. &lt;/script&gt;
30. &lt;/head&gt;
31. &lt;body&gt;
32. &lt;div id="panel"&gt;&lt;/div&gt;
33. &lt;/body&gt;
34. &lt;/html&gt;

```
<script type="text/javascript">
Ext.onReady(function(){

  Ext.ExtendPanel= Ext.extend(Ext.Panel,{
	initComponent:function(){
		Ext.ExtendPanel.superclass.initComponent.call(this);
		 this.addEvents("click");
	},
	onRender: function(ct, position){
		  Ext.ExtendPanel.superclass.onRender.apply(this, arguments);
		   var c = this.body;
		  c.on("click", this.onClick, this);
	},
	onClick:function(e){
		 this.fireEvent("click", e);
	}
   });

	var ep=new Ext.ExtendPanel({
			renderTo:'panel',
			width:500,
			height:500,
			html:'点击试试',
			listeners:{
				click:function(e){
					alert("被点击了!"+e.getTarget());
				}
			}
	});
});
        </script>
    </head>
    <body>
        <div id="panel"></div>
    </body>
</html>
```

 

   9:五步掌握Ext的拖放好文章地址：

      [http://blog.csdn.net/zhangxin09/archive/2010/05/03/5551665.aspx](http://blog.csdn.net/zhangxin09/archive/2010/05/03/5551665.aspx)

  

  10:Ext extend解释好文章 

     [http://kaizhongfan.blog.163.com/blog/static/108708240201012411257716/](http://kaizhongfan.blog.163.com/blog/static/108708240201012411257716/)     

     [http://damoqiongqiu.iteye.com/blog/370591](http://damoqiongqiu.iteye.com/blog/370591)

 

  11:用户界面与业务逻辑的解耦(来自：[http://nickevin.iteye.com/blog/691340](http://nickevin.iteye.com/blog/691340))

    UI定义

 

Java代码 [![复制代码](http://babydeed.iteye.com/images/icon_copy.gif)](http://babydeed.iteye.com/blog/737050 "复制代码")

01. // Account.ui.js 定义UI
02. &nbsp;AccountUi = Ext.extend(Ext.form.FormPanel, {
03. title: 'Account',
04. labelWidth: 100,
05. labelAlign: 'left',
06. layout: 'form',
07. width: 600,
08. frame: **true**,
09. initComponent: function() {
10. **this**.items = [
11. {
12. xtype: 'container',
13. autoEl: 'div',
14. layout: 'column',
15. items: [
16. {
17. xtype: 'container',
18. autoEl: 'div',
19. layout: 'form',
20. columnWidth: 0.5,
21. items: [
22. {
23. xtype: 'textfield',
24. fieldLabel: 'First Name',
25. anchor: '95%',
26. name: 'fname',
27. ref: '../../fname'
28. },
29. {
30. xtype: 'datefield',
31. fieldLabel: 'Birth of day',
32. anchor: '95%',
33. name: 'birthday',
34. ref: '../../birthday'
35. }
36. ]
37. },
38. {
39. xtype: 'container',
40. autoEl: 'div',
41. layout: 'form',
42. columnWidth: 0.5,
43. items: [
44. {
45. xtype: 'textfield',
46. fieldLabel: 'Last Name',
47. anchor: '95%',
48. name: 'lname',
49. ref: '../../lname'
50. },
51. {
52. xtype: 'combo',
53. fieldLabel: 'Sex',
54. anchor: '95%',
55. name: 'sex',
56. ref: '../../sex'
57. }
58. ]
59. }
60. ]
61. },
62. {
63. xtype: 'htmleditor',
64. anchor: '98%',
65. fieldLabel: 'Memo',
66. height: 150,
67. width: 300,
68. name: 'memo',
69. ref: 'memo'
70. }
71. ];
72. **this**.fbar = {
73. xtype: 'toolbar',