---
title: "(转) Extjs整体总结"
author: "ghl116"
date: "2012-04-03T20:42:56Z"
tags: []
categories: ["Web前端"]
slug: "extjs"
draft: false
lastmod: "2012-04-03T20:42:56Z"
id: 1473545
url: "https://ghl116.iteye.com/blog/1473545"
---

### [Extjs整体总结](http://blog.csdn.net/vickyfei/article/details/7251442)

分类： [ExtJS](http://blog.csdn.net/vickyfei/article/category/929087)2012-02-11 19:12 8人阅读 [评论](http://blog.csdn.net/vickyfei/article/details/7251442#comments)(0) [收藏](http://blog.csdn.net/vickyfei/article/details/7251442 "收藏") [举报](http://blog.csdn.net/vickyfei/article/details/7251442#report "举报")

 **一、如何同步调用Ajax远程数据**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. // 同步方式，API不直接提供，获取XHR的conn的引用即可
02. var url = "myApp/getUserList.do";
03. var conn = new Ext.data.Connection()conn;
04. conn.open("POST", url, false);
05. conn.send(null);
06. var json = Ext.decode(conn.responseText);
07. // 异步方式，这是常用的方式
08. new Ext.data.Connection().request({
09. // 此即是Ext和Struts交互的关键
10. url: 'myApp/getUserList.do',
11. params: {id: 10001,name: '测试'},
12. failure: requestFailed,
13. success: requestSuccessful
14. }

 

**二、全局性、强制指定HTTP方法（动词）**

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. Ext.Ajax.on('beforerequest', function(){
2. arguments\[1].method = 'GET' // or 'POST'/'PUT'/'DELETE'
3. });

 

**三、怎么对form中的textfield赋值**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. Ext.getCmp("TextField\_id").setValue("value");

 

**四、布局一些已知的限制**

'fit'的layout中items只能放一个子组件，即使放多个，也只会显示第一个。而且aotuHeight属性页不能和fit一起使用；'border'布局方式中，分为东西南北中五个region，其中center是自动计算大小的。而'south','north'只能设置高度，'west','east'只能设置宽度。 （by 佚名网友）

 

**五、返回当前类的静态成员的另外一种方法：constructor.prototype**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. /\**
02. * @class xyj.Controlller
03. * A Model class represents and manages a tables in a database.
04. * Model instances represent individual records in the table.
05. * Models follow the ‘Active Record’ design pattern for object-relational mapping.
06. \*/
07. xyj.data.Controlller = function(config){
08. this.parents   = \[];
09. this.children  = \[];
10. Object.apply(this, config);
11. Array.each(this.belongTo, this.assignElment, {scope:this, which: 0});
12. Array.each(this.hasMany,  this.assignElment, {scope:this, which: 1});
13. };
14. xyj.data.Controlller.prototype = {
15. /\**
16. \*
17. * 原本函数是这样的（this还是指当前实例）：
18. * &lt;code&gt;
19. var \_instancePrototype = this.constructor.prototype;
20. Array.each(this.belongTo, function(i){
21. if (typeof i == 'string') {
22. \_instancePrototype.belongTo.call(this, i);
23. }
24. else
25. if (NJS.Array.isArray(i)) {
26. \_instancePrototype.belongTo.call(this, i\[0], i\[1]);
27. }
28. }, this);
29. Array.each(this.hasMany, function(i){
30. if (typeof i == 'string') {
31. \_instancePrototype.hasMany.call(this, i);
32. }
33. else
34. if (NJS.Array.isArray(i)) {
35. \_instancePrototype.hasMany.call(this, i\[0], i\[1]);
36. }
37. }, this);
38. &lt;/code&gt;
39. * 当前，我们变成这样：
40. * @param {} schema
41. \*/
42. assignElment : function(i){
43. var \_instancePrototype = this.scope.constructor.prototype;
44. if (typeof i == 'string') {
45. \_instancePrototype\[this.which?'hasMany':'belongTo'].call(
46. this.scope, i
47. );
48. }else if(Array.isArray(i)) {
49. \_instancePrototype\[this.which?'hasMany':'belongTo'].call(
50. this.scope, i\[0], i\[1]
51. );
52. }
53. }
54. }

 

**六、GridPanel如何加上自动的顺序号？**   
制定一个列Column对象：new Ext.grid.RowNumberer()

 

**七、如何在树Tree or Grid表格中添加CheckBox呢？**

For Grid:

**![](http://kxv1ug.blu.livefilestore.com/y1px4dQysSP2dWvEQUBI2VZFhwWb_qyi9iUwLDjahDxOodycmDiE4psTn3CXhXW8zk06Xiug3hfc7yFyQW974qot7DLa2PMVAOr/%7B2DC247B2-8FE8-D1C1-3CA8-1CBF74B025FC%7D.jpg)** 

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var sm = new Ext.grid.CheckboxSelectionModel();
2. var cm = new Ext.grid.ColumnModel([
3. …,
4. sm, // 添加的地方
5. …
6. ]);

 

For Tree:

 

![](http://kxv1ug.blu.livefilestore.com/y1p-tjlzagkYQd8KDKZDtJo8_Ppg4gHNc2B_QY3W4nrFHI07CQFPI8gwfW4T-osuXOgqvWXqSsgghBRjl9jPW-2PKls-82JMiV2/%7B3D3C32EE-AB02-E0C4-EB2E-01C42455DC63%7D.jpg)

**八、EXT怎么给IMAGE或者DIV控件加右键菜单**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. &lt;script src="ext-core.js"&gt;&lt;/script&gt;
2. &lt;img id="foo" src="http://p.blog.csdn.net/images/p\_blog\_csdn\_net/zhangxin09/EntryImages/20091109/book\_10.gif" /&gt;
3. &lt;script&gt;
4. Ext.onReady(function(){
5. Ext.fly('foo').on('contextmenu', function(){alert('你右击了一下图片')})
6. });
7. &lt;/script&gt;

 

注意：那个ext-core.js要引入上

 

**九、手动触发浏览器事件** ，IE与FF有别:

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. // No way to get the event of 'submit' on FF,
02. //uses 'onsubmit="return false;' in HTML insteaed!
03. function doSubmit(e, el){
04. if(e.browserEvent.type =='submit'){
05. IE caught OK!
06. };
07. if (Ext.isIE)
08. el.fireEvent('onsubmit');
09. else {
10. var e = document.createEvent("Events");
11. e.initEvent("submit", true, true);
12. el.dispatchEvent(e);
13. }
14. }

 

注意不是submit()的执行方法，而是触发、分发事件，有一定区别。

 

**十、如何选取Grid的数据记录？** 行选择模式的话，将是：

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var rowcount = grid.getSelectionNode().getSelections();

可以获取全部选中的记录，得到的rowcount将是一个Array，比如想获取sex列的数据，语句如下:

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var strsex = rowcount\[i].get(‘sex’);

 

**十一、Grid单元格选取模式**

如果在GridPanel的配置属性增加sm属性如下,则就是“单元格选择模式”:

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. sm: new Ext.grid.CellSelectionModel();

当单击时将选中对应的某一个单元格，而不是默认的选择某一行。选择方式如下:

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var cell = grid.getSelectionNode().getSelectedCell();

得到的cell记录了当前选择的行(cell\[0])以及列(cell\[1]).可以通过一下语句得到该单元格数据:

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var colname = grid.getColumnModel().getDataIndex(cell\[1]);  //获取列名
2. var celldata = grid.getStore().getAt(cell\[0]).get(colname); //获取数据
3. getStore():获取表格的数据集
4. getAt():获取该数据集cell\[0]行
5. get():获取该行colname的数据

 

**十二、Tree节点的拖放。** 重写beforeNodeDrop/nodeDrop函数

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. Client.Tree.UI = Ext.extend(Ext.tree.TreePanel, {
02. beforeNodeDrop: function(e){
03. var s = e.data.selections, r = \[];
04. for (var i = 0, len = s.length; i &lt; len; i++) {
05. var ticket = s\[i].data.ID; // s\[i] is a Record from the grid
06. if (!e.target.findChild('ID', ticket)) { // &lt;-- filter duplicates
07. r.push(new Ext.tree.TreeNode({ // build array of TreeNodes to add
08. allowDrop: false,
09. text: 'Ticket #' + ticket,
10. ticket: ticket,
11. action: 'view'
12. //qtip: String.format('&lt;b&gt;{0}&lt;/b&gt;&lt;br /&gt;{1}', s\[i].data.summary, s\[i].data.excerpt)
13. }));
14. }
15. }
16. e.dropNode = r; // return the new nodes to the Tree DD
17. e.cancel = r.length &lt; 1; // cancel if all nodes were duplicates
18. },
19. nodeDrop: function(e){
20. //      watchList.setText(String.format('My Watch List ({0})', watchList.childNodes.length));
21. //      storeWatchList goes here;
22. }
23. });

 

**十三、Grid被拖动过程中， 修改提示文字。** 重写getDragDropText函数

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. getDragDropText: function(){
02. var s = this.getSelectionModel().getSelections();
03. if (s.length == 1) {
04. return String.format('&lt;b&gt;&lt;h6&gt;You are now dragging &lt;/h6&gt; #{0}&lt;b&gt;', s\[0].data.ID);
05. }
06. else {
07. var tickets = \[];
08. for (var i = 0, len = s.length; i &lt; len; i++) {
09. tickets.push('#' + s\[i].data.ID);
10. }
11. return String.format('&lt;b&gt;&lt;h6&gt;You are now dragging the {0} selected&lt;/h6&gt; &lt;/b&gt;{1}', s.length, tickets.join(', '));
12. }
13. }

 

 

**十四、 用Ext Core插入Flash到页面。** 只需要这个小小的函数：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. /\**
02. * 插入Flash电影文件到页面。原本Robert Nyman的是用字符串拼凑的，现改为JSON2HTML。
03. * 例子：（在插入的地方）&lt;mce:script type="text/javascript"&gt;&lt;!--
04. Edk.setFlash({src:'images/ani.swf'});
05. // --&gt;&lt;/mce:script&gt;
06. * @param {Object} config 配置参数
07. * @cfg {String} src    Flash电影的文件路径（SWF）
08. * @cfg {String} id     Flash电影元素的id（可选的）
09. * @cfg {Nubmer} width  Flash电影的宽度（可选的）
10. * @cfg {Nubmer} height Flash电影的高度（可选的）
11. * @cfg {Object} params 参数（可选的）
12. * credit: Robert Nyman,  http://code.google.com/p/flashreplace/
13. \*/
14. function setFlash (config){
15. /\**
16. * 检测Flash是否安装
17. * @param {Number} version
18. * @return {Boolean} True表示已安装符合版本要求的Flash
19. \*/
20. function checkForFlash (version){
21. if(Ext.isIE){
22. try{
23. new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + version);
24. return true;
25. }catch(e){
26. return false;
27. }
28. }else{
29. var \_plugins = navigator.plugins;
30. if( \_plugins && navigator.mimeTypes.length &gt; 0){
31. if(\_plugins\["Shockwave Flash"] && \_plugins\["Shockwave Flash"]\['description'].replace(/.\*/s(/d+/./d+).\*/, "$1") &gt;= version)
32. {
33. return true;
34. }
35. }else{
36. return false;
37. }
38. }
39. }
40. if(!checkForFlash(config.version || 7 /\*defaultFlashVersion\*/)){
41. throw 'Flash is NOT Readly!';
42. }
43. var children = [
44. {
45. tag   : 'param'
46. ,name  : 'movie'
47. ,value : config.src
48. }
49. ,{
50. tag   : 'embed'
51. ,type  : "application/x-shockwave-flash"
52. ,src   : config.src
53. ,width : config.width
54. ,height: config.height
55. }
56. ];
57. var \_params = config.params;
58. if(\_params){
59. for(var i in \_params){
60. children.push({
61. tag  :  'param'
62. ,name :  i
63. ,value:  \_params\[i]
64. });
65. }
66. }
67. Ext.fly(config.el).createChild(Object.apply({
68. tag      : 'object'
69. ,classid  : "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
70. ,data     : config.src
71. ,children : children
72. }, config));
73. }

 

**十五、为HTMLEditor加入“插入图片”按钮。** 如图：

 

![](http://p.blog.csdn.net/images/p_blog_csdn_net/zhangxin09/EntryImages/20091119/h.gif)

使用以下插件

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. /\**
02. * http://extjs.com/forum/showthread.php?p=128146#post128146
03. * @param {Object} config
04. \*/
05. Ext.ux.HtmlEditorImageInsert = function(config){
06. Ext.apply(this, config);
07. }
08. Ext.ux.HtmlEditorImageInsert.prototype = {
09. popTitle: '插入图片',
10. popMsg: '请粘贴你要插入图片的地址',
11. popWidth: 350,
12. popValue:  '',
13. init:function(htmlEditor){
14. this.editor = htmlEditor;
15. this.editor.on('render', this.onRender, this);
16. },
17. onRender:function(){
18. if (!Ext.isSafari) {
19. this.editor.tb.add({
20. itemId: 'htmlEditorImage',
21. iconCls: 'icon16-Ext-ux-HtmlEditorImageInsert',
22. enableToggle: false,
23. scope: this,
24. handler:  function(){
25. Ext.MessageBox.show({
26. title: this.popTitle,
27. msg: this.popMsg,
28. width: this.popWidth,
29. buttons: Ext.MessageBox.OKCANCEL,
30. prompt: true,
31. value: this.popValue,
32. scope: this,
33. fn: function(btn, text){
34. //@todo 验证url地址
35. if (btn == 'ok')
36. this.editor.relayCmd('insertimage', text);
37. }
38. });
39. },
40. clickEvent: 'mousedown',
41. tabIndex: -1
42. });
43. }
44. }
45. }

 

用法如下：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var htmlEditor = new Ext.form.HtmlEditor({
2. plugins  : new Ext.ux.HtmlEditorImageInsert
3. ,applyTo  : this.formEl.child('textarea.edk-htmlEditor')
4. });

 

**十六、FireFox中文字体问题**

不少朋友加载汉化包之后，可全面实现中文的操作环境。但是有一点美中不足的是在FireFox浏览器下面会出现字体失真的问题，其现象如图。要解决这个问题，可从覆盖CSS文件、修正原CSS规则定义。

 

![](http://p.blog.csdn.net/images/p_blog_csdn_net/zhangxin09/EntryImages/20091121/image029.png)

 

**\[css]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. /* Ext中文字体修正补丁。须客户端上安装Pmingliu繁体字体\*/
02. .x-toolbar label, .x-toolbar div.xtb-text{
03. font-size:9pt;
04. }
05. .x-window-footer {
06. position: relative;
07. top: 0;
08. right: 0;
09. }
10. .x-tab-strip SPAN.x-tab-strip-text {
11. font-size: 12px;
12. }
13. .x-panel-header {
14. font-size: 12px;
15. }
16. .x-tree-node {
17. font-size: 12px;
18. }
19. .x-grid3-hd-row TD {
20. font-size: 12px;
21. }
22. .x-grid3-row TD {
23. font-size: 12px;
24. LINE-HEIGHT: 16px;
25. }
26. .x-tip .x-tip-bd {
27. font-size: 12px;
28. }
29. .x-tip h3 {
30. font-size: 12px;
31. }
32. .x-tip .x-tip-bd-inner {
33. font-size: 12px;
34. }
35. .x-panel-tl .x-panel-header {
36. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
37. font-size: 12px;
38. }
39. .x-form-field {
40. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
41. font-size: 12px;
42. }
43. .x-small-editor .x-form-field {
44. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
45. font-size: 12px;
46. }
47. .x-combo-list-item {
48. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
49. font-size: 12px;
50. }
51. .x-menu-list-item {
52. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
53. font-size: 12px;
54. }
55. .x-window-tl .x-window-header {
56. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
57. font-size: 12px;
58. }
59. .x-layout-split-west .x-layout-mini {
60. BACKGROUND-IMAGE: url(../images/mini-left.jpg);
61. }
62. .ext-ie .x-form-text {
63. margin-top: 1px;
64. }
65. /* the textField missing bottom line\*/
66. .x-form-item {
67. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
68. font-size: 12px;
69. }
70. .x-grid-group-hd DIV {
71. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
72. font-size: 12px;
73. }
74. .x-btn-text-icon .x-btn-center .x-btn-text {
75. background-position: 0pt 2px;
76. background-repeat: no-repeat;
77. padding: 3px 0pt 2px 18px;
78. }
79. .ext-gecko .x-btn button {
80. padding-left: 0pt;
81. padding-right: 0pt;
82. }
83. .x-btn button {
84. font-family: Pmingliu,Verdana,Geneva,Arial,Helvetica,sans-serif;
85. font-size: 12px;
86. }
87. /* -------End-----Ext 2.0 中文字体修正补丁。须客户端上安装Pmingliu繁体字体-----\*/

 

**十七、可靠地判别Array类型。**   
有时候用typeof/instanceof/constructor在某些浏览器上不能通过。因此我们使用另外一种方法来判断对象是否为数组。

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. /\**
2. * @param {any} o 被检测的对象
3. * @return {boolean} 是否为数组
4. \*/
5. function isArray(o) {
6. o = o.length || 0; // dummy
7. return typeof o === 'number' && isFinite(o) && (/^/d+$/).test(o.valueOf()) && typeof(o.splice) == 'function';
8. }

 

**十八、判断该值是否为一个合法的数字**

Ext里面也有Ext.isArray；这个是来自YUI的

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. /\**
2. * @credit YUI
3. * @param  {any} o 被检测的值
4. * @return {boolean} 结果
5. \*/
6. function isNumber(o) {
7. return typeof o === 'number' && isFinite(o) && (/^/d+$/).test(o.valueOf());
8. }

 

**十九、删除某个树节点下面的所有节点**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. while(node.firstChild) {
2. node.removeChild(node.firstChild);
3. }

 

**二十、如何获取Grid记录集合**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. grid.getSelectionModel().getSelections()// 会得到选择到的数据，以行为单位，作为数组返回。

 

这个其实前面都有说的了，遍历里Grid数据又是怎么来着？遍历Grid就是遍历Store：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. grid.getStore().data.each(function(){}); // store.data数据集合，each()是遍历的方法

 

**二十一、grid可以自动排列每列的宽度**

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. viewConfig{forceFit:true}

 

**二十二、简单实现多语言界面（i18n in JS）**

翻译界面语言的话，推荐将所有翻译文本作为公共类的成员出现，重写原先类的prototype的属性，也就是使用Ext.override()，如下例：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. /\**
02. * 斯洛伐克语版的教程之本地化文件
03. \*/
04. if(Tutorial.LocalizationWin) {
05. Ext.override(Tutorial.LocalizationWin, {
06. titleText:'Príklad lokalizácie'
07. ,selectLangText:'Zvoľ jazyk'
08. ,textFieldText:'Textové pole'
09. ,dateFieldText:'Dátumové pole'
10. });
11. }

 

**二十三、Ext拖拽小解**

DragDrop 是一个基类，它定义了一些可以被拖拽的元素的接口和基本操作，如 startDrag, onDrag, onDragOver 和 onDragOut 等 Drag 事件。而继承自这个类的子类，功能上主要分为两类。一个是可以使得对象被拖动；一个是使得拖动对象可以被放置在 DropTarget 中。

- DD 类：用户可以通过调用 DD 的构造函数来使得对象能够被拖动。这种拖动使得对象会跟随鼠标的移动而移动。
- DDProxy 类：DDProxy 类继承自 DD 类。使用这个类来构造被拖动的对象时，该对象的边框会跟随鼠标的移动而移动。而等到鼠标释放时，该对象会被重新放置到鼠标停止的位置。
- DDTarget 类：拖动对象可以被放置在其他DDTarget中，然后，DragTarget 继承自 DDTarget。将元素作为参数传递到 DDTarget 中，那么这个元素就可以是一个 Drop Target 。

*要点：*   
第一， 只有 Drag 元素和 DropTarget 元素具有同样 DragDropGroup 名字的，Drag 元素才能够被拖放到正确的 DropTarget 元素中去。  
第二， 在 DragTarget 中，还需要实现 notifyDrop(DragSource source, EventObject e, DragData data) 方法以实现拖动后的效果，例如可实现从当前 Tree 中删除选中节点和在 Grid 中增加记录的操作。notifyDrop()中，source 是指可以被拖动到 DropTarget 上的元素； e 是指当前的事件； data 是指被拖动元素所包含的数据对象。

![](http://p.blog.csdn.net/images/p_blog_csdn_net/zhangxin09/EntryImages/20091212/image001.jpg)

**二十四、实现Ext表单对checkBoxGroup的统一管理**

对于类型是checkboxgroup的数据，数据库中保存数据的格式是value1,value2...valueN，其中1~N的数据有可能不存在，如果选中则存在，最后拼接成一个串。为了适应我们采用的数据格式，对于该组件的setValue（被setValues调用）和getValue（获取到已加工的数据，此事后话）也要进行重写。故而对于形如：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. {
02. xtype: 'checkboxgroup',
03. name: 'biztype',
04. width: 220,
05. columns: 3,
06. fieldLabel: '业务类别',
07. items: [
08. {boxLabel: '类别1', inputValue: '01'},
09. {boxLabel: '类别2', inputValue: '02'},
10. {boxLabel: '类别3', inputValue: '03'},
11. {boxLabel: '类别4', inputValue: '04'}
12. }

 

的checkboxgroup定义，需重写类如下：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. Ext.override(Ext.form.CheckboxGroup,{
02. //在inputValue中找到定义的内容后，设置到items里的各个checkbox中
03. setValue : function(value){
04. this.items.each(function(f){
05. if(value.indexOf(f.inputValue) != -1){
06. f.setValue(true);
07. }else{
08. f.setValue(false);
09. }
10. });
11. },
12. //以value1,value2的形式拼接group内的值
13. getValue : function(){
14. var re = "";
15. this.items.each(function(f){
16. if(f.getValue() == true){
17. re += f.inputValue + ",";
18. }
19. });
20. return re.substr(0,re.length - 1);
21. },
22. //在Field类中定义的getName方法不符合CheckBoxGroup中默认的定义，因此需要重写该方法使其可以被BasicForm找到
23. getName : function(){
24. return this.name;
25. }
26. });

 

这个方法同样适用于上面定义的checkboxgroup，如此就可以把前后台的数据通过json统一起来了。

**二十五、如何添加/删除表格的某几列**

参见[官方论坛](http://extjs.com/forum/showthread.php?p=308635#post308635) 。

 

**二十六、两个Panel一个放上面，一个放下面，怎么写**

经典方法：可以用broder一个south 另外一个center；

其他方法：表单布局layout：'from'的话，放两个panel也可以到达上下排列

 

**二十六、Grid加装数据超时**

解决方法就是修改默认的XHR通讯请求时间。修改Grid的就是修改Store的HttpProxy:

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. var myBigTimeout = 90000; // 90 sec
2. myStore =  new Ext.data.JsonStore({
3. proxy: new Ext.data.HttpProxy({
4. url: "http://www.example.com/test.php",
5. timeout: myBigTimeout
6. }),
7. //url: "http://www.example.com/test.php",
8. ...
9. });

 

Thanks to [沉默](http://blog.mfaathp.com/2009/10/%E4%B8%BAjsonstore%E8%AE%BE%E7%BD%AEtimeout/) 。

**二十七、如何调出自带的consloe**

旧版的是console.log();3.0中Consloe有更新，调用方法：Ext.log()。如图:

![](http://p.blog.csdn.net/images/p_blog_csdn_net/zhangxin09/EntryImages/20091230/debugger.gif)

**二十八、JavaScript中的“负负得正”**

*Rocky 16:48:37*   
Opera:  !!window.opera, 这样写的原因谁知道？  
*一夕 16:52:15*   
测试window.opera方法或属性是否可用   
*Rocky 16:52:31*   
我是说 为什么前面要两个!  
*一夕 16:53:22*   
因为window.opera返回的值不一定的BOOLEAN的,这样的话就不用担心这个了   
*Rocky 16:53:25*   
我知道了 是为了保证 该变量的 boolean  类型

**二十九、Ext.get()方法和document.getElementById()有什么区别?**

我在使用Ext.get()方法时，发现与document.getElementById不完全一样，如  
var myDiv=Ext.get('my\_Div')如果修改myDiv的innerHTML时必须加上myDiv.dom.innerHTML，如果用getElementById的话直接用myDiv.innerHTML就可以，这是为什么？  
Ext.get()得到的是一个Element对象，要变为一般的Dom对象要调用它的Dom属性。

document.getElementById()和Ext.getDom()一样  
Ext.get()只是得到Ext的对象

**三十、ext精华函数解析(仅个人见解)**

- One:    Ext的最先开始的精华函数要算Ext.namespace,它采取的是命名空间的方式.从而可以避免各种变量啊.对象的冲突问题
- Two:    Ext的apply采取的是对象继承方式,Ext.apply(o,c,object),既o继承c的所有属性.并且o也拥有object的一切属性
- Three   Ext的applyIf采取的对象继承方式,这个跟上面的继承有一点不同,Ext.applyIf(o,c)就是只有当o里的对象不存在时才继承.反之就不继承.
- Four:   Ext的extend,这个也是整个Ext的精华所在,所有的对象继承,扩展都是根据Ext.extend的方法而来.本人写的一个htmlEditor也才是看懂了extend方法才搞清楚如何写扩展.

**三十一、Ext.onReady 这个是不是很关键**

页面上所有的元素（DOM树）加载完毕（浏览器loading/parse完成，将dom树加载好的内存中去）

**三十二、parseInt()注意/建議事項**

使用parseInt將字串轉換成數字時，最好使用有兩個參數的版本，明確指定字串所表達數字是幾進位的。否則的話會出現 parseInt("08") ==&gt; 0，只有parseInt("08", 10)能正確轉換成8。

**三十三、Fn.createDelegate()的作用**

createDelegate()只限于函数类型的对象所使用。createDelegate()的作用，简单一点的说就是做一件本来不能做到的事情。当然自己无力完成所以委托给别人来做,我们再来看看简单的应用，演示如下：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. Ext.onReady(function(){
02. Ext.QuickTips.init()
03. var myclass=new Object();
04. // myclass并没有alert方法,我们也不打算为它写一个alert方法。我们希望它和window.alert有一样的行为,所以我们委托window来做
05. myclass.alert=window.alert.createDelegate(window);
06. // 我们还希望他有个更漂亮的show方法和Ext.MessageBox的show功能一样，所以我们又得委托给Ext.MessageBox来做这事了
07. myclass.show=Ext.MessageBox.show.createDelegate(Ext.MessageBox);
08. // 我们的myclass也有alert和show方法了
09. myclass.alert('alert1');
10. myclass.show({title:'title',msg:'message'});
11. });

 

看看 createCallback/createDelegate源码的实现，核心的都只有一句return method.apply(window, args);和 return method.apply(obj || window, callArgs);

**三十四、ExtJS，框架乎？类库乎？**

这段时间，笔者一直在学习和分析ExtJS的源代码，跟着Jack的思绪感悟了一把牛人的设计风格。同时，自己也在思考一个问题，Ext到底是什么？框架？类库？我们先来看看框架和类库的概念吧！框架一般来说是满足某种领域需求的半成品，一般都提供了扩展点给用户定制开发自己的需求代码，所以从宏观上来说，是有框架来调用用户所提供的定制code。而类库则不同，caller调用者主要是用户代码，类库通过其所提供的API来暴露出其功能性接口，以便供用户代码调用，类库代码为callee，即被调用者。Ext作者的将其定位为派生UI组件的引擎，所以应该是可以看做是框架。

**三十五、如果有大量的ComboBox记录，欲对其分页，如何实现？**

设置pageSize&gt;0即可。pageSize 如果值大于0，则在下拉列表的底部显示一个分页工具条，并且在执行过滤查询时将传递起始页和限制参数。注意：只在 mode = 'remote'时生效（默认为 0）。请[实时的参考例子](http://www.moriwaki.net/ext/zip.html) 。例子如图：

 

![](http://kxv1ug.blu.livefilestore.com/y1pLRu31wk_SUNEDFhRT35svdHQkzEenXtarnDFdg5DHS0ocNCSux1iGumXClgtL1dSjlOMfnt3dxVIOml8bcM2rTWFz6Mecxmj/paginComboBox.GIF)

### 三十六、iFrame在IE与FF中的区别

原来在FF中IFRAME的“document”不叫document，改名叫contentDocument, "window"改名叫contentWindow，这就是区别了。

### 三十七、Ext 3.2中关于背景图片的改进

一个小小的应用，却意想不到地看出作者十分高明的安排，这儿所说的便是Ext背景图片的源地址使用上了base64编码的图片inline形式。FF/Opera等一批自然铁杆支持base64，而IE8或以上支持了base64内嵌图片了，于是排除了Ext.isIE6 || Ext.isIE7 || Ext.isAir就可以顺当地使用base64图片。这不~还给省下了s.gif的HTTP请求。再细想一想，拿了什么好处！？虽然看似不起眼的1x1 pix的透明背景图，只有1KB不到大小，——经过此番节省下来，按其影响来说，为低碳、为节能、为免掉多余的HTTP头字节^\_^……莫不是功德无量！？

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

1. BLANK\_IMAGE\_URL : Ext.isIE6 || Ext.isIE7 || Ext.isAir ?
2. 'http:/' + '/extjs.com/s.gif' :
3. 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',

 

### **三十八、如何Ext DataView分页+过滤+查询**

见[文章](http://www.ineeke.com/archives/ext-dataview-paging-filter-query-drag/) by Neeke。

### 三十九、如何使 DataView自身分页

如图，by Neeke。

 

![](http://ijswjq.blu.livefilestore.com/y1pbFVHk_HBD2nLKO5GFT_itxjFA_dcrXt3M3Fk8hQSgD5G0uRScEw7gIBizDlDTo-eW-myGQypUtpw5O692DSv9du2go_5bxDI/dd.gif)

在DataView的render事件中调用如下函数：

 

**\[javascript]** [view plain](http://blog.csdn.net/zhangxin09/article/details/4769886 "view plain")[copy](http://blog.csdn.net/zhangxin09/article/details/4769886 "copy")

01. function onDataViewRender(v){
02. //创建拖拽对象
03. var dd = new Ext.dd.DragDrop(v.el);
04. //存储被拖拽的节点
05. var dragData = null;
06. dd.onMouseDown = function(e) {
07. var t,idx,record;
08. try {
09. t = e.getTarget(v.itemSelector);
10. idx = v.indexOf(t);
11. record = v.getStore().getAt(idx);
12. // Found a record to move
13. if (t &amp;&amp; record) {
14. dragData = {
15. origIdx : idx,
16. lastIdx : idx,
17. record  : record
18. };
19. return true;
20. }
21. } catch (ex) { dragData = null; }
22. return false;
23. },
24. //开始拖拽
25. dd.startDrag = function(x, y) {
26. if (!dragData) { return false; }
27. Ext.fly(v.getNode(dragData.origIdx)).addClass('thumb');
28. v.el.addClass('thumb-wrap-selected');
29. },
30. //结束拖拽
31. dd.endDrag = function(e) {
32. if (!dragData) { return true; }
33. Ext.fly(v.getNode(dragData.lastIdx)).removeClass('thumb');
34. v.el.removeClass('thumb-wrap-selected');
35. return true;
36. },
37. dd.onDrag = function(e) {
38. var t,idx,record,data = dragData;
39. if (!data) { return false; }
40. try {
41. t = e.getTarget(v.itemSelector);
42. idx = v.indexOf(t);
43. record = v.getStore().getAt(idx);
44. if (idx === data.lastIdx) { return true; }
45. //将数据插入到新的位置
46. if (t &amp;&amp; record) {
47. data.lastIdx = idx;
48. v.getStore().remove(data.record);
49. v.getStore().insert(idx, \[data.record]);
50. Ext.fly(v.getNode(idx)).addClass('thumb');
51. return true;
52. }
53. } catch (ex) { return false; }
54. return false;
55. }
56. }