code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * @class Ext.tree.TreeEditor * @extends Ext.Editor * Provides editor functionality for inline tree node editing. Any valid {@link Ext.form.Field} can be used * as the editor field. * 为树节点提供即时的编辑功能,所有合法{@link Ext.form.Field}都可作为其编辑字段。 * @constructor * @param {TreePanel} tree * @param {Object} config Either a prebuilt {@link Ext.form.Field} instance or a Field config object 既可以是内建的{@link Ext.form.Field}实例也可以Field的配置项对象 */ Ext.tree.TreeEditor = function(tree, config){ config = config || {}; var field = config.events ? config : new Ext.form.TextField(config); Ext.tree.TreeEditor.superclass.constructor.call(this, field); this.tree = tree; if(!tree.rendered){ tree.on('render', this.initEditor, this); }else{ this.initEditor(tree); } }; Ext.extend(Ext.tree.TreeEditor, Ext.Editor, { /** * @cfg {String} alignment * The position to align to (see {@link Ext.Element#alignTo} for more details, defaults to "l-l"). * 要对象的方向(参阅{@link Ext.Element#alignTo}了解更多,默认为"l-l") */ alignment: "l-l", // inherit autoSize: false, /** * @cfg {Boolean} hideEl * True to hide the bound element while the editor is displayed (defaults to false) * True表示为,当编辑器显示时隐藏绑定的元素(缺省为false) */ hideEl : false, /** * @cfg {String} cls * CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor") * 编辑器用到的CSS样式类(默认为"x-small-editor x-tree-editor") */ cls: "x-small-editor x-tree-editor", /** * @cfg {Boolean} shim * True to shim the editor if selects/iframes could be displayed beneath it (defaults to false) * 如果要避免有select元素或iframe元素遮挡编辑器显示,就使用一个“垫片(shim)”来提供显示(默认为false) */ shim:false, // inherit shadow:"frame", /** * @cfg {Number} maxWidth * The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed * the containing tree element's size, it will be automatically limited for you to the container width, taking * scroll and client offsets into account prior to each edit. * 编辑器最大的宽度,单位是橡树。注意如果最大尺寸超过放置树元素的尺寸,那么将自动为你适应容器的尺寸,包括滚动条和client offsets into account prior to each edit。 */ maxWidth: 250, /** * @cfg {Number} editDelay The number of milliseconds between clicks to register a double-click * that will trigger editing on the current node (defaults to 350). If two clicks occur on the same node within this time span, * the editor for the node will display, otherwise it will be processed as a regular click. * 该节点点击一开始,持续多久才等级双击的事件(双击的事件执行时会翻转当前的编辑模式,默认为350)。 * 如果在同一个节点上,两次点击都是发生在该时间(time span),那么节点的编辑器将会显示,否则它将被作为规则点击处理。 */ editDelay : 350, initEditor : function(tree){ tree.on('beforeclick', this.beforeNodeClick, this); this.on('complete', this.updateNode, this); this.on('beforestartedit', this.fitToTree, this); this.on('startedit', this.bindScroll, this, {delay:10}); this.on('specialkey', this.onSpecialKey, this); }, // private fitToTree : function(ed, el){ var td = this.tree.getTreeEl().dom, nd = el.dom; if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible td.scrollLeft = nd.offsetLeft; } var w = Math.min( this.maxWidth, (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5); this.setSize(w, ''); }, // private triggerEdit : function(node){ this.completeEdit(); this.editNode = node; this.startEdit(node.ui.textNode, node.text); }, // private bindScroll : function(){ this.tree.getTreeEl().on('scroll', this.cancelEdit, this); }, // private beforeNodeClick : function(node, e){ var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0); this.lastClick = new Date(); if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){ e.stopEvent(); this.triggerEdit(node); return false; } }, // private updateNode : function(ed, value){ this.tree.getTreeEl().un('scroll', this.cancelEdit, this); this.editNode.setText(value); }, // private onHide : function(){ Ext.tree.TreeEditor.superclass.onHide.call(this); if(this.editNode){ this.editNode.ui.focus(); } }, // private onSpecialKey : function(field, e){ var k = e.getKey(); if(k == e.ESC){ e.stopEvent(); this.cancelEdit(); }else if(k == e.ENTER && !e.hasModifier()){ e.stopEvent(); this.completeEdit(); } } });
JavaScript
/** * @class Ext.tree.TreeFilter * 注意这个类是试验性的所以不会更新节点的缩进(连线)或者展开收回图标 * @param {TreePanel} tree * @param {Object} config 配置项(可选的) */ Ext.tree.TreeFilter = function(tree, config){ this.tree = tree; this.filtered = {}; Ext.apply(this, config); }; Ext.tree.TreeFilter.prototype = { clearBlank:false, reverse:false, autoClear:false, remove:false, /** * 通过指定的属性过滤数据 * @param {String/RegExp} value既可以是属性值开头的字符串也可以是针对这个属性的正则表达式 * @param {String} attr (可选)这个被传递的属性是你的属性的集合中的。默认是"text" * @param {TreeNode} startNode (可选)从这个节点开始是过滤的 */ filter : function(value, attr, startNode){ attr = attr || "text"; var f; if(typeof value == "string"){ var vlen = value.length; // auto clear empty filter if(vlen == 0 && this.clearBlank){ this.clear(); return; } value = value.toLowerCase(); f = function(n){ return n.attributes[attr].substr(0, vlen).toLowerCase() == value; }; }else if(value.exec){ // regex? f = function(n){ return value.test(n.attributes[attr]); }; }else{ throw 'Illegal filter type, must be string or regex'; } this.filterBy(f, null, startNode); }, /** * 通过一个函数过滤,这个被传递的函数将被这棵树中的每个节点调用(或从startNode开始)。如果函数返回true,那么该节点将保留否则它将被过滤掉. * 如果一个节点被过滤掉,那么它的子节点也都被过滤掉了 * @param {Function} fn 过滤函数 * @param {Object} scope (可选的)函数的作用域(默认是现在这个节点) */ filterBy : function(fn, scope, startNode){ startNode = startNode || this.tree.root; if(this.autoClear){ this.clear(); } var af = this.filtered, rv = this.reverse; var f = function(n){ if(n == startNode){ return true; } if(af[n.id]){ return false; } var m = fn.call(scope || n, n); if(!m || rv){ af[n.id] = n; n.ui.hide(); return false; } return true; }; startNode.cascade(f); if(this.remove){ for(var id in af){ if(typeof id != "function"){ var n = af[id]; if(n && n.parentNode){ n.parentNode.removeChild(n); } } } } }, /** * 清理现在的过滤。注意:设置的过滤带有remove选项的不能被清理 */ clear : function(){ var t = this.tree; var af = this.filtered; for(var id in af){ if(typeof id != "function"){ var n = af[id]; if(n){ n.ui.show(); } } } this.filtered = {}; } };
JavaScript
/** * @class Ext.tree.TreePanel * <p> * TreePanel为树状的数据结构提供了树状结构UI表示层。 * </p> * <p>{@link Ext.tree.TreeNode TreeNode}s是加入到TreePanel的节点,可采用其{@link Ext.tree.TreeNode#attributes attributes}属性 * 来定义程序的元数据</p> * <p><b>TreePanel渲染之前必须有一个{@link #root}根节点的对象</b>。除了可以用{@link #root}配置选项指定外,还可以使用{@link #setRootNode}的方法。 * @extends Ext.Panel * @cfg {Ext.tree.TreeNode} root 树的根节点 * @cfg {Boolean} rootVisible false表示隐藏根节点(默认为true) * @cfg {Boolean} lines false禁止显示树的虚线(默认为true) * @cfg {Boolean} enableDD true表示允许拖放 * @cfg {Boolean} enableDrag true表示仅激活拖动 * @cfg {Boolean} enableDrop true表示仅激活投下 * @cfg {Object} dragConfig 自定义的配置对象,作用到{@link Ext.tree.TreeDragZone}实例 * @cfg {Object} dropConfig 自定义的配置对象,作用到{@link Ext.tree.TreeDropZone}实例 * @cfg {String} ddGroup 此TreePanel所隶属的DD组 * @cfg {String} ddAppendOnly True if the tree should only allow append drops (用于树的排序) * @cfg {Boolean} ddScroll true表示激活主干部分的滚动 * @cfg {Boolean} containerScroll true用ScrollerManagee登记该容器 * @cfg {Boolean} hlDrop false表示在置下时禁止节点的高亮(默认为Ext.enableFx的值) * @cfg {String} hlColor 节点对象高亮的颜色(默认为C3DAF9) * @cfg {Boolean} animate true表示激活展开、闭合的动画(默认为Ext.enableFx的值) * @cfg {Boolean} singleExpand true表示只有一个节点的分支可展开 * @cfg {Boolean} selModel 此TreePanel所用的选区模型(默认为{@link Ext.tree.DefaultSelectionModel}) * @cfg {Ext.tree.TreeLoader} loader 此TreePanel所用的{@link Ext.tree.TreeLoader}对象 * @cfg {String} pathSeparator 分离路径的标识符(默认为‘/’) * * @constructor * @param {Object} config 配置项对象 */ Ext.tree.TreePanel = Ext.extend(Ext.Panel, { rootVisible : true, animate: Ext.enableFx, lines : true, enableDD : false, hlDrop : Ext.enableFx, pathSeparator: "/", initComponent : function(){ Ext.tree.TreePanel.superclass.initComponent.call(this); if(!this.eventModel){ this.eventModel = new Ext.tree.TreeEventModel(this); } this.nodeHash = {}; /** * 树的根节点对象 * @type Ext.tree.TreeNode * @property root */ if(this.root){ this.setRootNode(this.root); } this.addEvents( /** * @event append * Fires when a new child node is appended to a node in this tree. * 当新节点添加到树中的某个节点作为子节点时触发 * @param {Tree} tree 所在的树对象 * @param {Node} parent 父节点 * @param {Node} node 新添加的节点 * @param {Number} index 刚加入节点的索引位置 */ "append", /** * @event remove * Fires when a child node is removed from a node in this tree. * 从该树中的某个节点移除下级的节点是触发 * @param {Tree} tree 所在的树对象 * @param {Node} parent 父节点 * @param {Node} node 被移除节点对象 */ "remove", /** * @event movenode * Fires when a node is moved to a new location in the tree * 树中的某个节点被移除到新位置时触发 * @param {Tree} tree 所在的树对象 * @param {Node} node 节点对象 moved * @param {Node} oldParent 改节点的原始值 * @param {Node} newParent 该节点的新值 * @param {Number} index 移动到索引位置 */ "movenode", /** * @event insert * Fires when a new child node is inserted in a node in this tree. * 当有一个新的集合插入到该树的某个节点上触发 * @param {Tree} tree 所在的树对象 * @param {Node} parent 父节点 * @param {Node} node 要插入的下级项 * @param {Node} refNode 说明在这个节点之前加入 */ "insert", /** * @event beforeappend * Fires before a new child is appended to a node in this tree, return false to cancel the append. * 当这棵树有下级项(child)被被添加到另外一个地方的时候触发,若有false返回就取消添加 * @param {Tree} tree 所在的树对象 * @param {Node} parent 父节点 * @param {Node} node 要添加的子节点 */ "beforeappend", /** * @event beforeremove * Fires before a child is removed from a node in this tree, return false to cancel the remove. * 当这棵树有下级项(child)被被移动到另外一个地方的时候触发,若有false返回就取消移动 * @param {Tree} tree 所在的树对象 * @param {Node} parent 父节点 * @param {Node} node 要被移除的节点 */ "beforeremove", /** * @event beforemovenode * Fires before a node is moved to a new location in the tree. Return false to cancel the move. * 当这棵树有节点被被移动到另外一个地方的时候触发,若有false返回就取消移动 * @param {Tree} tree 所在的树对象 * @param {Node} node 节点对象 being moved * @param {Node} oldParent 节点上一级对象 * @param {Node} newParent The new parent 节点对象 is moving to * @param {Number} index The index it is being moved to */ "beforemovenode", /** * @event beforeinsert * Fires before a new child is inserted in a node in this tree, return false to cancel the insert. * 当这棵树有新项(new child)被插入的时候触发,若有false返回就取消插入 * @param {Tree} tree 所在的树对象 * @param {Node} parent 父节点 * @param {Node} node 要插入的子节点 * @param {Node} refNode The child node 节点对象 is being inserted before */ "beforeinsert", /** * @event beforeload * Fires before a node is loaded, return false to cancel * 在节点加载之前触发,若有false返回就取消事件 * @param {Node} node 被加载的节点对象 */ "beforeload", /** * @event load * Fires when a node is loaded * 在节点加载后触发 * @param {Node} node 已加载的节点对象 */ "load", /** * @event textchange * Fires when the text for a node is changed * 在节点的文本修过后触发 * @param {Node} node 节点对象 * @param {String} text 新文本 * @param {String} oldText 旧文本 */ "textchange", /** * @event beforeexpandnode * Fires before a node is expanded, return false to cancel. * 在节点展开之前触发,若有false返回就取消事件 * @param {Node} node 节点对象 * @param {Boolean} deep 深度 * @param {Boolean} anim 动画 */ "beforeexpandnode", /** * @event beforecollapsenode * Fires before a node is collapsed, return false to cancel. * 在节点闭合之前触发,若有false返回就取消事件 * @param {Node} node 节点对象 * @param {Boolean} deep 深度 * @param {Boolean} anim 动画 */ "beforecollapsenode", /** * @event expandnode * Fires when a node is expanded * 当节点展开是触发 * @param {Node} node 节点对象 */ "expandnode", /** * @event disabledchange * Fires when the disabled status of a node changes * 当节点的disabled状态改变后触发 * @param {Node} node 节点对象 * @param {Boolean} disabled 禁止 */ "disabledchange", /** * @event collapsenode * Fires when a node is collapsed * 当节点闭合后触发 * @param {Node} node 节点对象 */ "collapsenode", /** * @event beforeclick * Fires before click processing on a node. Return false to cancel the default action. * 当单击在某个节点进行之前触发。返回false则取消默认的动作。 * @param {Node} node 节点对象 * @param {Ext.EventObject} e 事件对象 */ "beforeclick", /** * @event click * Fires when a node is clicked * 当节点单击时触发 * @param {Node} node 节点对象 * @param {Ext.EventObject} e 事件对象 */ "click", /** * @event checkchange * Fires when a node with a checkbox's checked property changes * 当一个带有checkbox控件的节点的checked属性被改变时触发 * @param {Node} this 这个节点 * @param {Boolean} checked */ "checkchange", /** * @event dblclick * Fires when a node is double clicked * 当节点双击时触发 * @param {Node} node 节点对象 * @param {Ext.EventObject} e 事件对象 */ "dblclick", /** * @event contextmenu * Fires when a node is right clicked * 当节点被右击时触发 * @param {Node} node 节点对象 * @param {Ext.EventObject} e 事件对象 */ "contextmenu", /** * @event beforechildrenrendered * Fires right before the child nodes for a node are rendered * 就在节点的子节点被渲染之前触发 * @param {Node} node 节点对象 */ "beforechildrenrendered", /** * @event startdrag * Fires when a node starts being dragged * 当节点开始拖动时触发 * @param {Ext.tree.TreePanel} this treePanel * @param {Ext.tree.TreeNode} node 节点 * @param {event} e 原始浏览器事件对象 */ "startdrag", /** * @event enddrag * Fires when a drag operation is complete * 当一次拖动操作完成后触发 * @param {Ext.tree.TreePanel} this treePanel * @param {Ext.tree.TreeNode} node 节点 * @param {event} e 原始浏览器事件对象 */ "enddrag", /** * @event dragdrop * Fires when a dragged node is dropped on a valid DD target * 当一个拖动节点在一个有效的DD目标上置下时触发 * @param {Ext.tree.TreePanel} this treePanel * @param {Ext.tree.TreeNode} node 节点 * @param {DD} dd 被投下的dd对象 * @param {event} e 原始浏览器事件对象 */ "dragdrop", /** * @event beforenodedrop * 当一个DD对象在置下到某个节点之前触发,用于预处理(preprocessing) * 返回false则取消置下 * 传入的dropEvent处理函数有以下的属性:<br /> * <ul style="padding:5px;padding-left:16px;"> * <li>tree - TreePanel对象</li> * <li>target - 投下的节点对象(目标)</li> * <li>data - 拖动的数据源</li> * <li>point - 投下的方式-添加、上方或下方</li> * <li>source - 拖动源</li> * <li>rawEvent - 原始鼠标事件</li> * <li>dropNode - 由源提供的置下节点,<b>或</b>在该对象设置你要插入的节点</li> * <li>cancel - 设置为true表示签名投下为不允许</li> * </ul> * @param {Object} dropEvent 事件对象 */ "beforenodedrop", /** * @event nodedrop * 当树节点有一个DD对象被投放后触发。传入的dropEvent处理函数有以下的属性:<br /> * <ul style="padding:5px;padding-left:16px;"> * <li>tree - TreePanel对象</li> * <li>target - 投下的节点对象(目标)</li> * <li>data - 拖动的数据源</li> * <li>point - 投下的方式-添加、上方或下方</li> * <li>source - 拖动源</li> * <li>rawEvent - 原始鼠标事件</li> * <li>dropNode - 投下的节点</li> * </ul> * @param {Object} dropEvent 事件对象 */ "nodedrop", /** * @event nodedragover * 当树节点成为拖动目标时触发,返回false签名这次置下将不允许。传入的dropEvent处理函数有以下的属性: * <br /> * <ul style="padding:5px;padding-left:16px;"> * <li>tree - TreePanel对象</li> * <li>target - 投下的节点对象(目标)</li> * <li>data - 拖动的数据源</li> * <li>point - 投下的方式-添加、上方或下方</li> * <li>source - 拖动源</li> * <li>rawEvent - 原始鼠标事件</li> * <li>dropNode - 由源提供的投下节点</li> * <li>cancel - 设置为true表示签名投下为不允许</li> * </ul> * @param {Object} dragOverEvent 事件对象 */ "nodedragover" ); if(this.singleExpand){ this.on("beforeexpandnode", this.restrictExpand, this); } }, // private proxyNodeEvent : function(ename, a1, a2, a3, a4, a5, a6){ if(ename == 'collapse' || ename == 'expand' || ename == 'beforecollapse' || ename == 'beforeexpand' || ename == 'move' || ename == 'beforemove'){ ename = ename+'node'; } // args inline for performance while bubbling events return this.fireEvent(ename, a1, a2, a3, a4, a5, a6); }, /** * 返回树的根节点 * @return {Node} */ getRootNode : function(){ return this.root; }, /** * Sets the root node for this tree during initialization. * 在初始化过程中设置该树的根节点 * @param {Node} node * @return {Node} */ setRootNode : function(node){ this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); if(!this.rootVisible){ var uiP = node.attributes.uiProvider; node.ui = uiP ? new uiP(node) : new Ext.tree.RootTreeNodeUI(node); } return node; }, /** * * 返回树的ID * @param {String} id ID * @return {Node} */ getNodeById : function(id){ return this.nodeHash[id]; }, // private registerNode : function(node){ this.nodeHash[node.id] = node; }, // private unregisterNode : function(node){ delete this.nodeHash[node.id]; }, // private toString : function(){ return "[Tree"+(this.id?" "+this.id:"")+"]"; }, // private restrictExpand : function(node){ var p = node.parentNode; if(p){ if(p.expandedChild && p.expandedChild.parentNode == p){ p.expandedChild.collapse(); } p.expandedChild = node; } }, /** * 返回选中的节点,或已选中的节点的特定的属性(例如:“id”) * @param {String} attribute (可选的)默认为null(返回实际节点) * @param {TreeNode} startNode (可选的)开始的节点对象 to start from,默认为根节点 * @return {Array} */ getChecked : function(a, startNode){ startNode = startNode || this.root; var r = []; var f = function(){ if(this.attributes.checked){ r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a])); } } startNode.cascade(f); return r; }, /** * 返回TreePanel所在的容器元素 * @return {Element} 返回TreePanel容器的元素 */ getEl : function(){ return this.el; }, /** *返回该树的 {@link Ext.tree.TreeLoader}对象 * @return {Ext.tree.TreeLoader} 该树的TreeLoader */ getLoader : function(){ return this.loader; }, /** * 展开所有节点 */ expandAll : function(){ this.root.expand(true); }, /** * 闭合所有节点 */ collapseAll : function(){ this.root.collapse(true); }, /** * 返回这个treePanel所用的选区模型 * @return {TreeSelectionModel} TreePanel用着的选区模型 */ getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.tree.DefaultSelectionModel(); } return this.selModel; }, /** * 展开指定的路径。路径可以从{@link Ext.data.Node#getPath}对象上获取 * @param {String} path 路径 * @param {String} attr (可选的)路径中使用的属性(参阅{@link Ext.data.Node#getPath}了解个功能) * @param {Function} callback (可选的)当展开完成时执行的回调。回调执行时会有以下两个参数 * (bSuccess, oLastNode)bSuccess表示展开成功而oLastNode就表示展开的最后一个节点 */ expandPath : function(path, attr, callback){ attr = attr || "id"; var keys = path.split(this.pathSeparator); var curNode = this.root; if(curNode.attributes[attr] != keys[1]){ // invalid root if(callback){ callback(false, null); } return; } var index = 1; var f = function(){ if(++index == keys.length){ if(callback){ callback(true, curNode); } return; } var c = curNode.findChild(attr, keys[index]); if(!c){ if(callback){ callback(false, curNode); } return; } curNode = c; c.expand(false, false, f); }; curNode.expand(false, false, f); }, /** * 选择树的指定的路径。路径可以从{@link Ext.data.Node#getPath}对象上获取 * @param {String} path 路径 * @param {String} attr (可选的)路径中使用的属性(参阅{@link Ext.data.Node#getPath}了解个功能) * @param {Function} callback (可选的)当展开完成时执行的回调。回调执行时会有以下两个参数 * (bSuccess, oLastNode)bSuccess表示选区已成功创建而oLastNode就表示展开的最后一个节点 */ selectPath : function(path, attr, callback){ attr = attr || "id"; var keys = path.split(this.pathSeparator); var v = keys.pop(); if(keys.length > 0){ var f = function(success, node){ if(success && node){ var n = node.findChild(attr, v); if(n){ n.select(); if(callback){ callback(true, n); } }else if(callback){ callback(false, n); } }else{ if(callback){ callback(false, n); } } }; this.expandPath(keys.join(this.pathSeparator), attr, f); }else{ this.root.select(); if(callback){ callback(true, this.root); } } }, /** * 返回tree所属的元素 * @return {Ext.Element} 元素 */ getTreeEl : function(){ return this.body; }, // private onRender : function(ct, position){ Ext.tree.TreePanel.superclass.onRender.call(this, ct, position); this.el.addClass('x-tree'); this.innerCt = this.body.createChild({tag:"ul", cls:"x-tree-root-ct " + (this.lines ? "x-tree-lines" : "x-tree-no-lines")}); }, // private initEvents : function(){ Ext.tree.TreePanel.superclass.initEvents.call(this); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.body); } if((this.enableDD || this.enableDrop) && !this.dropZone){ /** * 若干置下有效的话,tree所用的dropZone * @type Ext.tree.TreeDropZone */ this.dropZone = new Ext.tree.TreeDropZone(this, this.dropConfig || { ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true }); } if((this.enableDD || this.enableDrag) && !this.dragZone){ /** * 若干拖动有效的话,tree所用的dragZone * @type Ext.tree.TreeDragZone */ this.dragZone = new Ext.tree.TreeDragZone(this, this.dragConfig || { ddGroup: this.ddGroup || "TreeDD", scroll: this.ddScroll }); } this.getSelectionModel().init(this); }, // private afterRender : function(){ Ext.tree.TreePanel.superclass.afterRender.call(this); this.root.render(); if(!this.rootVisible){ this.root.renderChildren(); } }, onDestroy : function(){ if(this.rendered){ this.body.removeAllListeners(); Ext.dd.ScrollManager.unregister(this.body); if(this.dropZone){ this.dropZone.unreg(); } if(this.dragZone){ this.dragZone.unreg(); } } this.root.destroy(); this.nodeHash = null; Ext.tree.TreePanel.superclass.onDestroy.call(this); } /** * @cfg {String/Number} activeItem * @hide */ /** * @cfg {Boolean} autoDestroy * @hide */ /** * @cfg {Object/String/Function} autoLoad * @hide */ /** * @cfg {Boolean} autoWidth * @hide */ /** * @cfg {Boolean/Number} bufferResize * @hide */ /** * @cfg {String} defaultType * @hide */ /** * @cfg {Object} defaults * @hide */ /** * @cfg {Boolean} hideBorders * @hide */ /** * @cfg {Mixed} items * @hide */ /** * @cfg {String} layout * @hide */ /** * @cfg {Object} layoutConfig * @hide */ /** * @cfg {Boolean} monitorResize * @hide */ /** * @property items * @hide */ /** * @method add * @hide */ /** * @method cascade * @hide */ /** * @method doLayout * @hide */ /** * @method find * @hide */ /** * @method findBy * @hide */ /** * @method findById * @hide */ /** * @method findByType * @hide */ /** * @method getComponent * @hide */ /** * @method getLayout * @hide */ /** * @method getUpdater * @hide */ /** * @method insert * @hide */ /** * @method load * @hide */ /** * @method remove * @hide */ /** * @event add * @hide */ /** * @event afterLayout * @hide */ /** * @event beforeadd * @hide */ /** * @event beforeremove * @hide */ /** * @event remove * @hide */ }); Ext.reg('treepanel', Ext.tree.TreePanel);
JavaScript
/** * @class Ext.tree.TreeDropZone * @extends Ext.dd.DropZone * @constructor * @param {String/HTMLElement/Element} tree 要允许落下的{@link Ext.tree.TreePanel} * @param {Object} config */ if(Ext.dd.DropZone){ Ext.tree.TreeDropZone = function(tree, config){ /** * @cfg {Boolean} allowParentInsert * Allow inserting a dragged node between an expanded parent node and its first child that will become a * sibling of the parent when dropped (defaults to false) */ this.allowParentInsert = false; /** * @cfg {String} allowContainerDrop * True if drops on the tree container (outside of a specific tree node) are allowed (defaults to false) */ this.allowContainerDrop = false; /** * @cfg {String} appendOnly * True if the tree should only allow append drops (use for trees which are sorted, defaults to false) */ this.appendOnly = false; Ext.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config); /** * The TreePanel for this drop zone * @type Ext.tree.TreePanel * @property */ this.tree = tree; /** * Arbitrary data that can be associated with this tree and will be included in the event object that gets * passed to any nodedragover event handler (defaults to {}) * @type Ext.tree.TreePanel * @property */ this.dragOverData = {}; // private this.lastInsertClass = "x-tree-no-status"; }; Ext.extend(Ext.tree.TreeDropZone, Ext.dd.DropZone, { /** * @cfg {String} ddGroup * 该对象隶属于组的名称。如果已指定组,那该对象只会与同组下其他拖放成员相交互(默认为“TreeDD”)。 */ ddGroup : "TreeDD", /** * @cfg {String} expandDelay * 在拖动到一个可落下的节点时,到目标上方,距离展开树节点 等待的毫秒数。(默认为1000) */ expandDelay : 1000, // private expandNode : function(node){ if(node.hasChildNodes() && !node.isExpanded()){ node.expand(false, null, this.triggerCacheRefresh.createDelegate(this)); } }, // private queueExpand : function(node){ this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]); }, // private cancelExpand : function(){ if(this.expandProcId){ clearTimeout(this.expandProcId); this.expandProcId = false; } }, // private isValidDropPoint : function(n, pt, dd, e, data){ if(!n || !data){ return false; } var targetNode = n.node; var dropNode = data.node; // default drop rules if(!(targetNode && targetNode.isTarget && pt)){ return false; } if(pt == "append" && targetNode.allowChildren === false){ return false; } if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){ return false; } if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){ return false; } // reuse the object var overEvent = this.dragOverData; overEvent.tree = this.tree; overEvent.target = targetNode; overEvent.data = data; overEvent.point = pt; overEvent.source = dd; overEvent.rawEvent = e; overEvent.dropNode = dropNode; overEvent.cancel = false; var result = this.tree.fireEvent("nodedragover", overEvent); return overEvent.cancel === false && result !== false; }, // private getDropPoint : function(e, n, dd){ var tn = n.node; if(tn.isRoot){ return tn.allowChildren !== false ? "append" : false; // always append for root } var dragEl = n.ddel; var t = Ext.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight; var y = Ext.lib.Event.getPageY(e); var noAppend = tn.allowChildren === false || tn.isLeaf(); if(this.appendOnly || tn.parentNode.allowChildren === false){ return noAppend ? false : "append"; } var noBelow = false; if(!this.allowParentInsert){ noBelow = tn.hasChildNodes() && tn.isExpanded(); } var q = (b - t) / (noAppend ? 2 : 3); if(y >= t && y < (t + q)){ return "above"; }else if(!noBelow && (noAppend || y >= b-q && y <= b)){ return "below"; }else{ return "append"; } }, // private onNodeEnter : function(n, dd, e, data){ this.cancelExpand(); }, // private onNodeOver : function(n, dd, e, data){ var pt = this.getDropPoint(e, n, dd); var node = n.node; // auto node expand check if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){ this.queueExpand(node); }else if(pt != "append"){ this.cancelExpand(); } // set the insert point style on the target node var returnCls = this.dropNotAllowed; if(this.isValidDropPoint(n, pt, dd, e, data)){ if(pt){ var el = n.ddel; var cls; if(pt == "above"){ returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between"; cls = "x-tree-drag-insert-above"; }else if(pt == "below"){ returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between"; cls = "x-tree-drag-insert-below"; }else{ returnCls = "x-tree-drop-ok-append"; cls = "x-tree-drag-append"; } if(this.lastInsertClass != cls){ Ext.fly(el).replaceClass(this.lastInsertClass, cls); this.lastInsertClass = cls; } } } return returnCls; }, // private onNodeOut : function(n, dd, e, data){ this.cancelExpand(); this.removeDropIndicators(n); }, // private onNodeDrop : function(n, dd, e, data){ var point = this.getDropPoint(e, n, dd); var targetNode = n.node; targetNode.ui.startDrop(); if(!this.isValidDropPoint(n, point, dd, e, data)){ targetNode.ui.endDrop(); return false; } // first try to find the drop node var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null); var dropEvent = { tree : this.tree, target: targetNode, data: data, point: point, source: dd, rawEvent: e, dropNode: dropNode, cancel: !dropNode }; var retval = this.tree.fireEvent("beforenodedrop", dropEvent); if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){ targetNode.ui.endDrop(); return false; } // allow target changing targetNode = dropEvent.target; if(point == "append" && !targetNode.isExpanded()){ targetNode.expand(false, null, function(){ this.completeDrop(dropEvent); }.createDelegate(this)); }else{ this.completeDrop(dropEvent); } return true; }, // private completeDrop : function(de){ var ns = de.dropNode, p = de.point, t = de.target; if(!(ns instanceof Array)){ ns = [ns]; } var n; for(var i = 0, len = ns.length; i < len; i++){ n = ns[i]; if(p == "above"){ t.parentNode.insertBefore(n, t); }else if(p == "below"){ t.parentNode.insertBefore(n, t.nextSibling); }else{ t.appendChild(n); } } n.ui.focus(); if(this.tree.hlDrop){ n.ui.highlight(); } t.ui.endDrop(); this.tree.fireEvent("nodedrop", de); }, // private afterNodeMoved : function(dd, data, e, targetNode, dropNode){ if(this.tree.hlDrop){ dropNode.ui.focus(); dropNode.ui.highlight(); } this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e); }, // private getTree : function(){ return this.tree; }, // private removeDropIndicators : function(n){ if(n && n.ddel){ var el = n.ddel; Ext.fly(el).removeClass([ "x-tree-drag-insert-above", "x-tree-drag-insert-below", "x-tree-drag-append"]); this.lastInsertClass = "_noclass"; } }, // private beforeDragDrop : function(target, e, id){ this.cancelExpand(); return true; }, // private afterRepair : function(data){ if(data && Ext.enableFx){ data.node.ui.highlight(); } this.hideProxy(); } }); }
JavaScript
/** * @class Ext.tree.MultiSelectionModel * @extends Ext.util.Observable * 一个多选择区的TreePanel */ Ext.tree.MultiSelectionModel = function(config){ this.selNodes = []; this.selMap = {}; this.addEvents( /** * @event selectionchange * 当选中的选区有变动时触发 * @param {MultiSelectionModel} this * @param {Array} nodes 选中节点组成的数组 */ "selectionchange" ); Ext.apply(this, config); Ext.tree.MultiSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.tree.MultiSelectionModel, Ext.util.Observable, { init : function(tree){ this.tree = tree; tree.getTreeEl().on("keydown", this.onKeyDown, this); tree.on("click", this.onNodeClick, this); }, onNodeClick : function(node, e){ this.select(node, e, e.ctrlKey); }, /** * 将节点放入选择区 * @param {TreeNode} node 要放入的节点 * @param {EventObject} e 为选择区分配的event对象 * @param {Boolean} keepExisting 如果为true,则保存选择区中已存在的节点 * @return {TreeNode} 选中的节点 */ select : function(node, e, keepExisting){ if(keepExisting !== true){ this.clearSelections(true); } if(this.isSelected(node)){ this.lastSelNode = node; return node; } this.selNodes.push(node); this.selMap[node.id] = node; this.lastSelNode = node; node.ui.onSelectedChange(true); this.fireEvent("selectionchange", this, this.selNodes); return node; }, /** * 如果传入的节点在选择区则从中删除 * @param {TreeNode} node 待删除的节点 */ unselect : function(node){ if(this.selMap[node.id]){ node.ui.onSelectedChange(false); var sn = this.selNodes; var index = sn.indexOf(node); if(index != -1){ this.selNodes.splice(index, 1); } delete this.selMap[node.id]; this.fireEvent("selectionchange", this, this.selNodes); } }, /** * 清理选择区中的节点 */ clearSelections : function(suppressEvent){ var sn = this.selNodes; if(sn.length > 0){ for(var i = 0, len = sn.length; i < len; i++){ sn[i].ui.onSelectedChange(false); } this.selNodes = []; this.selMap = {}; if(suppressEvent !== true){ this.fireEvent("selectionchange", this, this.selNodes); } } }, /** * 如果节点已经在选择区中则返回true * @param {TreeNode} node 检查的节点 * @return {Boolean} */ isSelected : function(node){ return this.selMap[node.id] ? true : false; }, /** * 返回选择区中所有的节点 * @return {Array} */ getSelectedNodes : function(){ return this.selNodes; }, onKeyDown : Ext.tree.DefaultSelectionModel.prototype.onKeyDown, selectNext : Ext.tree.DefaultSelectionModel.prototype.selectNext, selectPrevious : Ext.tree.DefaultSelectionModel.prototype.selectPrevious });
JavaScript
/** * @class Ext.tree.DefaultSelectionModel * @extends Ext.util.Observable * 默认是一个单选择区的TreePanel */ Ext.tree.DefaultSelectionModel = function(config){ this.selNode = null; this.addEvents( /** * @event selectionchange * 当选中的选区有变动时触发 * @param {DefaultSelectionModel} this * @param {TreeNode} node 新选区 */ "selectionchange", /** * @event beforeselect * 选中的节点加载之前触发,返回false则取消。 * @param {DefaultSelectionModel} this * @param {TreeNode} node 新选区 * @param {TreeNode} node 旧选区 */ "beforeselect" ); Ext.apply(this, config); Ext.tree.DefaultSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.tree.DefaultSelectionModel, Ext.util.Observable, { init : function(tree){ this.tree = tree; tree.getTreeEl().on("keydown", this.onKeyDown, this); tree.on("click", this.onNodeClick, this); }, onNodeClick : function(node, e){ this.select(node); }, /** * Select a node. 如果该节点不在选择区,则该节点放入选择区 * @param {TreeNode} node 要选择的节点 * @return {TreeNode} 选择的节点 */ select : function(node){ var last = this.selNode; if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){ if(last){ last.ui.onSelectedChange(false); } this.selNode = node; node.ui.onSelectedChange(true); this.fireEvent("selectionchange", this, node, last); } return node; }, /** * 如果该节点在选择区中,则将该节点移除选择区 * @param {TreeNode} node 被移除的节点 */ unselect : function(node){ if(this.selNode == node){ this.clearSelections(); } }, /** * 清空选择区,并返回选择区中的节点 */ clearSelections : function(){ var n = this.selNode; if(n){ n.ui.onSelectedChange(false); this.selNode = null; this.fireEvent("selectionchange", this, null); } return n; }, /** * 得到选择区中的节点 * @return {TreeNode} 选中的节点 */ getSelectedNode : function(){ return this.selNode; }, /** * 如果节点在选择区中则返回true * @param {TreeNode} node 待检查的节点 * @return {Boolean} */ isSelected : function(node){ return this.selNode == node; }, /** * 将选择区中的节点在这棵树中上一个节点放入选择区,而且是智能的检索。 * @return TreeNode 新选区 */ selectPrevious : function(){ var s = this.selNode || this.lastSelNode; if(!s){ return null; } var ps = s.previousSibling; if(ps){ if(!ps.isExpanded() || ps.childNodes.length < 1){ return this.select(ps); } else{ var lc = ps.lastChild; while(lc && lc.isExpanded() && lc.childNodes.length > 0){ lc = lc.lastChild; } return this.select(lc); } } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){ return this.select(s.parentNode); } return null; }, /** * 将选择区中的节点在这棵树中下一个节点放入选择区,而且是智能的检索。 * @return TreeNode 新选区 */ selectNext : function(){ var s = this.selNode || this.lastSelNode; if(!s){ return null; } if(s.firstChild && s.isExpanded()){ return this.select(s.firstChild); }else if(s.nextSibling){ return this.select(s.nextSibling); }else if(s.parentNode){ var newS = null; s.parentNode.bubble(function(){ if(this.nextSibling){ newS = this.getOwnerTree().selModel.select(this.nextSibling); return false; } }); return newS; } return null; }, onKeyDown : function(e){ var s = this.selNode || this.lastSelNode; // undesirable, but required var sm = this; if(!s){ return; } var k = e.getKey(); switch(k){ case e.DOWN: e.stopEvent(); this.selectNext(); break; case e.UP: e.stopEvent(); this.selectPrevious(); break; case e.RIGHT: e.preventDefault(); if(s.hasChildNodes()){ if(!s.isExpanded()){ s.expand(); }else if(s.firstChild){ this.select(s.firstChild, e); } } break; case e.LEFT: e.preventDefault(); if(s.hasChildNodes() && s.isExpanded()){ s.collapse(); }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){ this.select(s.parentNode, e); } break; }; } });
JavaScript
/** * @class Ext.tree.AsyncTreeNode * @extends Ext.tree.TreeNode * @cfg {TreeLoader} loader 加载这个节点使用的TreeLoader(默认是加载该节点所在树的TreeLoader) A TreeLoader to be used by this node (defaults to the loader defined on the tree) * @constructor * @param {Object/String} attributes 该节点的属性/配置对象,也可以是带有文本的一个字符串。 The attributes/config for the node or just a string with the text for the node */ Ext.tree.AsyncTreeNode = function(config){ this.loaded = false; this.loading = false; Ext.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments); /** * @event beforeload * 节点加载之前触发,返回false则取消。 * @param {Node} this This node */ this.addEvents('beforeload', 'load'); /** * @event load * 此节点加载完毕后触发 * @param {Node} this This node */ /** * 节点使用的Loader(默认使用tree定义的loader) * @property loader */ }; Ext.extend(Ext.tree.AsyncTreeNode, Ext.tree.TreeNode, { expand : function(deep, anim, callback){ if(this.loading){ // if an async load is already running, waiting til it's done var timer; var f = function(){ if(!this.loading){ // done loading clearInterval(timer); this.expand(deep, anim, callback); } }.createDelegate(this); timer = setInterval(f, 200); return; } if(!this.loaded){ if(this.fireEvent("beforeload", this) === false){ return; } this.loading = true; this.ui.beforeLoad(this); var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader(); if(loader){ loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback])); return; } } Ext.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback); }, /** * 如果该节点被加载过则返回true。 * Returns true if this node has been loaded * @return {Boolean} */ isLoading : function(){ return this.loading; }, loadComplete : function(deep, anim, callback){ this.loading = false; this.loaded = true; this.ui.afterLoad(this); this.fireEvent("load", this); this.expand(deep, anim, callback); }, /** * 如果该节点被加载过则返回true。 * Returns true if this node has been loaded * @return {Boolean} */ isLoaded : function(){ return this.loaded; }, hasChildNodes : function(){ if(!this.isLeaf() && !this.loaded){ return true; }else{ return Ext.tree.AsyncTreeNode.superclass.hasChildNodes.call(this); } }, /** * 重新加载该节点。Trigger a reload for this node * @param {Function} callback */ reload : function(callback){ this.collapse(false, false); while(this.firstChild){ this.removeChild(this.firstChild); } this.childrenRendered = false; this.loaded = false; if(this.isHiddenRoot()){ this.expanded = false; } this.expand(false, false, callback); } });
JavaScript
Ext.tree.TreeEventModel = function(tree){ this.tree = tree; this.tree.on('render', this.initEvents, this); } Ext.tree.TreeEventModel.prototype = { initEvents : function(){ var el = this.tree.getTreeEl(); el.on('click', this.delegateClick, this); el.on('mouseover', this.delegateOver, this); el.on('mouseout', this.delegateOut, this); el.on('dblclick', this.delegateDblClick, this); el.on('contextmenu', this.delegateContextMenu, this); }, getNode : function(e){ var t; if(t = e.getTarget('.x-tree-node-el', 10)){ var id = Ext.fly(t, '_treeEvents').getAttributeNS('ext', 'tree-node-id'); if(id){ return this.tree.getNodeById(id); } } return null; }, getNodeTarget : function(e){ var t = e.getTarget('.x-tree-node-icon', 1); if(!t){ t = e.getTarget('.x-tree-node-el', 6); } return t; }, delegateOut : function(e, t){ if(!this.beforeEvent(e)){ return; } t = this.getNodeTarget(e); if(t && !e.within(t, true)){ this.onNodeOut(e, this.getNode(e)); } }, delegateOver : function(e, t){ if(!this.beforeEvent(e)){ return; } t = this.getNodeTarget(e); if(t){ this.onNodeOver(e, this.getNode(e)); } }, delegateClick : function(e, t){ if(!this.beforeEvent(e)){ return; } if(e.getTarget('input[type=checkbox]', 1)){ this.onCheckboxClick(e, this.getNode(e)); } else if(e.getTarget('.x-tree-ec-icon', 1)){ this.onIconClick(e, this.getNode(e)); } else if(this.getNodeTarget(e)){ this.onNodeClick(e, this.getNode(e)); } }, delegateDblClick : function(e, t){ if(this.beforeEvent(e) && this.getNodeTarget(e)){ this.onNodeDblClick(e, this.getNode(e)); } }, delegateContextMenu : function(e, t){ if(this.beforeEvent(e) && this.getNodeTarget(e)){ this.onNodeContextMenu(e, this.getNode(e)); } }, onNodeClick : function(e, node){ node.ui.onClick(e); }, onNodeOver : function(e, node){ node.ui.onOver(e); }, onNodeOut : function(e, node){ node.ui.onOut(e); }, onIconClick : function(e, node){ node.ui.ecClick(e); }, onCheckboxClick : function(e, node){ node.ui.onCheckChange(e); }, onNodeDblClick : function(e, node){ node.ui.onDblClick(e); }, onNodeContextMenu : function(e, node){ node.ui.onContextMenu(e); }, beforeEvent : function(e){ if(this.disabled){ e.stopEvent(); return false; } return true; }, disable: function(){ this.disabled = true; }, enable: function(){ this.disabled = false; } };
JavaScript
/** * @class Ext.tree.TreeLoader * @extends Ext.util.Observable * 树加载器(TreeLoader)的目的是从URL延迟加载树节点{@link Ext.tree.TreeNode}的子节点。 * 返回值必须是以树格式的javascript数组。 * 例如: * <pre><code> [{ id: 1, text: 'A leaf Node', leaf: true },{ id: 2, text: 'A folder Node', children: [{ id: 3, text: 'A child Node', leaf: true }] }] </code></pre> * <br><br> * 向服务端发送请求后,只有当展开时才会读取子节点信息。 * 需要取值的节点id被传到服务端并用于产生正确子节点。 * <br><br> * 当需要传递更多的参数时,可以把一个事件句柄邦定在"beforeload"事件上, * 然后把数据放到TreeLoader的baseParams属性上: * <pre><code> myTreeLoader.on("beforeload", function(treeLoader, node) { this.baseParams.category = node.attributes.category; }, this); </code></pre> * 如上代码,将会传递一个该节点的,名为"category"的参数到服务端上。 * @constructor * 创建一个Treeloader * @param {Object} config 该Treeloader的配置属性。 */ Ext.tree.TreeLoader = function(config){ this.baseParams = {}; Ext.apply(this, config); this.addEvents( /** * @event beforeload * 在为子节点获取JSON文本进行网路请求之前触发。 * @param {Object} 本TreeLoader对象 * @param {Object} node 已加载好的{@link Ext.tree.TreeNode}的对象 * @param {Object} callback 在{@link #load}调用中指定的回调函数 */ "beforeload", /** * @event load * 当节点加载成功时触发。 * @param {Object} 本TreeLoader对象 * @param {Object} node 已加载好的{@link Ext.tree.TreeNode}的对象 * @param {Object} response 服务器响应的数据对象 */ "load", /** * @event loadexception * 当网路连接失败时触发 * @param {Object} 本TreeLoader对象 * @param {Object} node 已加载好的{@link Ext.tree.TreeNode}的对象 * @param {Object} response 服务器响应的数据对象 */ "loadexception" ); Ext.tree.TreeLoader.superclass.constructor.call(this); }; Ext.extend(Ext.tree.TreeLoader, Ext.util.Observable, { /** * @cfg {String} dataUrl 进行请求的URL。 */ /** * @cfg {String} requestMethod 下载数据的HTTP请求方法(默认{@link Ext.Ajax#method}的值)。 */ /** * @cfg {String} url 相当于{@link #dataUrl}. */ /** * @cfg {Boolean} preloadChildren 若为true,则loader在节点第一次访问时加载"children"的属性。 */ /** * @cfg {Object} baseParams (可选) 一个分别对每个节点进行参数传递的集合对象。 */ /** * @cfg {Object} baseAttrs (可选) 一个对所有节点进行参数传递的集合对象。如果已经传递这个参数了,则他们优先。 */ /** * @cfg {Object} uiProviders (可选) 一个针对制定节点 {@link Ext.tree.TreeNodeUI} 进行参数传递的集合对象。 * 如果传入了该<i>uiProvider</i>参数,返回string而非TreeNodeUI对象 */ uiProviders : {}, /** * @cfg {Boolean} clearOnLoad (可选) 默认为true。 在读取数据前移除已存在的节点。 */ clearOnLoad : true, /** * 从URL中读取树节点 {@link Ext.tree.TreeNode}。 * 本函数在节点展开时自动调用,但也可以被用于reload节点。(或是在{@link #clearOnLoad}属性为false时增加新节点) * @param {Ext.tree.TreeNode} node * @param {Function} callback */ load : function(node, callback){ if(this.clearOnLoad){ while(node.firstChild){ node.removeChild(node.firstChild); } } if(this.doPreload(node)){ // preloaded json children if(typeof callback == "function"){ callback(); } }else if(this.dataUrl||this.url){ this.requestData(node, callback); } }, doPreload : function(node){ if(node.attributes.children){ if(node.childNodes.length < 1){ // preloaded? var cs = node.attributes.children; node.beginUpdate(); for(var i = 0, len = cs.length; i < len; i++){ var cn = node.appendChild(this.createNode(cs[i])); if(this.preloadChildren){ this.doPreload(cn); } } node.endUpdate(); } return true; }else { return false; } }, getParams: function(node){ var buf = [], bp = this.baseParams; for(var key in bp){ if(typeof bp[key] != "function"){ buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&"); } } buf.push("node=", encodeURIComponent(node.id)); return buf.join(""); }, requestData : function(node, callback){ if(this.fireEvent("beforeload", this, node, callback) !== false){ this.transId = Ext.Ajax.request({ method:this.requestMethod, url: this.dataUrl||this.url, success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {callback: callback, node: node}, params: this.getParams(node) }); }else{ // if the load is cancelled, make sure we notify // the node that we are done if(typeof callback == "function"){ callback(); } } }, isLoading : function(){ return this.transId ? true : false; }, abort : function(){ if(this.isLoading()){ Ext.Ajax.abort(this.transId); } }, /** * 自定义节点覆盖此方法 */ createNode : function(attr){ // apply baseAttrs, nice idea Corey! if(this.baseAttrs){ Ext.applyIf(attr, this.baseAttrs); } if(this.applyLoader !== false){ attr.loader = this; } if(typeof attr.uiProvider == 'string'){ attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider); } return(attr.leaf ? new Ext.tree.TreeNode(attr) : new Ext.tree.AsyncTreeNode(attr)); }, processResponse : function(response, node, callback){ var json = response.responseText; try { var o = eval("("+json+")"); node.beginUpdate(); for(var i = 0, len = o.length; i < len; i++){ var n = this.createNode(o[i]); if(n){ node.appendChild(n); } } node.endUpdate(); if(typeof callback == "function"){ callback(this, node); } }catch(e){ this.handleFailure(response); } }, handleResponse : function(response){ this.transId = false; var a = response.argument; this.processResponse(response, a.node, a.callback); this.fireEvent("load", this, a.node, response); }, handleFailure : function(response){ this.transId = false; var a = response.argument; this.fireEvent("loadexception", this, a.node, response); if(typeof a.callback == "function"){ a.callback(this, a.node); } } });
JavaScript
/** * @class Ext.tree.TreeNode * @extends Ext.data.Node * @cfg {String} text 该节点所显示的文本。The text for this node * @cfg {Boolean} expanded 如果为"true",该节点被展开。true to start the node expanded * @cfg {Boolean} allowDrag 如果dd为on时,设置为fals将使得该节点不能拖拽。False to make this node undraggable if {@link #draggable} = true (defaults to true) * @cfg {Boolean} allowDrop 为false时该节点不能将拖拽的对象放在该节点下。False if this node cannot have child nodes dropped on it (defaults to true) * @cfg {Boolean} disabled 为true该节点被禁止。true to start the node disabled * @cfg {String} icon 设置该节点上图标的路径.这种方式是首选的,比使用cls或iconCls属性和为这个图标加一个CSS的background-image都好。 The path to an icon for the node. The preferred way to do this * is to use the cls or iconCls attributes and add the icon via a CSS background image. * @cfg {String} cls 为该节点设置css样式类。A css class to be added to the node * @cfg {String} iconCls 为该节点上的图标元素应用背景。 A css class to be added to the nodes icon element for applying css background images * @cfg {String} href 设置该节点url连接(默认是#)。 URL of the link used for the node (defaults to #) * @cfg {String} hrefTarget 设置该连接应用到那个frame。 target frame for the link * @cfg {Boolean} hidden True to render hidden. (Defaults to false). * @cfg {String} qtip 该节点设置用于提示的文本。An Ext QuickTip for the node * @cfg {Boolean} expandable If set to true, the node will always show a plus/minus icon, even when empty * @cfg {String} qtipCfg 为该节点设置QuickTip类(用于替换qtip属性)。An Ext QuickTip config for the node (used instead of qtip) * @cfg {Boolean} singleClickExpand 为true时当节点被单击时展开。 True for single click expand on this node * @cfg {Function} uiProvider 该节点所使用的UI类(默认时Ext.tree.TreeNodeUI)。 A UI <b>class</b> to use for this node (defaults to Ext.tree.TreeNodeUI) * @cfg {Boolean} checked 为true将为该节点添加checkbox选择框,为false将不添加(默认为undefined是不添加checkbox的)。True to render a checked checkbox for this node, false to render an unchecked checkbox * (defaults to undefined with no checkbox rendered) * @cfg {Boolean} draggable True to make this node draggable (defaults to false) * @cfg {Boolean} isTarget False to not allow this node to act as a drop target (defaults to true) * @cfg {Boolean} allowChildren False to not allow this node to have child nodes (defaults to true) * @cfg {Boolean} editable False to not allow this node to be edited by an (@link Ext.tree.TreeEditor} (defaults to true) * @constructor * @param {Object/String} attributes 该节点的属性/配置对象,也可以是带有文本的一个字符串。The attributes/config for the node or just a string with the text for the node */ Ext.tree.TreeNode = function(attributes){ attributes = attributes || {}; if(typeof attributes == "string"){ attributes = {text: attributes}; } this.childrenRendered = false; this.rendered = false; Ext.tree.TreeNode.superclass.constructor.call(this, attributes); this.expanded = attributes.expanded === true; this.isTarget = attributes.isTarget !== false; this.draggable = attributes.draggable !== false && attributes.allowDrag !== false; this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false; /** * 只读属性,该节点所显示的文本.可以用setText方法改变。 * Read-only. The text for this node. To change it use setText(). * @type String */ this.text = attributes.text; /** * 如果该节点为disabled那为true。 * True if this node is disabled. * @type Boolean */ this.disabled = attributes.disabled === true; /** * True if this node is hidden. * @type Boolean */ this.hidden = attributes.hidden === true; this.addEvents( /** * @event textchange * 当这个节点的显示文本被改变时触发。 * Fires when the text for this node is changed * @param {Node} this 该节点。This node * @param {String} text 新的文本。The new text * @param {String} oldText 以前的文本。The old text */ "textchange", /** * @event beforeexpand * 当该节点被展开之前触发,返回false将取消事件。 * Fires before this node is expanded, return false to cancel. * @param {Node} this 该节点。This node * @param {Boolean} deep 该节点当前是否也展开所有子节点的状态。 * @param {Boolean} anim 该节点当前是否启用动画效果的状态。 */ "beforeexpand", /** * @event beforecollapse * 当该节点被收回之前触发,返回false将取消事件。 * Fires before this node is collapsed, return false to cancel. * @param {Node} this This node * @param {Boolean} deep 该节点当前是否也展开所有子节点的状态。 * @param {Boolean} anim 该节点当前是否启用动画效果的状态。 */ "beforecollapse", /** * @event expand * 当该节点被展开时触发。 * Fires when this node is expanded * @param {Node} this 该节点。This node */ "expand", /** * @event disabledchange * 当该节点的disabled状态被改变时触发。 * Fires when the disabled status of this node changes * @param {Node} this 该节点。This node * @param {Boolean} disabled 该节点的disabled属性的状态。 */ "disabledchange", /** * @event collapse * 当该节点被收回时触发。 * Fires when this node is collapsed * @param {Node} this 该节点。This node */ "collapse", /** * @event beforeclick * 单击处理之前触发,返回false将停止默认的动作。 * Fires before click processing. Return false to cancel the default action. * @param {Node} this 该节点。This node * @param {Ext.EventObject} e 事件对象。The event object */ "beforeclick", /** * @event click * 当节点被点击时触发。 * Fires when this node is clicked * @param {Node} this 该节点。This node * @param {Ext.EventObject} e 事件对象。The event object */ "click", /** * @event checkchange * 当节点的checkbox的状态被改变时触发。 * Fires when a node with a checkbox's checked property changes * @param {Node} this 该节点。 This node * @param {Boolean} checked 当前节点checkbox的状态。 */ "checkchange", /** * @event dblclick * 当节点被双点击时触发。 * Fires when this node is double clicked * @param {Node} this 该节点。This node * @param {Ext.EventObject} e 事件对象。The event object */ "dblclick", /** * @event contextmenu * Fires when this node is right clicked * @param {Node} this This node * @param {Ext.EventObject} e The event object */ "contextmenu", /** * @event beforechildrenrendered * 当节点的子节点被渲染之前触发。 * Fires right before the child nodes for this node are rendered * @param {Node} this 该节点。This node */ "beforechildrenrendered" ); var uiClass = this.attributes.uiProvider || this.defaultUI || Ext.tree.TreeNodeUI; /** * 这个节点的UI。 * Read-only. The UI for this node * @type TreeNodeUI */ this.ui = new uiClass(this); }; Ext.extend(Ext.tree.TreeNode, Ext.data.Node, { preventHScroll: true, /** * 如果该节点被展开则返回true。 * Returns true if this node is expanded * @return {Boolean} */ isExpanded : function(){ return this.expanded; }, /** * 返回该节点的UI对象。 * Returns the UI object for this node. * @return {TreeNodeUI} The object which is providing the user interface for this tree * node. Unless otherwise specified in the {@link #uiProvider}, this will be an instance * of {@link Ext.tree.TreeNodeUI} */ getUI : function(){ return this.ui; }, getLoader : function(){ var owner; return this.loader || ((owner = this.getOwnerTree()) && owner.loader ? owner.loader : new Ext.tree.TreeLoader()); }, // private override setFirstChild : function(node){ var of = this.firstChild; Ext.tree.TreeNode.superclass.setFirstChild.call(this, node); if(this.childrenRendered && of && node != of){ of.renderIndent(true, true); } if(this.rendered){ this.renderIndent(true, true); } }, // private override setLastChild : function(node){ var ol = this.lastChild; Ext.tree.TreeNode.superclass.setLastChild.call(this, node); if(this.childrenRendered && ol && node != ol){ ol.renderIndent(true, true); } if(this.rendered){ this.renderIndent(true, true); } }, // these methods are overridden to provide lazy rendering support // private override appendChild : function(n){ if(!n.render && !Ext.isArray(n)){ n = this.getLoader().createNode(n); } var node = Ext.tree.TreeNode.superclass.appendChild.call(this, n); if(node && this.childrenRendered){ node.render(); } this.ui.updateExpandIcon(); return node; }, // private override removeChild : function(node){ this.ownerTree.getSelectionModel().unselect(node); Ext.tree.TreeNode.superclass.removeChild.apply(this, arguments); // if it's been rendered remove dom node if(this.childrenRendered){ node.ui.remove(); } if(this.childNodes.length < 1){ this.collapse(false, false); }else{ this.ui.updateExpandIcon(); } if(!this.firstChild && !this.isHiddenRoot()) { this.childrenRendered = false; } return node; }, // private override insertBefore : function(node, refNode){ if(!node.render){ node = this.getLoader().createNode(node); } var newNode = Ext.tree.TreeNode.superclass.insertBefore.call(this, node, refNode); if(newNode && refNode && this.childrenRendered){ node.render(); } this.ui.updateExpandIcon(); return newNode; }, /** * 设置该节点的显示文本。 * Sets the text for this node * @param {String} text */ setText : function(text){ var oldText = this.text; this.text = text; this.attributes.text = text; if(this.rendered){ // event without subscribing this.ui.onTextChange(this, text, oldText); } this.fireEvent("textchange", this, text, oldText); }, /** * 选取该节点所在树选择的选区模型。 * Triggers selection of this node */ select : function(){ this.getOwnerTree().getSelectionModel().select(this); }, /** * 取消选择该节点所在树的选区模型。 * Triggers deselection of this node */ unselect : function(){ this.getOwnerTree().getSelectionModel().unselect(this); }, /** * 如果该节点被选中则返回true。 * Returns true if this node is selected * @return {Boolean} */ isSelected : function(){ return this.getOwnerTree().getSelectionModel().isSelected(this); }, /** * 展开这个节点。 * Expand this node. * @param {Boolean} deep 如果为true展开所有的子节点。(optional)True to expand all children as well * @param {Boolean} anim 如果为false不启用动画效果。(optional)false to cancel the default animation * @param {Function} callback 当展开完成时调用这个callback(不等待所有子节点都展开完成后才执行)。调用带有一个参数,就是该节点。 * (optional)A callback to be called when expanding this node completes (does not wait for deep expand to complete). * Called with 1 parameter, this node. */ expand : function(deep, anim, callback){ if(!this.expanded){ if(this.fireEvent("beforeexpand", this, deep, anim) === false){ return; } if(!this.childrenRendered){ this.renderChildren(); } this.expanded = true; if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){ this.ui.animExpand(function(){ this.fireEvent("expand", this); if(typeof callback == "function"){ callback(this); } if(deep === true){ this.expandChildNodes(true); } }.createDelegate(this)); return; }else{ this.ui.expand(); this.fireEvent("expand", this); if(typeof callback == "function"){ callback(this); } } }else{ if(typeof callback == "function"){ callback(this); } } if(deep === true){ this.expandChildNodes(true); } }, isHiddenRoot : function(){ return this.isRoot && !this.getOwnerTree().rootVisible; }, /** * 展开该节点。 * Collapse this node. * @param {Boolean} deep 为true则也展开所有的子结点。(optional)True to collapse all children as well * @param {Boolean} anim 如果为false不启用动画效果。(optional)false to cancel the default animation */ collapse : function(deep, anim){ if(this.expanded && !this.isHiddenRoot()){ if(this.fireEvent("beforecollapse", this, deep, anim) === false){ return; } this.expanded = false; if((this.getOwnerTree().animate && anim !== false) || anim){ this.ui.animCollapse(function(){ this.fireEvent("collapse", this); if(deep === true){ this.collapseChildNodes(true); } }.createDelegate(this)); return; }else{ this.ui.collapse(); this.fireEvent("collapse", this); } } if(deep === true){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].collapse(true, false); } } }, // private delayedExpand : function(delay){ if(!this.expandProcId){ this.expandProcId = this.expand.defer(delay, this); } }, // private cancelExpand : function(){ if(this.expandProcId){ clearTimeout(this.expandProcId); } this.expandProcId = false; }, /** * 轮回该节点的展开/收回状态。 * Toggles expanded/collapsed state of the node */ toggle : function(){ if(this.expanded){ this.collapse(); }else{ this.expand(); } }, /** * 确保所有的父节点都被展开了(没理解这个函数的作用)。 * Ensures all parent nodes are expanded, and if necessary, scrolls the node into view. * @param {Function} callback (optional) A function to call when the node has been made visible. */ ensureVisible : function(callback){ var tree = this.getOwnerTree(); tree.expandPath(this.parentNode ? this.parentNode.getPath() : this.getPath(), false, function(){ var node = tree.getNodeById(this.id); // Somehow if we don't do this, we lose changes that happened to node in the meantime tree.getTreeEl().scrollChildIntoView(node.ui.anchor); Ext.callback(callback); }.createDelegate(this)); }, /** * 展开所有的子节点。 * Expand all child nodes * @param {Boolean} deep 如果为true,子节点如果还有子节点也将被展开。(optional)true if the child nodes should also expand their child nodes */ expandChildNodes : function(deep){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].expand(deep); } }, /** * 收回所有的子节点。 * Collapse all child nodes * @param {Boolean} deep 如果为true,子节点如果还有子节点也将被收回。(optional)true if the child nodes should also collapse their child nodes */ collapseChildNodes : function(deep){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].collapse(deep); } }, /** * 禁用这个节点。 * Disables this node */ disable : function(){ this.disabled = true; this.unselect(); if(this.rendered && this.ui.onDisableChange){ // event without subscribing this.ui.onDisableChange(this, true); } this.fireEvent("disabledchange", this, true); }, /** * 启用该节点。 * Enables this node */ enable : function(){ this.disabled = false; if(this.rendered && this.ui.onDisableChange){ // event without subscribing this.ui.onDisableChange(this, false); } this.fireEvent("disabledchange", this, false); }, // private renderChildren : function(suppressEvent){ if(suppressEvent !== false){ this.fireEvent("beforechildrenrendered", this); } var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].render(true); } this.childrenRendered = true; }, // private sort : function(fn, scope){ Ext.tree.TreeNode.superclass.sort.apply(this, arguments); if(this.childrenRendered){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].render(true); } } }, // private render : function(bulkRender){ this.ui.render(bulkRender); if(!this.rendered){ // make sure it is registered this.getOwnerTree().registerNode(this); this.rendered = true; if(this.expanded){ this.expanded = false; this.expand(false, false); } } }, // private renderIndent : function(deep, refresh){ if(refresh){ this.ui.childIndent = null; } this.ui.renderIndent(); if(deep === true && this.childrenRendered){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].renderIndent(true, refresh); } } }, beginUpdate : function(){ this.childrenRendered = false; }, endUpdate : function(){ if(this.expanded && this.rendered){ this.renderChildren(); } }, destroy : function(){ if(this.childNodes){ for(var i = 0,l = this.childNodes.length; i < l; i++){ this.childNodes[i].destroy(); } this.childNodes = null; } if(this.ui.destroy){ this.ui.destroy(); } }, // private onIdChange: function(id){ this.ui.onIdChange(id); } }); Ext.tree.TreePanel.nodeTypes.node = Ext.tree.TreeNode;
JavaScript
/** /** * @class Ext.tree.TreeSorter * 提供一个可排序节点的Tree面板 * @cfg {Boolean} folderSort 设置为真时则同级的叶节点排在 * @cfg {String} property 用节点上的那个属性排序(默认是text属性) * @cfg {String} dir 排序的方式(升序或降序)(默认时升序) * @cfg {String} leafAttr 叶子节点在目录排序中的属性(defaults to "leaf") * @cfg {Boolean} caseSensitive 排序时大小写敏感(默认时false) * @cfg {Function} sortType 在排序之前可以写一个强转函数用来转换节点的值 * @constructor * @param {TreePanel} tree * @param {Object} config */ Ext.tree.TreeSorter = function(tree, config){ Ext.apply(this, config); tree.on("beforechildrenrendered", this.doSort, this); tree.on("append", this.updateSort, this); tree.on("insert", this.updateSort, this); var dsc = this.dir && this.dir.toLowerCase() == "desc"; var p = this.property || "text"; var sortType = this.sortType; var fs = this.folderSort; var cs = this.caseSensitive === true; var leafAttr = this.leafAttr || 'leaf'; this.sortFn = function(n1, n2){ if(fs){ if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){ return 1; } if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){ return -1; } } var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase()); var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase()); if(v1 < v2){ return dsc ? +1 : -1; }else if(v1 > v2){ return dsc ? -1 : +1; }else{ return 0; } }; }; Ext.tree.TreeSorter.prototype = { doSort : function(node){ node.sort(this.sortFn); }, compareNodes : function(n1, n2){ return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1); }, updateSort : function(tree, node){ if(node.childrenRendered){ this.doSort.defer(1, this, [node]); } } };
JavaScript
/** * @class Ext.tree.RootTreeNodeUI * This class provides the default UI implementation for <b>root</b> Ext TreeNodes. * The RootTreeNode UI implementation allows customizing the appearance of the root tree node.<br> * <p> * If you are customizing the Tree's user interface, you * may need to extend this class, but you should never need to instantiate this class.<br> */ Ext.tree.RootTreeNodeUI = Ext.extend(Ext.tree.TreeNodeUI, { // private render : function(){ if(!this.rendered){ var targetNode = this.node.ownerTree.innerCt.dom; this.node.expanded = true; targetNode.innerHTML = '<div class="x-tree-root-node"></div>'; this.wrap = this.ctNode = targetNode.firstChild; } }, collapse : Ext.emptyFn, expand : Ext.emptyFn });
JavaScript
/** * @class Ext.tree.TreeDragZone * @extends Ext.dd.DragZone * @constructor * @param {String/HTMLElement/Element} tree 要进行拖动的{@link Ext.tree.TreePanel} * @param {Object} config 配置项对象 */ if(Ext.dd.DragZone){ Ext.tree.TreeDragZone = function(tree, config){ Ext.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config); /** * The TreePanel for this drag zone * @type Ext.tree.TreePanel * @property */ this.tree = tree; }; Ext.extend(Ext.tree.TreeDragZone, Ext.dd.DragZone, { /** * @cfg {String} ddGroup * 该对象隶属于组的名称。如果已指定组,那该对象只会与同组下其他拖放成员相交互(默认为“TreeDD”)。 */ ddGroup : "TreeDD", // private onBeforeDrag : function(data, e){ var n = data.node; return n && n.draggable && !n.disabled; }, // private onInitDrag : function(e){ var data = this.dragData; this.tree.getSelectionModel().select(data.node); this.tree.eventModel.disable(); this.proxy.update(""); data.node.ui.appendDDGhost(this.proxy.ghost.dom); this.tree.fireEvent("startdrag", this.tree, data.node, e); }, // private getRepairXY : function(e, data){ return data.node.ui.getDDRepairXY(); }, // private onEndDrag : function(data, e){ this.tree.eventModel.enable.defer(100, this.tree.eventModel); this.tree.fireEvent("enddrag", this.tree, data.node, e); }, // private onValidDrop : function(dd, e, id){ this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e); this.hideProxy(); }, // private beforeInvalidDrop : function(e, id){ // this scrolls the original position back into view var sm = this.tree.getSelectionModel(); sm.clearSelections(); sm.select(this.dragData.node); } }); }
JavaScript
/** * @class Ext.ColorPalette * @extends Ext.Component * 选择颜色使用的简单的调色板。调色板可在任意窗口内渲染。<br /> * 这里是一个典型用例: * <pre><code> var cp = new Ext.ColorPalette({value:'993300'}); // 初始化时选中的颜色 cp.render('my-div'); cp.on('select', function(palette, selColor){ // 用 selColor 来做此事情 }); </code></pre> * @constructor * 创建一个 ColorPalette 对象 * @param {Object} config 配置项对象 */ Ext.ColorPalette = function(config){ Ext.ColorPalette.superclass.constructor.call(this, config); this.addEvents( /** * @event select * 颜色被选取时触发 * @param {ColorPalette} this * @param {String} color 6位16进制颜色编码(没有 # 符号) */ 'select' ); if(this.handler){ this.on("select", this.handler, this.scope, true); } }; Ext.extend(Ext.ColorPalette, Ext.Component, { /** * @cfg {String} itemCls * 容器元素应用的 CSS 样式类(默认为 "x-color-palette") */ itemCls : "x-color-palette", /** * @cfg {String} value * 初始化时高亮的颜色(必须为不包含 # 符号的6位16进制颜色编码)。注意16进制编码是区分大小写的。 */ value : null, clickEvent:'click', // private ctype: "Ext.ColorPalette", /** * @cfg {Boolean} allowReselect 如果值为 true, 则在触发 select 事件时重选已经选择的颜色 */ allowReselect : false, /** * <p>一个由6位16进制颜色编码组成的数组(不包含 # 符号)。此数组可以包含任意个数颜色, * 且每个16进制编码必须是唯一的。调色板的宽度可以通过设置样式表中的 'x-color-palette' 类的 width 属性来控制(或者指定一个定制类), * 因此你可以通过调整颜色的个数和调色板的宽度来使调色板保持对称。</p> * <p>你可以根据需要覆写单个的颜色:</p> * <pre><code> var cp = new Ext.ColorPalette(); cp.colors[0] = "FF0000"; // 把第一个选框换成红色 </code></pre> 或者自己提供一个定制的数组来实现完全控制: <pre><code> var cp = new Ext.ColorPalette(); cp.colors = ["000000", "993300", "333300"]; </code></pre> * @type Array */ colors : [ "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333", "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080", "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696", "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0", "FF99CC", "FFCC99", "FFFF99", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF" ], // private onRender : function(container, position){ var t = new Ext.XTemplate( '<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on">&#160;</span></em></a></tpl>' ); var el = document.createElement("div"); el.className = this.itemCls; t.overwrite(el, this.colors); container.dom.insertBefore(el, position); this.el = Ext.get(el); this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"}); if(this.clickEvent != 'click'){ this.el.on('click', Ext.emptyFn, this, {delegate: "a", preventDefault:true}); } }, // private afterRender : function(){ Ext.ColorPalette.superclass.afterRender.call(this); if(this.value){ var s = this.value; this.value = null; this.select(s); } }, // private handleClick : function(e, t){ e.preventDefault(); if(!this.disabled){ var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1]; this.select(c.toUpperCase()); } }, /** * 在调色板中选择指定的颜色(触发 select 事件) * @param {String} color 6位16进制颜色编码(如果含有 # 符号则自动舍去) */ select : function(color){ color = color.replace("#", ""); if(color != this.value || this.allowReselect){ var el = this.el; if(this.value){ el.child("a.color-"+this.value).removeClass("x-color-palette-sel"); } el.child("a.color-"+color).addClass("x-color-palette-sel"); this.value = color; this.fireEvent("select", this, color); } } }); Ext.reg('colorpalette', Ext.ColorPalette);
JavaScript
/** * @class Ext.Tip * @extends Ext.Panel * 这是 {@link Ext.QuickTip} 和 {@link Ext.Tooltip} 对象的基类,提供了所有基于提示的类所必须的基础布局和定位。 * 这个类可以直接用于简单的、静态定位、需要编程显示的提示,还可以提供实现自定义扩展的提示。 * @constructor * 创建一个 Tip 对象 * @param {Object} config 配置选项对象 */ Ext.Tip = Ext.extend(Ext.Panel, { /** * @cfg {Boolean} closable 值为 true 则在工具提示的头部渲染一个关闭按钮(默认为 false)。 */ /** * @cfg {Number} minWidth 以像素为单位表示的提示的最小宽度(默认为 40)。 */ minWidth : 40, /** * @cfg {Number} maxWidth 以像素为单位表示的提示的最大宽度(默认为 300)。 */ maxWidth : 300, /** * @cfg {Boolean/String} shadow 值为 true 或者 "sides" 时展现默认效果,值为 "frame" 时则在4个方向展现阴影,值为 "drop" 时则在右下角展现阴影(默认为 "sides")。 */ shadow : "sides", /** * @cfg {String} defaultAlign <b>试验性的</b>。默认为 {@link Ext.Element#alignTo} 锚点定位值,用来让该提示定位到它所属元素的关联位置(默认为 "tl-bl?")。 */ defaultAlign : "tl-bl?", autoRender: true, quickShowInterval : 250, // private panel overrides frame:true, hidden:true, baseCls: 'x-tip', floating:{shadow:true,shim:true,useDisplay:true,constrain:false}, autoHeight:true, // private initComponent : function(){ Ext.Tip.superclass.initComponent.call(this); if(this.closable && !this.title){ this.elements += ',header'; } }, // private afterRender : function(){ Ext.Tip.superclass.afterRender.call(this); if(this.closable){ this.addTool({ id: 'close', handler: this.hide, scope: this }); } }, /** * 在指定的 XY 坐标处显示该提示。用法示例: * <pre><code> // 在 x:50、y:100 处显示提示 tip.showAt([50,100]); </code></pre> * @param {Array} xy 一个由 x、y 坐标组成的数组 */ showAt : function(xy){ Ext.Tip.superclass.show.call(this); if(this.measureWidth !== false && (!this.initialConfig || typeof this.initialConfig.width != 'number')){ var bw = this.body.getTextWidth(); if(this.title){ bw = Math.max(bw, this.header.child('span')。getTextWidth(this.title)); } bw += this.getFrameWidth() + (this.closable ? 20 : 0) + this.body.getPadding("lr"); this.setWidth(bw.constrain(this.minWidth, this.maxWidth)); } if(this.constrainPosition){ xy = this.el.adjustForConstraints(xy); } this.setPagePosition(xy[0], xy[1]); }, /** * <b>试验性的</b>。根据标准的 {@link Ext.Element#alignTo} 锚点定位值在另一个元素的关联位置上显示该提示。用法示例: * <pre><code> // 在默认位置显示该提示 ('tl-br?') tip.showBy('my-el'); // 将该提示的左上角对齐到元素的右上角 tip.showBy('my-el', 'tl-tr'); </code></pre> * @param {Mixed} el 一个 HTMLElement、Ext.Element 或者要对齐的目标元素的 ID 文本 * @param {String} position (可选)一个有效的 {@link Ext.Element#alignTo} 锚点定位值(默认为 'tl-br?' 或者 {@link #defaultAlign} 中指定的值,如果设置过该值的话)。 */ showBy : function(el, pos){ if(!this.rendered){ this.render(Ext.getBody()); } this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign)); }, initDraggable : function(){ this.dd = new Ext.Tip.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable); this.header.addClass('x-tip-draggable'); } }); // private - custom Tip DD implementation Ext.Tip.DD = function(tip, config){ Ext.apply(this, config); this.tip = tip; Ext.Tip.DD.superclass.constructor.call(this, tip.el.id, 'WindowDD-'+tip.id); this.setHandleElId(tip.header.id); this.scroll = false; }; Ext.extend(Ext.Tip.DD, Ext.dd.DD, { moveOnly:true, scroll:false, headerOffsets:[100, 25], startDrag : function(){ this.tip.el.disableShadow(); }, endDrag : function(e){ this.tip.el.enableShadow(true); } });
JavaScript
/** * @class Ext.QuickTip * @extends Ext.ToolTip * 一个专门的tooltip类 for tooltips that can be specified in markup and automatically managed by the 全局 * {@link Ext.QuickTips} instance. 更多信息请参看QuickTips类 header for 附带的例子和详细用法. * @constructor * 创建一个新提示 * @param {Object} config 配置选项 */ Ext.QuickTip = Ext.extend(Ext.ToolTip, { /** * @cfg {Mixed} target 目标HTML元素,与这个quicktip相关联的Ext.Element或id (默认为document). */ /** * @cfg {Boolean} interceptTitles为True表示如果DOM的title值可用时则使用此值 (默认为false). */ interceptTitles : false, // 私有 tagConfig : { namespace : "ext", attribute : "qtip", width : "qwidth", target : "target", title : "qtitle", hide : "hide", cls : "qclass", align : "qalign" }, // 私有 initComponent : function(){ this.target = this.target || Ext.getDoc(); this.targets = this.targets || {}; Ext.QuickTip.superclass.initComponent.call(this); }, /** * 配置一个新的quick tip实例并将其分配到一个目标元素.支持下列各项配置值 * (用法参见 {@link Ext.QuickTips} 类的header): * <div class="mdetail-params"><ul> * <li>autoHide</li> * <li>cls</li> * <li>dismissDelay (overrides the singleton value)</li> * <li>target (required)</li> * <li>text (required)</li> * <li>title</li> * <li>width</li></ul></div> * @param {Object} config 配置对象 */ register : function(config){ var cs = config instanceof Array ? config : arguments; for(var i = 0, len = cs.length; i < len; i++){ var c = cs[i]; var target = c.target; if(target){ if(target instanceof Array){ for(var j = 0, jlen = target.length; j < jlen; j++){ this.targets[Ext.id(target[j])] = c; } } else{ this.targets[Ext.id(target)] = c; } } } }, /** * 从元素中移除quick tip并且销毁它. * @param {String/HTMLElement/Element} el 将要被移除的quick tip的所属元素 */ unregister : function(el){ delete this.targets[Ext.id(el)]; }, // 私有 onTargetOver : function(e){ if(this.disabled){ return; } this.targetXY = e.getXY(); var t = e.getTarget(); if(!t || t.nodeType !== 1 || t == document || t == document.body){ return; } if(this.activeTarget && t == this.activeTarget.el){ this.clearTimer('hide'); this.show(); return; } if(t && this.targets[t.id]){ this.activeTarget = this.targets[t.id]; this.activeTarget.el = t; this.delayShow(); return; } var ttp, et = Ext.fly(t), cfg = this.tagConfig; var ns = cfg.namespace; if(this.interceptTitles && t.title){ ttp = t.title; t.qtip = ttp; t.removeAttribute("title"); e.preventDefault(); } else{ ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute); } if(ttp){ var autoHide = et.getAttributeNS(ns, cfg.hide); this.activeTarget = { el: t, text: ttp, width: et.getAttributeNS(ns, cfg.width), autoHide: autoHide != "user" && autoHide !== 'false', title: et.getAttributeNS(ns, cfg.title), cls: et.getAttributeNS(ns, cfg.cls), align: et.getAttributeNS(ns, cfg.align) }; this.delayShow(); } }, // 私有 onTargetOut : function(e){ this.clearTimer('show'); if(this.autoHide !== false){ this.delayHide(); } }, // 继承文档 showAt : function(xy){ var t = this.activeTarget; if(t){ if(!this.rendered){ this.render(Ext.getBody()); } if(t.width){ this.setWidth(t.width); this.measureWidth = false; } else{ this.measureWidth = true; } this.setTitle(t.title || ''); this.body.update(t.text); this.autoHide = t.autoHide; this.dismissDelay = t.dismissDelay || this.dismissDelay; if(this.lastCls){ this.el.removeClass(this.lastCls); delete this.lastCls; } if(t.cls){ this.el.addClass(t.cls); this.lastCls = t.cls; } if(t.align){ // TODO: this doesn't seem to work consistently xy = this.el.getAlignToXY(t.el, t.align); this.constrainPosition = false; } else{ this.constrainPosition = true; } } Ext.QuickTip.superclass.showAt.call(this, xy); }, // 继承文档 hide: function(){ delete this.activeTarget; Ext.QuickTip.superclass.hide.call(this); } });
JavaScript
/** * @class Ext.ToolTip * @extends Ext.Tip * 一个标准的快捷提示实现,用于悬浮在目标元素之上时出现的提示信息。 * @constructor * 建立快捷提示新对象 * @param {Object} config 配置项对象 */ Ext.ToolTip = Ext.extend(Ext.Tip, { /** * @cfg {Mixed} target HTMLElement目标元素,既可是Ext.Element或是与这个快捷提示相关联的id。 */ /** * @cfg {Boolean} autoHide * 值为 true 时在鼠标移出目标元素自动隐藏快捷提示(默认为 true)。与{@link #dismissDelay}协同生效(默认为true)。 * 若{@link closable},一个关闭的按钮会出现在快捷提示的开头。 */ /** * @cfg {Number} showDelay * 以毫秒表示的当鼠标进入目标元素后显示快捷提示的延迟时间(默认为 500) */ showDelay: 500, /** * @cfg {Number} hideDelay * 以毫秒表示的隐藏快捷提示的延迟时间。设置为0立即隐藏快捷提示。 */ hideDelay: 200, /** * @cfg {Number} dismissDelay * 以毫秒表示的隐藏快捷提示的延迟时间, 仅在 autoDismiss = true 时生效(默认为 5000)。要禁止隐藏,设置dismissDelay = 0 */ dismissDelay: 5000, /** * @cfg {Array} mouseOffset Tooltip显示时,距离鼠标位置一定的XY偏移(默认[15,18])。 */ mouseOffset: [15,18], /** * @cfg {Boolean} trackMouse 值为 true 时当鼠标经过目标对象时快捷提示将跟随鼠标移动(默认为 false) */ trackMouse : false, constrainPosition: true, // private initComponent: function(){ Ext.ToolTip.superclass.initComponent.call(this); this.lastActive = new Date(); this.initTarget(); }, // private initTarget : function(){ if(this.target){ this.target = Ext.get(this.target); this.target.on('mouseover', this.onTargetOver, this); this.target.on('mouseout', this.onTargetOut, this); this.target.on('mousemove', this.onMouseMove, this); } }, // private onMouseMove : function(e){ this.targetXY = e.getXY(); if(!this.hidden && this.trackMouse){ this.setPagePosition(this.getTargetXY()); } }, // private getTargetXY : function(){ return [this.targetXY[0]+this.mouseOffset[0], this.targetXY[1]+this.mouseOffset[1]]; }, // private onTargetOver : function(e){ if(this.disabled || e.within(this.target.dom, true)){ return; } this.clearTimer('hide'); this.targetXY = e.getXY(); this.delayShow(); }, // private delayShow : function(){ if(this.hidden && !this.showTimer){ if(this.lastActive.getElapsed() < this.quickShowInterval){ this.show(); }else{ this.showTimer = this.show.defer(this.showDelay, this); } }else if(!this.hidden && this.autoHide !== false){ this.show(); } }, // private onTargetOut : function(e){ if(this.disabled || e.within(this.target.dom, true)){ return; } this.clearTimer('show'); if(this.autoHide !== false){ this.delayHide(); } }, // private delayHide : function(){ if(!this.hidden && !this.hideTimer){ this.hideTimer = this.hide.defer(this.hideDelay, this); } }, /** * 隐藏快捷提示。 */ hide: function(){ this.clearTimer('dismiss'); this.lastActive = new Date(); Ext.ToolTip.superclass.hide.call(this); }, /** * 在当前事件对象XY的位置上显示快捷提示。 * */ show : function(){ this.showAt(this.getTargetXY()); }, // inherit docs showAt : function(xy){ this.lastActive = new Date(); this.clearTimers(); Ext.ToolTip.superclass.showAt.call(this, xy); if(this.dismissDelay && this.autoHide !== false){ this.dismissTimer = this.hide.defer(this.dismissDelay, this); } }, // private clearTimer : function(name){ name = name + 'Timer'; clearTimeout(this[name]); delete this[name]; }, // private clearTimers : function(){ this.clearTimer('show'); this.clearTimer('dismiss'); this.clearTimer('hide'); }, // private onShow : function(){ Ext.ToolTip.superclass.onShow.call(this); Ext.getDoc().on('mousedown', this.onDocMouseDown, this); }, // private onHide : function(){ Ext.ToolTip.superclass.onHide.call(this); Ext.getDoc().un('mousedown', this.onDocMouseDown, this); }, // private onDocMouseDown : function(e){ if(this.autoHide !== false && !e.within(this.el.dom)){ this.disable(); this.enable.defer(100, this); } }, // private onDisable : function(){ this.clearTimers(); this.hide(); }, // private adjustPosition : function(x, y){ // keep the position from being under the mouse var ay = this.targetXY[1], h = this.getSize().height; if(this.constrainPosition && y <= ay && (y+h) >= ay){ y = ay-h-5; } return {x : x, y: y}; }, // private onDestroy : function(){ Ext.ToolTip.superclass.onDestroy.call(this); if(this.target){ this.target.un('mouseover', this.onTargetOver, this); this.target.un('mouseout', this.onTargetOut, this); this.target.un('mousemove', this.onMouseMove, this); } } });
JavaScript
/** * @class Ext.QuickTips * <p>为所有元素提供有吸引力和可定制的工具提示。QuickTips 是一个单态(singleton)类,被用来为多个元素的提示进行通用地、全局地配置和管理。 * 想要最大化地定制一个工具提示,你可以考虑使用 {@link Ext.Tip} 或者 {@link Ext.ToolTip}。</p> * <p>Quicktips 对象可以直接通过标签的属性来配置,或者在程序中通过 {@link #register} 方法注册提示。</p> * <p>单态的 {@link Ext.QuickTip} 对象实例可以通过 {@link #getQuickTip} 方法得到,并且提供所有的方法和所有 Ext.QuickTip 对象中的配置属性。 * 这些设置会被应用于所有显示的工具提示。</p> * <p>下面是可用的配置属性的汇总。详细的说明可以参见 {@link #getQuickTip}</p> * <p><b>QuickTips 单态配置项(所有均为可选项)</b></p> * <div class="mdetail-params"><ul><li>dismissDelay</li> * <li>hideDelay</li> * <li>maxWidth</li> * <li>minWidth</li> * <li>showDelay</li> * <li>trackMouse</li></ul></div> * <p><b>目标元素配置项(除有说明的均为可选项)</b></p> * <div class="mdetail-params"><ul><li>autoHide</li> * <li>cls</li> * <li>dismissDelay (将覆写单态同名选项值)</li> * <li>target (必须)</li> * <li>text (必须)</li> * <li>title</li> * <li>width</li></ul></div> * <p>下面是一个用来说明其中的一些配置选项如何使用的例子:</p> * <pre><code> // 初始化单态类。所有基于标签的提示将开始启用。 Ext.QuickTips.init(); // 应用配置选项到对象上 Ext.apply(Ext.QuickTips.getQuickTip(), { maxWidth: 200, minWidth: 100, showDelay: 50, trackMouse: true }); // 手动注册一个工具提示到指定的元素上 q.register({ target: 'my-div', title: 'My Tooltip', text: 'This tooltip was added in code', width: 100, dismissDelay: 20 }); </code></pre> * <p>在标签中注册一个快捷提示,只需要简单地一个或多个有效的 QuickTip 属性并加上 <b>ext:</b> 作为命名空间前缀。 * HTML 元素自身将自动地被设置为快捷提示的目标。下面是可用的属性的汇总(除有说明的均为可选项):</p> * <ul><li><b>hide</b>:指定为 "user" 等同于设置 autoHide = false。其他任何值则相当于 autoHide = true。</li> * <li><b>qclass</b>:应用于快捷提示的 CSS 类(等同于目标元素中的 'cls' 配置)。</li> * <li><b>qtip (必须)</b>:快捷提示的文本(等同于目标元素中的 'text' 配置)。</li> * <li><b>qtitle</b>:快捷提示的标题(等同于目标元素中的 'title' 配置)。</li> * <li><b>qwidth</b>:快捷提示的宽度(等同于目标元素中的 'width' 配置)。</li></ul> * <p>下面是一个说明如何通过使用标签在 HTML 元素上显示快捷提示的例子:</p> * <pre><code> // 往一个 HTML 的按钮中添加快捷提示 &lt;input type="button" value="OK" ext:qtitle="OK Button" ext:qwidth="100" ext:qtip="This is a quick tip from markup!">&lt;/input> </code></pre> * @singleton */ Ext.QuickTips = function(){ var tip, locks = []; return { /** * 初始化全局 QuickTips 实例 */ init : function(){ if(!tip){ tip = new Ext.QuickTip({elements:'header,body'}); } }, /** * 打开全局快速提示功能. */ enable : function(){ if(tip){ locks.pop(); if(locks.length < 1){ tip.enable(); } } }, /** * 关闭全局快速提示功能. */ disable : function(){ if(tip){ tip.disable(); } locks.push(1); }, /** * 获取一个值,该值指示此quick tips是否可以对用户交互作出响应。 * @return {Boolean} */ isEnabled : function(){ return tip && !tip.disabled; }, /** * 获得全局QuickTips实例. */ getQuickTip : function(){ return tip; }, /** * 配置一个新的quick tip实例并将其分配到一个目标元素. 详细信息请查看 * {@link Ext.QuickTip#register}. * @param {Object} config 配置对象 */ register : function(){ tip.register.apply(tip, arguments); }, /** * 从目标元素中移除并销毁所有已注册的quick tip * @param {String/HTMLElement/Element} el 将要被移除的quick tip的所属元素. */ unregister : function(){ tip.unregister.apply(tip, arguments); }, /** * {@link #register}的别名. * @param {Object} config 配置对象 */ tips :function(){ tip.register.apply(tip, arguments); } } }();
JavaScript
/* * Ext JS Library 2.1 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.StatusBar * <p>Basic status bar component that can be used as the bottom toolbar of any {@link Ext.Panel}. In addition to * supporting the standard {@link Ext.Toolbar} interface for adding buttons, menus and other items, the StatusBar * provides a greedy status element that can be aligned to either side and has convenient methods for setting the * status text and icon. You can also indicate that something is processing using the {@link #showBusy} method.</p> * <p>Example StatusBar configuration:</p> * <pre><code> new Ext.Panel({ title: 'StatusBar', // etc. bbar: new Ext.StatusBar({ id: 'my-status', // defaults to use when the status is cleared: defaultText: 'Default status text', defaultIconCls: 'default-icon', // values to set initially: text: 'Ready', iconCls: 'ready-icon', // any standard Toolbar items: items: [{ text: 'A Button' }, '-', 'Plain Text'] }) }); // Update the status bar later in code: var sb = Ext.getCmp('my-status'); sb.setStatus({ text: 'OK', iconCls: 'ok-icon', clear: true // auto-clear after a set interval }); // Set the status bar to show that something is processing: sb.showBusy(); // processing.... sb.clearStatus(); // once completeed </code></pre> * @extends Ext.Toolbar * @constructor * Creates a new StatusBar * @param {Object/Array} config A config object */ Ext.StatusBar = Ext.extend(Ext.Toolbar, { /** * @cfg {String} statusAlign * The alignment of the status element within the overall StatusBar layout. When the StatusBar is rendered, * it creates an internal div containing the status text and icon. Any additional Toolbar items added in the * StatusBar's {@link #items} config, or added via {@link #add} or any of the supported add* methods, will be * rendered, in added order, to the opposite side. The status element is greedy, so it will automatically * expand to take up all sapce left over by any other items. Example usage: * <pre><code> // Create a left-aligned status bar containing a button, // separator and text item that will be right-aligned (default): new Ext.Panel({ title: 'StatusBar', // etc. bbar: new Ext.StatusBar({ defaultText: 'Default status text', id: 'status-id', items: [{ text: 'A Button' }, '-', 'Plain Text'] }) }); // By adding the statusAlign config, this will create the // exact same toolbar, except the status and toolbar item // layout will be reversed from the previous example: new Ext.Panel({ title: 'StatusBar', // etc. bbar: new Ext.StatusBar({ defaultText: 'Default status text', id: 'status-id', statusAlign: 'right', items: [{ text: 'A Button' }, '-', 'Plain Text'] }) }); </code></pre> */ /** * @cfg {String} defaultText * The default {@link #text} value. This will be used anytime the status bar is cleared with the * <tt>useDefaults:true</tt> option (defaults to ''). */ /** * @cfg {String} defaultIconCls * The default {@link #iconCls} value (see the iconCls docs for additional details about customizing the icon). * This will be used anytime the status bar is cleared with the <tt>useDefaults:true</tt> option (defaults to ''). */ /** * @cfg {String} text * A string that will be rendered into the status element as the status message (defaults to ''); */ /** * @cfg {String} iconCls * A CSS class that will be applied to the status element and is expected to provide a background image that will * serve as the status bar icon (defaults to ''). The class is applied directly to the div that also contains the * status text, so the rule should provide the appropriate padding on the div to make room for the image. * Example usage:<pre><code> // Example CSS rule: .x-statusbar .x-status-custom { padding-left: 25px; background: transparent url(images/custom-icon.gif) no-repeat 3px 3px; } // Initializing the status bar: var sb = new Ext.StatusBar({ defaultIconCls: 'x-status-custom' }); // Setting it in code: sb.setStatus({ text: 'New status', iconCls: 'x-status-custom' }); </code></pre> */ /** * @cfg {String} cls * The base class applied to the containing element for this component on render (defaults to 'x-statusbar') */ cls : 'x-statusbar', /** * @cfg {String} busyIconCls * The default {@link #iconCls} applied when calling {@link #showBusy} (defaults to 'x-status-busy'). It can be * overridden at any time by passing the <tt>iconCls</tt> argument into <tt>showBusy</tt>. See the * iconCls docs for additional details about customizing the icon. */ busyIconCls : 'x-status-busy', /** * @cfg {String} busyText * The default {@link #text} applied when calling {@link #showBusy} (defaults to 'Loading...'). It can be * overridden at any time by passing the <tt>text</tt> argument into <tt>showBusy</tt>. */ busyText : 'Loading...', /** * @cfg {Number} autoClear * The number of milliseconds to wait after setting the status via {@link #setStatus} before automatically * clearing the status text and icon (defaults to 5000). Note that this only applies when passing the * <tt>clear</tt> argument to setStatus since that is the only way to defer clearing the status. This can * be overridden by specifying a different <tt>wait</tt> value in setStatus. Calls to {@link #clearStatus} * always clear the status bar immediately and ignore this value. */ autoClear : 5000, // private activeThreadId : 0, // private initComponent : function(){ if(this.statusAlign=='right'){ this.cls += ' x-status-right'; } Ext.StatusBar.superclass.initComponent.call(this); }, // private afterRender : function(){ Ext.StatusBar.superclass.afterRender.call(this); var right = this.statusAlign=='right', td = Ext.get(this.nextBlock()); if(right){ this.tr.appendChild(td.dom); }else{ td.insertBefore(this.tr.firstChild); } this.statusEl = td.createChild({ cls: 'x-status-text ' + (this.iconCls || this.defaultIconCls || ''), html: this.text || this.defaultText || '' }); this.statusEl.unselectable(); this.spacerEl = td.insertSibling({ tag: 'td', style: 'width:100%', cn: [{cls:'ytb-spacer'}] }, right ? 'before' : 'after'); }, /** * Sets the status {@link #text} and/or {@link #iconCls}. Also supports automatically clearing the * status that was set after a specified interval. * @param {Object/String} config A config object specifying what status to set, or a string assumed * to be the status text (and all other options are defaulted as explained below). A config * object containing any or all of the following properties can be passed:<ul> * <li><tt>text</tt> {String} : (optional) The status text to display. If not specified, any current * status text will remain unchanged.</li> * <li><tt>iconCls</tt> {String} : (optional) The CSS class used to customize the status icon (see * {@link #iconCls} for details). If not specified, any current iconCls will remain unchanged.</li> * <li><tt>clear</tt> {Boolean/Number/Object} : (optional) Allows you to set an internal callback that will * automatically clear the status text and iconCls after a specified amount of time has passed. If clear is not * specified, the new status will not be auto-cleared and will stay until updated again or cleared using * {@link #clearStatus}. If <tt>true</tt> is passed, the status will be cleared using {@link #autoClear}, * {@link #defaultText} and {@link #defaultIconCls} via a fade out animation. If a numeric value is passed, * it will be used as the callback interval (in milliseconds), overriding the {@link #autoClear} value. * All other options will be defaulted as with the boolean option. To customize any other options, * you can pass an object in the format:<ul> * <li><tt>wait</tt> {Number} : (optional) The number of milliseconds to wait before clearing * (defaults to {@link #autoClear}).</li> * <li><tt>anim</tt> {Number} : (optional) False to clear the status immediately once the callback * executes (defaults to true which fades the status out).</li> * <li><tt>useDefaults</tt> {Number} : (optional) False to completely clear the status text and iconCls * (defaults to true which uses {@link #defaultText} and {@link #defaultIconCls}).</li> * </ul></li></ul> * Example usage:<pre><code> // Simple call to update the text statusBar.setStatus('New status'); // Set the status and icon, auto-clearing with default options: statusBar.setStatus({ text: 'New status', iconCls: 'x-status-custom', clear: true }); // Auto-clear with custom options: statusBar.setStatus({ text: 'New status', iconCls: 'x-status-custom', clear: { wait: 8000, anim: false, useDefaults: false } }); </code></pre> * @return {Ext.StatusBar} this */ setStatus : function(o){ o = o || {}; if(typeof o == 'string'){ o = {text:o}; } if(o.text !== undefined){ this.setText(o.text); } if(o.iconCls !== undefined){ this.setIcon(o.iconCls); } if(o.clear){ var c = o.clear, wait = this.autoClear, defaults = {useDefaults: true, anim: true}; if(typeof c == 'object'){ c = Ext.applyIf(c, defaults); if(c.wait){ wait = c.wait; } }else if(typeof c == 'number'){ wait = c; c = defaults; }else if(typeof c == 'boolean'){ c = defaults; } c.threadId = this.activeThreadId; this.clearStatus.defer(wait, this, [c]); } return this; }, /** * Clears the status {@link #text} and {@link #iconCls}. Also supports clearing via an optional fade out animation. * @param {Object} config (optional) A config object containing any or all of the following properties. If this * object is not specified the status will be cleared using the defaults below:<ul> * <li><tt>anim</tt> {Boolean} : (optional) True to clear the status by fading out the status element (defaults * to false which clears immediately).</li> * <li><tt>useDefaults</tt> {Boolean} : (optional) True to reset the text and icon using {@link #defaultText} and * {@link #defaultIconCls} (defaults to false which sets the text to '' and removes any existing icon class).</li> * </ul> * @return {Ext.StatusBar} this */ clearStatus : function(o){ o = o || {}; if(o.threadId && o.threadId !== this.activeThreadId){ // this means the current call was made internally, but a newer // thread has set a message since this call was deferred. Since // we don't want to overwrite a newer message just ignore. return this; } var text = o.useDefaults ? this.defaultText : '', iconCls = o.useDefaults ? this.defaultIconCls : ''; if(o.anim){ this.statusEl.fadeOut({ remove: false, useDisplay: true, scope: this, callback: function(){ this.setStatus({ text: text, iconCls: iconCls }); this.statusEl.show(); } }); }else{ // hide/show the el to avoid jumpy text or icon this.statusEl.hide(); this.setStatus({ text: text, iconCls: iconCls }); this.statusEl.show(); } return this; }, /** * Convenience method for setting the status text directly. For more flexible options see {@link #setStatus}. * @param {String} text (optional) The text to set (defaults to '') * @return {Ext.StatusBar} this */ setText : function(text){ this.activeThreadId++; this.text = text || ''; if(this.rendered){ this.statusEl.update(this.text); } return this; }, /** * Returns the current status text. * @return {String} The status text */ getText : function(){ return this.text; }, /** * Convenience method for setting the status icon directly. For more flexible options see {@link #setStatus}. * See {@link #iconCls} for complete details about customizing the icon. * @param {String} iconCls (optional) The icon class to set (defaults to '', and any current icon class is removed) * @return {Ext.StatusBar} this */ setIcon : function(cls){ this.activeThreadId++; cls = cls || ''; if(this.rendered){ if(this.currIconCls){ this.statusEl.removeClass(this.currIconCls); this.currIconCls = null; } if(cls.length > 0){ this.statusEl.addClass(cls); this.currIconCls = cls; } }else{ this.currIconCls = cls; } return this; }, /** * Convenience method for setting the status text and icon to special values that are pre-configured to indicate * a "busy" state, usually for loading or processing activities. * @param {Object/String} config (optional) A config object in the same format supported by {@link #setStatus}, or a * string to use as the status text (in which case all other options for setStatus will be defaulted). Use the * <tt>text</tt> and/or <tt>iconCls</tt> properties on the config to override the default {@link #busyText} * and {@link #busyIconCls} settings. If the config argument is not specified, {@link #busyText} and * {@link #busyIconCls} will be used in conjunction with all of the default options for {@link #setStatus}. * @return {Ext.StatusBar} this */ showBusy : function(o){ if(typeof o == 'string'){ o = {text:o}; } o = Ext.applyIf(o || {}, { text: this.busyText, iconCls: this.busyIconCls }); return this.setStatus(o); } }); Ext.reg('statusbar', Ext.StatusBar);
JavaScript
/** * @class Ext.CycleButton * @extends Ext.SplitButton * 一个包含 {@link Ext.menu.CheckItem} 元素的特殊分割按钮。按钮会在点击时自动循环选中每个菜单项,并以该项为活动项触发按钮的 {@link #change} 事件 * (或者调用按钮的 {@link #changeHandler} 函数,如果设置过的话)。通过点击箭头区域即可像普通分割按钮那样显示下拉列表。使用示例: * <pre><code> var btn = new Ext.CycleButton({ showText: true, prependText: 'View as ', items: [{ text:'text only', iconCls:'view-text', checked:true },{ text:'HTML', iconCls:'view-html' }], changeHandler:function(btn, item){ Ext.Msg.alert('Change View', item.text); } }); </code></pre> * @constructor * 创建一个分割按钮 * @param {Object} config 配置选项对象 */ Ext.CycleButton = Ext.extend(Ext.SplitButton, { /** * @cfg {Array} items 一个由 {@link Ext.menu.CheckItem} <b>config</b> 配置选项对象组成的数组,用来创建按钮的菜单项(例如:{text:'Foo', iconCls:'foo-icon'}) */ /** * @cfg {Boolean} showText 值为 True 时则将活动项的文本显示为按钮的文本(默认为 false) */ /** * @cfg {String} prependText 当没有活动项时按钮显示的文本(仅仅当 showText = true 时有效,默认为 '') */ /** * @cfg {Function} changeHandler 每次改变活动项时被调用的函数。如果没有指定该配置项,则分割按钮将触发活动项的 {@link #change} 事件。 * 调用该函数时将携带下列参数:(SplitButton this, Ext.menu.CheckItem item) */ // private getItemText : function(item){ if(item && this.showText === true){ var text = ''; if(this.prependText){ text += this.prependText; } text += item.text; return text; } return undefined; }, /** * 设置按钮的活动菜单项。 * @param {Ext.menu.CheckItem} item 被设置的活动项 * @param {Boolean} suppressEvent 值为 True 时阻止触发按钮的 change 事件(默认为 false) */ setActiveItem : function(item, suppressEvent){ if(item){ if(!this.rendered){ this.text = this.getItemText(item); this.iconCls = item.iconCls; }else{ var t = this.getItemText(item); if(t){ this.setText(t); } this.setIconClass(item.iconCls); } this.activeItem = item; if(!suppressEvent){ this.fireEvent('change', this, item); } } }, /** * 获取当前活动菜单项。 * @return {Ext.menu.CheckItem} 活动项 */ getActiveItem : function(){ return this.activeItem; }, // private initComponent : function(){ this.addEvents( /** * @event change * 在按钮的活动项改变之后触发。注意,如果按钮指定了 {@link #changeHandler} 函数,则会调用该函数而不触发此事件。 * @param {Ext.CycleButton} this * @param {Ext.menu.CheckItem} item 选中的菜单项 */ "change" ); if(this.changeHandler){ this.on('change', this.changeHandler, this.scope||this); delete this.changeHandler; } this.itemCount = this.items.length; this.menu = {cls:'x-cycle-menu', items:[]}; var checked; for(var i = 0, len = this.itemCount; i < len; i++){ var item = this.items[i]; item.group = item.group || this.id; item.itemIndex = i; item.checkHandler = this.checkHandler; item.scope = this; item.checked = item.checked || false; this.menu.items.push(item); if(item.checked){ checked = item; } } this.setActiveItem(checked, true); Ext.CycleButton.superclass.initComponent.call(this); this.on('click', this.toggleSelected, this); }, // private checkHandler : function(item, pressed){ if(pressed){ this.setActiveItem(item); } }, /** * 通常情况下该函数仅仅被内部调用,但也可以在外部调用使得按钮将活动项指向菜单中的下一个选项。 * 如果当前项是菜单中的最后一项,则活动项会被设置为菜单中的第一项。 */ toggleSelected : function(){ this.menu.render(); var nextIdx, checkItem; for (var i = 1; i < this.itemCount; i++) { nextIdx = (this.activeItem.itemIndex + i) % this.itemCount; // check the potential item checkItem = this.menu.items.itemAt(nextIdx); // if its not disabled then check it. if (!checkItem.disabled) { checkItem.setChecked(true); break; } } } }); Ext.reg('cycle', Ext.CycleButton);
JavaScript
/** * @class Ext.form.TextArea * @extends Ext.form.TextField * 多行文本域。可以直接用于替代textarea,支持自动调整大小。 * @constructor * 创建一个新的TextArea对象 * @param {Object} config 配置选项 */ Ext.form.TextArea = Ext.extend(Ext.form.TextField, { /** * @cfg {Number} growMin 当grow = true时允许的高度下限(默认为60) */ growMin : 60, /** * @cfg {Number} growMax 当grow = true时允许的高度上限(默认为1000) */ growMax: 1000, growAppend : '&#160;\n&#160;', growPad : 0, enterIsSpecial : false, /** * @cfg {Boolean} preventScrollbars 为True时在为本域中将禁止滑动条,不论域中文本的数量(相当于设置overflow为hidden,默认值为false) */ preventScrollbars: false, /** * @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为 * {tag: "textarea", style: "width:300px;height:60px;", autocomplete: "off"}) */ // private onRender : function(ct, position){ if(!this.el){ this.defaultAutoCreate = { tag: "textarea", style:"width:100px;height:60px;", autocomplete: "off" }; } Ext.form.TextArea.superclass.onRender.call(this, ct, position); if(this.grow){ this.textSizeEl = Ext.DomHelper.append(document.body, { tag: "pre", cls: "x-form-grow-sizer" }); if(this.preventScrollbars){ this.el.setStyle("overflow", "hidden"); } this.el.setHeight(this.growMin); } }, onDestroy : function(){ if(this.textSizeEl){ Ext.removeNode(this.textSizeEl); } Ext.form.TextArea.superclass.onDestroy.call(this); }, fireKey : function(e){ if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){ this.fireEvent("specialkey", this, e); } }, // private onKeyUp : function(e){ if(!e.isNavKeyPress() || e.getKey() == e.ENTER){ this.autoSize(); } }, /** * 自动适应文本行数,直到所设置的最大行数。 * 仅当grow = true时触发自适应高度事件。 */ autoSize : function(){ if(!this.grow || !this.textSizeEl){ return; } var el = this.el; var v = el.dom.value; var ts = this.textSizeEl; ts.innerHTML = ''; ts.appendChild(document.createTextNode(v)); v = ts.innerHTML; Ext.fly(ts).setWidth(this.el.getWidth()); if(v.length < 1){ v = "&#160;&#160;"; }else{ if(Ext.isIE){ v = v.replace(/\n/g, '<p>&#160;</p>'); } v += this.growAppend; } ts.innerHTML = v; var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin)+this.growPad); if(h != this.lastHeight){ this.lastHeight = h; this.el.setHeight(h); this.fireEvent("autosize", this, h); } } }); Ext.reg('textarea', Ext.form.TextArea);
JavaScript
/** * @class Ext.form.TimeField * @extends Ext.form.ComboBox * 提供一个带有下拉框和自动时间验证的时间输入框。</br> * @构造函数constructor * Create a new TimeField * @参数{Object} config */ Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, { /** * @cfg {Date/String} minValue *允许输入的最早的时间。可以是JavaScriptDate对象,也可以是一个格式正确的字符串(默认为null) */ minValue : null, /** * @cfg {Date/String} maxValue * 允许输入的最晚时间。可以是JavaScriptDate对象,也可以是一个格式正确的字符串(默认为null) */ maxValue : null, /** * @cfg {String} minText *单元格里的时间早于限定的最早时间的错误信息。(默认为: The time in this field must be equal to or after {0}') */ minText : "The time in this field must be equal to or after {0}", /** * @cfg {String} maxText * 单元格里的时间晚于限定的最早时间的错误信息。(默认为:'The time in this field must be equal to or before {0}'). */ maxText : "The time in this field must be equal to or before {0}", /** * @cfg {String} invalidText * 单元格里的时间不符合格式的错误信息。(默认为: * '{value} is not a valid time - it must be in the format {format}'). */ invalidText : "{0} is not a valid time", /** * @cfg {String} format * 默认的字符串时间的格式,可以被覆盖以支持本地化。表示此格式的该字符串必须符合 * {@link Date#parseDate} (默认:'m/d/y')的格式。 */ format : "g:i A", /** * @cfg {String} altFormats * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined * format (defaults to 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d'). */ altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H", /** * @cfg {Number} increment *下拉框里显示时间的步长(默认为15分钟) 。PS:数字的单位是分钟 */ increment: 15, // private override mode: 'local', // private override triggerAction: 'all', // private override typeAhead: false, // private initComponent : function(){ Ext.form.TimeField.superclass.initComponent.call(this); if(typeof this.minValue == "string"){ this.minValue = this.parseDate(this.minValue); } if(typeof this.maxValue == "string"){ this.maxValue = this.parseDate(this.maxValue); } if(!this.store){ var min = this.parseDate(this.minValue); if(!min){ min = new Date().clearTime(); } var max = this.parseDate(this.maxValue); if(!max){ max = new Date().clearTime().add('mi', (24 * 60) - 1); } var times = []; while(min <= max){ times.push([min.dateFormat(this.format)]); min = min.add('mi', this.increment); } this.store = new Ext.data.SimpleStore({ fields: ['text'], data : times }); this.displayField = 'text'; } }, // inherited docs getValue : function(){ var v = Ext.form.TimeField.superclass.getValue.call(this); return this.formatDate(this.parseDate(v)) || ''; }, // inherited docs setValue : function(value){ Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value))); }, // private overrides validateValue : Ext.form.DateField.prototype.validateValue, parseDate : Ext.form.DateField.prototype.parseDate, formatDate : Ext.form.DateField.prototype.formatDate, // private beforeBlur : function(){ var v = this.parseDate(this.getRawValue()); if(v){ this.setValue(v.dateFormat(this.format)); } } /** * @cfg {Boolean} grow @hide */ /** * @cfg {Number} growMin @hide */ /** * @cfg {Number} growMax @hide */ /** * @hide * @method autoSize */ }); Ext.reg('timefield', Ext.form.TimeField);
JavaScript
/** * @class Ext.form.Hidden * @extends Ext.form.Field * 用于存放表单里需要被传递到后台的隐藏值得隐藏域。 * @constructor * 生成一个隐藏字段。 * @param {Object} config 配置项 */ Ext.form.Hidden = Ext.extend(Ext.form.Field, { // private inputType : 'hidden', // private onRender : function(){ Ext.form.Hidden.superclass.onRender.apply(this, arguments); }, // private initEvents : function(){ this.originalValue = this.getValue(); }, // These are all private overrides setSize : Ext.emptyFn, setWidth : Ext.emptyFn, setHeight : Ext.emptyFn, setPosition : Ext.emptyFn, setPagePosition : Ext.emptyFn, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn }); Ext.reg('hidden', Ext.form.Hidden);
JavaScript
/** * @类 Ext.form.Action.Submit * @继承于 Ext.form.Action * <p>处理数据表单{@link Ext.form.BasicForm Form} 和返回的response对象的类。</p> * <p>该类的实例仅在表单{@link Ext.form.BasicForm#submit submit}的时候由{@link Ext.form.BasicForm Form}创建。</p> * <p>返回的数据包必须包含一个 boolean 类型的<tt style="font-weight:bold">success</tt> 属性,和一个含有无效字段的错误信息的可选<tt style="font-weight:bold">errors</tt> 属性。</p> * <p>默认情况下,response数据包被认为是一个JSON对象, 所以典型的response数据包看起来像是这样的:</p><pre><code> { success: false, errors: { clientCode: "Client not found", portOfLoading: "This field must not be null" } }</code></pre> * <p>其他的数据可能会由{@link Ext.form.BasicForm}的回调函数甚至事件处理函数置入response,由这个JSON解码的对象也在{@link #result} 属性里。 * <p>另外, 如果指定了一个{@link Ext.data.XmlReader XmlReader}的{@link #errorReader}:</p><pre><code> errorReader: new Ext.data.XmlReader({ record : 'field', success: '@success' }, [ 'id', 'msg' ] ) </code></pre> * <p>那么结果集将会以XML形式返回。:</p><pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;message success="false"&gt; &lt;errors&gt; &lt;field&gt; &lt;id&gt;clientCode&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;field&gt; &lt;id&gt;portOfLoading&lt;/id&gt; &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt; &lt;/field&gt; &lt;/errors&gt; &lt;/message&gt; </code></pre> * <p>{@link Ext.form.BasicForm}表单的回调函数或者时间处理函数可以向相应的XML里置入其他的元素,XML文档在{@link #errorReader}的{@link Ext.data.XmlReader#xmlData xmlData}属性里。 */ Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { /** * @cfg {Ext.data.DataReader} errorReader <b>可选的。 解读JSON对象不需要errorReader.</b> * <p>从返回结果中读取一条记录的Reader。DataReader的<b>success</b> 属性指明决定是否提交成功。Record对象的数据提供了任何未通过验证(非法)的表单字段的错误信息</P> */ /** * @cfg {boolean} clientValidation Determines whether a Form's fields are validated * @cfg {boolean} clientValidation 表明一个表单的字段是否都合法。在表单最终提交前调用{@link Ext.form.BasicForm#isValid isValid}。 * 在表单的提交选项中选择 <tt>false</tt> 可以避免执行该操作。如果没有定义改属性,执行提交前的表单验证。 */ type : 'submit', // 私有的 run : function(){ var o = this.options; var method = this.getMethod(); var isGet = method == 'GET'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(isGet), method: method, headers: o.headers, params:!isGet ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ // client validation failed this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, // 私有的 success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, // 私有的 handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++) { var r = rs.records[i]; errors[i] = r.data; } } if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } }); /** * 类 Ext.form.Action.Load * @继承于 Ext.form.Action * <p>处理从服务器加载数据到{@link Ext.form.BasicForm}的字段的类。</p> * <p>该类的实例仅在{@link Ext.form.BasicForm Form}表单{@link Ext.form.BasicForm#load load}加载的时候才被创建。</p> * <p>相应数据包<b>必须</b>包含一个boolean类型的<tt style="font-weight:bold">success</tt>属性,和一个<tt style="font-weight:bold">data</tt> 属性。<tt style="font-weight:bold">data</tt> 属性 * 包含了表单字段要加载的数据。每个值对象被传递到字段的{@link Ext.form.Field#setValue setValue}方法里。</p> * <p>默认情况下,相应数据包会被认为是一个JSON对象,所以典型的相应数据包看起来是这样的:</p><pre><code> { success: true, data: { clientName: "Fred. Olsen Lines", portOfLoading: "FXT", portOfDischarge: "OSL" } }</code></pre> * <p> * 其他的数据可以由{@link Ext.form.BasicForm Form}的回调函数甚至是事件处理函数置入response对象进行处理。解码的JSON对象在{@link #result}属性里。 * </p> */ Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { // private type : 'load', // private run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), headers: this.options.headers, params:this.getParams() })); }, // private success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, // private handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit };
JavaScript
/** * @class Ext.form.Radio * @extends Ext.form.Checkbox * 单个的radio按钮。与Checkbox类似,提供一种简便,自动的输入方式。 * 如果你给radio按钮组中的每个按钮相同的名字(属性name值相同),按钮组会自动被浏览器编组。 * @constructor * 创建一个新的radio按钮对象 * @param {Object} config 配置选项 */ Ext.form.Radio = Ext.extend(Ext.form.Checkbox, { inputType: 'radio', /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ markInvalid : Ext.emptyFn, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ clearInvalid : Ext.emptyFn, /** * 如果该radio是组的一部分,将返回已选中的值。 * @return {String} */ getGroupValue : function(){ return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value; } }); Ext.reg('radio', Ext.form.Radio);
JavaScript
/** * @class Ext.form.Field * @extends Ext.BoxComponent * 表单元素的基类,提供事件操作、尺寸调整、值操作与其它功能。 * @constructor * 创建一个新的字段 * @param {Object} config 配制选项 */ Ext.form.Field = Ext.extend(Ext.BoxComponent, { /** * @cfg {String} * 表单元素无效时标在上面的CSS样式(默认为"x-form-invalid") */ invalidClass : "x-form-invalid", /** * @cfg {String} invalidText * 表单元素无效时标在上面的文本信息(默认为"The value in this field is invalid") */ invalidText : "The value in this field is invalid", /** * @cfg {String} focusClass * 当表单元素获取焦点时的CSS样式(默认为"x-form-focus") */ focusClass : "x-form-focus", /** * @cfg {String/Boolean} validationEvent * 初始化元素验证的事件名,如果设假,则不进行验证(默认"keyup") */ validationEvent : "keyup", /** * @cfg {Boolean} validateOnBlur * 是否当失去焦点时验证此表单元素(默认真)。 */ validateOnBlur : true, /** * @cfg {Number} validationDelay * 用户输入开始到验证开始的间隔毫秒数(默认250毫秒) */ validationDelay : 250, /** * @cfg {String/Object} autoCreate * 一个指定的DomHelper对象,如果为真则为一个默认对象(默认 {tag: "input", type: "text", size: "20", autocomplete: "off"}) */ defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"}, /** * @cfg {String} fieldClass * 表单元素一般状态CSS样式(默认为"x-form-field") */ fieldClass : "x-form-field", /** * @cfg {String} msgTarget * 错误提示的显示位置。 可以是以下列表中的任意一项(默认为"qtip") *<pre> Value Description ----------- ---------------------------------------------------------------------- qtip Display a quick tip when the user hovers over the field 当鼠标旋停在表单元素上时显示。 title Display a default browser title attribute popup 显示浏览器默认"popup"提示。 under Add a block div beneath the field containing the error text 创建一个包函错误信息的"div"对象(块显示方式)在表单元素下面。 side Add an error icon to the right of the field with a popup on hover 在表单元素右侧加错误图标,鼠标旋停上面时显示错误信息。 [element id] Add the error text directly to the innerHTML of the specified element 直接在指定的对象的"innerHTML"属性里添加错误信息。 </pre> */ msgTarget : 'qtip', /** * @cfg {String} msgFx <b>Experimental</b> * 表单元素无效提示显示的动画效果(默认为"normal") */ msgFx : 'normal', /** * @cfg {Boolean} readOnly * 如果为真,则在HTML时标明此表单元素为只读 -- 注意:只是设置表单对象的只读属性。 */ readOnly : false, /** * @cfg {Boolean} disabled * 为真则标明此表单元素为不可用(默认为假) */ disabled : false, /** * @cfg {String} inputType * "input"类表单元素的类型属性 -- 例如:radio,text,password (默认为"text") */ isFormField : true, hasFocus : false, initComponent : function(){ Ext.form.Field.superclass.initComponent.call(this); this.addEvents( /** * @event focus * 当此元素获取焦点时激发此事件。 * @param {Ext.form.Field} this */ 'focus', /** * @event blur * 当此元素推动焦点时激发此事件。 * @param {Ext.form.Field} this */ 'blur', /** * @event specialkey * 任何一个关于导航类键(arrows,tab,enter,esc等)被敲击则触发此事件。你可以查看{@link Ext.EventObject#getKey}去断定哪个键被敲击。 * @param {Ext.form.Field} this * @param {Ext.EventObject} e The event object */ 'specialkey', /** * @event change * 当元素失去焦点时,如果值被修改则触发此事件。 * @param {Ext.form.Field} this * @param {Mixed} newValue 新值 * @param {Mixed} oldValue 原始值 */ 'change', /** * @event invalid * 当此元素被标为无效后触发此事件。 * @param {Ext.form.Field} this * @param {String} msg 验证信息 */ 'invalid', /** * @event valid * 在此元素被验证有效后触发此事件。 * @param {Ext.form.Field} this */ 'valid' ); }, /** * 试图获取元素的名称。 * @return {String} name 域名 */ getName: function(){ return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || ''); }, onRender : function(ct, position){ Ext.form.Field.superclass.onRender.call(this, ct, position); if(!this.el){ var cfg = this.getAutoCreate(); if(!cfg.name){ cfg.name = this.name || this.id; } if(this.inputType){ cfg.type = this.inputType; } this.el = ct.createChild(cfg, position); } var type = this.el.dom.type; if(type){ if(type == 'password'){ type = 'text'; } this.el.addClass('x-form-'+type); } if(this.readOnly){ this.el.dom.readOnly = true; } if(this.tabIndex !== undefined){ this.el.dom.setAttribute('tabIndex', this.tabIndex); } this.el.addClass([this.fieldClass, this.cls]); this.initValue(); }, /** * 把组件应用到一个现有的对象上。这个被用来代替render()方法。 * @param {String/HTMLElement/Element} el 节点对象的ID、DOM节点或一个现有对象。 * @return {Ext.form.Fielhd} this */ initValue : function(){ if(this.value !== undefined){ this.setValue(this.value); }else if(this.el.dom.value.length > 0){ this.setValue(this.el.dom.value); } }, /** * 它的原始值没有变更,并且它是可用的则返回真。 * @return {Boolean} */ isDirty : function() { if(this.disabled) { return false; } return String(this.getValue()) !== String(this.originalValue); }, // private afterRender : function(){ Ext.form.Field.superclass.afterRender.call(this); this.initEvents(); }, // private fireKey : function(e){ if(e.isSpecialKey()){ this.fireEvent("specialkey", this, e); } }, /** * 重置此元素的值到原始值,并且清除所有无效提示信息。 */ reset : function(){ this.setValue(this.originalValue); this.clearInvalid(); }, initEvents : function(){ this.el.on(Ext.isIE || Ext.isSafari3 ? "keydown" : "keypress", this.fireKey, this); this.el.on("focus", this.onFocus, this); this.el.on("blur", this.onBlur, this); this.originalValue = this.getValue(); }, onFocus : function(){ if(!Ext.isOpera && this.focusClass){ this.el.addClass(this.focusClass); } if(!this.hasFocus){ this.hasFocus = true; this.startValue = this.getValue(); this.fireEvent("focus", this); } }, beforeBlur : Ext.emptyFn, onBlur : function(){ this.beforeBlur(); if(!Ext.isOpera && this.focusClass){ this.el.removeClass(this.focusClass); } this.hasFocus = false; if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){ this.validate(); } var v = this.getValue(); if(String(v) !== String(this.startValue)){ this.fireEvent('change', this, v, this.startValue); } this.fireEvent("blur", this); }, /** * 此元素是否有效。 * @param {Boolean} preventMark 为真则不去标志此对象任何无效信息。 * @return {Boolean} 有效过则返回真,否则返回假。 */ isValid : function(preventMark){ if(this.disabled){ return true; } var restore = this.preventMark; this.preventMark = preventMark === true; var v = this.validateValue(this.processValue(this.getRawValue())); this.preventMark = restore; return v; }, /** * 验证域的值 * @return {Boolean} True表示为值有效,否则为false */ validate : function(){ if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){ this.clearInvalid(); return true; } return false; }, processValue : function(value){ return value; }, validateValue : function(value){ return true; }, /** * 让该域无效 * @param {String} msg 验证的信息 */ markInvalid : function(msg){ if(!this.rendered || this.preventMark){ // 未渲染的 return; } this.el.addClass(this.invalidClass); msg = msg || this.invalidText; switch(this.msgTarget){ case 'qtip': this.el.dom.qtip = msg; this.el.dom.qclass = 'x-form-invalid-tip'; if(Ext.QuickTips){ // 修改拖放时的 editors浮动问题 Ext.QuickTips.enable(); } break; case 'title': this.el.dom.title = msg; break; case 'under': if(!this.errorEl){ var elp = this.getErrorCt(); this.errorEl = elp.createChild({cls:'x-form-invalid-msg'}); this.errorEl.setWidth(elp.getWidth(true)-20); } this.errorEl.update(msg); Ext.form.Field.msgFx[this.msgFx].show(this.errorEl, this); break; case 'side': if(!this.errorIcon){ var elp = this.getErrorCt(); this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'}); } this.alignErrorIcon(); this.errorIcon.dom.qtip = msg; this.errorIcon.dom.qclass = 'x-form-invalid-tip'; this.errorIcon.show(); this.on('resize', this.alignErrorIcon, this); break; default: var t = Ext.getDom(this.msgTarget); t.innerHTML = msg; t.style.display = this.msgDisplay; break; } this.fireEvent('invalid', this, msg); }, getErrorCt : function(){ return this.el.findParent('.x-form-element', 5, true) || this.el.findParent('.x-form-field-wrap', 5, true); }, alignErrorIcon : function(){ this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]); }, /** * 清除元素任何无效标志样式与信息。 */ clearInvalid : function(){ if(!this.rendered || this.preventMark){ // 未渲染的 return; } this.el.removeClass(this.invalidClass); switch(this.msgTarget){ case 'qtip': this.el.dom.qtip = ''; break; case 'title': this.el.dom.title = ''; break; case 'under': if(this.errorEl){ Ext.form.Field.msgFx[this.msgFx].hide(this.errorEl, this); } break; case 'side': if(this.errorIcon){ this.errorIcon.dom.qtip = ''; this.errorIcon.hide(); this.un('resize', this.alignErrorIcon, this); } break; default: var t = Ext.getDom(this.msgTarget); t.innerHTML = ''; t.style.display = 'none'; break; } this.fireEvent('valid', this); }, /** * 返回可能无效的原始值。 * @return {Mixed} value The field value */ getRawValue : function(){ var v = this.rendered ? this.el.getValue() : Ext.value(this.value, ''); if(v === this.emptyText){ v = ''; } return v; }, /** * 返回格式化后的数据(未定义或空值则会返回'')。返回原始值可以查看{@link #getRawValue}。 * @return {Mixed} value The field value */ getValue : function(){ if(!this.rendered) { return this.value; } var v = this.el.getValue(); if(v === this.emptyText || v === undefined){ v = ''; } return v; }, /** * 跃过验证直接设置DOM元素值。需要验证的设值方法可以查看{@link #setValue}。 * @param {Mixed} value 要设置的值 */ setRawValue : function(v){ return this.el.dom.value = (v === null || v === undefined ? '' : v); }, /** * 设置元素值并加以验证。如果想跃过验证直接设值则请看{@link #setRawValue}。 * @param {Mixed} value 要设置的值 */ setValue : function(v){ this.value = v; if(this.rendered){ this.el.dom.value = (v === null || v === undefined ? '' : v); this.validate(); } }, adjustSize : function(w, h){ var s = Ext.form.Field.superclass.adjustSize.call(this, w, h); s.width = this.adjustWidth(this.el.dom.tagName, s.width); return s; }, adjustWidth : function(tag, w){ tag = tag.toLowerCase(); if(typeof w == 'number' && !Ext.isSafari){ if(Ext.isIE && (tag == 'input' || tag == 'textarea')){ if(tag == 'input' && !Ext.isStrict){ return this.inEditor ? w : w - 3; } if(tag == 'input' && Ext.isStrict){ return w - (Ext.isIE6 ? 4 : 1); } if(tag == 'textarea' && Ext.isStrict){ return w-2; } }else if(Ext.isOpera && Ext.isStrict){ if(tag == 'input'){ return w + 2; } if(tag == 'textarea'){ return w-2; } } } return w; } }); Ext.form.Field.msgFx = { normal : { show: function(msgEl, f){ msgEl.setDisplayed('block'); }, hide : function(msgEl, f){ msgEl.setDisplayed(false).update(''); } }, slide : { show: function(msgEl, f){ msgEl.slideIn('t', {stopFx:true}); }, hide : function(msgEl, f){ msgEl.slideOut('t', {stopFx:true,useDisplay:true}); } }, slideRight : { show: function(msgEl, f){ msgEl.fixDisplay(); msgEl.alignTo(f.el, 'tl-tr'); msgEl.slideIn('l', {stopFx:true}); }, hide : function(msgEl, f){ msgEl.slideOut('l', {stopFx:true,useDisplay:true}); } } }; Ext.reg('field', Ext.form.Field);
JavaScript
/** * @class Ext.form.VTypes * 提供一个简单的、易于扩展的、可重写的表单验证功能。 * @singleton */ Ext.form.VTypes = function(){ // 对下列变量进行闭包,所以只会创建一次 var alpha = /^[a-zA-Z_]+$/; var alphanum = /^[a-zA-Z0-9_]+$/; var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/; var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i; // 所有这些信息和函数都是可配置的 return { /** * 用于验证Email地址的函数 * @param {String} value The email address */ 'email' : function(v){ return email.test(v); }, /** * 当Email验证返回值为false到时候显示的错误信息 * @type String */ 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"', /** * 只允许email地址格式的正则表达式 * @type RegExp */ 'emailMask' : /[a-z0-9_\.\-@]/i, /** * 验证URL地址的函数 * @param {String} value The URL */ 'url' : function(v){ return url.test(v); }, /** * 当URL验证返回值为false到时候显示的错误信息 * @type String */ 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"', /** * 验证alpha到函数 * @param {String} value The value */ 'alpha' : function(v){ return alpha.test(v); }, /** * 当alpha验证返回值为false到时候显示的错误信息 * @type String */ 'alphaText' : 'This field should only contain letters and _', /** * The keystroke filter mask to be applied on alpha input * @type RegExp */ 'alphaMask' : /[a-z_]/i, /** * 验证数字的函数 * @param {String} value The value */ 'alphanum' : function(v){ return alphanum.test(v); }, /** * 验证数字返回false时候显示的错误信息 * @type String */ 'alphanumText' : 'This field should only contain letters, numbers and _', /** * 只允文数字(alphanum)的正则表达式 * @type RegExp */ 'alphanumMask' : /[a-z0-9_]/i }; }();
JavaScript
/** * @class Ext.form.Action.Load * @extends Ext.form.Action * A class which handles loading of data from a server into the Fields of * an {@link Ext.form.BasicForm}. * <br><br> * Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * submitting. * <br><br> * A response packet <b>must</b> contain a boolean <tt style="font-weight:bold">success</tt> property, and * a <tt style="font-weight:bold">data</tt> property. The <tt style="font-weight:bold">data</tt> property contains the * values of Fields to load. The individual value object for each Field * is passed to the Field's {@link Ext.form.Field#setValue setValue} method. * <br><br> * By default, response packets are assumed to be JSON, so a typical response * packet may look like this: * <br><br><pre><code> { success: true, data: { clientName: "Fred. Olsen Lines", portOfLoading: "FXT", portOfDischarge: "OSL" } }</code></pre> * <br><br> * Other data may be placed into the response for processing the the {@link Ext.form.BasicForm Form}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property. */ Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { // private type : 'load', // private run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), params:this.getParams() })); }, // private success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, // private handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit }
JavaScript
/** * @class Ext.form.Action * <p>该类的子类提供在{@link Ext.form.BasicForm Form}上执行的行为。</p> * <p>该类的实例尽在{@link Ext.form.BasicForm Form}要执行提交或者加载动作的时候才由 Form 创建 ,下列该类的配置选项通过表单的 * action methods {@link Ext.form.BasicForm#submit submit},{@link Ext.form.BasicForm#load load} 和 {@link Ext.form.BasicForm#doAction doAction}设置</p> * <p>执行了表单动作的Action的实例被传递到表单的 success,failure 回调函数({@link Ext.form.BasicForm#submit submit}, * {@link Ext.form.BasicForm#load load} 和 {@link Ext.form.BasicForm#doAction doAction}), * 以及 {@link Ext.form.BasicForm#actioncomplete actioncomplete} 和{@link Ext.form.BasicForm#actionfailed actionfailed}事件处理器</p> */ Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; /** * 当客户端的表单验证出现错误而中断提交动作的时候返回的错误类型。 * @type {String} * @static */ Ext.form.Action.CLIENT_INVALID = 'client'; /** * 服务端验证表单出错时返回的错误类型,在response的<tt style="font-weight:bold">errors</tt>属性里指明具体的字段错误信息。 * @type {String} * @static */ Ext.form.Action.SERVER_INVALID = 'server'; /** * 尝试向远程服务器发送请求遇到通信错误返回的错误类型。 * @type {String} * @static */ Ext.form.Action.CONNECT_FAILURE = 'connect'; /** * 服务端response的<tt style="font-weight:bold">data</tt> 属性没有返回任何字段的值得时候返回的错误类型。 * @type {String} * @static */ Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { /** * @cfg {String} url Action调用的URL资源。 */ /** * @cfg {Boolean} reset 当设置为 <tt><b>true</b></tt>的时候, 导致表单重置 {@link Ext.form.BasicForm.reset reset} * 如果指定了该值,reset将在表单的{@link #success} 回调函数<b>前</b>和{@link Ext.form.BasicForm.actioncomplete actioncomplete}事件被激发前执行。 * event fires. */ /** * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the * @cfg {String} method 获取请求的URL的HTTP方法。默认为{@link Ext.form.BasicForm}的方法。如果没有指定,使用DOM表单的方法。 */ /** * @cfg {Mixed} params 传递到额外值。它们添加到表单的{@link Ext.form.BasicForm#baseParams}由表单的输入字段传递到指定的URL。 */ /** * @cfg {Number} timeout 在服务端返回 {@link #CONNECT_FAILURE}这样的{@link #failureType}之前等待的毫秒数。 */ /** * @cfg {Function} success 当接收到一个有效的成功返回的数据包的时候调用的回调函数。 * 这个函数传递以下的参数:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">作出请求动作的表单</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">Action类。该对象的{@link #result} * 属性可能被检查,用来执行自定义的后期处理。 </ul> */ /** * @cfg {Function} failure 当接收到一个返回失败的数据包或者在Ajax通信时发生错误调用的回调函数。 * 这个函数传递以下的参数:<ul class="mdetail-params"> * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">作出请求动作的表单</div></li> * <li><b>action</b> : Ext.form.Action<div class="sub-desc">Action类。如果发生了Ajax异常, * 错误类型会在{@link #failureType}里。该对象的{@link #result} 属性可能被检查,用来执行自定义的后期处理。 </ul> */ /** * @cfg {Object} scope 回调函数执行的范围。<tt>this</tt> 指改回调函数自身。 */ /** * @cfg {String} waitMsg 在调用一个action的处理过程中调用 {@link Ext.MessageBox#wait} 显示的信息。 */ /** * @cfg {String} waitMsg 在调用一个action的处理过程中调用 {@link Ext.MessageBox#wait} 显示的标题。 */ /** * 改Action的实例执行的action类型。 * 目前仅支持“提交”和“加载”。 * @type {String} */ type : 'default', /** * 错误检查类型。见 {@link #Ext.form.Action.CLIENT_INVALID CLIENT_INVALID}, {@link #Ext.form.Action.SERVER_INVALID SERVER_INVALID}, * {@link #Ext.form.Action.CONNECT_FAILURE CONNECT_FAILURE}, {@link #Ext.form.Action.LOAD_FAILURE LOAD_FAILURE} * @property failureType * @type {String} *//** * 用来执行action的XMLHttpRequest对象。 * @property response * @type {Object} *//** * 解码了的response对象包含一个boolean类型的 <tt style="font-weight:bold">success</tt> 属性和一些action的属性。 * @property result * @type {Object} */ // 接口方法 run : function(options){ }, // 接口方法 success : function(response){ }, // 接口方法 handleResponse : function(response){ }, // 默认的连接错误 failure : function(response){ this.response = response; this.failureType = Ext.form.Action.CONNECT_FAILURE; this.form.afterAction(this, false); }, // 私有的 processResponse : function(response){ this.response = response; if(!response.responseText){ return true; } this.result = this.handleResponse(response); return this.result; }, // 内部使用的工具函数 getUrl : function(appendParams){ var url = this.options.url || this.form.url || this.form.el.dom.action; if(appendParams){ var p = this.getParams(); if(p){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; } } return url; }, // 私有的 getMethod : function(){ return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); }, // 私有的 getParams : function(){ var bp = this.form.baseParams; var p = this.options.params; if(p){ if(typeof p == "object"){ p = Ext.urlEncode(Ext.applyIf(p, bp)); }else if(typeof p == 'string' && bp){ p += '&' + Ext.urlEncode(bp); } }else if(bp){ p = Ext.urlEncode(bp); } return p; }, // 私有的 createCallback : function(opts){ var opts = opts || {}; return { success: this.success, failure: this.failure, scope: this, timeout: (opts.timeout*1000) || (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } };
JavaScript
/** * @class Ext.form.FieldSet * @extends Ext.Panel * 针对某一组字段的标准容器 * @constructor * @param {Object} config 配置选项 */ Ext.form.FieldSet = Ext.extend(Ext.Panel, { /** * @cfg {Boolean} checkboxToggle True表示在lengend标签之前fieldset的范围内渲染一个checkbox(默认为false)。 * 选择该checkbox会为展开、收起该面板服务。 */ /** * @cfg {String} checkboxName 分配到fieldset的checkbox的名称,在{@link #checkboxToggle} = true的情况有效 * (defaults to '[checkbox id]-checkbox'). */ /** * @cfg {Number} labelWidth 标签的宽度,该属性会影响下级的子容器 */ /** * @cfg {String} itemCls 各字段下面的x-form-item的CSS样式类, 该属性会影响下级的子容器 */ /** * @cfg {String} baseCls 应用fieldset到基础样式类(默认为'x-fieldset') */ baseCls:'x-fieldset', /** * @cfg {String} layout fieldset所在的{@link Ext.Container#layout}的类型(默认为'form')。 */ layout: 'form', // private onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('fieldset'); this.el.id = this.id; this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header'; } Ext.form.FieldSet.superclass.onRender.call(this, ct, position); if(this.checkboxToggle){ var o = typeof this.checkboxToggle == 'object' ? this.checkboxToggle : {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}; this.checkbox = this.header.insertFirst(o); this.checkbox.dom.checked = !this.collapsed; this.checkbox.on('click', this.onCheckClick, this); } }, // private onCollapse : function(doAnim, animArg){ if(this.checkbox){ this.checkbox.dom.checked = false; } this.afterCollapse(); }, // private onExpand : function(doAnim, animArg){ if(this.checkbox){ this.checkbox.dom.checked = true; } this.afterExpand(); }, /* //protected * This function is called by the fieldset's checkbox when it is toggled (only applies when * checkboxToggle = true). This method should never be called externally, but can be * overridden to provide custom behavior when the checkbox is toggled if needed. */ onCheckClick : function(){ this[this.checkbox.dom.checked ? 'expand' : 'collapse'](); } /** * @cfg {String/Number} activeItem * @hide */ /** * @cfg {Mixed} applyTo * @hide */ /** * @cfg {Object/Array} bbar * @hide */ /** * @cfg {Boolean} bodyBorder * @hide */ /** * @cfg {Boolean} border * @hide */ /** * @cfg {Boolean/Number} bufferResize * @hide */ /** * @cfg {String} buttonAlign * @hide */ /** * @cfg {Array} buttons * @hide */ /** * @cfg {Boolean} collapseFirst * @hide */ /** * @cfg {String} defaultType * @hide */ /** * @cfg {String} disabledClass * @hide */ /** * @cfg {String} elements * @hide */ /** * @cfg {Boolean} floating * @hide */ /** * @cfg {Boolean} footer * @hide */ /** * @cfg {Boolean} frame * @hide */ /** * @cfg {Boolean} header * @hide */ /** * @cfg {Boolean} headerAsText * @hide */ /** * @cfg {Boolean} hideCollapseTool * @hide */ /** * @cfg {String} iconCls * @hide */ /** * @cfg {Boolean/String} shadow * @hide */ /** * @cfg {Number} shadowOffset * @hide */ /** * @cfg {Boolean} shim * @hide */ /** * @cfg {Object/Array} tbar * @hide */ /** * @cfg {Boolean} titleCollapse * @hide */ /** * @cfg {Array} tools * @hide */ /** * @cfg {String} xtype * @hide */ /** * @property header * @hide */ /** * @property footer * @hide */ /** * @method focus * @hide */ /** * @method getBottomToolbar * @hide */ /** * @method getTopToolbar * @hide */ /** * @method setIconClass * @hide */ /** * @event activate * @hide */ /** * @event beforeclose * @hide */ /** * @event bodyresize * @hide */ /** * @event close * @hide */ /** * @event deactivate * @hide */ }); Ext.reg('fieldset', Ext.form.FieldSet);
JavaScript
/** * @class Ext.form.TriggerField * @extends Ext.form.TextField * 为添加了带有可触发事件的按钮的TextFields(文本域)提供一个方便的封装(很像一个默认combobox)。 * 触发器没有默认行为(action),因此你必须通过重写方法{@link #onTriggerClick}的方式,指派一个方法实现触发器的点击事件处理。 * 你可以直接创建一个TriggerField(触发域),由于它会呈现与combobox相像的效果,你可以通过它提供一种自定义的实现。例如: * <pre><code> var trigger = new Ext.form.TriggerField(); trigger.onTriggerClick = myTriggerFn; trigger.applyTo('my-field'); </code></pre> * * 然而,你可能会更倾向于将TriggerField作为一个可复用容器的基类。 * {@link Ext.form.DateField}和{@link Ext.form.ComboBox}就是两个较好的样板. * @cfg {String} triggerClass 配置项triggerClass(字符串)是一个附加的CSS类,用于为触发器按钮设置样式。 * 配置项triggerClass(触发器样式)如果被指定则会被<b>附加</b>,否则默认为“x-form-trigger” * @constructor * 创建一个新TriggerField的对象。 * @param {Object} config 配置选择(对于有效的{@Ext.form.TextField}配置项也会被传入到TextField) */ Ext.form.TriggerField = Ext.extend(Ext.form.TextField, { /** * @cfg {String} triggerClass 应用到触发器身上的CSS样式类 */ /** * @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为 * {tag: "input", type: "text", size: "16", autocomplete: "off"}) */ defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"}, /** * @cfg {Boolean} hideTrigger 为true时隐藏触发元素,只显示基本文本域(默认为false)。 */ hideTrigger:false, /** * @hide * @method autoSize */ autoSize: Ext.emptyFn, // private monitorTab : true, // private deferHeight : true, // private mimicing : false, // private onResize : function(w, h){ Ext.form.TriggerField.superclass.onResize.call(this, w, h); if(typeof w == 'number'){ this.el.setWidth(this.adjustWidth('input', w - this.trigger.getWidth())); } this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()); }, // private adjustSize : Ext.BoxComponent.prototype.adjustSize, // private getResizeEl : function(){ return this.wrap; }, // private getPositionEl : function(){ return this.wrap; }, // private alignErrorIcon : function(){ this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]); }, // private onRender : function(ct, position){ Ext.form.TriggerField.superclass.onRender.call(this, ct, position); this.wrap = this.el.wrap({cls: "x-form-field-wrap"}); this.trigger = this.wrap.createChild(this.triggerConfig || {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}); if(this.hideTrigger){ this.trigger.setDisplayed(false); } this.initTrigger(); if(!this.width){ this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()); } }, // private initTrigger : function(){ this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true}); this.trigger.addClassOnOver('x-form-trigger-over'); this.trigger.addClassOnClick('x-form-trigger-click'); }, // private onDestroy : function(){ if(this.trigger){ this.trigger.removeAllListeners(); this.trigger.remove(); } if(this.wrap){ this.wrap.remove(); } Ext.form.TriggerField.superclass.onDestroy.call(this); }, // private onFocus : function(){ Ext.form.TriggerField.superclass.onFocus.call(this); if(!this.mimicing){ this.wrap.addClass('x-trigger-wrap-focus'); this.mimicing = true; Ext.get(Ext.isIE ? document.body : document).on("mousedown", this.mimicBlur, this, {delay: 10}); if(this.monitorTab){ this.el.on("keydown", this.checkTab, this); } } }, // private checkTab : function(e){ if(e.getKey() == e.TAB){ this.triggerBlur(); } }, // private onBlur : function(){ // do nothing }, // private mimicBlur : function(e){ if(!this.wrap.contains(e.target) && this.validateBlur(e)){ this.triggerBlur(); } }, // private triggerBlur : function(){ this.mimicing = false; Ext.get(Ext.isIE ? document.body : document).un("mousedown", this.mimicBlur); if(this.monitorTab){ this.el.un("keydown", this.checkTab, this); } this.beforeBlur(); this.wrap.removeClass('x-trigger-wrap-focus'); Ext.form.TriggerField.superclass.onBlur.call(this); }, beforeBlur : Ext.emptyFn, // private //这个方法须有子类重写(覆盖),需要确认该域是否可以被雾化。 validateBlur : function(e){ return true; }, // private onDisable : function(){ Ext.form.TriggerField.superclass.onDisable.call(this); if(this.wrap){ this.wrap.addClass('x-item-disabled'); } }, // private onEnable : function(){ Ext.form.TriggerField.superclass.onEnable.call(this); if(this.wrap){ this.wrap.removeClass('x-item-disabled'); } }, // private onShow : function(){ if(this.wrap){ this.wrap.dom.style.display = ''; this.wrap.dom.style.visibility = 'visible'; } }, // private onHide : function(){ this.wrap.dom.style.display = 'none'; }, /** * 该方法应该用于处理触发器的click事件。默认为空方法,要被某个实现的方法重写后才会有效。 * @method * @param {EventObject} e 参数e是({EventObject}类型) */ onTriggerClick : Ext.emptyFn /** * @cfg {Boolean} grow @hide */ /** * @cfg {Number} growMin @hide */ /** * @cfg {Number} growMax @hide */ }); // TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class // to be extended by an implementing class. For an example of implementing this class, see the custom // SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, { initComponent : function(){ Ext.form.TwinTriggerField.superclass.initComponent.call(this); this.triggerConfig = { tag:'span', cls:'x-form-twin-triggers', cn:[ {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class}, {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class} ]}; }, getTrigger : function(index){ return this.triggers[index]; }, initTrigger : function(){ var ts = this.trigger.select('.x-form-trigger', true); this.wrap.setStyle('overflow', 'hidden'); var triggerField = this; ts.each(function(t, all, index){ t.hide = function(){ var w = triggerField.wrap.getWidth(); this.dom.style.display = 'none'; triggerField.el.setWidth(w-triggerField.trigger.getWidth()); }; t.show = function(){ var w = triggerField.wrap.getWidth(); this.dom.style.display = ''; triggerField.el.setWidth(w-triggerField.trigger.getWidth()); }; var triggerIndex = 'Trigger'+(index+1); if(this['hide'+triggerIndex]){ t.dom.style.display = 'none'; } t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true}); t.addClassOnOver('x-form-trigger-over'); t.addClassOnClick('x-form-trigger-click'); }, this); this.triggers = ts.elements; }, onTrigger1Click : Ext.emptyFn, onTrigger2Click : Ext.emptyFn }); Ext.reg('trigger', Ext.form.TriggerField);
JavaScript
/** * @class Ext.form.BasicForm * @extends Ext.util.Observable * 提供表单的多种动作("actions")功能,并且初始化 Ext.form.Field 类型在现有的标签上 * @constructor * @param {String/HTMLElement/Ext.Element} el 表单对象或它的ID * @param {Object} config 配置表单对象的配置项选项 */ Ext.form.BasicForm = function(el, config){ Ext.apply(this, config); /** * 所有表单内元素的集合。 * @type MixedCollection */ this.items = new Ext.util.MixedCollection(false, function(o){ return o.id || (o.id = Ext.id()); }); this.addEvents( /** * @event beforeaction * 在任何动作被执行前被触发。如果返回假则取消这个动作 * @param {Form} this * @param {Action} action 要被执行的动作对象 */ 'beforeaction', /** * @event actionfailed * 当动作失败时被触发。 * @param {Form} this * @param {Action} action 失败的动作对象 */ 'actionfailed', /** * @event actioncomplete * 当动作完成时被触发。 * @param {Form} this * @param {Action} action 完成的动作对象 */ 'actioncomplete' ); if(el){ this.initEl(el); } Ext.form.BasicForm.superclass.constructor.call(this); }; Ext.extend(Ext.form.BasicForm, Ext.util.Observable, { /** * @cfg {String} method * 所有动作的默认表单请求方法(GET 或 POST) */ /** * @cfg {DataReader} reader * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read data when executing "load" actions. * This is optional as there is built-in support for processing JSON. * 一个Ext.data.DataReader对象(e.g. {@link Ext.data.XmlReader}),当执行"load"动作时被用来读取数据 * 它是一个可选项,因为这里已经有了一个内建对象来读取JSON数据 */ /** * @cfg {DataReader} errorReader * 一个Ext.data.DataReader对象(e.g. {@link Ext.data.XmlReader}),当执行"submit"动作出错时被用来读取数据 */ /** * @cfg {String} url * 当动作选项未指定url时使用 */ /** * @cfg {Boolean} fileUpload. * 当为true时,表单为文件上传类型。 * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b> * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the * DOM <tt>&lt;form></tt> element temporarily modified to have its * {@link http://www.w3.org/TR/REC-html40/present/frames.html#adef-target target} set to refer * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document * but removed after the return data has been gathered.</p> * <p>The server response is parsed by the browser to create the document for the IFRAME. If the * server is using JSON to send the return object, then the * {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 Content-Type} header * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p> * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object * is created containing a <tt>responseText</tt> property in order to conform to the * requirements of event handlers and callbacks.</p> * <p>Be aware that file upload packets are sent with the content type {@link http://www.faqs.org/rfcs/rfc2388.html multipart/form} * and some server technologies (notably JEE) may require some custom processing in order to * retrieve parameter names and parameter values from the packet content.</p> */ /** * @cfg {Object} baseParams * 表单请求时传递的参数。例,baseParams: {id: '123', foo: 'bar'} */ /** * @cfg {Number} timeout * 表单动作的超时秒数(默认30秒) */ timeout: 30, activeAction : null, /** * @cfg {Boolean} trackResetOnLoad 如果为true,表单对象的form.reset()方法重置到最后一次加载或setValues()数据, * */ trackResetOnLoad : false, /** * @cfg {Boolean} standardSubmit If set to true, standard HTML form submits are used instead of XHR (Ajax) style * form submissions. (defaults to false) */ /** * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific * element by passing it or its id or mask the form itself by passing in true. * 默认的等待提示窗口为Ext.MessageBox.wait。也可以指定一个对象或它的ID做为遮罩目标,如果指定为真则直接遮罩在表单对象上 * @type Mixed * @property waitMsgTarget */ initEl : function(el){ this.el = Ext.get(el); this.id = this.el.id || Ext.id(); if(!this.standardSubmit){ this.el.on('submit', this.onSubmit, this); } this.el.addClass('x-form'); }, getEl: function(){ return this.el; }, onSubmit : function(e){ e.stopEvent(); }, destroy: function() { this.items.each(function(f){ Ext.destroy(f); }); if(this.el){ this.el.removeAllListeners(); this.el.remove(); } this.purgeListeners(); }, /** * 如果客户端的验证通过则返回真 * @return Boolean */ isValid : function(){ var valid = true; this.items.each(function(f){ if(!f.validate()){ valid = false; } }); return valid; }, /** * 如果自从被加载后任何一个表单元素被修了,则返回真 * @return Boolean */ isDirty : function(){ var dirty = false; this.items.each(function(f){ if(f.isDirty()){ dirty = true; return false; } }); return dirty; }, /** * Performs a predefined action ({@link Ext.form.Action.Submit} or * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action} * to perform application-specific processing. * @param {String/Object} actionName The name of the predefined action type, * or instance of {@link Ext.form.Action} to perform. * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}. * All of the config options listed below are supported by both the submit * and load actions unless otherwise noted (custom actions could also accept * other config options):<ul> * <li><b>url</b> : String<p style="margin-left:1em">The url for the action (defaults * to the form's url.)</p></li> * <li><b>method</b> : String<p style="margin-left:1em">The form method to use (defaults * to the form's method, or POST if not defined)</p></li> * <li><b>params</b> : String/Object<p style="margin-left:1em">The params to pass * (defaults to the form's baseParams, or none if not defined)</p></li> * <li><b>headers</b> : Object<p style="margin-left:1em">Request headers to set for the action * (defaults to the form's default headers)</p></li> * <li><b>success</b> : Function<p style="margin-left:1em">The callback that will * be invoked after a successful response. Note that this is HTTP success * (the transaction was sent and received correctly), but the resulting response data * can still contain data errors. The function is passed the following parameters:<ul> * <li><code>form</code> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><code>action</code> : Ext.form.Action<div class="sub-desc">The Action class. The {@link Ext.form.Action#result result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul></p></li> * <li><b>failure</b> : Function<p style="margin-left:1em">The callback that will * be invoked after a failed transaction attempt. Note that this is HTTP failure, * which means a non-successful HTTP code was returned from the server. The function * is passed the following parameters:<ul> * <li><code>form</code> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li> * <li><code>action</code> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax * error ocurred, the failure type will be in {@link Ext.form.Action#failureType failureType}. The {@link Ext.form.Action#result result} * property of this object may be examined to perform custom postprocessing.</div></li> * </ul></p></li> * <li><b>scope</b> : Object<p style="margin-left:1em">The scope in which to call the * callback functions (The <tt>this</tt> reference for the callback functions).</p></li> * <li><b>clientValidation</b> : Boolean<p style="margin-left:1em">Submit Action only. * Determines whether a Form's fields are validated in a final call to * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt> * to prevent this. If undefined, pre-submission field validation is performed.</p></li></ul> * @return {BasicForm} this */ doAction2_1: function(){}, /** * Performs a predefined action (submit or load) or custom actions you define on this form. * 执行一个预定义的(提交或加载)或一个在表单上自定义的动作, * @param {String} actionName The name of the action type 行为名称 * @param {Object} options (optional) The options to pass to the action. All of the config options listed * below are supported by both the submit and load actions unless otherwise noted (custom actions could also * accept other config options): * 传递给行动作象的选项配制。除非另有声明(自定义的动作仍然可以有附加的选项配制),下面是所有提供给提交与加载动作的选项配制列表。 * <pre> * Property Type Description * ---------------- --------------- ---------------------------------------------------------------------------------- * url String The url for the action (defaults to the form's url) * method String The form method to use (defaults to the form's method, or POST if not defined) * params String/Object The params to pass (defaults to the form's baseParams, or none if not defined) * clientValidation Boolean Applies to submit only. Pass true to call form.isValid() prior to posting to * validate the form on the client (defaults to false) * </pre> * 属性 类型 描述 * ---------------- --------------- ---------------------------------------------------------------------------------- * url String 动作请求的url (默认为表单的url) * method String 表单使用的提交方式 (默认为表单的方法,如果没有指定则"POST") * params String/Object 要传递的参数 (默认为表单的基本参数,如果没有指定则为空) * clientValidation Boolean 只应用到提交方法。为真则在提交前调用表单对像的isValid方法,实现在客户端的验证。(默认为假) * * @return {BasicForm} this */ doAction : function(action, options){ if(typeof action == 'string'){ action = new Ext.form.Action.ACTION_TYPES[action](this, options); } if(this.fireEvent('beforeaction', this, action) !== false){ this.beforeAction(action); action.run.defer(100, action); } return this; }, /** * 做提交动作的简便方法。 * @param {Object} options 传递给动作对象的选项配制 (请见 {@link #doAction} ) * @return {BasicForm} this */ submit : function(options){ if(this.standardSubmit){ var v = this.isValid(); if(v){ this.el.dom.submit(); } return v; } this.doAction('submit', options); return this; }, /** * 做加载动作的简便方法。 * @param {Object} options 传递给动作对象的选项配制 (请见 {@link #doAction} ) * @return {BasicForm} this */ load : function(options){ this.doAction('load', options); return this; }, /** * Persists the values in this form into the passed Ext.data.Record object in a beginEdit/endEdit block. * 表单内的元素数据考贝到所传递的Ext.data.Record对象中(beginEdit/endEdit块中进行赋值操作)。 * @param {Record} record The record to edit * @return {BasicForm} this */ updateRecord : function(record){ record.beginEdit(); var fs = record.fields; fs.each(function(f){ var field = this.findField(f.name); if(field){ record.set(f.name, field.getValue()); } }, this); record.endEdit(); return this; }, /** * Loads an Ext.data.Record into this form. * 加载Ext.data.Record对象的数据到表单元素中。 * @param {Record} record The record to load * @return {BasicForm} this */ loadRecord : function(record){ this.setValues(record.data); return this; }, // private beforeAction : function(action){ var o = action.options; if(o.waitMsg){ if(this.waitMsgTarget === true){ this.el.mask(o.waitMsg, 'x-mask-loading'); }else if(this.waitMsgTarget){ this.waitMsgTarget = Ext.get(this.waitMsgTarget); this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading'); }else{ Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle || 'Please Wait...'); } } }, // private afterAction : function(action, success){ this.activeAction = null; var o = action.options; if(o.waitMsg){ if(this.waitMsgTarget === true){ this.el.unmask(); }else if(this.waitMsgTarget){ this.waitMsgTarget.unmask(); }else{ Ext.MessageBox.updateProgress(1); Ext.MessageBox.hide(); } } if(success){ if(o.reset){ this.reset(); } Ext.callback(o.success, o.scope, [this, action]); this.fireEvent('actioncomplete', this, action); }else{ Ext.callback(o.failure, o.scope, [this, action]); this.fireEvent('actionfailed', this, action); } }, /** * 按传递的ID、索引或名称查询表单中的元素。 * @param {String} id 所要查询的值 * @return Field */ findField : function(id){ var field = this.items.get(id); if(!field){ this.items.each(function(f){ if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){ field = f; return false; } }); } return field || null; }, /** * 可以批量的标记表单元素为失效的。 * @param {Array/Object} errors 即可以是像这样的 [{id:'fieldId', msg:'The message'},...] 数组,也可以是像这样 {id: msg, id2: msg2} 的一个HASH结构对象。 * @return {BasicForm} this */ markInvalid : function(errors){ if(Ext.isArray(errors)){ for(var i = 0, len = errors.length; i < len; i++){ var fieldError = errors[i]; var f = this.findField(fieldError.id); if(f){ f.markInvalid(fieldError.msg); } } }else{ var field, id; for(id in errors){ if(typeof errors[id] != 'function' && (field = this.findField(id))){ field.markInvalid(errors[id]); } } } return this; }, /** * 表单元素批量赋值。 * @param {Array/Object} values 即可以是像这样的 [{id:'fieldId', value:'foo'},...] 数组,也可以是像这样 {id: value, id2: value2} 的一个HASH结构对象。 * @return {BasicForm} this */ setValues : function(values){ if(Ext.isArray(values)){ // array of objects for(var i = 0, len = values.length; i < len; i++){ var v = values[i]; var f = this.findField(v.id); if(f){ f.setValue(v.value); if(this.trackResetOnLoad){ f.originalValue = f.getValue(); } } } }else{ // object hash var field, id; for(id in values){ if(typeof values[id] != 'function' && (field = this.findField(id))){ field.setValue(values[id]); if(this.trackResetOnLoad){ field.originalValue = field.getValue(); } } } } return this; }, /** * 返回以键/值形式包函表单所有元素的信息对象。 * 如果表单元素中有相同名称的对象,则返回一个同名数组。 * @param {Boolean} asString 如果为真则返回一个字串,如果为假则返回一个键/值对象。(默认为假) * @return {Object} */ getValues : function(asString){ var fs = Ext.lib.Ajax.serializeForm(this.el.dom); if(asString === true){ return fs; } return Ext.urlDecode(fs); }, /** * 清除表单中所有校验错误的显示信息。 * @return {BasicForm} this */ clearInvalid : function(){ this.items.each(function(f){ f.clearInvalid(); }); return this; }, /** * 重置表单。 * @return {BasicForm} this */ reset : function(){ this.items.each(function(f){ f.reset(); }); return this; }, /** * 向表单中清加组件。 * @param {Field} field1 * @param {Field} field2 (optional) * @param {Field} etc (optional) * @return {BasicForm} this */ add : function(){ this.items.addAll(Array.prototype.slice.call(arguments, 0)); return this; }, /** * 从表单对象集中清除一个元素(不清除它的页面标签)。 * @param {Field} field * @return {BasicForm} this */ remove : function(field){ this.items.remove(field); return this; }, /** * 遍历表单所有元素,以ID属性检查它们是否在页面上存在, * 以它的ID为值调用每个元素的applyTo方法到现有的页面对象。 * @return {BasicForm} this */ render : function(){ this.items.each(function(f){ if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists f.applyToMarkup(f.id); } }); return this; }, /** * 遍历表单元素并以传递的对象为参调用 {@link Ext#apply} 方法。 * @param {Object} values * @return {BasicForm} this */ applyToFields : function(o){ this.items.each(function(f){ Ext.apply(f, o); }); return this; }, /** * 遍历表单元素并以传递的对象为参调用 {@link Ext#applyIf} 方法。 * @param {Object} values * @return {BasicForm} this */ applyIfToFields : function(o){ this.items.each(function(f){ Ext.applyIf(f, o); }); return this; } }); // back compat Ext.BasicForm = Ext.form.BasicForm;
JavaScript
/** * @class Ext.form.TextField * @extends Ext.form.Field * 基本的文本字段。可以被当作传统文本转入框的直接代替, 或者当作其他更复杂输入控件的基础类(比如 {@link Ext.form.TextArea} 和 {@link Ext.form.ComboBox})。 * @constructor * 创建一个 TextField 对象 * @param {Object} config 配置项 */ Ext.form.TextField = Ext.extend(Ext.form.Field, { /** * @cfg {Boolean} grow 当值为 true 时表示字段可以根据内容自动伸缩 */ grow : false, /** * @cfg {Number} growMin 当 grow = true 时允许的字段最小宽度(默认为 30) */ growMin : 30, /** * @cfg {Number} growMax 当 grow = true 时允许的字段最大宽度(默认为 800) */ growMax : 800, /** * @cfg {String} vtype {@link Ext.form.VTypes} 中定义的效验类型名(默认为 null) */ vtype : null, /** * @cfg {String} maskRe 一个用来过滤无效按键的正则表达式(默认为 null) */ maskRe : null, /** * @cfg {Boolean} disableKeyFilter 值为 true 时禁用输入按键过滤(默认为 false) */ disableKeyFilter : false, /** * @cfg {Boolean} allowBlank 值为 false 时将效验输入字符个数大于0(默认为 true) */ allowBlank : true, /** * @cfg {Number} minLength 输入字段所需的最小字符数(默认为 0) */ minLength : 0, /** * @cfg {Number} maxLength 输入字段允许的最大字符数(默认为 Number.MAX_VALUE) */ maxLength : Number.MAX_VALUE, /** * @cfg {String} minLengthText 输入字符数小于最小字符数时显示的文本(默认为 "The minimum length for this field is {minLength}") */ minLengthText : "The minimum length for this field is {0}", /** * @cfg {String} maxLengthText 输入字符数小于最小字符数时显示的文本(默认为 "The maximum length for this field is {maxLength}") */ maxLengthText : "The maximum length for this field is {0}", /** * @cfg {Boolean} selectOnFocus 值为 ture 时表示字段获取焦点时自动选择字段既有文本(默认为 false) */ selectOnFocus : false, /** * @cfg {String} blankText 当允许为空效验失败时显示的错误文本(默认为 "This field is required") */ blankText : "This field is required", /** * @cfg {Function} validator 字段效验时调用的自定义的效验函数(默认为 null)。如果启用此项, 则此函数将在所有基础效验成功之后被调用, 调用函数时传递的参数为该字段的值。且此函数的有效返回应为成功时返回 true, 失败时返回错误文本。 */ validator : null, /** * @cfg {RegExp} regex 一个用以在效验时使用的 JavaScript 正则表达式对象(默认为 null)。如果启用此项, 则此正则表达式将在所有基础效验成功之后被执行, 执行此正则表达式时传递的参数为该字段的值。如果效验失败, 则根据 {@link #regexText} 的设置将字段标记为无效。 */ regex : null, /** * @cfg {String} regexText 当 {@link #regex} 被设置且效验失败时显示的错误文本(默认为 "") */ regexText : "", /** * @cfg {String} emptyText 空字段中显示的文本(默认为 null)。 */ emptyText : null, /** * @cfg {String} emptyClass {@link #emptyText} 使用的CSS样式类名(默认为 'x-form-empty-field')。此类的添加与移除均由当前字段是否有值来自动处理。 */ emptyClass : 'x-form-empty-field', /** * @cfg {Boolean} enableKeyEvents True to enable the proxying of key events for the HTML input field (defaults to false) * True表示,为HTML的input输入字段激活键盘事件的代理(默认为false) */ initComponent : function(){ Ext.form.TextField.superclass.initComponent.call(this); this.addEvents( /** * @event autosize * Fires when the autosize function is triggered. The field may or may not have actually changed size * according to the default logic, but this event provides a hook for the developer to apply additional * logic at runtime to resize the field if needed. * 当autosize函数调用时触发。根据缺省的逻辑,字段有可能不会真正地改变大小,但该事件的目的至于,允许开发人员在运行时加入额外的逻辑,以备调整输入字段的大小。 * @param {Ext.form.Field} this This text field 文本输入字段 * @param {Number} width 新宽度 */ 'autosize', /** * @event keydown * Keydown input field event. This event only fires if enableKeyEvents is set to true. * 输入字段键盘下降时的事件。该事件只会在enableKeyEvents为true时有效。 * @param {Ext.form.TextField} this This text field 文本输入字段 * @param {Ext.EventObject} e */ 'keydown', /** * @event keyup * Keyup input field event. This event only fires if enableKeyEvents is set to true. * 输入字段键盘升起时的事件。该事件只会在enableKeyEvents为true时有效。 * @param {Ext.form.TextField} this This text field 文本输入字段 * @param {Ext.EventObject} e */ 'keyup', /** * @event keypress * Keypress input field event. This event only fires if enableKeyEvents is set to true. * 输入字段键盘按下时的事件。该事件只会在enableKeyEvents为true时有效。 * @param {Ext.form.TextField} this This text field 文本输入字段 * @param {Ext.EventObject} e */ 'keypress' ); }, // private initEvents : function(){ Ext.form.TextField.superclass.initEvents.call(this); if(this.validationEvent == 'keyup'){ this.validationTask = new Ext.util.DelayedTask(this.validate, this); this.el.on('keyup', this.filterValidation, this); } else if(this.validationEvent !== false){ this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay}); } if(this.selectOnFocus || this.emptyText){ this.on("focus", this.preFocus, this); if(this.emptyText){ this.on('blur', this.postBlur, this); this.applyEmptyText(); } } if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){ this.el.on("keypress", this.filterKeys, this); } if(this.grow){ this.el.on("keyup", this.onKeyUpBuffered, this, {buffer:50}); this.el.on("click", this.autoSize, this); } if(this.enableKeyEvents){ this.el.on("keyup", this.onKeyUp, this); this.el.on("keydown", this.onKeyDown, this); this.el.on("keypress", this.onKeyPress, this); } }, processValue : function(value){ if(this.stripCharsRe){ var newValue = value.replace(this.stripCharsRe, ''); if(newValue !== value){ this.setRawValue(newValue); return newValue; } } return value; }, filterValidation : function(e){ if(!e.isNavKeyPress()){ this.validationTask.delay(this.validationDelay); } }, // private onKeyUpBuffered : function(e){ if(!e.isNavKeyPress()){ this.autoSize(); } }, // private onKeyUp : function(e){ this.fireEvent('keyup', this, e); }, // private onKeyDown : function(e){ this.fireEvent('keydown', this, e); }, // private onKeyPress : function(e){ this.fireEvent('keypress', this, e); }, /** * 将字段值重置为原始值, 并清除所有效验信息。如果原始值为空时还将使 emptyText 和 emptyClass 属性生效。 */ reset : function(){ Ext.form.TextField.superclass.reset.call(this); this.applyEmptyText(); }, applyEmptyText : function(){ if(this.rendered && this.emptyText && this.getRawValue().length < 1){ this.setRawValue(this.emptyText); this.el.addClass(this.emptyClass); } }, // private preFocus : function(){ if(this.emptyText){ if(this.el.dom.value == this.emptyText){ this.setRawValue(''); } this.el.removeClass(this.emptyClass); } if(this.selectOnFocus){ this.el.dom.select(); } }, // private postBlur : function(){ this.applyEmptyText(); }, // private filterKeys : function(e){ var k = e.getKey(); if(!Ext.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){ return; } var c = e.getCharCode(), cc = String.fromCharCode(c); if(Ext.isIE && (e.isSpecialKey() || !cc)){ return; } if(!this.maskRe.test(cc)){ e.stopEvent(); } }, setValue : function(v){ if(this.emptyText && this.el && v !== undefined && v !== null && v !== ''){ this.el.removeClass(this.emptyClass); } Ext.form.TextField.superclass.setValue.apply(this, arguments); this.applyEmptyText(); this.autoSize(); }, /** * 根据字段的效验规则效验字段值, 并在效验失败时将字段标记为无效 * @param {Mixed} value 要效验的值 * @return {Boolean} 值有效时返回 true, 否则返回 false */ validateValue : function(value){ if(value.length < 1 || value === this.emptyText){ // if it's blank if(this.allowBlank){ this.clearInvalid(); return true; }else{ this.markInvalid(this.blankText); return false; } } if(value.length < this.minLength){ this.markInvalid(String.format(this.minLengthText, this.minLength)); return false; } if(value.length > this.maxLength){ this.markInvalid(String.format(this.maxLengthText, this.maxLength)); return false; } if(this.vtype){ var vt = Ext.form.VTypes; if(!vt[this.vtype](value, this)){ this.markInvalid(this.vtypeText || vt[this.vtype +'Text']); return false; } } if(typeof this.validator == "function"){ var msg = this.validator(value); if(msg !== true){ this.markInvalid(msg); return false; } } if(this.regex && !this.regex.test(value)){ this.markInvalid(this.regexText); return false; } return true; }, /** * 选择此字段中的文本 * @param {Number} start (可选项) 选择区域的索引起点(默认为 0) * @param {Number} end (可选项) 选择区域的索引终点(默认为文本长度) */ selectText : function(start, end){ var v = this.getRawValue(); if(v.length > 0){ start = start === undefined ? 0 : start; end = end === undefined ? v.length : end; var d = this.el.dom; if(d.setSelectionRange){ d.setSelectionRange(start, end); }else if(d.createTextRange){ var range = d.createTextRange(); range.moveStart("character", start); range.moveEnd("character", end-v.length); range.select(); } } }, /** * 自动增长字段宽度以便容纳字段所允许的最大文本。仅在 grow = true 时有效, 并触发 autosize 事件。 */ autoSize : function(){ if(!this.grow || !this.rendered){ return; } if(!this.metrics){ this.metrics = Ext.util.TextMetrics.createInstance(this.el); } var el = this.el; var v = el.dom.value; var d = document.createElement('div'); d.appendChild(document.createTextNode(v)); v = d.innerHTML; d = null; v += "&#160;"; var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin)); this.el.setWidth(w); this.fireEvent("autosize", this, w); } }); Ext.reg('textfield', Ext.form.TextField);
JavaScript
/** * @class Ext.form.NumberField * @extends Ext.form.TextField * 数字型文本域,提供自动键击过滤和数字校验。 * @constructor * 创建一个新的NumberField对象 * @param {Object} config 配置选项 */ Ext.form.NumberField = Ext.extend(Ext.form.TextField, { /** * @cfg {String} fieldClass 设置该域的CSS,默认为x-form-field x-form-num-field */ fieldClass: "x-form-field x-form-num-field", /** * @cfg {Boolean} allowDecimals 值为 False时将不接受十进制值 (默认为true) */ allowDecimals : true, /** * @cfg {String} decimalSeparator 设置十进制数分割符(默认为 '.')(??指的大概是小数点) */ decimalSeparator : ".", /** * @cfg {Number} decimalPrecision 设置小数点后最大精确位数(默认为 2) */ decimalPrecision : 2, /** * @cfg {Boolean} allowNegative 值为 False时只允许为正数 (默认为 true,即默认允许为负数) */ allowNegative : true, /** * @cfg {Number} minValue 允许的最小值 (默认为 Number.NEGATIVE_INFINITY) */ minValue : Number.NEGATIVE_INFINITY, /** * @cfg {Number} maxValue 允许的最大值 (默认为Number.MAX_VALUE) */ maxValue : Number.MAX_VALUE, /** * @cfg {String} minText 最小值验证失败(ps:超出设置的最小值范围)时显示该错误信息(默认为"The minimum value for this field is {0}") */ minText : "The minimum value for this field is {0}", /** * @cfg {String} maxText 最大值验证失败(ps:超出设置的最大值范围)时显示该错误信息(默认为 "The maximum value for this field is {maxValue}") */ maxText : "The maximum value for this field is {0}", /** * @cfg {String} nanText 当值非数字时显示此错误信息。例如,如果仅仅合法字符如'.' 或 '-'而没有其他任何数字出现在该域时,会显示该错误信息。(默认为"{value} is not a valid number") */ nanText : "{0} is not a valid number", /** * @cfg {String} baseChars * 接受有效数字的一组基础字符(默认为0123456789) */ baseChars : "0123456789", // private initEvents : function(){ Ext.form.NumberField.superclass.initEvents.call(this); var allowed = this.baseChars+''; if(this.allowDecimals){ allowed += this.decimalSeparator; } if(this.allowNegative){ allowed += "-"; } this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi'); var keyPress = function(e){ var k = e.getKey(); if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){ return; } var c = e.getCharCode(); if(allowed.indexOf(String.fromCharCode(c)) === -1){ e.stopEvent(); } }; this.el.on("keypress", keyPress, this); }, // private validateValue : function(value){ if(!Ext.form.NumberField.superclass.validateValue.call(this, value)){ return false; } if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid return true; } value = String(value).replace(this.decimalSeparator, "."); if(isNaN(value)){ this.markInvalid(String.format(this.nanText, value)); return false; } var num = this.parseValue(value); if(num < this.minValue){ this.markInvalid(String.format(this.minText, this.minValue)); return false; } if(num > this.maxValue){ this.markInvalid(String.format(this.maxText, this.maxValue)); return false; } return true; }, getValue : function(){ return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this))); }, setValue : function(v){ Ext.form.NumberField.superclass.setValue.call(this, String(parseFloat(v)).replace(".", this.decimalSeparator)); }, // private parseValue : function(value){ value = parseFloat(String(value).replace(this.decimalSeparator, ".")); return isNaN(value) ? '' : value; }, // private fixPrecision : function(value){ var nan = isNaN(value); if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){ return nan ? '' : value; } return parseFloat(parseFloat(value).toFixed(this.decimalPrecision)); }, beforeBlur : function(){ var v = this.parseValue(this.getRawValue()); if(v){ this.setValue(this.fixPrecision(v)); } } }); Ext.reg('numberfield', Ext.form.NumberField);
JavaScript
/** * @class Ext.form.Action.Submit * @extends Ext.form.Action * A class which handles submission of data from {@link Ext.form.BasicForm Form}s * and processes the returned response. * <br><br> * Instances of this class are only created by a {@link Ext.form.BasicForm Form} when * submitting. * <br><br> * A response packet must contain a boolean <tt style="font-weight:bold">success</tt> property, and, optionally * an <tt style="font-weight:bold">errors</tt> property. The <tt style="font-weight:bold">errors</tt> property contains error * messages for invalid fields. * <br><br> * By default, response packets are assumed to be JSON, so a typical response * packet may look like this: * <br><br><pre><code> { success: false, errors: { clientCode: "Client not found", portOfLoading: "This field must not be null" } }</code></pre> * <br><br> * Other data may be placed into the response for processing the the {@link Ext.form.BasicForm}'s callback * or event handler methods. The object decoded from this JSON is available in the {@link #result} property. */ Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { /** * @cfg {boolean} clientValidation Determines whether a Form's fields are validated * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission. * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation * is performed. */ type : 'submit', // private run : function(){ var o = this.options; var method = this.getMethod(); var isPost = method == 'POST'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(!isPost), method: method, params:isPost ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ // client validation failed this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, // private success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, // private handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++) { var r = rs.records[i]; errors[i] = r.data; } } if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } });
JavaScript
/** * @class Ext.form.HtmlEditor * @extends Ext.form.Field * 提供一个轻量级的 HTML 编辑器组件。 * <br><br><b>注意: 此组件不支持由 Ext.form.Field 继承而来的 focus/blur 和效验函数。</b><br/><br/> * 编辑器组件是非常敏感的, 因此它并不能应用于所有标准字段的场景。在 Safari 和 Firefox 中, 在任何 display 属性被设置为 'none' 的元素中使用该组件都会造成错误<br/><br/> * <b>注意:</b> 在 Ext 1.1 中, 一个页面只能使用一个 HtmlEditor 组件。而在 Ext 2.0+ 没有这个限制了。 */ Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, { /** * @cfg {Boolean} enableFormat 允许粗体、斜体和下划线按钮(默认为 true) */ enableFormat : true, /** * @cfg {Boolean} enableFontSize 允许增大/缩小字号按钮(默认为 true) */ enableFontSize : true, /** * @cfg {Boolean} enableColors 允许前景/高亮颜色按钮(默认为 true) */ enableColors : true, /** * @cfg {Boolean} enableAlignments 允许居左、居中、居右按钮(默认为 true) */ enableAlignments : true, /** * @cfg {Boolean} enableLists 允许项目和列表符号按钮。Safari 中无效。(默认为 true) */ enableLists : true, /** * @cfg {Boolean} enableSourceEdit 允许切换到源码编辑按钮。Safari 中无效。(默认为 true) */ enableSourceEdit : true, /** * @cfg {Boolean} enableLinks 允许创建链接按钮。Safari 中无效。(默认为 true) */ enableLinks : true, /** * @cfg {Boolean} enableFont 允许字体选项。Safari 中无效。(默认为 true) */ enableFont : true, /** * @cfg {String} createLinkText 创建链接时提示的默认文本 */ createLinkText : 'Please enter the URL for the link:', /** * @cfg {String} defaultLinkValue 创建链接时提示的默认值(默认为 http:/ /) */ defaultLinkValue : 'http:/'+'/', /** * @cfg {Array} fontFamilies 一个有效的字体列表数组 */ fontFamilies : [ 'Arial', 'Courier New', 'Tahoma', 'Times New Roman', 'Verdana' ], defaultFont: 'tahoma', // private properties validationEvent : false, deferHeight: true, initialized : false, activated : false, sourceEditMode : false, onFocus : Ext.emptyFn, iframePad:3, hideMode:'offsets', defaultAutoCreate : { tag: "textarea", style:"width:500px;height:300px;", autocomplete: "off" }, // private initComponent : function(){ this.addEvents( /** * @event initialize * 当编辑器完全初始化后触发(包括 iframe) * @param {HtmlEditor} this */ 'initialize', /** * @event activate * 当编辑器首次获取焦点时触发。所有的插入操作都必须等待此事件完成。 * @param {HtmlEditor} this */ 'activate', /** * @event beforesync * 在把编辑器的 iframe 中的内容同步更新到文本域之前触发。返回 false 可取消更新。 * @param {HtmlEditor} this * @param {String} html */ 'beforesync', /** * @event beforepush * 在把文本域中的内容同步更新到编辑器的 iframe 之前触发。返回 false 可取消更新。 * @param {HtmlEditor} this * @param {String} html */ 'beforepush', /** * @event sync * 当把编辑器的 iframe 中的内容同步更新到文本域后触发。 * @param {HtmlEditor} this * @param {String} html */ 'sync', /** * @event push * 当把文本域中的内容同步更新到编辑器的 iframe 后触发。 * @param {HtmlEditor} this * @param {String} html */ 'push', /** * @event editmodechange * 当切换了编辑器的编辑模式后触发 * @param {HtmlEditor} this * @param {Boolean} sourceEdit 值为 true 时表示源码编辑模式, false 表示常规编辑模式。 */ 'editmodechange' ) }, createFontOptions : function(){ var buf = [], fs = this.fontFamilies, ff, lc; for(var i = 0, len = fs.length; i< len; i++){ ff = fs[i]; lc = ff.toLowerCase(); buf.push( '<option value="',lc,'" style="font-family:',ff,';"', (this.defaultFont == lc ? ' selected="true">' : '>'), ff, '</option>' ); } return buf.join(''); }, /** * 受保护的方法(Protected method), 一般不会被直接调用。当编辑器创建工具栏时调用此方法。如果你需要添加定制的工具栏按钮, 你可以覆写此方法。 * @param {HtmlEditor} editor HtmlEditor对象 */ createToolbar : function(editor){ function btn(id, toggle, handler){ return { itemId : id, cls : 'x-btn-icon x-edit-'+id, enableToggle:toggle !== false, scope: editor, handler:handler||editor.relayBtnCmd, clickEvent:'mousedown', tooltip: editor.buttonTips[id] || undefined, tabIndex:-1 }; } // build the toolbar var tb = new Ext.Toolbar({ renderTo:this.wrap.dom.firstChild }); // stop form submits tb.el.on('click', function(e){ e.preventDefault(); }); if(this.enableFont && !Ext.isSafari){ this.fontSelect = tb.el.createChild({ tag:'select', cls:'x-font-select', html: this.createFontOptions() }); this.fontSelect.on('change', function(){ var font = this.fontSelect.dom.value; this.relayCmd('fontname', font); this.deferFocus(); }, this); tb.add( this.fontSelect.dom, '-' ); }; if(this.enableFormat){ tb.add( btn('bold'), btn('italic'), btn('underline') ); }; if(this.enableFontSize){ tb.add( '-', btn('increasefontsize', false, this.adjustFont), btn('decreasefontsize', false, this.adjustFont) ); }; if(this.enableColors){ tb.add( '-', { itemId:'forecolor', cls:'x-btn-icon x-edit-forecolor', clickEvent:'mousedown', tooltip: editor.buttonTips['forecolor'] || undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ allowReselect: true, focus: Ext.emptyFn, value:'000000', plain:true, selectHandler: function(cp, color){ this.execCmd('forecolor', Ext.isSafari || Ext.isIE ? '#'+color : color); this.deferFocus(); }, scope: this, clickEvent:'mousedown' }) }, { itemId:'backcolor', cls:'x-btn-icon x-edit-backcolor', clickEvent:'mousedown', tooltip: editor.buttonTips['backcolor'] || undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ focus: Ext.emptyFn, value:'FFFFFF', plain:true, allowReselect: true, selectHandler: function(cp, color){ if(Ext.isGecko){ this.execCmd('useCSS', false); this.execCmd('hilitecolor', color); this.execCmd('useCSS', true); this.deferFocus(); }else{ this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isSafari || Ext.isIE ? '#'+color : color); this.deferFocus(); } }, scope:this, clickEvent:'mousedown' }) } ); }; if(this.enableAlignments){ tb.add( '-', btn('justifyleft'), btn('justifycenter'), btn('justifyright') ); }; if(!Ext.isSafari){ if(this.enableLinks){ tb.add( '-', btn('createlink', false, this.createLink) ); }; if(this.enableLists){ tb.add( '-', btn('insertorderedlist'), btn('insertunorderedlist') ); } if(this.enableSourceEdit){ tb.add( '-', btn('sourceedit', true, function(btn){ this.toggleSourceEdit(btn.pressed); }) ); } } this.tb = tb; }, /** * 受保护的方法, 一般不会被直接调用。当编辑器利用 HTML 内容初始化 iframe 时调用些方法。如果你想要更改初始化 iframe 的代码, 你可以覆写此方法(例如: 添加一个样式表). */ getDocMarkup : function(){ return '<html><head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>'; }, getEditorBody : function(){ return this.doc.body || this.doc.documentElement; }, // private onRender : function(ct, position){ Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position); this.el.dom.style.border = '0 none'; this.el.dom.setAttribute('tabIndex', -1); this.el.addClass('x-hidden'); if(Ext.isIE){ // fix IE 1px bogus margin this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;') } this.wrap = this.el.wrap({ cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'} }); this.createToolbar(this); this.tb.items.each(function(item){ if(item.itemId != 'sourceedit'){ item.disable(); } }); var iframe = document.createElement('iframe'); iframe.name = Ext.id(); iframe.frameBorder = 'no'; iframe.src=(Ext.SSL_SECURE_URL || "javascript:false"); this.wrap.dom.appendChild(iframe); this.iframe = iframe; if(Ext.isIE){ iframe.contentWindow.document.designMode = 'on'; this.doc = iframe.contentWindow.document; this.win = iframe.contentWindow; } else { this.doc = (iframe.contentDocument || window.frames[iframe.name].document); this.win = window.frames[iframe.name]; this.doc.designMode = 'on'; } this.doc.open(); this.doc.write(this.getDocMarkup()) this.doc.close(); var task = { // must defer to wait for browser to be ready run : function(){ if(this.doc.body || this.doc.readyState == 'complete'){ Ext.TaskMgr.stop(task); this.doc.designMode="on"; this.initEditor.defer(10, this); } }, interval : 10, duration:10000, scope: this }; Ext.TaskMgr.start(task); if(!this.width){ this.setSize(this.el.getSize()); } }, // private onResize : function(w, h){ Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments); if(this.el && this.iframe){ if(typeof w == 'number'){ var aw = w - this.wrap.getFrameWidth('lr'); this.el.setWidth(this.adjustWidth('textarea', aw)); this.iframe.style.width = aw + 'px'; } if(typeof h == 'number'){ var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight(); this.el.setHeight(this.adjustWidth('textarea', ah)); this.iframe.style.height = ah + 'px'; if(this.doc){ this.getEditorBody().style.height = (ah - (this.iframePad*2)) + 'px'; } } } }, /** * 在编辑器的常规和源码编辑模板之间切换。 * @param {Boolean} sourceEdit (可选项) 值为 true 时表示源码编辑模式, false 表示常规编辑模式。 */ toggleSourceEdit : function(sourceEditMode){ if(sourceEditMode === undefined){ sourceEditMode = !this.sourceEditMode; } this.sourceEditMode = sourceEditMode === true; var btn = this.tb.items.get('sourceedit'); if(btn.pressed !== this.sourceEditMode){ btn.toggle(this.sourceEditMode); return; } if(this.sourceEditMode){ this.tb.items.each(function(item){ if(item.itemId != 'sourceedit'){ item.disable(); } }); this.syncValue(); this.iframe.className = 'x-hidden'; this.el.removeClass('x-hidden'); this.el.dom.removeAttribute('tabIndex'); this.el.focus(); }else{ if(this.initialized){ this.tb.items.each(function(item){ item.enable(); }); } this.pushValue(); this.iframe.className = ''; this.el.addClass('x-hidden'); this.el.dom.setAttribute('tabIndex', -1); this.deferFocus(); } var lastSize = this.lastSize; if(lastSize){ delete this.lastSize; this.setSize(lastSize); } this.fireEvent('editmodechange', this, this.sourceEditMode); }, // private used internally createLink : function(){ var url = prompt(this.createLinkText, this.defaultLinkValue); if(url && url != 'http:/'+'/'){ this.relayCmd('createlink', url); } }, // private (for BoxComponent) adjustSize : Ext.BoxComponent.prototype.adjustSize, // private (for BoxComponent) getResizeEl : function(){ return this.wrap; }, // private (for BoxComponent) getPositionEl : function(){ return this.wrap; }, // private initEvents : function(){ this.originalValue = this.getValue(); }, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ markInvalid : Ext.emptyFn, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ clearInvalid : Ext.emptyFn, setValue : function(v){ Ext.form.HtmlEditor.superclass.setValue.call(this, v); this.pushValue(); }, /** * 受保护的方法, 一般不会被直接调用。如果你需(想)要定制清除 HTML 的代码, 你就得覆写此方法。 * @param {String} html 要清除的 HTML 代码 * return {String} 清除的 HTML 代码 */ cleanHtml : function(html){ html = String(html); if(html.length > 5){ if(Ext.isSafari){ // strip safari nonsense html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, ''); } } if(html == '&nbsp;'){ html = ''; } return html; }, /** * 受保护的方法, 一般不会被直接调用。将编辑器的 iframe 的值更新到文本域中。 */ syncValue : function(){ if(this.initialized){ var bd = this.getEditorBody(); var html = bd.innerHTML; if(Ext.isSafari){ var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element! var m = bs.match(/text-align:(.*?);/i); if(m && m[1]){ html = '<div style="'+m[0]+'">' + html + '</div>'; } } html = this.cleanHtml(html); if(this.fireEvent('beforesync', this, html) !== false){ this.el.dom.value = html; this.fireEvent('sync', this, html); } } }, /** * 受保护的方法, 一般不会被直接调用。将文本域的值更新到编辑器的 iframe 中。 */ pushValue : function(){ if(this.initialized){ var v = this.el.dom.value; if(!this.activated && v.length < 1){ v = '&nbsp;'; } if(this.fireEvent('beforepush', this, v) !== false){ this.getEditorBody().innerHTML = v; this.fireEvent('push', this, v); } } }, // private deferFocus : function(){ this.focus.defer(10, this); }, // doc'ed in Field focus : function(){ if(this.win && !this.sourceEditMode){ this.win.focus(); }else{ this.el.focus(); } }, // private initEditor : function(){ var dbody = this.getEditorBody(); var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat'); ss['background-attachment'] = 'fixed'; // w3c dbody.bgProperties = 'fixed'; // ie Ext.DomHelper.applyStyles(dbody, ss); Ext.EventManager.on(this.doc, { 'mousedown': this.onEditorEvent, 'dblclick': this.onEditorEvent, 'click': this.onEditorEvent, 'keyup': this.onEditorEvent, buffer:100, scope: this }); if(Ext.isGecko){ Ext.EventManager.on(this.doc, 'keypress', this.applyCommand, this); } if(Ext.isIE || Ext.isSafari || Ext.isOpera){ Ext.EventManager.on(this.doc, 'keydown', this.fixKeys, this); } this.initialized = true; this.fireEvent('initialize', this); this.pushValue(); }, // private onDestroy : function(){ if(this.rendered){ this.tb.items.each(function(item){ if(item.menu){ item.menu.removeAll(); if(item.menu.el){ item.menu.el.destroy(); } } item.destroy(); }); this.wrap.dom.innerHTML = ''; this.wrap.remove(); } }, // private onFirstFocus : function(){ this.activated = true; this.tb.items.each(function(item){ item.enable(); }); if(Ext.isGecko){ // prevent silly gecko errors this.win.focus(); var s = this.win.getSelection(); if(!s.focusNode || s.focusNode.nodeType != 3){ var r = s.getRangeAt(0); r.selectNodeContents(this.getEditorBody()); r.collapse(true); this.deferFocus(); } try{ this.execCmd('useCSS', true); this.execCmd('styleWithCSS', false); }catch(e){} } this.fireEvent('activate', this); }, // private adjustFont: function(btn){ var adjust = btn.itemId == 'increasefontsize' ? 1 : -1; if(Ext.isSafari){ // safari adjust *= 2; } var v = parseInt(this.doc.queryCommandValue('FontSize')|| 3, 10); v = Math.max(1, v+adjust); this.execCmd('FontSize', v + (Ext.isSafari ? 'px' : 0)); }, onEditorEvent : function(e){ this.updateToolbar(); }, /** * 受保护的方法, 一般不会被直接调用。它会通过读取编辑器中当前选中区域的标记状态触发对工具栏的更新操作。 */ updateToolbar: function(){ if(!this.activated){ this.onFirstFocus(); return; } var btns = this.tb.items.map, doc = this.doc; if(this.enableFont && !Ext.isSafari){ var name = (this.doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase(); if(name != this.fontSelect.dom.value){ this.fontSelect.dom.value = name; } } if(this.enableFormat){ btns.bold.toggle(doc.queryCommandState('bold')); btns.italic.toggle(doc.queryCommandState('italic')); btns.underline.toggle(doc.queryCommandState('underline')); } if(this.enableAlignments){ btns.justifyleft.toggle(doc.queryCommandState('justifyleft')); btns.justifycenter.toggle(doc.queryCommandState('justifycenter')); btns.justifyright.toggle(doc.queryCommandState('justifyright')); } if(!Ext.isSafari && this.enableLists){ btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist')); btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist')); } Ext.menu.MenuMgr.hideAll(); this.syncValue(); }, // private relayBtnCmd : function(btn){ this.relayCmd(btn.itemId); }, /** * 对编辑的文本执行一条 Midas 指令, 并完成必要的聚焦和工具栏的更新动作。<b>此方法只能在编辑器初始化后被调用。</b> * @param {String} cmd Midas 指令 * @param {String/Boolean} value (可选项) 传递给指令的值(默认为 null) */ relayCmd : function(cmd, value){ this.win.focus(); this.execCmd(cmd, value); this.updateToolbar(); this.deferFocus(); }, /** * 对编辑的文本直接执行一条 Midas 指令。 * 对于可视化的指令, 应采用 {@link #relayCmd} 方法。 * <b>此方法只能在编辑器初始化后被调用。</b> * @param {String} cmd Midas 指令 * @param {String/Boolean} value (可选项) 传递给指令的值(默认为 null) */ execCmd : function(cmd, value){ this.doc.execCommand(cmd, false, value === undefined ? null : value); this.syncValue(); }, // private applyCommand : function(e){ if(e.ctrlKey){ var c = e.getCharCode(), cmd; if(c > 0){ c = String.fromCharCode(c); switch(c){ case 'b': cmd = 'bold'; break; case 'i': cmd = 'italic'; break; case 'u': cmd = 'underline'; break; } if(cmd){ this.win.focus(); this.execCmd(cmd); this.deferFocus(); e.preventDefault(); } } } }, /** * 在光标当前所在位置插入给定的文本。注意: 编辑器必须已经初始化且处于活动状态才能插入本文。 * @param {String} text */ insertAtCursor : function(text){ if(!this.activated){ return; } if(Ext.isIE){ this.win.focus(); var r = this.doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML(text); this.syncValue(); this.deferFocus(); } }else if(Ext.isGecko || Ext.isOpera){ this.win.focus(); this.execCmd('InsertHTML', text); this.deferFocus(); }else if(Ext.isSafari){ this.execCmd('InsertText', text); this.deferFocus(); } }, // private fixKeys : function(){ // load time branching for fastest keydown performance if(Ext.isIE){ return function(e){ var k = e.getKey(), r; if(k == e.TAB){ e.stopEvent(); r = this.doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }else if(k == e.ENTER){ r = this.doc.selection.createRange(); if(r){ var target = r.parentElement(); if(!target || target.tagName.toLowerCase() != 'li'){ e.stopEvent(); r.pasteHTML('<br />'); r.collapse(false); r.select(); } } } }; }else if(Ext.isOpera){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.win.focus(); this.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }; }else if(Ext.isSafari){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.execCmd('InsertText','\t'); this.deferFocus(); } }; } }(), /** * 返回编辑器的工具栏。<b>此方法在编辑器被渲染后才可用。</b> * @return {Ext.Toolbar} */ getToolbar : function(){ return this.tb; }, /** * 编辑器中工具栏上按钮的工具提示对象的集合。关键在于, 对象ID必须与按钮相同且值应为一个有效的 QuickTips 对象。 * 例如: <pre><code> { bold : { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: 'x-html-editor-tip' }, italic : { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: 'x-html-editor-tip' }, ... </code></pre> * @type Object */ buttonTips : { bold : { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: 'x-html-editor-tip' }, italic : { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: 'x-html-editor-tip' }, underline : { title: 'Underline (Ctrl+U)', text: 'Underline the selected text.', cls: 'x-html-editor-tip' }, increasefontsize : { title: 'Grow Text', text: 'Increase the font size.', cls: 'x-html-editor-tip' }, decreasefontsize : { title: 'Shrink Text', text: 'Decrease the font size.', cls: 'x-html-editor-tip' }, backcolor : { title: 'Text Highlight Color', text: 'Change the background color of the selected text.', cls: 'x-html-editor-tip' }, forecolor : { title: 'Font Color', text: 'Change the color of the selected text.', cls: 'x-html-editor-tip' }, justifyleft : { title: 'Align Text Left', text: 'Align text to the left.', cls: 'x-html-editor-tip' }, justifycenter : { title: 'Center Text', text: 'Center text in the editor.', cls: 'x-html-editor-tip' }, justifyright : { title: 'Align Text Right', text: 'Align text to the right.', cls: 'x-html-editor-tip' }, insertunorderedlist : { title: 'Bullet List', text: 'Start a bulleted list.', cls: 'x-html-editor-tip' }, insertorderedlist : { title: 'Numbered List', text: 'Start a numbered list.', cls: 'x-html-editor-tip' }, createlink : { title: 'Hyperlink', text: 'Make the selected text a hyperlink.', cls: 'x-html-editor-tip' }, sourceedit : { title: 'Source Edit', text: 'Switch to source editing mode.', cls: 'x-html-editor-tip' } } // hide stuff that is not compatible /** * @event blur * @hide */ /** * @event change * @hide */ /** * @event focus * @hide */ /** * @event specialkey * @hide */ /** * @cfg {String} fieldClass @hide */ /** * @cfg {String} focusClass @hide */ /** * @cfg {String} autoCreate @hide */ /** * @cfg {String} inputType @hide */ /** * @cfg {String} invalidClass @hide */ /** * @cfg {String} invalidText @hide */ /** * @cfg {String} msgFx @hide */ /** * @cfg {String} validateOnBlur @hide */ }); Ext.reg('htmleditor', Ext.form.HtmlEditor);
JavaScript
/* * Ext JS Library 2.1 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.form.Label * @extends Ext.BoxComponent * Basic Label field. * @constructor * Creates a new Label * @param {Ext.Element/String/Object} config The configuration options. If an element is passed, it is set as the internal * element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element * and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component. */ Ext.form.Label = Ext.extend(Ext.BoxComponent, { /** * @cfg {String} text The text to display within the label */ /** * @cfg {String} forId The id of the element to which this label will be bound */ onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('label'); this.el.id = this.getId(); this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || ''); if(this.forId){ this.el.setAttribute('htmlFor', this.forId); } } Ext.form.Label.superclass.onRender.call(this, ct, position); } }); Ext.reg('label', Ext.form.Label);
JavaScript
/** * @class Ext.form.Form * @extends Ext.form.BasicForm * 使用js为类{@link Ext.form.BasicForm}添加动态加载效果的能力 * @constructor * @param {Object} config 配置选项 */Ext.FormPanel = Ext.extend(Ext.Panel, { /** * @cfg {Number} labelWidth 标签的宽度。该属性级联于子容器。 */ /** * @cfg {String} itemCls一个应用字段“x-form-item”的样式(css)类型,该属性级联于子容器 */ /** * @cfg {String} buttonAlign 有效值为"left," "center" 和 "right" (默认为"center") */ buttonAlign:'center', /** * @cfg {Number} minButtonWidth 每个button的最小宽度(默认75) */ minButtonWidth:75, /** * @cfg {String} labelAlign 有效值为"left," "top" 和 "right" (默认为"left")。 * 该属性级联于没有设定此属性的子容器。 */ labelAlign:'left', /** * @cfg {Boolean} monitorValid true表示为通过不断触发一个事件,来监视有效值的状态(<b>在客户端进行</b>) * 该项须绑定到有配置项formBind:true的按钮的valid state */ monitorValid : false, /** * @cfg {Number} monitorPoll 检验valid state的间隔毫秒数,如monitorValid非真则忽略改项。(默认为200) */ monitorPoll : 200, /** * 在布局堆栈中打开一个新的{@link Ext.form.Column}类容器。如果所有域在配置之后被通过,域将被添加同时该column被关闭, * 如果没有域被通过该column仍然打开,直至end()方法被调用。 * @param {Object} config 传入column的配置 * @param {Field} field1 (可选的) 参数变量field1(Field类型) * @param {Field} field2 (可选的) 参数变量field2(Field类型) * @param {Field} etc (可选的) 可以自行添加多个域参数 * @return Column 该column容器对象 */ layout: 'form', // private initComponent :function(){ this.form = this.createForm(); Ext.FormPanel.superclass.initComponent.call(this); this.addEvents( /** * @event clientvalidation * If the monitorValid config option is true, this event fires repetitively to notify of valid state * 如果配置项monitorValid为true,那么为通知验证的状态(valid state)该事件将不断地触发。 * @param {Ext.form.FormPanel} this * @param {Boolean} 如果客户端验证都通过的话传入一个true */ 'clientvalidation' ); this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']); }, // private createForm: function(){ delete this.initialConfig.listeners; return new Ext.form.BasicForm(null, this.initialConfig); }, // private initFields : function(){ var f = this.form; var formPanel = this; var fn = function(c){ if(c.doLayout && c != formPanel){ Ext.applyIf(c, { labelAlign: c.ownerCt.labelAlign, labelWidth: c.ownerCt.labelWidth, itemCls: c.ownerCt.itemCls }); if(c.items){ c.items.each(fn); } }else if(c.isFormField){ f.add(c); } } this.items.each(fn); }, // private getLayoutTarget : function(){ return this.form.el; }, /** * Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains. * 返回面板对象包含的 {@link Ext.form.BasicForm Form}以供访问。 * @return {Ext.form.BasicForm} The {@link Ext.form.BasicForm Form} which this Panel contains. 该面板对象包含的 {@link Ext.form.BasicForm Form} */ getForm : function(){ return this.form; }, // private onRender : function(ct, position){ this.initFields(); Ext.FormPanel.superclass.onRender.call(this, ct, position); var o = { tag: 'form', method : this.method || 'POST', id : this.formId || Ext.id() }; if(this.fileUpload) { o.enctype = 'multipart/form-data'; } this.form.initEl(this.body.createChild(o)); }, // private beforeDestroy: function(){ Ext.FormPanel.superclass.beforeDestroy.call(this); Ext.destroy(this.form); }, // private initEvents : function(){ Ext.FormPanel.superclass.initEvents.call(this); this.items.on('remove', this.onRemove, this); this.items.on('add', this.onAdd, this); if(this.monitorValid){ // initialize after render this.startMonitoring(); } }, // private onAdd : function(ct, c) { if (c.isFormField) { this.form.add(c); } }, // private onRemove : function(c) { if (c.isFormField) { Ext.destroy(c.container.up('.x-form-item')); this.form.remove(c); } }, /** * Starts monitoring of the valid state of this form. Usually this is done by passing the config * option "monitorValid" * 开始监视该表单的验证过程。通常这是由配置项"monitorValid"完成的。 */ startMonitoring : function(){ if(!this.bound){ this.bound = true; Ext.TaskMgr.start({ run : this.bindHandler, interval : this.monitorPoll || 200, scope: this }); } }, /** * 停止监视该form的验证状态。 */ stopMonitoring : function(){ this.bound = false; }, /** * 这是BasicForm{@link Ext.form.BasicForm#load}方法调用时所在的代理。 * @param {Object} options The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details) * 传入动作的选项(参阅{@link Ext.form.BasicForm#doAction}了解更多)。 */ load : function(){ this.form.load.apply(this.form, arguments); }, // private onDisable : function(){ Ext.FormPanel.superclass.onDisable.call(this); if(this.form){ this.form.items.each(function(){ this.disable(); }); } }, // private onEnable : function(){ Ext.FormPanel.superclass.onEnable.call(this); if(this.form){ this.form.items.each(function(){ this.enable(); }); } }, // private bindHandler : function(){ if(!this.bound){ return false; // stops binding } var valid = true; this.form.items.each(function(f){ if(!f.isValid(true)){ valid = false; return false; } }); if(this.buttons){ for(var i = 0, len = this.buttons.length; i < len; i++){ var btn = this.buttons[i]; if(btn.formBind === true && btn.disabled === valid){ btn.setDisabled(!valid); } } } this.fireEvent('clientvalidation', this, valid); } }); Ext.reg('form', Ext.FormPanel); Ext.form.FormPanel = Ext.FormPanel;
JavaScript
/** * @class Ext.form.ComboBox * @extends Ext.form.TriggerField * A combobox control with support for autocomplete, remote-loading, paging and many other features. * @constructor * Create a new ComboBox. * @param {Object} config Configuration options */ Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, { /** * @cfg {Mixed} transform The id, DOM node or element of an existing select to convert to a ComboBox */ /** * @cfg {Boolean} lazyRender True to prevent the ComboBox from rendering until requested (should always be used when * rendering into an Ext.Editor, defaults to false) */ /** * @cfg {Boolean/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to: * {tag: "input", type: "text", size: "24", autocomplete: "off"}) */ /** * @cfg {Ext.data.Store} store The data store to which this combo is bound (defaults to undefined) */ /** * @cfg {String} title If supplied, a header element is created containing this text and added into the top of * the dropdown list (defaults to undefined, with no header element) */ // private defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"}, /** * @cfg {Number} listWidth The width in pixels of the dropdown list (defaults to the width of the ComboBox field) */ /** * @cfg {String} displayField The underlying data field name to bind to this ComboBox (defaults to undefined if * mode = 'remote' or 'text' if transforming a select) */ /** * @cfg {String} valueField The underlying data value name to bind to this ComboBox (defaults to undefined if * mode = 'remote' or 'value' if transforming a select) Note: use of a valueField requires the user to make a selection * in order for a value to be mapped. */ /** * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the * field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically * post during a form submission. */ /** * @cfg {String} hiddenId If {@link #hiddenName} is specified, hiddenId can also be provided to give the hidden field * a unique id (defaults to the hiddenName). The hiddenId and combo {@link #id} should be different, since no two DOM * nodes should share the same id. */ /** * @cfg {String} listClass CSS class to apply to the dropdown list element (defaults to '') */ listClass: '', /** * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected') */ selectedClass: 'x-combo-selected', /** * @cfg {String} triggerClass An additional CSS class used to style the trigger button. The trigger will always get the * class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger' * which displays a downward arrow icon). */ triggerClass : 'x-form-arrow-trigger', /** * @cfg {Boolean/String} shadow True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right */ shadow:'sides', /** * @cfg {String} listAlign A valid anchor position value. See {@link Ext.Element#alignTo} for details on supported * anchor positions (defaults to 'tl-bl') */ listAlign: 'tl-bl?', /** * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300) */ maxHeight: 300, /** * @cfg {String} triggerAction The action to execute when the trigger field is activated. Use 'all' to run the * query specified by the allQuery config option (defaults to 'query') */ triggerAction: 'query', /** * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and typeahead activate * (defaults to 4 if remote or 0 if local, does not apply if editable = false) */ minChars : 4, /** * @cfg {Boolean} typeAhead True to populate and autoselect the remainder of the text being typed after a configurable * delay (typeAheadDelay) if it matches a known value (defaults to false) */ typeAhead: false, /** * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and sending the * query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local') */ queryDelay: 500, /** * @cfg {Number} pageSize If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the * filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0) */ pageSize: 0, /** * @cfg {Boolean} selectOnFocus True to select any existing text in the field immediately on focus. Only applies * when editable = true (defaults to false) */ selectOnFocus:false, /** * @cfg {String} queryParam Name of the query as it will be passed on the querystring (defaults to 'query') */ queryParam: 'query', /** * @cfg {String} loadingText The text to display in the dropdown list while data is loading. Only applies * when mode = 'remote' (defaults to 'Loading...') */ loadingText: 'Loading...', /** * @cfg {Boolean} resizable True to add a resize handle to the bottom of the dropdown list (defaults to false) */ resizable: false, /** * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8) */ handleHeight : 8, /** * @cfg {Boolean} editable False to prevent the user from typing text directly into the field, just like a * traditional select (defaults to true) */ editable: true, /** * @cfg {String} allQuery The text query to send to the server to return all records for the list with no filtering (defaults to '') */ allQuery: '', /** * @cfg {String} mode Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server) */ mode: 'remote', /** * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if * listWidth has a higher value) */ minListWidth : 70, /** * @cfg {Boolean} forceSelection True to restrict the selected value to one of the values in the list, false to * allow the user to set arbitrary text into the field (defaults to false) */ forceSelection:false, /** * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed * if typeAhead = true (defaults to 250) */ typeAheadDelay : 250, /** * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined) */ /** * @cfg {Boolean} lazyInit True to not initialize the list for this combo until the field is focused. (defaults to true) */ lazyInit : true, initComponent : function(){ Ext.form.ComboBox.superclass.initComponent.call(this); this.addEvents( /** * @event expand * Fires when the dropdown list is expanded * @param {Ext.form.ComboBox} combo This combo box */ 'expand', /** * @event collapse * Fires when the dropdown list is collapsed * @param {Ext.form.ComboBox} combo This combo box */ 'collapse', /** * @event beforeselect * Fires before a list item is selected. Return false to cancel the selection. * @param {Ext.form.ComboBox} combo This combo box * @param {Ext.data.Record} record The data record returned from the underlying store * @param {Number} index The index of the selected item in the dropdown list */ 'beforeselect', /** * @event select * Fires when a list item is selected * @param {Ext.form.ComboBox} combo This combo box * @param {Ext.data.Record} record The data record returned from the underlying store * @param {Number} index The index of the selected item in the dropdown list */ 'select', /** * @event beforequery * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's * cancel property to true. * @param {Object} queryEvent An object that has these properties:<ul> * <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">This combo box</div></li> * <li><code>query</code> : String <div class="sub-desc">The query</div></li> * <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li> * <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li> * </ul> */ 'beforequery' ); if(this.transform){ this.allowDomMove = false; var s = Ext.getDom(this.transform); if(!this.hiddenName){ this.hiddenName = s.name; } if(!this.store){ this.mode = 'local'; var d = [], opts = s.options; for(var i = 0, len = opts.length;i < len; i++){ var o = opts[i]; var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text; if(o.selected) { this.value = value; } d.push([value, o.text]); } this.store = new Ext.data.SimpleStore({ 'id': 0, fields: ['value', 'text'], data : d }); this.valueField = 'value'; this.displayField = 'text'; } s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference if(!this.lazyRender){ this.target = true; this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate); Ext.removeNode(s); // remove it this.render(this.el.parentNode); }else{ Ext.removeNode(s); // remove it } } this.selectedIndex = -1; if(this.mode == 'local'){ if(this.initialConfig.queryDelay === undefined){ this.queryDelay = 10; } if(this.initialConfig.minChars === undefined){ this.minChars = 0; } } }, // private onRender : function(ct, position){ Ext.form.ComboBox.superclass.onRender.call(this, ct, position); if(this.hiddenName){ this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)}, 'before', true); this.hiddenField.value = this.hiddenValue !== undefined ? this.hiddenValue : this.value !== undefined ? this.value : ''; // prevent input submission this.el.dom.removeAttribute('name'); } if(Ext.isGecko){ this.el.dom.setAttribute('autocomplete', 'off'); } if(!this.lazyInit){ this.initList(); }else{ this.on('focus', this.initList, this, {single: true}); } if(!this.editable){ this.editable = true; this.setEditable(false); } }, initList : function(){ if(!this.list){ var cls = 'x-combo-list'; this.list = new Ext.Layer({ shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false }); var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth); this.list.setWidth(lw); this.list.swallowEvent('mousewheel'); this.assetHeight = 0; if(this.title){ this.header = this.list.createChild({cls:cls+'-hd', html: this.title}); this.assetHeight += this.header.getHeight(); } this.innerList = this.list.createChild({cls:cls+'-inner'}); this.innerList.on('mouseover', this.onViewOver, this); this.innerList.on('mousemove', this.onViewMove, this); this.innerList.setWidth(lw - this.list.getFrameWidth('lr')); if(this.pageSize){ this.footer = this.list.createChild({cls:cls+'-ft'}); this.pageTb = new Ext.PagingToolbar({ store:this.store, pageSize: this.pageSize, renderTo:this.footer }); this.assetHeight += this.footer.getHeight(); } if(!this.tpl){ /** * @cfg {String/Ext.XTemplate} tpl The template string, or {@link Ext.XTemplate} * instance to use to display each item in the dropdown list. Use * this to create custom UI layouts for items in the list. * <p> * If you wish to preserve the default visual look of list items, add the CSS * class name <pre>x-combo-list-item</pre> to the template's container element. * <p> * <b>The template must contain one or more substitution parameters using field * names from the Combo's</b> {@link #store Store}. An example of a custom template * would be adding an <pre>ext:qtip</pre> attribute which might display other fields * from the Store. * <p> * The dropdown list is displayed in a DataView. See {@link Ext.DataView} for details. */ this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>'; } /** * The {@link Ext.DataView DataView} used to display the ComboBox's options. * @type Ext.DataView */ this.view = new Ext.DataView({ applyTo: this.innerList, tpl: this.tpl, singleSelect: true, selectedClass: this.selectedClass, itemSelector: this.itemSelector || '.' + cls + '-item' }); this.view.on('click', this.onViewClick, this); this.bindStore(this.store, true); if(this.resizable){ this.resizer = new Ext.Resizable(this.list, { pinned:true, handles:'se' }); this.resizer.on('resize', function(r, w, h){ this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight; this.listWidth = w; this.innerList.setWidth(w - this.list.getFrameWidth('lr')); this.restrictHeight(); }, this); this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px'); } } }, // private bindStore : function(store, initial){ if(this.store && !initial){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.collapse, this); if(!store){ this.store = null; if(this.view){ this.view.setStore(null); } } } if(store){ this.store = Ext.StoreMgr.lookup(store); this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.collapse, this); if(this.view){ this.view.setStore(store); } } }, // private initEvents : function(){ Ext.form.ComboBox.superclass.initEvents.call(this); this.keyNav = new Ext.KeyNav(this.el, { "up" : function(e){ this.inKeyMode = true; this.selectPrev(); }, "down" : function(e){ if(!this.isExpanded()){ this.onTriggerClick(); }else{ this.inKeyMode = true; this.selectNext(); } }, "enter" : function(e){ this.onViewClick(); //return true; }, "esc" : function(e){ this.collapse(); }, "tab" : function(e){ this.onViewClick(false); return true; }, scope : this, doRelay : function(foo, bar, hname){ if(hname == 'down' || this.scope.isExpanded()){ return Ext.KeyNav.prototype.doRelay.apply(this, arguments); } return true; }, forceKeyDown : true }); this.queryDelay = Math.max(this.queryDelay || 10, this.mode == 'local' ? 10 : 250); this.dqTask = new Ext.util.DelayedTask(this.initQuery, this); if(this.typeAhead){ this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this); } if(this.editable !== false){ this.el.on("keyup", this.onKeyUp, this); } if(this.forceSelection){ this.on('blur', this.doForce, this); } }, onDestroy : function(){ if(this.view){ this.view.el.removeAllListeners(); this.view.el.remove(); this.view.purgeListeners(); } if(this.list){ this.list.destroy(); } this.bindStore(null); Ext.form.ComboBox.superclass.onDestroy.call(this); }, // private fireKey : function(e){ if(e.isNavKeyPress() && !this.list.isVisible()){ this.fireEvent("specialkey", this, e); } }, // private onResize: function(w, h){ Ext.form.ComboBox.superclass.onResize.apply(this, arguments); if(this.list && this.listWidth === undefined){ var lw = Math.max(w, this.minListWidth); this.list.setWidth(lw); this.innerList.setWidth(lw - this.list.getFrameWidth('lr')); } }, // private onDisable: function(){ Ext.form.ComboBox.superclass.onDisable.apply(this, arguments); if(this.hiddenField){ this.hiddenField.disabled = this.disabled; } }, /** * Allow or prevent the user from directly editing the field text. If false is passed, * the user will only be able to select from the items defined in the dropdown list. This method * is the runtime equivalent of setting the 'editable' config option at config time. * @param {Boolean} value True to allow the user to directly edit the field text */ setEditable : function(value){ if(value == this.editable){ return; } this.editable = value; if(!value){ this.el.dom.setAttribute('readOnly', true); this.el.on('mousedown', this.onTriggerClick, this); this.el.addClass('x-combo-noedit'); }else{ this.el.dom.setAttribute('readOnly', false); this.el.un('mousedown', this.onTriggerClick, this); this.el.removeClass('x-combo-noedit'); } }, // private onBeforeLoad : function(){ if(!this.hasFocus){ return; } this.innerList.update(this.loadingText ? '<div class="loading-indicator">'+this.loadingText+'</div>' : ''); this.restrictHeight(); this.selectedIndex = -1; }, // private onLoad : function(){ if(!this.hasFocus){ return; } if(this.store.getCount() > 0){ this.expand(); this.restrictHeight(); if(this.lastQuery == this.allQuery){ if(this.editable){ this.el.dom.select(); } if(!this.selectByValue(this.value, true)){ this.select(0, true); } }else{ this.selectNext(); if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){ this.taTask.delay(this.typeAheadDelay); } } }else{ this.onEmptyResults(); } //this.el.focus(); }, // private onTypeAhead : function(){ if(this.store.getCount() > 0){ var r = this.store.getAt(0); var newValue = r.data[this.displayField]; var len = newValue.length; var selStart = this.getRawValue().length; if(selStart != len){ this.setRawValue(newValue); this.selectText(selStart, newValue.length); } } }, // private onSelect : function(record, index){ if(this.fireEvent('beforeselect', this, record, index) !== false){ this.setValue(record.data[this.valueField || this.displayField]); this.collapse(); this.fireEvent('select', this, record, index); } }, /** * Returns the currently selected field value or empty string if no value is set. * @return {String} value The selected value */ getValue : function(){ if(this.valueField){ return typeof this.value != 'undefined' ? this.value : ''; }else{ return Ext.form.ComboBox.superclass.getValue.call(this); } }, /** * Clears any text/value currently set in the field */ clearValue : function(){ if(this.hiddenField){ this.hiddenField.value = ''; } this.setRawValue(''); this.lastSelectionText = ''; this.applyEmptyText(); }, /** * Sets the specified value into the field. If the value finds a match, the corresponding record text * will be displayed in the field. If the value does not match the data value of an existing item, * and the valueNotFoundText config option is defined, it will be displayed as the default field text. * Otherwise the field will be blank (although the value will still be set). * @param {String} value The value to match */ setValue : function(v){ var text = v; if(this.valueField){ var r = this.findRecord(this.valueField, v); if(r){ text = r.data[this.displayField]; }else if(this.valueNotFoundText !== undefined){ text = this.valueNotFoundText; } } this.lastSelectionText = text; if(this.hiddenField){ this.hiddenField.value = v; } Ext.form.ComboBox.superclass.setValue.call(this, text); this.value = v; }, // private findRecord : function(prop, value){ var record; if(this.store.getCount() > 0){ this.store.each(function(r){ if(r.data[prop] == value){ record = r; return false; } }); } return record; }, // private onViewMove : function(e, t){ this.inKeyMode = false; }, // private onViewOver : function(e, t){ if(this.inKeyMode){ // prevent key nav and mouse over conflicts return; } var item = this.view.findItemFromChild(t); if(item){ var index = this.view.indexOf(item); this.select(index, false); } }, // private onViewClick : function(doFocus){ var index = this.view.getSelectedIndexes()[0]; var r = this.store.getAt(index); if(r){ this.onSelect(r, index); } if(doFocus !== false){ this.el.focus(); } }, // private restrictHeight : function(){ this.innerList.dom.style.height = ''; var inner = this.innerList.dom; var fw = this.list.getFrameWidth('tb'); var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight); this.innerList.setHeight(h < this.maxHeight ? 'auto' : this.maxHeight); this.list.beginUpdate(); this.list.setHeight(this.innerList.getHeight()+fw+(this.resizable?this.handleHeight:0)+this.assetHeight); this.list.alignTo(this.el, this.listAlign); this.list.endUpdate(); }, // private onEmptyResults : function(){ this.collapse(); }, /** * Returns true if the dropdown list is expanded, else false. */ isExpanded : function(){ return this.list && this.list.isVisible(); }, /** * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire. * The store must be loaded and the list expanded for this function to work, otherwise use setValue. * @param {String} value The data value of the item to select * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the * selected item if it is not currently in view (defaults to true) * @return {Boolean} True if the value matched an item in the list, else false */ selectByValue : function(v, scrollIntoView){ if(v !== undefined && v !== null){ var r = this.findRecord(this.valueField || this.displayField, v); if(r){ this.select(this.store.indexOf(r), scrollIntoView); return true; } } return false; }, /** * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire. * The store must be loaded and the list expanded for this function to work, otherwise use setValue. * @param {Number} index The zero-based index of the list item to select * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the * selected item if it is not currently in view (defaults to true) */ select : function(index, scrollIntoView){ this.selectedIndex = index; this.view.select(index); if(scrollIntoView !== false){ var el = this.view.getNode(index); if(el){ this.innerList.scrollChildIntoView(el, false); } } }, // private selectNext : function(){ var ct = this.store.getCount(); if(ct > 0){ if(this.selectedIndex == -1){ this.select(0); }else if(this.selectedIndex < ct-1){ this.select(this.selectedIndex+1); } } }, // private selectPrev : function(){ var ct = this.store.getCount(); if(ct > 0){ if(this.selectedIndex == -1){ this.select(0); }else if(this.selectedIndex != 0){ this.select(this.selectedIndex-1); } } }, // private onKeyUp : function(e){ if(this.editable !== false && !e.isSpecialKey()){ this.lastKey = e.getKey(); this.dqTask.delay(this.queryDelay); } }, // private validateBlur : function(){ return !this.list || !this.list.isVisible(); }, // private initQuery : function(){ this.doQuery(this.getRawValue()); }, // private doForce : function(){ if(this.el.dom.value.length > 0){ this.el.dom.value = this.lastSelectionText === undefined ? '' : this.lastSelectionText; this.applyEmptyText(); } }, /** * Execute a query to filter the dropdown list. Fires the beforequery event prior to performing the * query allowing the query action to be canceled if needed. * @param {String} query The SQL query to execute * @param {Boolean} forceAll True to force the query to execute even if there are currently fewer characters * in the field than the minimum specified by the minChars config option. It also clears any filter previously * saved in the current store (defaults to false) */ doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false || qe.cancel){ return false; } q = qe.query; forceAll = qe.forceAll; if(forceAll === true || (q.length >= this.minChars)){ if(this.lastQuery !== q){ this.lastQuery = q; if(this.mode == 'local'){ this.selectedIndex = -1; if(forceAll){ this.store.clearFilter(); }else{ this.store.filter(this.displayField, q); } this.onLoad(); }else{ this.store.baseParams[this.queryParam] = q; this.store.load({ params: this.getParams(q) }); this.expand(); } }else{ this.selectedIndex = -1; this.onLoad(); } } }, // private getParams : function(q){ var p = {}; //p[this.queryParam] = q; if(this.pageSize){ p.start = 0; p.limit = this.pageSize; } return p; }, /** * Hides the dropdown list if it is currently expanded. Fires the 'collapse' event on completion. */ collapse : function(){ if(!this.isExpanded()){ return; } this.list.hide(); Ext.getDoc().un('mousewheel', this.collapseIf, this); Ext.getDoc().un('mousedown', this.collapseIf, this); this.fireEvent('collapse', this); }, // private collapseIf : function(e){ if(!e.within(this.wrap) && !e.within(this.list)){ this.collapse(); } }, /** * Expands the dropdown list if it is currently hidden. Fires the 'expand' event on completion. */ expand : function(){ if(this.isExpanded() || !this.hasFocus){ return; } this.list.alignTo(this.wrap, this.listAlign); this.list.show(); Ext.getDoc().on('mousewheel', this.collapseIf, this); Ext.getDoc().on('mousedown', this.collapseIf, this); this.fireEvent('expand', this); }, // private // Implements the default empty TriggerField.onTriggerClick function onTriggerClick : function(){ if(this.disabled){ return; } if(this.isExpanded()){ this.collapse(); this.el.focus(); }else { this.onFocus({}); if(this.triggerAction == 'all') { this.doQuery(this.allQuery, true); } else { this.doQuery(this.getRawValue()); } this.el.focus(); } } /** * @hide * @method autoSize */ /** * @cfg {Boolean} grow @hide */ /** * @cfg {Number} growMin @hide */ /** * @cfg {Number} growMax @hide */ }); Ext.reg('combo', Ext.form.ComboBox);
JavaScript
/** * @class Ext.form.DateField * @extends Ext.form.TriggerField * Provides a date input field with a {@link Ext.DatePicker} dropdown and automatic date validation. * 提供一个包含 {@link Ext.DatePicker} 日期选择、自动效验控件的日期输入字段。 * @constructor * 创建一个 DateField 对象 * @param {Object} config */ Ext.form.DateField = Ext.extend(Ext.form.TriggerField, { /** * @cfg {String} format * 用以覆盖本地化的默认日期格式化字串。字串必须为符合 {@link Date#parseDate} 指定的形式(默认为 'm/d/y')。 */ format : "m/d/y", /** * @cfg {String} altFormats * 用 "|" 符号分隔的多个日期格式化字串, 当输入的日期与默认的格式不符时用来尝试格式化输入值(默认为 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d')。 */ altFormats : "m/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d", /** * @cfg {Array} disabledDays * 一个禁用的星期数组, 以 0 开始。例如, [0,6] 表示禁用周六和周日(默认为 null)。 */ disabledDays : null, /** * @cfg {String} disabledDaysText * 禁用星期上显示的工具提示(默认为 'Disabled') */ disabledDaysText : "Disabled", /** * @cfg {Array} disabledDates * 一个以字串形式表示的禁用的日期数组。这些字串将会被用来创建一个动态正则表达式, 所以它们是很强大的。一个例子: * <ul> * <li>["03/08/2003", "09/16/2003"] 将会禁用那些确切的日期</li> * <li>["03/08", "09/16"] 将会禁用每年中的那些日子</li> * <li>["^03/08"] 将会只匹配开头(当使用短年份时非常有用)</li> * <li>["03/../2006"] 将会禁用 2006 年 三月 的每一天</li> * <li>["^03"] 将会禁用每年三月的每一天</li> * </ul> * 为了提供正则表达式的支持, 如果你使用一个包含 "." 的日期格式, 你就得将小数点转义使用。例如: ["03\\.08\\.03"]。 */ disabledDates : null, /** * @cfg {String} disabledDatesText * 禁用日期上显示的工具提示(默认为 'Disabled') */ disabledDatesText : "Disabled", /** * @cfg {Date/String} minValue * 允许的最小日期。可以是一个 Javascript 日期对象或一个有效格式的字串(默认为 null) */ minValue : null, /** * @cfg {Date/String} maxValue * 允许的最大日期。可以是一个 Javascript 日期对象或一个有效格式的字串(默认为 null) */ maxValue : null, /** * @cfg {String} minText * 当字段的日期早于 minValue 属性指定值时显示的错误文本(默认为 'The date in this field must be after {minValue}')。 */ minText : "The date in this field must be equal to or after {0}", /** * @cfg {String} maxText * 当字段的日期晚于 maxValue 属性指定值时显示的错误文本(默认为 'The date in this field must be before {maxValue}')。 */ maxText : "The date in this field must be equal to or before {0}", /** * @cfg {String} invalidText * 当字段的日期无效时显示的错误文本(默认为 '{value} is not a valid date - it must be in the format {format}')。 */ invalidText : "{0} is not a valid date - it must be in the format {1}", /** * @cfg {String} triggerClass * 用以指定触发按钮的附加CSS样式类。触发按钮的类名将总是 'x-form-trigger', 而如果指定了 triggerClass 则会被<b>追加</b>在其后(默认为 'x-form-date-trigger' 用以显示一个日历图标)。 */ triggerClass : 'x-form-date-trigger', /** * @cfg {String/Object} autoCreate * 指定一个 DomHelper 元素, 或者 true 指定默认的元素(默认为 {tag: "input", type: "text", size: "10", autocomplete: "off"}) */ // private defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"}, initComponent : function(){ Ext.form.DateField.superclass.initComponent.call(this); if(typeof this.minValue == "string"){ this.minValue = this.parseDate(this.minValue); } if(typeof this.maxValue == "string"){ this.maxValue = this.parseDate(this.maxValue); } this.ddMatch = null; if(this.disabledDates){ var dd = this.disabledDates; var re = "(?:"; for(var i = 0; i < dd.length; i++){ re += dd[i]; if(i != dd.length-1) re += "|"; } this.ddMatch = new RegExp(re + ")"); } }, // private validateValue : function(value){ value = this.formatDate(value); if(!Ext.form.DateField.superclass.validateValue.call(this, value)){ return false; } if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid return true; } var svalue = value; value = this.parseDate(value); if(!value){ this.markInvalid(String.format(this.invalidText, svalue, this.format)); return false; } var time = value.getTime(); if(this.minValue && time < this.minValue.getTime()){ this.markInvalid(String.format(this.minText, this.formatDate(this.minValue))); return false; } if(this.maxValue && time > this.maxValue.getTime()){ this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue))); return false; } if(this.disabledDays){ var day = value.getDay(); for(var i = 0; i < this.disabledDays.length; i++) { if(day === this.disabledDays[i]){ this.markInvalid(this.disabledDaysText); return false; } } } var fvalue = this.formatDate(value); if(this.ddMatch && this.ddMatch.test(fvalue)){ this.markInvalid(String.format(this.disabledDatesText, fvalue)); return false; } return true; }, // private // Provides logic to override the default TriggerField.validateBlur which just returns true validateBlur : function(){ return !this.menu || !this.menu.isVisible(); }, /** * 返回当前日期字段的值。 * @return {Date} 日期值 */ getValue : function(){ return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || ""; }, /** * 设置日期字段的值。你可以传递一个日期对象或任何可以被转换为有效日期的字串, 使用 DateField.format 当作日期格式化字串, 与 {@link Date#parseDate} 规则相同。(默认的格式化字串为 "m/d/y")。 * <br />用法: * <pre><code> //所有的调用均设置同样的日期(May 4, 2006) //传递一个日期对象: var dt = new Date('5/4/06'); dateField.setValue(dt); //传递一个日期字串(采用默认的格式化字串): dateField.setValue('5/4/06'); //转换一个日期字串(自定义的格式化字串): dateField.format = 'Y-m-d'; dateField.setValue('2006-5-4'); </code></pre> * @param {String/Date} date 日期对象或有效的日期字串 */ setValue : function(date){ Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date))); }, // private parseDate : function(value){ if(!value || value instanceof Date){ return value; } var v = Date.parseDate(value, this.format); if(!v && this.altFormats){ if(!this.altFormatsArray){ this.altFormatsArray = this.altFormats.split("|"); } for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){ v = Date.parseDate(value, this.altFormatsArray[i]); } } return v; }, // private onDestroy : function(){ if(this.wrap){ this.wrap.remove(); } Ext.form.DateField.superclass.onDestroy.call(this); }, // private formatDate : function(date){ return (!date || !(date instanceof Date)) ? date : date.dateFormat(this.format); }, // private menuListeners : { select: function(m, d){ this.setValue(d); }, show : function(){ // retain focus styling this.onFocus(); }, hide : function(){ this.focus.defer(10, this); var ml = this.menuListeners; this.menu.un("select", ml.select, this); this.menu.un("show", ml.show, this); this.menu.un("hide", ml.hide, this); } }, // private // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker onTriggerClick : function(){ if(this.disabled){ return; } if(this.menu == null){ this.menu = new Ext.menu.DateMenu(); } Ext.apply(this.menu.picker, { minDate : this.minValue, maxDate : this.maxValue, disabledDatesRE : this.ddMatch, disabledDatesText : this.disabledDatesText, disabledDays : this.disabledDays, disabledDaysText : this.disabledDaysText, format : this.format, minText : String.format(this.minText, this.formatDate(this.minValue)), maxText : String.format(this.maxText, this.formatDate(this.maxValue)) }); this.menu.on(Ext.apply({}, this.menuListeners, { scope:this })); this.menu.picker.setValue(this.getValue() || new Date()); this.menu.show(this.el, "tl-bl?"); }, beforeBlur : function(){ var v = this.parseDate(this.getRawValue()); if(v){ this.setValue(v); } } /** * @cfg {Boolean} grow @hide */ /** * @cfg {Number} growMin @hide */ /** * @cfg {Number} growMax @hide */ /** * @hide * @method autoSize */ }); Ext.reg('datefield', Ext.form.DateField);
JavaScript
/** * @class Ext.form.Checkbox * @extends Ext.form.Field * 单独的checkbox域,可以直接代替传统checkbox域 * @constructor * 创建一个新的CheckBox对象 * @param {Object} config 配置项选项 */ Ext.form.Checkbox = Ext.extend(Ext.form.Field, { /** * checkbox得到焦点时所使用的样式表(css)默认为undefined */ focusClass : undefined, /** * checkbox默认的样式表(css)默认为x-form-field */ fieldClass: "x-form-field", /** * @cfg {Boolean} checked 如果checkbox需要呈现选中状态,设置checked为True(默认为false) */ checked: false, /** * @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为 * {tag: "input", type: "checkbox", autocomplete: "off"}) */ defaultAutoCreate : { tag: "input", type: 'checkbox', autocomplete: "off"}, /** * @cfg {String} boxLabel checkbox旁边显示的文字 * */ initComponent : function(){ Ext.form.Checkbox.superclass.initComponent.call(this); this.addEvents( 'check' ); }, // private onResize : function(){ Ext.form.Checkbox.superclass.onResize.apply(this, arguments); if(!this.boxLabel){ this.el.alignTo(this.wrap, 'c-c'); } }, // private initEvents : function(){ Ext.form.Checkbox.superclass.initEvents.call(this); this.el.on("click", this.onClick, this); this.el.on("change", this.onClick, this); }, // private getResizeEl : function(){ return this.wrap; }, // private getPositionEl : function(){ return this.wrap; }, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ markInvalid : Ext.emptyFn, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ clearInvalid : Ext.emptyFn, // private onRender : function(ct, position){ Ext.form.Checkbox.superclass.onRender.call(this, ct, position); if(this.inputValue !== undefined){ this.el.dom.value = this.inputValue; } this.wrap = this.el.wrap({cls: "x-form-check-wrap"}); if(this.boxLabel){ this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel}); } if(this.checked){ this.setValue(true); }else{ this.checked = this.el.dom.checked; } }, // private onDestroy : function(){ if(this.wrap){ this.wrap.remove(); } Ext.form.Checkbox.superclass.onDestroy.call(this); }, // private initValue : Ext.emptyFn, /** * 返回checkbox的选择状态 * @return {Boolean} True表示为已选中,否则false */ getValue : function(){ if(this.rendered){ return this.el.dom.checked; } return false; }, // private onClick : function(){ if(this.el.dom.checked != this.checked){ this.setValue(this.el.dom.checked); } }, /** * 设置checkbox的选择状态 * @param {Boolean/String} 传入的参数可以为boolean或者String类型,值为True, 'true,' 或 '1'都表示选中,其他为没有选中 */ setValue : function(v){ this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on'); if(this.el && this.el.dom){ this.el.dom.checked = this.checked; this.el.dom.defaultChecked = this.checked; } this.fireEvent("check", this, this.checked); } }); Ext.reg('checkbox', Ext.form.Checkbox);
JavaScript
/** * @class Ext.grid.CellSelectionModel * @extends Ext.grid.AbstractSelectionModel * 本类提供了grid单元格选区的基本实现。 * 执行{@link getSelectedCell}的方法返回一个选区对象,这个对象包含下列的属性: * <div class="mdetail-params"><ul> * <li><b>record</b> : Ext.data.record<p class="sub-desc">提供所选行中的 {@link Ext.data.Record}数据</p></li> * <li><b>cell</b> : Ext.data.record<p class="sub-desc">一个包含下列属性的对象: * <div class="mdetail-params"><ul> * <li><b>rowIndex</b> : Number<p class="sub-desc">选中行的索引</p></li> * <li><b>cellIndex</b> : Number<p class="sub-desc">选中单元格的索引<br> * <b>注意有时会因为列渲染的问题,单元格索引不应用于 Record数据的索引。 * 因此,应该使用当前的字段<i>名称</i>来获取数据值,如::</b><pre><code> var fieldName = grid.getColumnModel().getDataIndex(cellIndex); var data = record.get(fieldName); </code></pre></p></li> * </ul></div></p></li> * </ul></div> * @constructor * @param {Object} config 针对该模型的配置对象。 */ Ext.grid.CellSelectionModel = function(config){ Ext.apply(this, config); this.selection = null; this.addEvents( /** * @event beforerowselect * 单元格被选中之前触发 * @param {SelectionModel} this * @param {Number} rowIndex 选中的行索引 * @param {Number} colIndex 选中的单元格索引 */ "beforecellselect", /** * @event cellselect * 当单元格被选中时触发 * @param {SelectionModel} this * @param {Number} rowIndex 选中的行索引 * @param {Number} colIndex 选中的单元格索引 */ "cellselect", /** * @event selectionchange * 当已激活的选区改变时触发 * @param {SelectionModel} this * @param {Object} selection null 代表没选区而object (o) 则代表有下列两个属性的对象: <ul> <li>o.record: 选区所在的record对象</li> <li>o.cell: [rowIndex, columnIndex]的数组</li> </ul> */ "selectionchange" ); Ext.grid.CellSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.CellSelectionModel, Ext.grid.AbstractSelectionModel, { /** @ignore */ initEvents : function(){ this.grid.on("cellmousedown", this.handleMouseDown, this); this.grid.getGridEl().on(Ext.isIE ? "keydown" : "keypress", this.handleKeyDown, this); var view = this.grid.view; view.on("refresh", this.onViewChange, this); view.on("rowupdated", this.onRowUpdated, this); view.on("beforerowremoved", this.clearSelections, this); view.on("beforerowsinserted", this.clearSelections, this); if(this.grid.isEditor){ this.grid.on("beforeedit", this.beforeEdit, this); } }, //private beforeEdit : function(e){ this.select(e.row, e.column, false, true, e.record); }, //private onRowUpdated : function(v, index, r){ if(this.selection && this.selection.record == r){ v.onCellSelect(index, this.selection.cell[1]); } }, //private onViewChange : function(){ this.clearSelections(true); }, /** * 返回当前选中的单元格。 * @return {Object} 选中的单元格,null就代表没选中 */ getSelectedCell : function(){ return this.selection ? this.selection.cell : null; }, /** * 清除所有选区。 * @param {Boolean} true表示改变时不通知gridview */ clearSelections : function(preventNotify){ var s = this.selection; if(s){ if(preventNotify !== true){ this.grid.view.onCellDeselect(s.cell[0], s.cell[1]); } this.selection = null; this.fireEvent("selectionchange", this, null); } }, /** * 有选区的话返回true * @return {Boolean} */ hasSelection : function(){ return this.selection ? true : false; }, /** @ignore */ handleMouseDown : function(g, row, cell, e){ if(e.button !== 0 || this.isLocked()){ return; }; this.select(row, cell); }, /** * 选中一个单元格。 * @param {Number} rowIndex * @param {Number} collIndex */ select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){ if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){ this.clearSelections(); r = r || this.grid.store.getAt(rowIndex); this.selection = { record : r, cell : [rowIndex, colIndex] }; if(!preventViewNotify){ var v = this.grid.getView(); v.onCellSelect(rowIndex, colIndex); if(preventFocus !== true){ v.focusCell(rowIndex, colIndex); } } this.fireEvent("cellselect", this, rowIndex, colIndex); this.fireEvent("selectionchange", this, this.selection); } }, //private isSelectable : function(rowIndex, colIndex, cm){ return !cm.isHidden(colIndex); }, /** @ignore */ handleKeyDown : function(e){ if(!e.isNavKeyPress()){ return; } var g = this.grid, s = this.selection; if(!s){ e.stopEvent(); var cell = g.walkCells(0, 0, 1, this.isSelectable, this); if(cell){ this.select(cell[0], cell[1]); } return; } var sm = this; var walk = function(row, col, step){ return g.walkCells(row, col, step, sm.isSelectable, sm); }; var k = e.getKey(), r = s.cell[0], c = s.cell[1]; var newCell; switch(k){ case e.TAB: if(e.shiftKey){ newCell = walk(r, c-1, -1); }else{ newCell = walk(r, c+1, 1); } break; case e.DOWN: newCell = walk(r+1, c, 1); break; case e.UP: newCell = walk(r-1, c, -1); break; case e.RIGHT: newCell = walk(r, c+1, 1); break; case e.LEFT: newCell = walk(r, c-1, -1); break; case e.ENTER: if(g.isEditor && !g.editing){ g.startEditing(r, c); e.stopEvent(); return; } break; }; if(newCell){ this.select(newCell[0], newCell[1]); e.stopEvent(); } }, acceptsNav : function(row, col, cm){ return !cm.isHidden(col) && cm.isCellEditable(col, row); }, onEditorKey : function(field, e){ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor; if(k == e.TAB){ if(e.shiftKey){ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); } e.stopEvent(); }else if(k == e.ENTER){ ed.completeEdit(); e.stopEvent(); }else if(k == e.ESC){ e.stopEvent(); ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } });
JavaScript
// private // This is a support class used internally by the Grid components Ext.grid.GridEditor = function(field, config){ Ext.grid.GridEditor.superclass.constructor.call(this, field, config); field.monitorTab = false; }; Ext.extend(Ext.grid.GridEditor, Ext.Editor, { alignment: "tl-tl", autoSize: "width", hideEl : false, cls: "x-small-editor x-grid-editor", shim:false, shadow:false });
JavaScript
/** * @class Ext.grid.EditorGridPanel * @extends Ext.grid.GridPanel * 创建和编辑GRID的类。 * @constructor */ Ext.grid.EditorGridPanel = Ext.extend(Ext.grid.GridPanel, { /** * @cfg {Number} clicksToEdit * 要转换单元格为编辑状态所需的鼠标点击数(默认为两下,即双击) */ clicksToEdit: 2, // private isEditor : true, // private detectEdit: false, /** * @cfg {Boolean} trackMouseOver @hide */ // private trackMouseOver: false, // causes very odd FF errors // private initComponent : function(){ Ext.grid.EditorGridPanel.superclass.initComponent.call(this); if(!this.selModel){ this.selModel = new Ext.grid.CellSelectionModel(); } this.activeEditor = null; this.addEvents( /** * @event beforeedit * 当一个单元格被切换到编辑之前触发。编辑的事件对象会有下列的属性:<br /> * <ul style="padding:5px;padding-left:16px;"> * <li>grid - grid本身</li> * <li>record - 正在编辑的record</li> * <li>field - 正在编辑的字段名</li> * <li>value - 正在设置的值(value)</li> * <li>row - grid行索引</li> * <li>column - grid列索引</li> * <li>cancel - 由句柄(handler)返回的布尔值,决定true为取消编辑,否则为false</li> * </ul> * @param {Object} e 一个编辑的事件(参阅上面的解释) */ "beforeedit", /** * @event afteredit * 当一个单元格被编辑后触发。<br /> * <ul style="padding:5px;padding-left:16px;"> * <li>grid - grid本身</li> * <li>record - 正在编辑的record</li> * <li>field - 正在编辑的字段名</li> * <li>value - 正在设置的值(value)</li> * <li>originalValue - 在编辑之前的原始值</li> * <li>row - grid行索引</li> * <li>column - grid列索引</li> * </ul> * @param {Object} e 一个编辑的事件(参阅上面的解释) */ "afteredit", /** * @event validateedit * 编辑单元格后触发,但发生在更改值被设置到record之前。如果返回false即取消更改。 * 编辑的事件有以下属性 <br /> * <ul style="padding:5px;padding-left:16px;"> * <li>grid - grid本身</li> * <li>record - 正在编辑的record</li> * <li>field - 正在编辑的字段名</li> * <li>value - 正在设置的值(value)</li> * <li>originalValue - 在编辑之前的原始值</li> * <li>row - grid行索引</li> * <li>column - grid列索引</li> * <li>cancel - 由句柄(handler)返回的布尔值,决定true为取消编辑,否则为false</li> * </ul> * @param {Object} e 一个编辑的事件(参阅上面的解释) */ "validateedit" ); }, // private initEvents : function(){ Ext.grid.EditorGridPanel.superclass.initEvents.call(this); this.on("bodyscroll", this.stopEditing, this); if(this.clicksToEdit == 1){ this.on("cellclick", this.onCellDblClick, this); }else { if(this.clicksToEdit == 'auto' && this.view.mainBody){ this.view.mainBody.on("mousedown", this.onAutoEditClick, this); } this.on("celldblclick", this.onCellDblClick, this); } this.getGridEl().addClass("xedit-grid"); }, // private onCellDblClick : function(g, row, col){ this.startEditing(row, col); }, // private onAutoEditClick : function(e, t){ var row = this.view.findRowIndex(t); var col = this.view.findCellIndex(t); if(row !== false && col !== false){ if(this.selModel.getSelectedCell){ // cell sm var sc = this.selModel.getSelectedCell(); if(sc && sc.cell[0] === row && sc.cell[1] === col){ this.startEditing(row, col); } }else{ if(this.selModel.isSelected(row)){ this.startEditing(row, col); } } } }, // private onEditComplete : function(ed, value, startValue){ this.editing = false; this.activeEditor = null; ed.un("specialkey", this.selModel.onEditorKey, this.selModel); if(String(value) !== String(startValue)){ var r = ed.record; var field = this.colModel.getDataIndex(ed.col); var e = { grid: this, record: r, field: field, originalValue: startValue, value: value, row: ed.row, column: ed.col, cancel:false }; if(this.fireEvent("validateedit", e) !== false && !e.cancel){ r.set(field, e.value); delete e.cancel; this.fireEvent("afteredit", e); } } this.view.focusCell(ed.row, ed.col); }, /** * 指定的行/列,进行单元格内容的编辑。 * @param {Number} rowIndex * @param {Number} colIndex */ startEditing : function(row, col){ this.stopEditing(); if(this.colModel.isCellEditable(col, row)){ this.view.ensureVisible(row, col, true); var r = this.store.getAt(row); var field = this.colModel.getDataIndex(col); var e = { grid: this, record: r, field: field, value: r.data[field], row: row, column: col, cancel:false }; if(this.fireEvent("beforeedit", e) !== false && !e.cancel){ this.editing = true; var ed = this.colModel.getCellEditor(col, row); if(!ed.rendered){ ed.render(this.view.getEditorParent(ed)); } (function(){ // complex but required for focus issues in safari, ie and opera ed.row = row; ed.col = col; ed.record = r; ed.on("complete", this.onEditComplete, this, {single: true}); ed.on("specialkey", this.selModel.onEditorKey, this.selModel); this.activeEditor = ed; var v = r.data[field]; ed.startEdit(this.view.getCell(row, col), v); }).defer(50, this); } } }, /** * 停止任何激活的行为。 */ stopEditing : function(){ if(this.activeEditor){ this.activeEditor.completeEdit(); } this.activeEditor = null; } }); Ext.reg('editorgrid', Ext.grid.EditorGridPanel);
JavaScript
/** * @class Ext.grid.GridView * @extends Ext.util.Observable * <p>此类是对{@link Ext.grid.GridPanel}用户界面的封装,其方法能为达到特殊的显示效果而访问用户界面的某些元素。 * 请不要改变用户界面的DOM结构。</p> * <p>此类不会提供途径来操控所属的数据。Grid所在的数据模型是由{@link Ext.data.Store}实现。</p> * @constructor * @param {Object} config */ Ext.grid.GridView = function(config){ Ext.apply(this, config); // These events are only used internally by the grid components this.addEvents( /** * @event beforerowremoved * 当行被移除之前触发。 * @param {Ext.grid.GridView} view * @param {Number} rowIndex 要移除行的索引。 * @param {Ext.data.Record} record 已移除的记录。 */ "beforerowremoved", /** * @event beforerowsinserted * 插入行之前触发。 * @param {Ext.grid.GridView} view * @param {Number} firstRow 被插入第一行的索引 * @param {Number} lastRow 被最后一行的索引 */ "beforerowsinserted", /** * @event beforerefresh * 在视图刷新之前触发 * @param {Ext.grid.GridView} view */ "beforerefresh", /** * @event rowremoved * 当有行被移除时触发 * @param {Ext.grid.GridView} view * @param {Number} rowIndex 被移除行的索引 * @param {Ext.data.Record} record 被移除的Record对象 */ "rowremoved", /** * @event rowsinserted * 当有行被插入时触发 * @param {Ext.grid.GridView} view * @param {Number} firstRow 插入所在位置的索引 * @param {Number} lastRow 插入位置上一行的索引 */ "rowsinserted", /** * @event rowupdated * 当有一行的内容被更新后触发。 * @param {Ext.grid.GridView} view * @param {Number} firstRow 更新行的索引 * @param {Ext.data.record} record 更新后行的Record对象 */ "rowupdated", /** * @event refresh * 当GridView主体刷新完毕后触发 * @param {Ext.grid.GridView} view */ "refresh" ); Ext.grid.GridView.superclass.constructor.call(this); }; Ext.extend(Ext.grid.GridView, Ext.util.Observable, { /** * Override this function to apply custom CSS classes to rows during rendering. You can also supply custom * parameters to the row template for the current row to customize how it is rendered using the <b>rowParams</b> * parameter. This function should return the CSS class name (or empty string '' for none) that will be added * to the row's wrapping div. To apply multiple class names, simply return them space-delimited within the string * (e.g., 'my-class another-class'). * @param {Record} record The {@link Ext.data.Record} corresponding to the current row * @param {Number} index The row index * @param {Object} rowParams A config object that is passed to the row template during rendering that allows * customization of various aspects of a body row, if applicable. Note that this object will only be applied if * {@link #enableRowBody} = true, otherwise it will be ignored. The object may contain any of these properties:<ul> * <li><code>body</code> : String <div class="sub-desc">An HTML fragment to be rendered as the cell's body content (defaults to '').</div></li> * <li><code>bodyStyle</code> : String <div class="sub-desc">A CSS style string that will be applied to the row's TR style attribute (defaults to '').</div></li> * <li><code>cols</code> : Number <div class="sub-desc">The column count to apply to the body row's TD colspan attribute (defaults to the current * column count of the grid).</div></li> * </ul> * 重写该函数就会在渲染过程中修改每一行的CSS样式类。 * 同样地,你也可以通过制定行模板(row template)的参数修改当前行样式,达到控制行渲染的目的,这个参数是<b>rowParams</b>。 * 该函数应该返回一个CSS样式类的名称(如没有就空白字符串 ''),应用当行所在的div元素上。可支持定义多个样式类的名称,用空白字符分割开即可。如('my-class another-class') * @param {Record} record 当然行所关联的{@link Ext.data.Record}对象 * @param {Number} index 行索引 * @param {Object} rowParams * 传入到行模板(row template)的配置项对象,以便渲染过程中可控制每行的部分是怎么显示的(可选的)。 * 注意该对象只会在{@link #enableRowBody} = true时有效,不然的话会被忽略。对象可以包含下例的属性: * <ul> * <li><code>body</code> : String <div class="sub-desc">渲染成为单元格内容部分的HTML判断(默认为'')。</div></li> * <li><code>bodyStyle</code> : String <div class="sub-desc">加入到行所在TR元素的CSS样式(默认为'')</div></li> * <li><code>cols</code> : Number <div class="sub-desc"> * 列的数量,与body 行的TDcolspan属性紧密联系(默认为当前grid的列数)。</div></li> * </ul> * @param {Store} ds The {@link Ext.data.Store} this grid is bound to 与此GRID所绑定的{@link Ext.data.Store}对象 * @method getRowClass * @return {String} a CSS class name to add to the row. 行新加入的样式类 */ /** * @cfg {Boolean} enableRowBody True to add a second TR element per row that can be used to provide a row body * that spans beneath the data row.Use the {@link #getRowClass} method's rowParams config to customize the row body. * True表示为在每一数据行的下方加入一个TR的元素,为行部分提供位置。应使用{@link #getRowClass}方法的rowParams的配置自定义行部分。 */ /** * @cfg {String} emptyText * Default text to display in the grid body when no rows are available (defaults to ''). * 当GRID没有一行可供显示时出现在body的提示文本(默认为"")。 */ /** * 预留给滚动条的空白位置(默认为19像素) * @type Number */ scrollOffset: 19, /** * @cfg {Boolean} autoFill * True to auto expand the columns to fit the grid <b>when the grid is created</b>. * True表示为<b>当GRID创建后</b>自动展开各列,自适应整个GRID。 */ autoFill: false, /** * @cfg {Boolean} forceFit * True to auto expand/contract the size of the columns to fit the grid width and prevent horizontal scrolling. * True表示除了auto expand(自动展开)外,还会对超出的部分进行缩减,让每一列的尺寸适应GRID的宽度大小,阻止水平滚动条的出现。 */ forceFit: false, /** * 排序时头部的CSS样式类(默认为["sort-asc", "sort-desc"])。 * @type Array */ sortClasses : ["sort-asc", "sort-desc"], /** * The text displayed in the "Sort Ascending" menu item * “升序”菜单项的提示文字 * @type String */ sortAscText : "Sort Ascending", /** * The text displayed in the "Sort Descending" menu item * “降序”菜单项的提示文字 * @type String */ sortDescText : "Sort Descending", /** * The text displayed in the "Columns" menu item * “列”菜单项的提示文字 * @type String */ columnsText : "Columns", // private borderWidth: 2, /* -------------------------------- UI Specific ----------------------------- */ // private initTemplates : function(){ var ts = this.templates || {}; if(!ts.master){ ts.master = new Ext.Template( '<div class="x-grid3" hidefocus="true">', '<div class="x-grid3-viewport">', '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>', '<div class="x-grid3-scroller"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>', "</div>", '<div class="x-grid3-resize-marker">&#160;</div>', '<div class="x-grid3-resize-proxy">&#160;</div>', "</div>" ); } if(!ts.header){ ts.header = new Ext.Template( '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>', "</table>" ); } if(!ts.hcell){ ts.hcell = new Ext.Template( '<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id}" style="{style}"><div {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '', '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />', "</div></td>" ); } if(!ts.body){ ts.body = new Ext.Template('{rows}'); } if(!ts.row){ ts.row = new Ext.Template( '<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<tbody><tr>{cells}</tr>', (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''), '</tbody></table></div>' ); } if(!ts.cell){ ts.cell = new Ext.Template( '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>', '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>', "</td>" ); } for(var k in ts){ var t = ts[k]; if(t && typeof t.compile == 'function' && !t.compiled){ t.disableFormats = true; t.compile(); } } this.templates = ts; this.tdClass = 'x-grid3-cell'; this.cellSelector = 'td.x-grid3-cell'; this.hdCls = 'x-grid3-hd'; this.rowSelector = 'div.x-grid3-row'; this.colRe = new RegExp("x-grid3-td-([^\\s]+)", ""); }, // private fly : function(el){ if(!this._flyweight){ this._flyweight = new Ext.Element.Flyweight(document.body); } this._flyweight.dom = el; return this._flyweight; }, // private getEditorParent : function(ed){ return this.scroller.dom; }, // private initElements : function(){ var E = Ext.Element; var el = this.grid.getGridEl().dom.firstChild; var cs = el.childNodes; this.el = new E(el); this.mainWrap = new E(cs[0]); this.mainHd = new E(this.mainWrap.dom.firstChild); this.innerHd = this.mainHd.dom.firstChild; this.scroller = new E(this.mainWrap.dom.childNodes[1]); if(this.forceFit){ this.scroller.setStyle('overflow-x', 'hidden'); } this.mainBody = new E(this.scroller.dom.firstChild); this.focusEl = new E(this.scroller.dom.childNodes[1]); this.focusEl.swallowEvent("click", true); this.resizeMarker = new E(cs[1]); this.resizeProxy = new E(cs[2]); }, // private getRows : function(){ return this.hasRows() ? this.mainBody.dom.childNodes : []; }, // finder methods, used with delegation // private findCell : function(el){ if(!el){ return false; } return this.fly(el).findParent(this.cellSelector, 3); }, // private findCellIndex : function(el, requiredCls){ var cell = this.findCell(el); if(cell && (!requiredCls || this.fly(cell).hasClass(requiredCls))){ return this.getCellIndex(cell); } return false; }, // private getCellIndex : function(el){ if(el){ var m = el.className.match(this.colRe); if(m && m[1]){ return this.cm.getIndexById(m[1]); } } return false; }, // private findHeaderCell : function(el){ var cell = this.findCell(el); return cell && this.fly(cell).hasClass(this.hdCls) ? cell : null; }, // private findHeaderIndex : function(el){ return this.findCellIndex(el, this.hdCls); }, // private findRow : function(el){ if(!el){ return false; } return this.fly(el).findParent(this.rowSelector, 10); }, // private findRowIndex : function(el){ var r = this.findRow(el); return r ? r.rowIndex : false; }, // getter methods for fetching elements dynamically in the grid /** * 指定一个行索引,返回该行的&lt;TR> HtmlElement * @param {Number} index 行索引 * @return {HtmlElement} &lt;TR>元素 */ getRow : function(row){ return this.getRows()[row]; }, /** * 指定一个单元格的坐标,返回该单元格的&lt;TD> HtmlElement * @param {Number} row 定位单元格的行索引 * @param {Number} col 单元格的列索引 * @return {HtmlElement} 坐标所在的&lt;TD>元素 */ getCell : function(row, col){ return this.getRow(row).getElementsByTagName('td')[col]; }, /** * 指定一个列索引,返回该列头部的单元格的&lt;TD> HtmlElement * @param {Number} index 列索引 * @return {HtmlElement} &lt;TD>元素 */ getHeaderCell : function(index){ return this.mainHd.dom.getElementsByTagName('td')[index]; }, // manipulating elements // private - use getRowClass to apply custom row classes addRowClass : function(row, cls){ var r = this.getRow(row); if(r){ this.fly(r).addClass(cls); } }, // private removeRowClass : function(row, cls){ var r = this.getRow(row); if(r){ this.fly(r).removeClass(cls); } }, // private removeRow : function(row){ Ext.removeNode(this.getRow(row)); }, // private removeRows : function(firstRow, lastRow){ var bd = this.mainBody.dom; for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){ Ext.removeNode(bd.childNodes[firstRow]); } }, // scrolling stuff // private getScrollState : function(){ var sb = this.scroller.dom; return {left: sb.scrollLeft, top: sb.scrollTop}; }, // private restoreScroll : function(state){ var sb = this.scroller.dom; sb.scrollLeft = state.left; sb.scrollTop = state.top; }, /** * 滚动grid到顶部 */ scrollToTop : function(){ this.scroller.dom.scrollTop = 0; this.scroller.dom.scrollLeft = 0; }, // private syncScroll : function(){ var mb = this.scroller.dom; this.innerHd.scrollLeft = mb.scrollLeft; this.innerHd.scrollLeft = mb.scrollLeft; // second time for IE (1/2 time first fails, other browsers ignore) this.grid.fireEvent("bodyscroll", mb.scrollLeft, mb.scrollTop); }, // private updateSortIcon : function(col, dir){ var sc = this.sortClasses; var hds = this.mainHd.select('td').removeClass(sc); hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]); }, // private updateAllColumnWidths : function(){ var tw = this.getTotalWidth(); var clen = this.cm.getColumnCount(); var ws = []; for(var i = 0; i < clen; i++){ ws[i] = this.getColumnWidth(i); } this.innerHd.firstChild.firstChild.style.width = tw; for(var i = 0; i < clen; i++){ var hd = this.getHeaderCell(i); hd.style.width = ws[i]; } var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; var row = ns[i].firstChild.rows[0]; for(var j = 0; j < clen; j++){ row.childNodes[j].style.width = ws[j]; } } this.onAllColumnWidthsUpdated(ws, tw); }, // private updateColumnWidth : function(col, width){ var w = this.getColumnWidth(col); var tw = this.getTotalWidth(); this.innerHd.firstChild.firstChild.style.width = tw; var hd = this.getHeaderCell(col); hd.style.width = w; var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; ns[i].firstChild.rows[0].childNodes[col].style.width = w; } this.onColumnWidthUpdated(col, w, tw); }, // private updateColumnHidden : function(col, hidden){ var tw = this.getTotalWidth(); this.innerHd.firstChild.firstChild.style.width = tw; var display = hidden ? 'none' : ''; var hd = this.getHeaderCell(col); hd.style.display = display; var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; ns[i].firstChild.rows[0].childNodes[col].style.display = display; } this.onColumnHiddenUpdated(col, hidden, tw); delete this.lastViewWidth; // force recalc this.layout(); }, // private doRender : function(cs, rs, ds, startRow, colCount, stripe){ var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1; var tstyle = 'width:'+this.getTotalWidth()+';'; // buffers var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r; for(var j = 0, len = rs.length; j < len; j++){ r = rs[j]; cb = []; var rowIndex = (j+startRow); for(var i = 0; i < colCount; i++){ c = cs[i]; p.id = c.id; p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); p.attr = p.cellAttr = ""; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); p.style = c.style; if(p.value == undefined || p.value === "") p.value = "&#160;"; if(r.dirty && typeof r.modified[c.name] !== 'undefined'){ p.css += ' x-grid3-dirty-cell'; } cb[cb.length] = ct.apply(p); } var alt = []; if(stripe && ((rowIndex+1) % 2 == 0)){ alt[0] = "x-grid3-row-alt"; } if(r.dirty){ alt[1] = " x-grid3-dirty-row"; } rp.cols = colCount; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex, rp, ds); } rp.alt = alt.join(" "); rp.cells = cb.join(""); buf[buf.length] = rt.apply(rp); } return buf.join(""); }, // private processRows : function(startRow, skipStripe){ if(this.ds.getCount() < 1){ return; } skipStripe = skipStripe || !this.grid.stripeRows; startRow = startRow || 0; var rows = this.getRows(); var cls = ' x-grid3-row-alt '; for(var i = startRow, len = rows.length; i < len; i++){ var row = rows[i]; row.rowIndex = i; if(!skipStripe){ var isAlt = ((i+1) % 2 == 0); var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1; if(isAlt == hasAlt){ continue; } if(isAlt){ row.className += " x-grid3-row-alt"; }else{ row.className = row.className.replace("x-grid3-row-alt", ""); } } } }, // private renderUI : function(){ var header = this.renderHeaders(); var body = this.templates.body.apply({rows:''}); var html = this.templates.master.apply({ body: body, header: header }); var g = this.grid; g.getGridEl().dom.innerHTML = html; this.initElements(); this.mainBody.dom.innerHTML = this.renderRows(); this.processRows(0, true); // get mousedowns early Ext.fly(this.innerHd).on("click", this.handleHdDown, this); this.mainHd.on("mouseover", this.handleHdOver, this); this.mainHd.on("mouseout", this.handleHdOut, this); this.mainHd.on("mousemove", this.handleHdMove, this); this.scroller.on('scroll', this.syncScroll, this); if(g.enableColumnResize !== false){ this.splitone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom); } if(g.enableColumnMove){ this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd); this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom); } if(g.enableHdMenu !== false){ if(g.enableColumnHide !== false){ this.colMenu = new Ext.menu.Menu({id:g.id + "-hcols-menu"}); this.colMenu.on("beforeshow", this.beforeColMenuShow, this); this.colMenu.on("itemclick", this.handleHdMenuClick, this); } this.hmenu = new Ext.menu.Menu({id: g.id + "-hctx"}); this.hmenu.add( {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"}, {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"} ); if(g.enableColumnHide !== false){ this.hmenu.add('-', {id:"columns", text: this.columnsText, menu: this.colMenu, iconCls: 'x-cols-icon'} ); } this.hmenu.on("itemclick", this.handleHdMenuClick, this); //g.on("headercontextmenu", this.handleHdCtx, this); } if(g.enableDragDrop || g.enableDrag){ var dd = new Ext.grid.GridDragZone(g, { ddGroup : g.ddGroup || 'GridDD' }); } this.updateHeaderSortState(); }, // private layout : function(){ if(!this.mainBody){ return; // not rendered } var g = this.grid; var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this; var csize = c.getSize(true); var vw = csize.width; if(vw < 20 || csize.height < 20){ // display: none? return; } if(g.autoHeight){ this.scroller.dom.style.overflow = 'visible'; }else{ this.el.setSize(csize.width, csize.height); var hdHeight = this.mainHd.getHeight(); var vh = csize.height - (hdHeight); this.scroller.setSize(vw, vh); if(this.innerHd){ this.innerHd.style.width = (vw)+'px'; } } if(this.forceFit){ if(this.lastViewWidth != vw){ this.fitColumns(false, false); this.lastViewWidth = vw; } }else { this.autoExpand(); } this.onLayout(vw, vh); }, // template functions for subclasses and plugins // these functions include precalculated values onLayout : function(vw, vh){ // do nothing }, onColumnWidthUpdated : function(col, w, tw){ }, onAllColumnWidthsUpdated : function(ws, tw){ }, onColumnHiddenUpdated : function(col, hidden, tw){ }, updateColumnText : function(col, text){ }, afterMove : function(colIndex){ }, /* ----------------------------------- Core Specific -------------------------------------------*/ // private init: function(grid){ this.grid = grid; this.initTemplates(); this.initData(grid.store, grid.colModel); this.initUI(grid); }, // private getColumnId : function(index){ return this.cm.getColumnId(index); }, // private renderHeaders : function(){ var cm = this.cm, ts = this.templates; var ct = ts.hcell; var cb = [], sb = [], p = {}; for(var i = 0, len = cm.getColumnCount(); i < len; i++){ p.id = cm.getColumnId(i); p.value = cm.getColumnHeader(i) || ""; p.style = this.getColumnStyle(i, true); if(cm.config[i].align == 'right'){ p.istyle = 'padding-right:16px'; } cb[cb.length] = ct.apply(p); } return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'}); }, // private beforeUpdate : function(){ this.grid.stopEditing(); }, // private updateHeaders : function(){ this.innerHd.firstChild.innerHTML = this.renderHeaders(); }, /** * 使指定的行得到焦点 * @param {Number} row 行索引 */ focusRow : function(row){ this.focusCell(row, 0, false); }, /** * 使指定的单元格得到焦点 * @param {Number} row 行索引 * @param {Number} col 列索引 * @param {Boolean} hscroll false含义为禁止水平滚动 */ focusCell : function(row, col, hscroll){ var el = this.ensureVisible(row, col, hscroll); if(el){ this.focusEl.alignTo(el, "tl-tl"); if(Ext.isGecko){ this.focusEl.focus(); }else{ this.focusEl.focus.defer(1, this.focusEl); } } }, // private ensureVisible : function(row, col, hscroll){ if(typeof row != "number"){ row = row.rowIndex; } if(row < 0 || row >= this.ds.getCount()){ return; } col = (col !== undefined ? col : 0); var rowEl = this.getRow(row), cellEl; if(!(hscroll === false && col === 0)){ while(this.cm.isHidden(col)){ col++; } cellEl = this.getCell(row, col); } if(!rowEl){ return; } var c = this.scroller.dom; var ctop = 0; var p = rowEl, stop = this.el.dom; while(p && p != stop){ ctop += p.offsetTop; p = p.offsetParent; } ctop -= this.mainHd.dom.offsetHeight; var cbot = ctop + rowEl.offsetHeight; var ch = c.clientHeight; var stop = parseInt(c.scrollTop, 10); var sbot = stop + ch; if(ctop < stop){ c.scrollTop = ctop; }else if(cbot > sbot){ c.scrollTop = cbot-ch; } if(hscroll !== false){ var cleft = parseInt(cellEl.offsetLeft, 10); var cright = cleft + cellEl.offsetWidth; var sleft = parseInt(c.scrollLeft, 10); var sright = sleft + c.clientWidth; if(cleft < sleft){ c.scrollLeft = cleft; }else if(cright > sright){ c.scrollLeft = cright-c.clientWidth; } } return cellEl || rowEl; }, // private insertRows : function(dm, firstRow, lastRow, isUpdate){ if(firstRow === 0 && lastRow == dm.getCount()-1){ this.refresh(); }else{ if(!isUpdate){ this.fireEvent("beforerowsinserted", this, firstRow, lastRow); } var html = this.renderRows(firstRow, lastRow); var before = this.getRow(firstRow); if(before){ Ext.DomHelper.insertHtml('beforeBegin', before, html); }else{ Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html); } if(!isUpdate){ this.fireEvent("rowsinserted", this, firstRow, lastRow); this.processRows(firstRow); } } }, // private deleteRows : function(dm, firstRow, lastRow){ if(dm.getRowCount()<1){ this.refresh(); }else{ this.fireEvent("beforerowsdeleted", this, firstRow, lastRow); this.removeRows(firstRow, lastRow); this.processRows(firstRow); this.fireEvent("rowsdeleted", this, firstRow, lastRow); } }, // private getColumnStyle : function(col, isHeader){ var style = !isHeader ? (this.cm.config[col].css || '') : ''; style += 'width:'+this.getColumnWidth(col)+';'; if(this.cm.isHidden(col)){ style += 'display:none;'; } var align = this.cm.config[col].align; if(align){ style += 'text-align:'+align+';'; } return style; }, // private getColumnWidth : function(col){ var w = this.cm.getColumnWidth(col); if(typeof w == 'number'){ return (Ext.isBorderBox ? w : (w-this.borderWidth > 0 ? w-this.borderWidth:0)) + 'px'; } return w; }, // private getTotalWidth : function(){ return this.cm.getTotalWidth()+'px'; }, // private fitColumns : function(preventRefresh, onlyExpand, omitColumn){ var cm = this.cm, leftOver, dist, i; var tw = cm.getTotalWidth(false); var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset; if(aw < 20){ // not initialized, so don't screw up the default widths return; } var extra = aw - tw; if(extra === 0){ return false; } var vc = cm.getColumnCount(true); var ac = vc-(typeof omitColumn == 'number' ? 1 : 0); if(ac === 0){ ac = 1; omitColumn = undefined; } var colCount = cm.getColumnCount(); var cols = []; var extraCol = 0; var width = 0; var w; for (i = 0; i < colCount; i++){ if(!cm.isHidden(i) && !cm.isFixed(i) && i !== omitColumn){ w = cm.getColumnWidth(i); cols.push(i); extraCol = i; cols.push(w); width += w; } } var frac = (aw - cm.getTotalWidth())/width; while (cols.length){ w = cols.pop(); i = cols.pop(); cm.setColumnWidth(i, Math.max(this.grid.minColumnWidth, Math.floor(w + w*frac)), true); } if((tw = cm.getTotalWidth(false)) > aw){ var adjustCol = ac != vc ? omitColumn : extraCol; cm.setColumnWidth(adjustCol, Math.max(1, cm.getColumnWidth(adjustCol)- (tw-aw)), true); } if(preventRefresh !== true){ this.updateAllColumnWidths(); } return true; }, // private autoExpand : function(preventUpdate){ var g = this.grid, cm = this.cm; if(!this.userResized && g.autoExpandColumn){ var tw = cm.getTotalWidth(false); var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset; if(tw != aw){ var ci = cm.getIndexById(g.autoExpandColumn); var currentWidth = cm.getColumnWidth(ci); var cw = Math.min(Math.max(((aw-tw)+currentWidth), g.autoExpandMin), g.autoExpandMax); if(cw != currentWidth){ cm.setColumnWidth(ci, cw, true); if(preventUpdate !== true){ this.updateColumnWidth(ci, cw); } } } } }, // private getColumnData : function(){ // build a map for all the columns var cs = [], cm = this.cm, colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ var name = cm.getDataIndex(i); cs[i] = { name : (typeof name == 'undefined' ? this.ds.fields.get(i).name : name), renderer : cm.getRenderer(i), id : cm.getColumnId(i), style : this.getColumnStyle(i) }; } return cs; }, // private renderRows : function(startRow, endRow){ // pull in all the crap needed to render rows var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows; var colCount = cm.getColumnCount(); if(ds.getCount() < 1){ return ""; } var cs = this.getColumnData(); startRow = startRow || 0; endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow; // records to render var rs = ds.getRange(startRow, endRow); return this.doRender(cs, rs, ds, startRow, colCount, stripe); }, // private renderBody : function(){ var markup = this.renderRows(); return this.templates.body.apply({rows: markup}); }, // private refreshRow : function(record){ var ds = this.ds, index; if(typeof record == 'number'){ index = record; record = ds.getAt(index); }else{ index = ds.indexOf(record); } var cls = []; this.insertRows(ds, index, index, true); this.getRow(index).rowIndex = index; this.onRemove(ds, record, index+1, true); this.fireEvent("rowupdated", this, index, record); }, /** * 刷新grid UI * @param {Boolean} headersToo (可选的)True表示为也刷新头部 */ refresh : function(headersToo){ this.fireEvent("beforerefresh", this); this.grid.stopEditing(); var result = this.renderBody(); this.mainBody.update(result); if(headersToo === true){ this.updateHeaders(); this.updateHeaderSortState(); } this.processRows(0, true); this.layout(); this.applyEmptyText(); this.fireEvent("refresh", this); }, // private applyEmptyText : function(){ if(this.emptyText && !this.hasRows()){ this.mainBody.update('<div class="x-grid-empty">' + this.emptyText + '</div>'); } }, // private updateHeaderSortState : function(){ var state = this.ds.getSortState(); if(!state){ return; } if(!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)){ this.grid.fireEvent('sortchange', this.grid, state); } this.sortState = state; var sortColumn = this.cm.findColumnIndex(state.field); if(sortColumn != -1){ var sortDir = state.direction; this.updateSortIcon(sortColumn, sortDir); } }, // private destroy : function(){ if(this.colMenu){ this.colMenu.removeAll(); Ext.menu.MenuMgr.unregister(this.colMenu); this.colMenu.getEl().remove(); delete this.colMenu; } if(this.hmenu){ this.hmenu.removeAll(); Ext.menu.MenuMgr.unregister(this.hmenu); this.hmenu.getEl().remove(); delete this.hmenu; } if(this.grid.enableColumnMove){ var dds = Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id]; if(dds){ for(var dd in dds){ if(!dds[dd].config.isTarget && dds[dd].dragElId){ var elid = dds[dd].dragElId; dds[dd].unreg(); Ext.get(elid).remove(); } else if(dds[dd].config.isTarget){ dds[dd].proxyTop.remove(); dds[dd].proxyBottom.remove(); dds[dd].unreg(); } if(Ext.dd.DDM.locationCache[dd]){ delete Ext.dd.DDM.locationCache[dd]; } } delete Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id]; } } Ext.destroy(this.resizeMarker, this.resizeProxy); this.initData(null, null); Ext.EventManager.removeResizeListener(this.onWindowResize, this); }, // private onDenyColumnHide : function(){ }, // private render : function(){ var cm = this.cm; var colCount = cm.getColumnCount(); if(this.grid.monitorWindowResize === true){ Ext.EventManager.onWindowResize(this.onWindowResize, this, true); } if(this.autoFill){ this.fitColumns(true, true); }else if(this.forceFit){ this.fitColumns(true, false); }else if(this.grid.autoExpandColumn){ this.autoExpand(true); } this.renderUI(); //this.refresh(); }, // private onWindowResize : function(){ if(!this.grid.monitorWindowResize || this.grid.autoHeight){ return; } this.layout(); }, /* --------------------------------- Model Events and Handlers --------------------------------*/ // private initData : function(ds, cm){ if(this.ds){ this.ds.un("load", this.onLoad, this); this.ds.un("datachanged", this.onDataChange, this); this.ds.un("add", this.onAdd, this); this.ds.un("remove", this.onRemove, this); this.ds.un("update", this.onUpdate, this); this.ds.un("clear", this.onClear, this); } if(ds){ ds.on("load", this.onLoad, this); ds.on("datachanged", this.onDataChange, this); ds.on("add", this.onAdd, this); ds.on("remove", this.onRemove, this); ds.on("update", this.onUpdate, this); ds.on("clear", this.onClear, this); } this.ds = ds; if(this.cm){ this.cm.un("configchange", this.onColConfigChange, this); this.cm.un("widthchange", this.onColWidthChange, this); this.cm.un("headerchange", this.onHeaderChange, this); this.cm.un("hiddenchange", this.onHiddenChange, this); this.cm.un("columnmoved", this.onColumnMove, this); this.cm.un("columnlockchange", this.onColumnLock, this); } if(cm){ cm.on("configchange", this.onColConfigChange, this); cm.on("widthchange", this.onColWidthChange, this); cm.on("headerchange", this.onHeaderChange, this); cm.on("hiddenchange", this.onHiddenChange, this); cm.on("columnmoved", this.onColumnMove, this); cm.on("columnlockchange", this.onColumnLock, this); } this.cm = cm; }, // private onDataChange : function(){ this.refresh(); this.updateHeaderSortState(); }, // private onClear : function(){ this.refresh(); }, // private onUpdate : function(ds, record){ this.refreshRow(record); }, // private onAdd : function(ds, records, index){ this.insertRows(ds, index, index + (records.length-1)); }, // private onRemove : function(ds, record, index, isUpdate){ if(isUpdate !== true){ this.fireEvent("beforerowremoved", this, index, record); } this.removeRow(index); if(isUpdate !== true){ this.processRows(index); this.applyEmptyText(); this.fireEvent("rowremoved", this, index, record); } }, // private onLoad : function(){ this.scrollToTop(); }, // private onColWidthChange : function(cm, col, width){ this.updateColumnWidth(col, width); }, // private onHeaderChange : function(cm, col, text){ this.updateHeaders(); }, // private onHiddenChange : function(cm, col, hidden){ this.updateColumnHidden(col, hidden); }, // private onColumnMove : function(cm, oldIndex, newIndex){ this.indexMap = null; var s = this.getScrollState(); this.refresh(true); this.restoreScroll(s); this.afterMove(newIndex); }, // private onColConfigChange : function(){ delete this.lastViewWidth; this.indexMap = null; this.refresh(true); }, /* -------------------- UI Events and Handlers ------------------------------ */ // private initUI : function(grid){ grid.on("headerclick", this.onHeaderClick, this); if(grid.trackMouseOver){ grid.on("mouseover", this.onRowOver, this); grid.on("mouseout", this.onRowOut, this); } }, // private initEvents : function(){ }, // private onHeaderClick : function(g, index){ if(this.headersDisabled || !this.cm.isSortable(index)){ return; } g.stopEditing(); g.store.sort(this.cm.getDataIndex(index)); }, // private onRowOver : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false){ this.addRowClass(row, "x-grid3-row-over"); } }, // private onRowOut : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){ this.removeRowClass(row, "x-grid3-row-over"); } }, // private handleWheel : function(e){ e.stopPropagation(); }, // private onRowSelect : function(row){ this.addRowClass(row, "x-grid3-row-selected"); }, // private onRowDeselect : function(row){ this.removeRowClass(row, "x-grid3-row-selected"); }, // private onCellSelect : function(row, col){ var cell = this.getCell(row, col); if(cell){ this.fly(cell).addClass("x-grid3-cell-selected"); } }, // private onCellDeselect : function(row, col){ var cell = this.getCell(row, col); if(cell){ this.fly(cell).removeClass("x-grid3-cell-selected"); } }, // private onColumnSplitterMoved : function(i, w){ this.userResized = true; var cm = this.grid.colModel; cm.setColumnWidth(i, w, true); if(this.forceFit){ this.fitColumns(true, false, i); this.updateAllColumnWidths(); }else{ this.updateColumnWidth(i, w); } this.grid.fireEvent("columnresize", i, w); }, // private handleHdMenuClick : function(item){ var index = this.hdCtxIndex; var cm = this.cm, ds = this.ds; switch(item.id){ case "asc": ds.sort(cm.getDataIndex(index), "ASC"); break; case "desc": ds.sort(cm.getDataIndex(index), "DESC"); break; default: index = cm.getIndexById(item.id.substr(4)); if(index != -1){ if(item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1){ this.onDenyColumnHide(); return false; } cm.setHidden(index, item.checked); } } return true; }, // private isHideableColumn : function(c){ return !c.hidden && !c.fixed; }, // private beforeColMenuShow : function(){ var cm = this.cm, colCount = cm.getColumnCount(); this.colMenu.removeAll(); for(var i = 0; i < colCount; i++){ if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){ this.colMenu.add(new Ext.menu.CheckItem({ id: "col-"+cm.getColumnId(i), text: cm.getColumnHeader(i), checked: !cm.isHidden(i), hideOnClick:false, disabled: cm.config[i].hideable === false })); } } }, // private handleHdDown : function(e, t){ if(Ext.fly(t).hasClass('x-grid3-hd-btn')){ e.stopEvent(); var hd = this.findHeaderCell(t); Ext.fly(hd).addClass('x-grid3-hd-menu-open'); var index = this.getCellIndex(hd); this.hdCtxIndex = index; var ms = this.hmenu.items, cm = this.cm; ms.get("asc").setDisabled(!cm.isSortable(index)); ms.get("desc").setDisabled(!cm.isSortable(index)); this.hmenu.on("hide", function(){ Ext.fly(hd).removeClass('x-grid3-hd-menu-open'); }, this, {single:true}); this.hmenu.show(t, "tl-bl?"); } }, // private handleHdOver : function(e, t){ var hd = this.findHeaderCell(t); if(hd && !this.headersDisabled){ this.activeHd = hd; this.activeHdIndex = this.getCellIndex(hd); var fly = this.fly(hd); this.activeHdRegion = fly.getRegion(); if(this.cm.isSortable(this.activeHdIndex) && !this.cm.isFixed(this.activeHdIndex)){ fly.addClass("x-grid3-hd-over"); this.activeHdBtn = fly.child('.x-grid3-hd-btn'); if(this.activeHdBtn){ this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight-1)+'px'; } } } }, // private handleHdMove : function(e, t){ if(this.activeHd && !this.headersDisabled){ var hw = this.splitHandleWidth || 5; var r = this.activeHdRegion; var x = e.getPageX(); var ss = this.activeHd.style; if(x - r.left <= hw && this.cm.isResizable(this.activeHdIndex-1)){ if(Ext.isSafari){ ss.cursor = 'e-resize';// col-resize not always supported }else{ ss.cursor = 'col-resize'; } }else if(r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)){ if(Ext.isSafari){ ss.cursor = 'w-resize'; // col-resize not always supported }else{ ss.cursor = 'col-resize'; } }else{ ss.cursor = ''; } } }, // private handleHdOut : function(e, t){ var hd = this.findHeaderCell(t); if(hd && (!Ext.isIE || !e.within(hd, true))){ this.activeHd = null; this.fly(hd).removeClass("x-grid3-hd-over"); hd.style.cursor = ''; } }, // private hasRows : function(){ var fc = this.mainBody.dom.firstChild; return fc && fc.className != 'x-grid-empty'; }, // back compat bind : function(d, c){ this.initData(d, c); } }); // private // This is a support class used internally by the Grid components Ext.grid.GridView.SplitDragZone = function(grid, hd){ this.grid = grid; this.view = grid.getView(); this.marker = this.view.resizeMarker; this.proxy = this.view.resizeProxy; Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this, hd, "gridSplitters" + this.grid.getGridEl().id, { dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); this.scroll = false; this.hw = this.view.splitHandleWidth || 5; }; Ext.extend(Ext.grid.GridView.SplitDragZone, Ext.dd.DDProxy, { b4StartDrag : function(x, y){ this.view.headersDisabled = true; var h = this.view.mainWrap.getHeight(); this.marker.setHeight(h); this.marker.show(); this.marker.alignTo(this.view.getHeaderCell(this.cellIndex), 'tl-tl', [-2, 0]); this.proxy.setHeight(h); var w = this.cm.getColumnWidth(this.cellIndex); var minw = Math.max(w-this.grid.minColumnWidth, 0); this.resetConstraints(); this.setXConstraint(minw, 1000); this.setYConstraint(0, 0); this.minX = x - minw; this.maxX = x + 1000; this.startPos = x; Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, handleMouseDown : function(e){ var t = this.view.findHeaderCell(e.getTarget()); if(t){ var xy = this.view.fly(t).getXY(), x = xy[0], y = xy[1]; var exy = e.getXY(), ex = exy[0], ey = exy[1]; var w = t.offsetWidth, adjust = false; if((ex - x) <= this.hw){ adjust = -1; }else if((x+w) - ex <= this.hw){ adjust = 0; } if(adjust !== false){ this.cm = this.grid.colModel; var ci = this.view.getCellIndex(t); if(adjust == -1){ while(this.cm.isHidden(ci+adjust)){ --adjust; if(ci+adjust < 0){ return; } } } this.cellIndex = ci+adjust; this.split = t.dom; if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } }else if(this.view.columnDrag){ this.view.columnDrag.callHandleMouseDown(e); } } }, endDrag : function(e){ this.marker.hide(); var v = this.view; var endX = Math.max(this.minX, e.getPageX()); var diff = endX - this.startPos; v.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); setTimeout(function(){ v.headersDisabled = false; }, 50); }, autoOffset : function(){ this.setDelta(0,0); } });
JavaScript
/** @class Ext.grid.RowSelectionModel * @extends Ext.grid.AbstractSelectionModel * The default SelectionModel used by {@link Ext.grid.GridPanel}. * It supports multiple selections and keyboard selection/navigation. The objects stored * as selections and returned by {@link #getSelected}, and {@link #getSelections} are * the {@link Ext.data.Record Record}s which provide the data for the selected rows. * @constructor * @param {Object} config */ Ext.grid.RowSelectionModel = function(config){ Ext.apply(this, config); this.selections = new Ext.util.MixedCollection(false, function(o){ return o.id; }); this.last = false; this.lastActive = false; this.addEvents( /** * @event selectionchange * 当选区改变时触发。Fires when the selection changes * @param {SelectionModel} this */ "selectionchange", /** * @event beforerowselect * 当行(row)是选中又被选择触发,返回false取消。Fires when a row is being selected, return false to cancel. * @param {SelectionModel} this * @param {Number} rowIndex The index to be selected * @param {Boolean} keepExisting 选中的索引。False if other selections will be cleared * @param {Record} record The record to be selected */ "beforerowselect", /** * @event rowselect * 当行(row)被选中时触发。Fires when a row is selected. * @param {SelectionModel} this * @param {Number} rowIndex 选中的索引。The selected index * @param {Ext.data.Record} r The selected record */ "rowselect", /** * @event rowdeselect * 当行(row)反选时触发。Fires when a row is deselected. * @param {SelectionModel} this * @param {Number} rowIndex 选中的索引。 * @param {Record} record */ "rowdeselect" ); Ext.grid.RowSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.RowSelectionModel, Ext.grid.AbstractSelectionModel, { /** * @cfg {Boolean} singleSelect * True表示为同时只能选单行(默认false)。True to allow selection of only one row at a time (defaults to false) */ singleSelect : false, /** * @cfg {Boolean} moveEditorOnEnter * False to turn off moving the editor to the next row down when the enter key is pressed * or the next row up when shift + enter keys are pressed. */ // private initEvents : function(){ if(!this.grid.enableDragDrop && !this.grid.enableDrag){ this.grid.on("rowmousedown", this.handleMouseDown, this); }else{ // allow click to work like normal this.grid.on("rowclick", function(grid, rowIndex, e) { if(e.button === 0 && !e.shiftKey && !e.ctrlKey) { this.selectRow(rowIndex, false); grid.view.focusRow(rowIndex); } }, this); } this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), { "up" : function(e){ if(!e.shiftKey || this.singleSelect){ this.selectPrevious(false); }else if(this.last !== false && this.lastActive !== false){ var last = this.last; this.selectRange(this.last, this.lastActive-1); this.grid.getView().focusRow(this.lastActive); if(last !== false){ this.last = last; } }else{ this.selectFirstRow(); } }, "down" : function(e){ if(!e.shiftKey || this.singleSelect){ this.selectNext(false); }else if(this.last !== false && this.lastActive !== false){ var last = this.last; this.selectRange(this.last, this.lastActive+1); this.grid.getView().focusRow(this.lastActive); if(last !== false){ this.last = last; } }else{ this.selectFirstRow(); } }, scope: this }); var view = this.grid.view; view.on("refresh", this.onRefresh, this); view.on("rowupdated", this.onRowUpdated, this); view.on("rowremoved", this.onRemove, this); }, // private onRefresh : function(){ var ds = this.grid.store, index; var s = this.getSelections(); this.clearSelections(true); for(var i = 0, len = s.length; i < len; i++){ var r = s[i]; if((index = ds.indexOfId(r.id)) != -1){ this.selectRow(index, true); } } if(s.length != this.selections.getCount()){ this.fireEvent("selectionchange", this); } }, // private onRemove : function(v, index, r){ if(this.selections.remove(r) !== false){ this.fireEvent('selectionchange', this); } }, // private onRowUpdated : function(v, index, r){ if(this.isSelected(r)){ v.onRowSelect(index); } }, /** * 选择多个记录。 * Select records. * @param {Array} records 要选择的record。The records to select * @param {Boolean} keepExisting (optional) (可选的)true表示为保持当前现有的选区。True to keep existing selections */ selectRecords : function(records, keepExisting){ if(!keepExisting){ this.clearSelections(); } var ds = this.grid.store; for(var i = 0, len = records.length; i < len; i++){ this.selectRow(ds.indexOf(records[i]), true); } }, /** * 获取已选择的行数。 * Gets the number of selected rows. * @return {Number} */ getCount : function(){ return this.selections.length; }, /** * 选择GRID的第一行。 * Selects the first row in the grid. */ selectFirstRow : function(){ this.selectRow(0); }, /** * 选择最后一行。 * Select the last row. * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。(optional) True to keep existing selections */ selectLastRow : function(keepExisting){ this.selectRow(this.grid.store.getCount() - 1, keepExisting); }, /** * 选取上次选取的最后一行。 * Selects the row immediately following the last selected row. * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。(optional)True to keep existing selections * @return {Boolean} True if there is a next row, else false */ selectNext : function(keepExisting){ if(this.hasNext()){ this.selectRow(this.last+1, keepExisting); this.grid.getView().focusRow(this.last); return true; } return false; }, /** * 选取上次选取的最前一行。 * Selects the row that precedes the last selected row. * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。(optional)True to keep existing selections * @return {Boolean} True表示为有前一行,false表示没有。True if there is a previous row, else false */ selectPrevious : function(keepExisting){ if(this.hasPrevious()){ this.selectRow(this.last-1, keepExisting); this.grid.getView().focusRow(this.last); return true; } return false; }, /** * 若有下一个可选取的记录返回true。 * Returns true if there is a next record to select * @return {Boolean} */ hasNext : function(){ return this.last !== false && (this.last+1) < this.grid.store.getCount(); }, /** * 若有前一个可选取的记录返回true。 * Returns true if there is a previous record to select * @return {Boolean} */ hasPrevious : function(){ return !!this.last; }, /** * 返回以选取的纪录。 * Returns the selected records * @return {Array} 已选取记录的数组。Array of selected records */ getSelections : function(){ return [].concat(this.selections.items); }, /** * 返回选区中的第一个记录。 * Returns the first selected record. * @return {Record} */ getSelected : function(){ return this.selections.itemAt(0); }, /** * 对选区执行传入函数。如果函数返回false,枚举将会中止,each函数就会返回false,否则返回true。 * Calls the passed function with each selection. If the function returns false, iteration is * stopped and this function returns false. Otherwise it returns true. * @param {Function} fn * @param {Object} scope (optional) * @return {Boolean} true表示为已枚举所有的记录。true if all selections were iterated */ each : function(fn, scope){ var s = this.getSelections(); for(var i = 0, len = s.length; i < len; i++){ if(fn.call(scope || this, s[i], i) === false){ return false; } } return true; }, /** * Clears all selections. */ clearSelections : function(fast){ if(this.isLocked()) return; if(fast !== true){ var ds = this.grid.store; var s = this.selections; s.each(function(r){ this.deselectRow(ds.indexOfId(r.id)); }, this); s.clear(); }else{ this.selections.clear(); } this.last = false; }, /** * Selects all rows. */ selectAll : function(){ if(this.isLocked()) return; this.selections.clear(); for(var i = 0, len = this.grid.store.getCount(); i < len; i++){ this.selectRow(i, true); } }, /** * Returns True if there is a selection. * @return {Boolean} */ hasSelection : function(){ return this.selections.length > 0; }, /** * Returns True if the specified row is selected. * @param {Number/Record} record The record or index of the record to check * @return {Boolean} */ isSelected : function(index){ var r = typeof index == "number" ? this.grid.store.getAt(index) : index; return (r && this.selections.key(r.id) ? true : false); }, /** * Returns True if the specified record id is selected. * @param {String} id The id of record to check * @return {Boolean} */ isIdSelected : function(id){ return (this.selections.key(id) ? true : false); }, // private handleMouseDown : function(g, rowIndex, e){ if(e.button !== 0 || this.isLocked()){ return; }; var view = this.grid.getView(); if(e.shiftKey && !this.singleSelect && this.last !== false){ var last = this.last; this.selectRange(last, rowIndex, e.ctrlKey); this.last = last; // reset the last view.focusRow(rowIndex); }else{ var isSelected = this.isSelected(rowIndex); if(e.ctrlKey && isSelected){ this.deselectRow(rowIndex); }else if(!isSelected || this.getCount() > 1){ this.selectRow(rowIndex, e.ctrlKey || e.shiftKey); view.focusRow(rowIndex); } } }, /** * 选取多行。Selects multiple rows. * @param {Array} rows 要选取行的索引的集合。Array of the indexes of the row to select * @param {Boolean} keepExisting (optional) (可选的)表示为保持现有的选区。True to keep existing selections (defaults to false) */ selectRows : function(rows, keepExisting){ if(!keepExisting){ this.clearSelections(); } for(var i = 0, len = rows.length; i < len; i++){ this.selectRow(rows[i], true); } }, /** * 选取某个范围内的行(rows)。所有在startRow和endRow之间的行都会被选中。Selects a range of rows. All rows in between startRow and endRow are also selected. * @param {Number} startRow 范围内的第一行之索引。The index of the first row in the range * @param {Number} endRow 范围内的最后一行之索引。The index of the last row in the range * @param {Boolean} keepExisting (optional)(可选的)表示为保持现有的选区。True to retain existing selections */ selectRange : function(startRow, endRow, keepExisting){ if(this.isLocked()) return; if(!keepExisting){ this.clearSelections(); } if(startRow <= endRow){ for(var i = startRow; i <= endRow; i++){ this.selectRow(i, true); } }else{ for(var i = startRow; i >= endRow; i--){ this.selectRow(i, true); } } }, /** * 反选某个范围内的行(rows)。所有在startRow和endRow之间的行都会被选反。Deselects a range of rows. All rows in between startRow and endRow are also deselected. * @param {Number} startRow 范围内的第一行之索引。The index of the first row in the range * @param {Number} endRow 范围内的最后一行之索引。The index of the last row in the range */ deselectRange : function(startRow, endRow, preventViewNotify){ if(this.isLocked()) return; for(var i = startRow; i <= endRow; i++){ this.deselectRow(i, preventViewNotify); } }, /** * 选择一行。Selects a row. * @param {Number} row 要选择行的索引 。The index of the row to select * @param {Boolean} keepExisting (optional) (可选的)表示为保持现有的选区。True to keep existing selections */ selectRow : function(index, keepExisting, preventViewNotify){ if(this.isLocked() || (index < 0 || index >= this.grid.store.getCount()) || this.isSelected(index)) return; var r = this.grid.store.getAt(index); if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){ if(!keepExisting || this.singleSelect){ this.clearSelections(); } this.selections.add(r); this.last = this.lastActive = index; if(!preventViewNotify){ this.grid.getView().onRowSelect(index); } this.fireEvent("rowselect", this, index, r); this.fireEvent("selectionchange", this); } }, /** * 反选一个行。Deselects a row. * @param {Number} row 反选行的索引。The index of the row to deselect */ deselectRow : function(index, preventViewNotify){ if(this.isLocked()) return; if(this.last == index){ this.last = false; } if(this.lastActive == index){ this.lastActive = false; } var r = this.grid.store.getAt(index); if(r){ this.selections.remove(r); if(!preventViewNotify){ this.grid.getView().onRowDeselect(index); } this.fireEvent("rowdeselect", this, index, r); this.fireEvent("selectionchange", this); } }, // private restoreLast : function(){ if(this._last){ this.last = this._last; } }, // private acceptsNav : function(row, col, cm){ return !cm.isHidden(col) && cm.isCellEditable(col, row); }, // private onEditorKey : function(field, e){ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor; var shift = e.shiftKey; if(k == e.TAB){ e.stopEvent(); ed.completeEdit(); if(shift){ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); } }else if(k == e.ENTER){ e.stopEvent(); ed.completeEdit(); if(this.moveEditorOnEnter !== false){ if(shift){ newCell = g.walkCells(ed.row - 1, ed.col, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row + 1, ed.col, 1, this.acceptsNav, this); } } }else if(k == e.ESC){ ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } });
JavaScript
// private // This is a support class used internally by the Grid components Ext.grid.HeaderDragZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.ddGroup = "gridHeader" + this.grid.getGridEl().id; Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd); if(hd2){ this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); } this.scroll = false; }; Ext.extend(Ext.grid.HeaderDragZone, Ext.dd.DragZone, { maxDragWidth: 120, getDragData : function(e){ var t = Ext.lib.Event.getTarget(e); var h = this.view.findHeaderCell(t); if(h){ return {ddel: h.firstChild, header:h}; } return false; }, onInitDrag : function(e){ this.view.headersDisabled = true; var clone = this.dragData.ddel.cloneNode(true); clone.id = Ext.id(); clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px"; this.proxy.update(clone); return true; }, afterValidDrop : function(){ var v = this.view; setTimeout(function(){ v.headersDisabled = false; }, 50); }, afterInvalidDrop : function(){ var v = this.view; setTimeout(function(){ v.headersDisabled = false; }, 50); } }); // private // This is a support class used internally by the Grid components Ext.grid.HeaderDropZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); // split the proxies so they don't interfere with mouse events this.proxyTop = Ext.DomHelper.append(document.body, { cls:"col-move-top", html:"&#160;" }, true); this.proxyBottom = Ext.DomHelper.append(document.body, { cls:"col-move-bottom", html:"&#160;" }, true); this.proxyTop.hide = this.proxyBottom.hide = function(){ this.setLeftTop(-100,-100); this.setStyle("visibility", "hidden"); }; this.ddGroup = "gridHeader" + this.grid.getGridEl().id; // temporarily disabled //Ext.dd.ScrollManager.register(this.view.scroller.dom); Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom); }; Ext.extend(Ext.grid.HeaderDropZone, Ext.dd.DropZone, { proxyOffsets : [-4, -9], fly: Ext.Element.fly, getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); var cindex = this.view.findCellIndex(t); if(cindex !== false){ return this.view.getHeaderCell(cindex); } }, nextVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.nextSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.nextSibling; } return null; }, prevVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.prevSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.prevSibling; } return null; }, positionIndicator : function(h, n, e){ var x = Ext.lib.Event.getPageX(e); var r = Ext.lib.Dom.getRegion(n.firstChild); var px, pt, py = r.top + this.proxyOffsets[1]; if((r.right - x) <= (r.right-r.left)/2){ px = r.right+this.view.borderWidth; pt = "after"; }else{ px = r.left; pt = "before"; } var oldIndex = this.view.getCellIndex(h); var newIndex = this.view.getCellIndex(n); if(this.grid.colModel.isFixed(newIndex)){ return false; } var locked = this.grid.colModel.isLocked(newIndex); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){ return false; } px += this.proxyOffsets[0]; this.proxyTop.setLeftTop(px, py); this.proxyTop.show(); if(!this.bottomOffset){ this.bottomOffset = this.view.mainHd.getHeight(); } this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset); this.proxyBottom.show(); return pt; }, onNodeEnter : function(n, dd, e, data){ if(data.header != n){ this.positionIndicator(data.header, n, e); } }, onNodeOver : function(n, dd, e, data){ var result = false; if(data.header != n){ result = this.positionIndicator(data.header, n, e); } if(!result){ this.proxyTop.hide(); this.proxyBottom.hide(); } return result ? this.dropAllowed : this.dropNotAllowed; }, onNodeOut : function(n, dd, e, data){ this.proxyTop.hide(); this.proxyBottom.hide(); }, onNodeDrop : function(n, dd, e, data){ var h = data.header; if(h != n){ var cm = this.grid.colModel; var x = Ext.lib.Event.getPageX(e); var r = Ext.lib.Dom.getRegion(n.firstChild); var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before"; var oldIndex = this.view.getCellIndex(h); var newIndex = this.view.getCellIndex(n); var locked = cm.isLocked(newIndex); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){ return false; } cm.setLocked(oldIndex, locked, true); cm.moveColumn(oldIndex, newIndex); this.grid.fireEvent("columnmove", oldIndex, newIndex); return true; } return false; } }); Ext.grid.GridView.ColumnDragZone = function(grid, hd){ Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null); this.proxy.el.addClass('x-grid3-col-dd'); }; Ext.extend(Ext.grid.GridView.ColumnDragZone, Ext.grid.HeaderDragZone, { handleMouseDown : function(e){ }, callHandleMouseDown : function(e){ Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e); } });
JavaScript
/** * @class Ext.grid.CheckboxSelectionModel * @extends Ext.grid.RowSelectionModel * 通过checkbox选择或反选时触发选区轮换的一个制定选区模型。 * @constructor * @param {Object} config 配置项选项 */ Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { /** * @cfg {String} header * 任何显示在checkbox列头部上有效的HTML片断(默认为 '&lt;div class="x-grid3-hd-checker">&#160;&lt;/div>') * 默认的CSS样式类'x-grid3-hd-checker'负责头部的那个checkbox,以支持全局单击、反选的行为。 * 这个字符串可以替换为任何有效的HTML片断,包括几句的文本字符串(如'Select Rows'), * 但是全局单击、反选行为的checkbox就只能“ x-grid3-hd-checker”的出现才能工作。 */ header: '<div class="x-grid3-hd-checker">&#160;</div>', /** * @cfg {Number} width * checkbox列默认的宽度(默认为20) */ width: 20, /** * @cfg {Boolean} sortable * True表示为checkbox列可以被排序(默认为fasle) */ sortable: false, // private fixed:true, dataIndex: '', id: 'checker', // private initEvents : function(){ Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); this.grid.on('render', function(){ var view = this.grid.getView(); view.mainBody.on('mousedown', this.onMouseDown, this); Ext.fly(view.innerHd).on('mousedown', this.onHdMouseDown, this); }, this); }, // private onMouseDown : function(e, t){ if(t.className == 'x-grid3-row-checker'){ e.stopEvent(); var row = e.getTarget('.x-grid3-row'); if(row){ var index = row.rowIndex; if(this.isSelected(index)){ this.deselectRow(index); }else{ this.selectRow(index, true); } } } }, // private onHdMouseDown : function(e, t){ if(t.className == 'x-grid3-hd-checker'){ e.stopEvent(); var hd = Ext.fly(t.parentNode); var isChecked = hd.hasClass('x-grid3-hd-checker-on'); if(isChecked){ hd.removeClass('x-grid3-hd-checker-on'); this.clearSelections(); }else{ hd.addClass('x-grid3-hd-checker-on'); this.selectAll(); } } }, // private renderer : function(v, p, record){ return '<div class="x-grid3-row-checker">&#160;</div>'; } });
JavaScript
/** * @class Ext.grid.GridPanel * @extends Ext.Panel * 基于Grid控件的一个面板组件,此类呈现了主要的接口。 * <br><br>用法: * <pre><code>var grid = new Ext.grid.GridPanel({ store: new Ext.data.Store({ reader: reader, data: xg.dummyData }), columns: [ {id:'company', header: "Company", width: 200, sortable: true, dataIndex: 'company'}, {header: "Price", width: 120, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'}, {header: "Change", width: 120, sortable: true, dataIndex: 'change'}, {header: "% Change", width: 120, sortable: true, dataIndex: 'pctChange'}, {header: "Last Updated", width: 135, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'} ], viewConfig: { forceFit: true }, sm: new Ext.grid.RowSelectionModel({singleSelect:true}), width:600, height:300, frame:true, title:'Framed with Checkbox Selection and Horizontal Scrolling', iconCls:'icon-grid' });</code></pre> * <b>注意:</b> * 尽管本类是由基类继承而得到的,但是不支持基类的某些功能,不能做到好像Panel类那样的方法,如autoScroll、layout、items等 * <br> * <br> * 要访问GRID中的数据,就必须通过由{@link #store Store}封装的数据模型。参与{@link #cellclick}事件。 * @constructor * @param {Object} config 配置项对象 */ Ext.grid.GridPanel = Ext.extend(Ext.Panel, { /** * @cfg {Ext.data.Store} store Grid应使用 {@link Ext.data.Store} 作为其数据源 (必须的). */ /** * @cfg {Object} cm {@link #colModel}的简写方式 */ /** * @cfg {Object} colModel 渲染Grid所使用的 {@link Ext.grid.ColumnModel} (必须的). */ /** * @cfg {Object} sm {@link #selModel}的简写方式 */ /** * @cfg {Object} selModel AbstractSelectionModel 的子类,以为Grid提供选区模型(selection model) * (默认为 {@link Ext.grid.RowSelectionModel} 如不指定). */ /** * @cfg {Array} columns 自动创建列模型 (ColumnModel)的数组。 */ /** * @cfg {Number} maxHeight 设置Grid的最大高度 (若autoHeight关闭则忽略)。 */ /** * @cfg {Boolean} disableSelection True表示为禁止grid的选区功能 (默认为 false). - 若指定了SelectionModel则忽略 */ /** * @cfg {Boolean} enableColumnMove False表示为在列拖动时禁止排序 (默认为 true). */ /** * @cfg {Boolean} enableColumnResize False 表示为关闭列的大小调节功能 (默认为 true). */ /** * @cfg {Object} viewConfig 作用在grid's UI试图上的配置项对象, * 任 {@link Ext.grid.GridView} 可用的配置选项都可在这里指定。 */ /** * 配置拖动代理中的文本 (缺省为 "{0} selected row(s)"). * 选中行的行数会替换到 {0}。 * @type String */ ddText : "{0} selected row{1}", /** * @cfg {Number} minColumnWidth 列的宽度的调整下限。默认为25。 */ minColumnWidth : 25, /** * @cfg {Boolean} autoSizeColumns True表示为在<b>初始渲染的时候</b>便根据每一列内容的宽度自适应列的大小 * 通过配置{@link Ext.grid.ColumnModel#width}的选项,精确指明每列的尺寸,会有更佳的效率。默认为false。 */ autoSizeColumns : false, /** * @cfg {Boolean} autoSizeHeaders True表示为根据头部内容的宽度调整列大小(默认为true)。 */ autoSizeHeaders : true, /** * @cfg {Boolean} monitorWindowResize True表示为windows调整大小时自动调整grid(默认为true)。 */ monitorWindowResize : true, /** * @cfg {Boolean} maxRowsToMeasure 如果autoSizeColumns打开,maxRowsToMeasure可用于检测每列宽度的最大行数。默认为0(所有的行) */ maxRowsToMeasure : 0, /** * @cfg {Boolean} trackMouseOver True表示为鼠标移动时高亮显示(默认为true)。 */ trackMouseOver : true, /** * @cfg {Boolean} enableDragDrop True表示为激活行的拖动(默认为false)。 */ enableDragDrop : false, /** * @cfg {Boolean} enableColumnMove True表示为激活列的拖动(默认为true)。 */ enableColumnMove : true, /** * @cfg {Boolean} enableColumnHide True表示为隐藏每列头部的邮件菜单(默认为true)。 */ enableColumnHide : true, /** * @cfg {Boolean} enableRowHeightSync True表示为在锁定和非锁定行之中手动同步行的高度。默认为false。 */ enableRowHeightSync : false, /** * @cfg {Boolean} stripeRows True表示为显示行的分隔符(默认为true)。 */ stripeRows : true, /** * @cfg {Boolean} autoHeight True说明会根据内容的高度自动调整grid的整体高度。默认为false */ autoHeight : false, /** * @cfg {String} autoExpandColumn 指定某个列之id,grid就会在这一列自动扩展宽度,以填满空白的位置,该id不能为0。默认为false。 */ autoExpandColumn : false, /** * @cfg {Number} autoExpandMin autoExpandColumn可允许最小之宽度(有激活的话)。默认为50。 */ autoExpandMin : 50, /** * @cfg {Number} autoExpandMax autoExpandColumn可允许最大之宽度(有激活的话)。默认为 1000。 */ autoExpandMax : 1000, /** * @cfg {Object} view Grid所使用的{@link Ext.grid.GridView}。该项可在render()调用之前设置。 */ view : null, /** * @cfg {Object} loadMask True表示为当grid加载过程中,会有一个{@link Ext.LoadMask}的遮罩效果。默认为false。 */ loadMask : false, // private rendered : false, // private viewReady: false, // private stateEvents: ["columnmove", "columnresize", "sortchange"], // private initComponent : function(){ Ext.grid.GridPanel.superclass.initComponent.call(this); // override any provided value since it isn't valid // and is causing too many bug reports ;) this.autoScroll = false; if(this.columns && (this.columns instanceof Array)){ this.colModel = new Ext.grid.ColumnModel(this.columns); delete this.columns; } // check and correct shorthanded configs if(this.ds){ this.store = this.ds; delete this.ds; } if(this.cm){ this.colModel = this.cm; delete this.cm; } if(this.sm){ this.selModel = this.sm; delete this.sm; } this.store = Ext.StoreMgr.lookup(this.store); this.addEvents( // raw events /** * @event click * 整个Grid被单击的原始事件。 * @param {Ext.EventObject} e */ "click", /** * @event dblclick * 整个Grid被双击的原始事件。 * @param {Ext.EventObject} e */ "dblclick", /** * @event contextmenu * 整个Grid被右击的原始事件。 * @param {Ext.EventObject} e */ "contextmenu", /** * @event mousedown * 整个Grid的mousedown的原始事件。 * @param {Ext.EventObject} e */ "mousedown", /** * @event mouseup * 整个Grid的mouseup的原始事件。 * @param {Ext.EventObject} e */ "mouseup", /** * @event mouseover * 整个Grid的mouseover的原始事件。 * @param {Ext.EventObject} e */ "mouseover", /** * @event mouseout * 整个Grid的mouseout的原始事件。 * @param {Ext.EventObject} e */ "mouseout", /** * @event keypress * 整个Grid的keypress的原始事件。 * @param {Ext.EventObject} e */ "keypress", /** * @event keydown * 整个Grid的keydown的原始事件。 * @param {Ext.EventObject} e */ "keydown", // custom events /** * @event cellmousedown * 当单元格被单击之前触发。 * @param {Grid} this * @param {Number} rowIndex * @param {Number} columnIndex * @param {Ext.EventObject} e */ "cellmousedown", /** * @event rowmousedown * 当行被单击之前触发。 * @param {Grid} this * @param {Number} rowIndex * @param {Ext.EventObject} e */ "rowmousedown", /** * @event headermousedown * 当头部被单击之前触发。 * @param {Grid} this * @param {Number} columnIndex * @param {Ext.EventObject} e */ "headermousedown", /** * @event cellclick * 当单元格被点击时触发。 * 单击格的数据保存在{@link Ext.data.Record Record}。要在侦听器函数内访问数据,可按照以下的办法: * <pre><code> function(grid, rowIndex, columnIndex, e) { var record = grid.getStore().getAt(rowIndex); // 返回Record对象 var fieldName = grid.getColumnModel().getDataIndex(columnIndex); // 返回字段名称 var data = record.get(fieldName); } </code></pre> * @param {Grid} this * @param {Number} rowIndex * @param {Number} columnIndex * @param {Ext.EventObject} e */ "cellclick", /** * @event celldblclick * 单元格(cell)被双击时触发 * @param {Grid} this * @param {Number} rowIndex 行索引 * @param {Number} columnIndex 列索引 * @param {Ext.EventObject} e */ "celldblclick", /** * @event rowclick * 行(row)被单击时触发 * @param {Grid} this * @param {Number} rowIndex 行索引 * @param {Ext.EventObject} e */ "rowclick", /** * @event rowdblclick * 行(row)被双击时触发 * @param {Grid} this * @param {Number} rowIndex 行索引 * @param {Ext.EventObject} e */ "rowdblclick", /** * @event headerclick * 头部(header)被单击时触发 * @param {Grid} this * @param {Number} columnIndex 列索引 * @param {Ext.EventObject} e */ "headerclick", /** * @event headerdblclick * 头部(header)被双击时触发 * @param {Grid} this * @param {Number} columnIndex 列索引 * @param {Ext.EventObject} e */ "headerdblclick", /** * @event rowcontextmenu * 行(row)被右击时触发 * @param {Grid} this * @param {Number} rowIndex 行索引 * @param {Ext.EventObject} e */ "rowcontextmenu", /** * @event cellcontextmenu * 单元格(cell)被右击时触发 * @param {Grid} this * @param {Number} rowIndex 行索引 * @param {Number} cellIndex 单元格索引 * @param {Ext.EventObject} e */ "cellcontextmenu", /** * @event headercontextmenu * 头部(header)被右击时触发 * @param {Grid} this * @param {Number} columnIndex * @param {Ext.EventObject} e */ "headercontextmenu", /** * @event bodyscroll * 当body元素被滚动后触发 * @param {Number} scrollLeft * @param {Number} scrollTop */ "bodyscroll", /** * @event columnresize * 当用户调整某个列(column)大小时触发 * @param {Number} columnIndex * @param {Number} newSize */ "columnresize", /** * @event columnmove * 当用户移动某个列(column)时触发 * @param {Number} oldIndex * @param {Number} newIndex */ "columnmove", /** * @event sortchange * 当行(row)开始被拖动时触发 * @param {Grid} this * @param {Object} sortInfo 包含键字段和方向的对象 */ "sortchange" ); }, // private onRender : function(ct, position){ Ext.grid.GridPanel.superclass.onRender.apply(this, arguments); var c = this.body; this.el.addClass('x-grid-panel'); var view = this.getView(); view.init(this); c.on("mousedown", this.onMouseDown, this); c.on("click", this.onClick, this); c.on("dblclick", this.onDblClick, this); c.on("contextmenu", this.onContextMenu, this); c.on("keydown", this.onKeyDown, this); this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]); this.getSelectionModel().init(this); this.view.render(); }, // private initEvents : function(){ Ext.grid.GridPanel.superclass.initEvents.call(this); if(this.loadMask){ this.loadMask = new Ext.LoadMask(this.bwrap, Ext.apply({store:this.store}, this.loadMask)); } }, initStateEvents : function(){ Ext.grid.GridPanel.superclass.initStateEvents.call(this); this.colModel.on('hiddenchange', this.saveState, this, {delay: 100}); }, applyState : function(state){ var cm = this.colModel; var cs = state.columns; if(cs){ for(var i = 0, len = cs.length; i < len; i++){ var s = cs[i]; var c = cm.getColumnById(s.id); if(c){ c.hidden = s.hidden; c.width = s.width; var oldIndex = cm.getIndexById(s.id); if(oldIndex != i){ cm.moveColumn(oldIndex, i); } } } } if(state.sort){ this.store[this.store.remoteSort ? 'setDefaultSort' : 'sort'](state.sort.field, state.sort.direction); } }, getState : function(){ var o = {columns: []}; for(var i = 0, c; c = this.colModel.config[i]; i++){ o.columns[i] = { id: c.id, width: c.width }; if(c.hidden){ o.columns[i].hidden = true; } } var ss = this.store.getSortState(); if(ss){ o.sort = ss; } return o; }, // private afterRender : function(){ Ext.grid.GridPanel.superclass.afterRender.call(this); this.view.layout(); this.viewReady = true; }, /** * 重新配置Grid的Store和Column Model(列模型)。视图会重新绑定对象并刷新。 * @param {Ext.data.Store} dataSource 另外一个{@link Ext.data.Store}对象 * @param {Ext.grid.ColumnModel} 另外一个{@link Ext.grid.ColumnModel}对象 */ reconfigure : function(store, colModel){ if(this.loadMask){ this.loadMask.destroy(); this.loadMask = new Ext.LoadMask(this.bwrap, Ext.apply({store:store}, this.initialConfig.loadMask)); } this.view.bind(store, colModel); this.store = store; this.colModel = colModel; if(this.rendered){ this.view.refresh(true); } }, // private onKeyDown : function(e){ this.fireEvent("keydown", e); }, // private onDestroy : function(){ if(this.rendered){ if(this.loadMask){ this.loadMask.destroy(); } var c = this.body; c.removeAllListeners(); this.view.destroy(); c.update(""); } this.colModel.purgeListeners(); Ext.grid.GridPanel.superclass.onDestroy.call(this); }, // private processEvent : function(name, e){ this.fireEvent(name, e); var t = e.getTarget(); var v = this.view; var header = v.findHeaderIndex(t); if(header !== false){ this.fireEvent("header" + name, this, header, e); }else{ var row = v.findRowIndex(t); var cell = v.findCellIndex(t); if(row !== false){ this.fireEvent("row" + name, this, row, e); if(cell !== false){ this.fireEvent("cell" + name, this, row, cell, e); } } } }, // private onClick : function(e){ this.processEvent("click", e); }, // private onMouseDown : function(e){ this.processEvent("mousedown", e); }, // private onContextMenu : function(e, t){ this.processEvent("contextmenu", e); }, // private onDblClick : function(e){ this.processEvent("dblclick", e); }, // private walkCells : function(row, col, step, fn, scope){ var cm = this.colModel, clen = cm.getColumnCount(); var ds = this.store, rlen = ds.getCount(), first = true; if(step < 0){ if(col < 0){ row--; first = false; } while(row >= 0){ if(!first){ col = clen-1; } first = false; while(col >= 0){ if(fn.call(scope || this, row, col, cm) === true){ return [row, col]; } col--; } row--; } } else { if(col >= clen){ row++; first = false; } while(row < rlen){ if(!first){ col = 0; } first = false; while(col < clen){ if(fn.call(scope || this, row, col, cm) === true){ return [row, col]; } col++; } row++; } } return null; }, // private getSelections : function(){ return this.selModel.getSelections(); }, // private onResize : function(){ Ext.grid.GridPanel.superclass.onResize.apply(this, arguments); if(this.viewReady){ this.view.layout(); } }, /** * 返回Grid的元素 * @return {Element} 元素 */ getGridEl : function(){ return this.body; }, // private for compatibility, overridden by editor grid stopEditing : function(){}, /** * 返回grid的SelectionModel. * @return {SelectionModel} 选区模型 */ getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.grid.RowSelectionModel( this.disableSelection ? {selectRow: Ext.emptyFn} : null); } return this.selModel; }, /** * 返回Grid的Data store。 * @return {DataSource} store对象 */ getStore : function(){ return this.store; }, /** * 返回Grid的列模型(ColumnModel)。 * @return {ColumnModel} 列模型 */ getColumnModel : function(){ return this.colModel; }, /** * 返回Grid的GridView对象。 * @return {GridView} GridView */ getView : function(){ if(!this.view){ this.view = new Ext.grid.GridView(this.viewConfig); } return this.view; }, /** *获取GRID拖动的代理文本(drag proxy text),默认返回this.ddText。 * @return {String} GRID拖动的代理文本 */ getDragDropText : function(){ var count = this.selModel.getCount(); return String.format(this.ddText, count, count == 1 ? '' : 's'); } /** * @cfg {String/Number} activeItem * @hide */ /** * @cfg {Boolean} autoDestroy * @hide */ /** * @cfg {Object/String/Function} autoLoad * @hide */ /** * @cfg {Boolean} autoWidth * @hide */ /** * @cfg {Boolean/Number} bufferResize * @hide */ /** * @cfg {String} defaultType * @hide */ /** * @cfg {Object} defaults * @hide */ /** * @cfg {Boolean} hideBorders * @hide */ /** * @cfg {Mixed} items * @hide */ /** * @cfg {String} layout * @hide */ /** * @cfg {Object} layoutConfig * @hide */ /** * @cfg {Boolean} monitorResize * @hide */ /** * @property items * @hide */ /** * @method add * @hide */ /** * @method cascade * @hide */ /** * @method doLayout * @hide */ /** * @method find * @hide */ /** * @method findBy * @hide */ /** * @method findById * @hide */ /** * @method findByType * @hide */ /** * @method getComponent * @hide */ /** * @method getLayout * @hide */ /** * @method getUpdater * @hide */ /** * @method insert * @hide */ /** * @method load * @hide */ /** * @method remove * @hide */ /** * @event add * @hide */ /** * @event afterLayout * @hide */ /** * @event beforeadd * @hide */ /** * @event beforeremove * @hide */ /** * @event remove * @hide */ }); Ext.reg('grid', Ext.grid.GridPanel);
JavaScript
/** * @class Ext.grid.AbstractSelectionModel * @extends Ext.util.Observable * Grid选区模型(SelectionModels)基本抽象类。本类提供了子类要实现的接口。该类不能被直接实例化。 * @constructor */ Ext.grid.AbstractSelectionModel = function(){ this.locked = false; Ext.grid.AbstractSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.AbstractSelectionModel, Ext.util.Observable, { /** @ignore grid自动调用。勿直接调用 */ init : function(grid){ this.grid = grid; this.initEvents(); }, /** * 锁定多个选区 */ lock : function(){ this.locked = true; }, /** * 解锁多个选区 */ unlock : function(){ this.locked = false; }, /** * 返回true如果选区被锁 * @return {Boolean} */ isLocked : function(){ return this.locked; } });
JavaScript
/** * @class Ext.grid.RowNumberer * 一个辅助类,用于传入到{@link Ext.grid.ColumnModel} ,作为自动列数字的生成。 * <br>用法::<br> <pre><code> //这是一个典型的例子,第一行生成数字序号 var colModel = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), {header: "Name", width: 80, sortable: true}, {header: "Code", width: 50, sortable: true}, {header: "Description", width: 200, sortable: true} ]); </code></pre> * @constructor * @param {Object} config 配置项选项 */ Ext.grid.RowNumberer = function(config){ Ext.apply(this, config); if(this.rowspan){ this.renderer = this.renderer.createDelegate(this); } }; Ext.grid.RowNumberer.prototype = { /** * @cfg {String} header 任何有效的HMTL片断,显示在单元格头部(缺省为'')。 */ header: "", /** * @cfg {Number} width 列的默认宽度(默认为23)。 */ width: 23, /** * @cfg {Boolean} sortable True表示为数字列可以被排序(默认为fasle) */ sortable: false, // private fixed:true, dataIndex: '', id: 'numberer', rowspan: undefined, // private renderer : function(v, p, record, rowIndex){ if(this.rowspan){ p.cellAttr = 'rowspan="'+this.rowspan+'"'; } return rowIndex+1; } };
JavaScript
/** * @class Ext.grid.PropertyRecord * {@link Ext.grid.PropertyGrid}的一种特定类型,用于表示一对“名称/值”的数据。数据的格式必须是{@link Ext.data.Record}类型。 * 典型的,属性记录(PropertyRecords)由于能够隐式生成而不需要直接创建, * 只需要配置适当的数据配置,即通过 {@link Ext.grid.PropertyGrid#source}的配置属性或是调用 {@link Ext.grid.PropertyGrid#setSource}的方法。 * 然而,如需要的情况下,这些记录也可以显式创建起来,例子如下: * <pre><code> var rec = new Ext.grid.PropertyRecord({ name: 'Birthday', value: new Date(Date.parse('05/26/1972')) }); //对当前的grid加入记录 grid.store.addSorted(rec); </code></pre> * @constructor * @param {Object} config 数据对象,格式如下: {name: [name], value: [value]}。Grid会自动读取指定值的格式以决定用哪种方式来显示。 */ Ext.grid.PropertyRecord = Ext.data.Record.create([ {name:'name',type:'string'}, 'value' ]); /** * @class Ext.grid.PropertyStore * @extends Ext.util.Observable * 一个属于{@link Ext.grid.PropertyGrid}的{@link Ext.data.Store}的制定包裹器。 * 该类负责属于grid的自定义数据对象与这个类 {@link Ext.grid.PropertyRecord}本身格式所需store之间的映射,使得两者可兼容一起。 * 一般情况下不需要直接使用该类--应该通过属性{@link #store} 从所属的store访问Grid的数据。 * @constructor * @param {Ext.grid.Grid} grid stroe所绑定的grid * @param {Object} source 配置项对象数据源 */ Ext.grid.PropertyStore = function(grid, source){ this.grid = grid; this.store = new Ext.data.Store({ recordType : Ext.grid.PropertyRecord }); this.store.on('update', this.onUpdate, this); if(source){ this.setSource(source); } Ext.grid.PropertyStore.superclass.constructor.call(this); }; Ext.extend(Ext.grid.PropertyStore, Ext.util.Observable, { // protected - should only be called by the grid. Use grid.setSource instead. setSource : function(o){ this.source = o; this.store.removeAll(); var data = []; for(var k in o){ if(this.isEditableValue(o[k])){ data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k)); } } this.store.loadRecords({records: data}, {}, true); }, // private onUpdate : function(ds, record, type){ if(type == Ext.data.Record.EDIT){ var v = record.data['value']; var oldValue = record.modified['value']; if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){ this.source[record.id] = v; record.commit(); this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue); }else{ record.reject(); } } }, // private getProperty : function(row){ return this.store.getAt(row); }, // private isEditableValue: function(val){ if(val && val instanceof Date){ return true; }else if(typeof val == 'object' || typeof val == 'function'){ return false; } return true; }, // private setValue : function(prop, value){ this.source[prop] = value; this.store.getById(prop).set('value', value); }, // protected - should only be called by the grid. Use grid.getSource instead. getSource : function(){ return this.source; } }); /** * @class Ext.grid.PropertyColumnModel * @extends Ext.grid.ColumnModel * 为{@link Ext.grid.PropertyGrid}制定的列模型一般情况下不需要直接使用该类 * @constructor * @param {Ext.grid.Grid} grid stroe所绑定的grid * @param {Object} source 配置项对象数据源 */ Ext.grid.PropertyColumnModel = function(grid, store){ this.grid = grid; var g = Ext.grid; g.PropertyColumnModel.superclass.constructor.call(this, [ {header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name'}, {header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value'} ]); this.store = store; this.bselect = Ext.DomHelper.append(document.body, { tag: 'select', cls: 'x-grid-editor x-hide-display', children: [ {tag: 'option', value: 'true', html: 'true'}, {tag: 'option', value: 'false', html: 'false'} ] }); var f = Ext.form; var bfield = new f.Field({ el:this.bselect, bselect : this.bselect, autoShow: true, getValue : function(){ return this.bselect.value == 'true'; } }); this.editors = { 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})), 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})), 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})), 'boolean' : new g.GridEditor(bfield) }; this.renderCellDelegate = this.renderCell.createDelegate(this); this.renderPropDelegate = this.renderProp.createDelegate(this); }; Ext.extend(Ext.grid.PropertyColumnModel, Ext.grid.ColumnModel, { // private - strings used for locale support nameText : 'Name', valueText : 'Value', dateFormat : 'm/j/Y', // private renderDate : function(dateVal){ return dateVal.dateFormat(this.dateFormat); }, // private renderBool : function(bVal){ return bVal ? 'true' : 'false'; }, // private isCellEditable : function(colIndex, rowIndex){ return colIndex == 1; }, // private getRenderer : function(col){ return col == 1 ? this.renderCellDelegate : this.renderPropDelegate; }, // private renderProp : function(v){ return this.getPropertyName(v); }, // private renderCell : function(val){ var rv = val; if(val instanceof Date){ rv = this.renderDate(val); }else if(typeof val == 'boolean'){ rv = this.renderBool(val); } return Ext.util.Format.htmlEncode(rv); }, // private getPropertyName : function(name){ var pn = this.grid.propertyNames; return pn && pn[name] ? pn[name] : name; }, // private getCellEditor : function(colIndex, rowIndex){ var p = this.store.getProperty(rowIndex); var n = p.data['name'], val = p.data['value']; if(this.grid.customEditors[n]){ return this.grid.customEditors[n]; } if(val instanceof Date){ return this.editors['date']; }else if(typeof val == 'number'){ return this.editors['number']; }else if(typeof val == 'boolean'){ return this.editors['boolean']; }else{ return this.editors['string']; } } }); /** * @class Ext.grid.PropertyGrid * @extends Ext.grid.EditorGridPanel * Grid的一种特殊实现,其意义为效仿IDE开发环境中的属性grid。 * Grid中的每一行表示一些对象当中的属性、数据,以“名称/值”的形式保存在{@link Ext.grid.PropertyRecord}中。举例如下: * <pre><code> var grid = new Ext.grid.PropertyGrid({ title: 'Properties Grid', autoHeight: true, width: 300, renderTo: 'grid-ct', source: { "(name)": "My Object", "Created": new Date(Date.parse('10/15/2006')), "Available": false, "Version": .01, "Description": "A test object" } }); </pre></code> * @constructor * @param {Object} config Grid配置参数 */ Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, { /** * @cfg {Object} source 数据对象,作为grid的数据源(参阅 {@link #setSource} )。 */ /** * @cfg {Object} customEditors An object containing name/value pairs of custom editor type definitions that allow * the grid to support additional types of editable fields. * 为了使grid能够支持一些可编辑字段,把这些编辑字段的类型的定义写在这个对象中, * 以“名称/值”的形式出现。 缺省下,Grid内置的表单编辑器支持强类型的编辑,如字符串、日期、数字和布尔型,但亦可以将任意的input控件关联到特定的编辑器。 * 编辑器的名字应该与属性的名字相一致,例如: * <pre><code> var grid = new Ext.grid.PropertyGrid({ ... customEditors: { 'Start Time': new Ext.grid.GridEditor(new Ext.form.TimeField({selectOnFocus:true})) }, source: { 'Start Time': '10:00 AM' } }); </code></pre> */ // private config overrides enableColLock:false, enableColumnMove:false, stripeRows:false, trackMouseOver: false, clicksToEdit:1, enableHdMenu : false, viewConfig : { forceFit:true }, // private initComponent : function(){ this.customEditors = this.customEditors || {}; this.lastEditRow = null; var store = new Ext.grid.PropertyStore(this); this.propStore = store; var cm = new Ext.grid.PropertyColumnModel(this, store); store.store.sort('name', 'ASC'); this.addEvents( /** * @event beforepropertychange * 当属性值改变时触发。如要取消事件可在这个句柄中返回一个false值(同时会内置调用{@link Ext.data.Record#reject}方法在这个属性的记录上) * @param {Object} source grid的数据源对象(与传入到配置属性的{@link #source}对象相一致 ) * @param {String} recordId Data store里面的记录id * @param {Mixed} value 当前被编辑的属性值 * @param {Mixed} oldValue 属性原始值 */ 'beforepropertychange', /** * @event propertychange * 当属性改变之后触发的事件 * @param {Object} source grid的数据源对象(与传入到配置属性的{@link #source}对象相一致 ) * @param {String} recordId Data store里面的记录id * @param {Mixed} value 当前被编辑的属性值 * @param {Mixed} oldValue 属性原始值 */ 'propertychange' ); this.cm = cm; this.ds = store.store; Ext.grid.PropertyGrid.superclass.initComponent.call(this); this.selModel.on('beforecellselect', function(sm, rowIndex, colIndex){ if(colIndex === 0){ this.startEditing.defer(200, this, [rowIndex, 1]); return false; } }, this); }, // private onRender : function(){ Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments); this.getGridEl().addClass('x-props-grid'); }, // private afterRender: function(){ Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments); if(this.source){ this.setSource(this.source); } }, /** * 设置包含属性的源数据对象。数据对象包含了一个或一个以上的“名称/值”格式的对象以显示在grid。这些数据也会自动加载到grid的 {@link #store}。如果grid已经包含数据,该方法会替换原有的数据。请参阅{@link #source} 的配置值。举例: * <pre><code> grid.setSource({ "(name)": "My Object", "Created": new Date(Date.parse('10/15/2006')), "Available": false, "Version": .01, "Description": "一个测试对象" }); </code></pre> * @param {Object} source 数据对象 */ setSource : function(source){ this.propStore.setSource(source); }, /** * Gets the source data object containing the property data. Seefor details regarding the * format of the data object. * 返回包含属性的数据对象源。参阅 {@link #setSource}以了解数据对象的格式 * @return {Object} 数据对象 */ getSource : function(){ return this.propStore.getSource(); } });
JavaScript
/** * @class Ext.grid.ColumnModel * @extends Ext.util.Observable * Grid的列模型(ColumnModel)的默认实现。该类由列配置组成的数组初始化。 * <br><br> * 不同列的配置对象定义了头部字符串,配合{@link Ext.data.Record}字段列描述了数据的来源, * 一个自定义数据格式的渲染函数,并允许通过和配置选项{@link #id}相同名称的CSS样式类来指定某列的样式。<br> * <br>用法:<br> <pre><code> var colModel = new Ext.grid.ColumnModel([ {header: "Ticker", width: 60, sortable: true}, {header: "Company Name", width: 150, sortable: true}, {header: "Market Cap.", width: 100, sortable: true}, {header: "$ Sales", width: 100, sortable: true, renderer: money}, {header: "Employees", width: 100, sortable: true, resizable: false} ]); </code></pre> * <p> * 该类列出的配置选项也适用于各个列的定义(column definition)。 * @constructor * @param {Object} config 列配置组成的数组,参阅关于本类的配置对象的更多资料。 */ Ext.grid.ColumnModel = function(config){ /** * 传入配置到构建函数 * @property {Array} config */ this.setConfig(config, true); /** * 列不指定宽度时的默认值(默认为100) * @type Number */ this.defaultWidth = 100; /** * 是否默认排序(默认为false) * @type Boolean */ this.defaultSortable = false; this.addEvents( /** * @event widthchange * 当列宽度变动时触发 * @param {ColumnModel} this * @param {Number} columnIndex 列索引 * @param {Number} newWidth 新宽度 */ "widthchange", /** * @event headerchange * 当头部文字改变时触发 * @param {ColumnModel} this * @param {Number} columnIndex 列索引 * @param {Number} newText 新头部文字 */ "headerchange", /** * @event hiddenchange * 当列隐藏或“反隐藏”时触发 * @param {ColumnModel} this * @param {Number} columnIndex 列索引 * @param {Number} hidden true:隐藏,false:“反隐藏” */ "hiddenchange", /** * @event columnmoved * 当列被移动时触发 * @param {ColumnModel} this * @param {Number} oldIndex * @param {Number} newIndex */ "columnmoved", // deprecated - to be removed "columnlockchange", /** * @event columlockchange * 当列锁定状态被改变时触发 * @param {ColumnModel} this */ "configchange" ); Ext.grid.ColumnModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.ColumnModel, Ext.util.Observable, { /** * @cfg {String} id (optional) Defaults to the column's initial ordinal position. * A name which identifies this column. The id is used to create a CSS class name which * is applied to all table cells (including headers) in that column. The class name * takes the form of <pre>x-grid3-td-<b>id</b></pre> * <br><br> * Header cells will also recieve this class name, but will also have the class <pr>x-grid3-hd</pre>, * so to target header cells, use CSS selectors such as:<pre>.x-grid3-hd.x-grid3-td-<b>id</b></pre> * The {@link Ext.grid.Grid#autoExpandColumn} grid config option references the column * via this identifier. */ /** * @cfg {String} header 在Grid头部视图中显示的文字。 */ /** * @cfg {String} dataIndex (可选的)数据索引,相当于Grid记录集({@link Ext.data.Store}里面的 * {@link Ext.data.Record} )中字段名称,字段的值用于展示列里面的值(column's value)。 * 如不指定,Record的数据列中的索引将作为列的索引。 */ /** * @cfg {Number} width (可选的)列的初始宽度(像素)。如采用{@link Ext.grid.Grid#autoSizeColumns} 性能较差。 */ /** * @cfg {Boolean} sortable (可选的)True表示为可在该列上进行排列。默认为true * 由{@link Ext.data.Store#remoteSort}指定本地排序抑或是远程排序。 */ /** * @cfg {Boolean} locked (可选的)True表示当滚动grid时,锁定列在某个位置。默认为false。 */ /** * @cfg {Boolean} resizable (可选的) False禁止列可变动大小。默认为true。 */ /** * @cfg {Boolean} hidden (可选的) True表示隐藏列,默认为false */ /** * @cfg {Function} renderer (可选的)该函数用于加工单元格的原始数据,转换成为HTML并返回给GridView进一步处理。 参阅{@link #setRenderer}。 * 如不指定,则对原始数据值进行默认地渲染。 */ /** * @cfg {String} align (可选的)设置列的CSS text-align 属性。默认为undefined。 */ /** * @cfg {Boolean} hideable (可选的)指定<tt>false</tt>可禁止用户隐藏该列。默认为True。 */ /** * @cfg {Ext.form.Field} editor (可选的)如果Grid的编辑器支持被打开,这属性指定了用户编辑时所用的编辑器{@link Ext.form.Field}。 */ /** * 返回指定index列的Id * @param {Number} index * @return {String} the id */ getColumnId : function(index){ return this.config[index].id; }, /** * 重新配置列模型 * @param {Array} config 列配置组成的数组 */ setConfig : function(config, initial){ if(!initial){ // cleanup delete this.totalWidth; for(var i = 0, len = this.config.length; i < len; i++){ var c = this.config[i]; if(c.editor){ c.editor.destroy(); } } } this.config = config; this.lookup = {}; // if no id, create one for(var i = 0, len = config.length; i < len; i++){ var c = config[i]; if(typeof c.renderer == "string"){ c.renderer = Ext.util.Format[c.renderer]; } if(typeof c.id == "undefined"){ c.id = i; } if(c.editor && c.editor.isFormField){ c.editor = new Ext.grid.GridEditor(c.editor); } this.lookup[c.id] = c; } if(!initial){ this.fireEvent('configchange', this); } }, /** * 返回指定id的列 * @param {String} id 列id * @return {Object} 列 */ getColumnById : function(id){ return this.lookup[id]; }, /** * 返回指定列id的索引 * @param {String} id 列id * @return {Number} 索引,-1表示找不到 */ getIndexById : function(id){ for(var i = 0, len = this.config.length; i < len; i++){ if(this.config[i].id == id){ return i; } } return -1; }, // private moveColumn : function(oldIndex, newIndex){ var c = this.config[oldIndex]; this.config.splice(oldIndex, 1); this.config.splice(newIndex, 0, c); this.dataMap = null; this.fireEvent("columnmoved", this, oldIndex, newIndex); }, // deprecated - to be removed isLocked : function(colIndex){ return this.config[colIndex].locked === true; }, // deprecated - to be removed setLocked : function(colIndex, value, suppressEvent){ if(this.isLocked(colIndex) == value){ return; } this.config[colIndex].locked = value; if(!suppressEvent){ this.fireEvent("columnlockchange", this, colIndex, value); } }, // deprecated - to be removed getTotalLockedWidth : function(){ var totalWidth = 0; for(var i = 0; i < this.config.length; i++){ if(this.isLocked(i) && !this.isHidden(i)){ this.totalWidth += this.getColumnWidth(i); } } return totalWidth; }, // deprecated - to be removed getLockedCount : function(){ for(var i = 0, len = this.config.length; i < len; i++){ if(!this.isLocked(i)){ return i; } } }, /** * 返回列数 * @return {Number} */ getColumnCount : function(visibleOnly){ if(visibleOnly === true){ var c = 0; for(var i = 0, len = this.config.length; i < len; i++){ if(!this.isHidden(i)){ c++; } } return c; } return this.config.length; }, /** * 传入一个function类型的参数,这个函数执行时会有(columnConfig, index)的参数,如函数返回true则加入到数组中并返回 * @param {Function} fn * @param {Object} scope (可选的) * @return {Array} result */ getColumnsBy : function(fn, scope){ var r = []; for(var i = 0, len = this.config.length; i < len; i++){ var c = this.config[i]; if(fn.call(scope||this, c, i) === true){ r[r.length] = c; } } return r; }, /** * 返回指定的列可否排序 * @param {Number} col 列索引 * @return {Boolean} */ isSortable : function(col){ if(typeof this.config[col].sortable == "undefined"){ return this.defaultSortable; } return this.config[col].sortable; }, /** * 返回对某个列的渲染(格式化)函数 * @param {Number} col 列索引 * @return {Function} 用于渲染单元格的那个函数。可参阅 {@link #setRenderer}。 */ getRenderer : function(col){ if(!this.config[col].renderer){ return Ext.grid.ColumnModel.defaultRenderer; } return this.config[col].renderer; }, /** * Sets the rendering (formatting) function for a column. See {@link Ext.util.Format} for some * default formatting functions. * @param {Number} col The column index * @param {Function} fn The function to use to process the cell's raw data * to return HTML markup for the grid view. The render function is called with * the following parameters:<ul> * <li><b>value</b> : Object<p class="sub-desc">The data value for the cell.</p></li> * <li><b>metadata</b> : Object<p class="sub-desc">An object in which you may set the following attributes:<ul> * <li><b>css</b> : String<p class="sub-desc">A CSS class name to add to the cell's TD element.</p></li> * <li><b>attr</b> : String<p class="sub-desc">An HTML attribute definition string to apply to the data container element <i>within</i> the table cell * (e.g. 'style="color:red;"').</p></li></ul></p></li> * <li><b>record</b> : Ext.data.record<p class="sub-desc">The {@link Ext.data.Record} from which the data was extracted.</p></li> * <li><b>rowIndex</b> : Number<p class="sub-desc">Row index</p></li> * <li><b>colIndex</b> : Number<p class="sub-desc">Column index</p></li> * <li><b>store</b> : Ext.data.Store<p class="sub-desc">The {@link Ext.data.Store} object from which the Record was extracted.</p></li></ul> */ /** * 设置对某个列的渲染(格式化formatting)函数 * @param {Number} col 列索引 * @param {Function} fn 该函数用于加工单元格的原始数据,转换成为HTML并返回给GridView进一步处理。 * 这个渲染函数调用时会有下列的参数:<ul> * <li><b>value</b> : Object<p class="sub-desc">单元格的数据值</p></li> * <li><b>metadata</b> : Object<p class="sub-desc">单元格元数据(Cell metadata)对象。 你也可以设置下列的属性:<ul> * <li><b>css</b> : String<p class="sub-desc">单元格CSS样式字符串,作用在td元素上。</p></li> * <li><b>attr</b> : String<p class="sub-desc">一段HTML属性的字符串,应用于表格单元格<i>内</i>的数据容器元素(如'style="color:red;"')</p></li></ul></p></li> * <li><b>record</b> : Ext.data.record<p class="sub-desc">从数据中提取的{@link Ext.data.Record}。</p></li> * <li><b>rowIndex</b> : Number<p class="sub-desc">行索引</p></li> * <li><b>colIndex</b> : Number<p class="sub-desc">列索引</p></li> * <li><b>store</b> : Ext.data.Store<p class="sub-desc">{@link Ext.data.Store}从Record中提取的对象。</p></li></ul> */ setRenderer : function(col, fn){ this.config[col].renderer = fn; }, /** * 返回某个列的宽度 * @param {Number} col 列索引 * @return {Number} */ getColumnWidth : function(col){ return this.config[col].width || this.defaultWidth; }, /** * 设置某个列的宽度 * @param {Number} col 列索引 * @param {Number} width 新宽度 */ setColumnWidth : function(col, width, suppressEvent){ this.config[col].width = width; this.totalWidth = null; if(!suppressEvent){ this.fireEvent("widthchange", this, col, width); } }, /** * 返回所有列宽度之和 * @param {Boolean} includeHidden True表示为包括隐藏的宽度 * @return {Number} */ getTotalWidth : function(includeHidden){ if(!this.totalWidth){ this.totalWidth = 0; for(var i = 0, len = this.config.length; i < len; i++){ if(includeHidden || !this.isHidden(i)){ this.totalWidth += this.getColumnWidth(i); } } } return this.totalWidth; }, /** * 返回某个列的头部(header) * @param {Number} col 列索引 * @return {String} */ getColumnHeader : function(col){ return this.config[col].header; }, /** * 设置某个列的头部(header) * @param {Number} col 列索引 * @param {String} header 新头部 */ setColumnHeader : function(col, header){ this.config[col].header = header; this.fireEvent("headerchange", this, col, header); }, /** * 返回某个列的工具提示(tooltip) * @param {Number} col 列索引 * @return {String} */ getColumnTooltip : function(col){ return this.config[col].tooltip; }, /** * 设置某个列的提示文字(tooltip) * @param {Number} col 列索引 * @param {String} tooltip 新tooltip */ setColumnTooltip : function(col, tooltip){ this.config[col].tooltip = tooltip; }, /** * 返回某个列的数据索引 * @param {Number} col 列索引 * @return {Number} */ getDataIndex : function(col){ return this.config[col].dataIndex; }, /** * 设置某个列的数据索引 * @param {Number} col 列索引 * @param {Number} dataIndex 新数据索引 */ setDataIndex : function(col, dataIndex){ this.config[col].dataIndex = dataIndex; }, findColumnIndex : function(dataIndex){ var c = this.config; for(var i = 0, len = c.length; i < len; i++){ if(c[i].dataIndex == dataIndex){ return i; } } return -1; }, /** * 返回单元格能否被编辑。 * @param {Number} colIndex 列索引 * @param {Number} rowIndex 行索引 * @return {Boolean} */ isCellEditable : function(colIndex, rowIndex){ return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false; }, /** * 返回单元格/列所定义的编辑器 * @param {Number} colIndex 列索引 * @param {Number} rowIndex 行索引 * @return {Object} */ getCellEditor : function(colIndex, rowIndex){ return this.config[colIndex].editor; }, /** * 设置列是否可编辑的。 * @param {Number} col 列索引 * @param {Boolean} editable True表示为列是可编辑的 */ setEditable : function(col, editable){ this.config[col].editable = editable; }, /** * 返回true如果列是隐藏的 * @param {Number} colIndex 列索引 * @return {Boolean} */ isHidden : function(colIndex){ return this.config[colIndex].hidden; }, /** * 返回true如果列是固定的 */ isFixed : function(colIndex){ return this.config[colIndex].fixed; }, /** * 如果列不能调整尺寸返回true * @return {Boolean} */ isResizable : function(colIndex){ return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true; }, /** * 设置列隐藏 * @param {Number} colIndex 列索引 * @param {Boolean} hidden True表示为列是已隐藏的 */ setHidden : function(colIndex, hidden){ var c = this.config[colIndex]; if(c.hidden !== hidden){ c.hidden = hidden; this.totalWidth = null; this.fireEvent("hiddenchange", this, colIndex, hidden); } }, /** * 为列设置编辑器 * @param {Number} col 列索引 * @param {Object} editor 编辑器对象 */ setEditor : function(col, editor){ this.config[col].editor = editor; } }); // private Ext.grid.ColumnModel.defaultRenderer = function(value){ if(typeof value == "string" && value.length < 1){ return "&#160;"; } return value; }; // Alias for backwards compatibility Ext.grid.DefaultColumnModel = Ext.grid.ColumnModel;
JavaScript
/** * @class Ext.grid.GroupingView * @extends Ext.grid.GridView * Adds the ability for single level grouping to the grid. *<pre><code>var grid = new Ext.grid.GridPanel({ // A groupingStore is required for a GroupingView store: new Ext.data.GroupingStore({ reader: reader, data: xg.dummyData, sortInfo:{field: 'company', direction: "ASC"}, groupField:'industry' }), columns: [ {id:'company',header: "Company", width: 60, sortable: true, dataIndex: 'company'}, {header: "Price", width: 20, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'}, {header: "Change", width: 20, sortable: true, dataIndex: 'change', renderer: Ext.util.Format.usMoney}, {header: "Industry", width: 20, sortable: true, dataIndex: 'industry'}, {header: "Last Updated", width: 20, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'} ], view: new Ext.grid.GroupingView({ forceFit:true, // custom grouping text template to display the number of items per group groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' }), frame:true, width: 700, height: 450, collapsible: true, animCollapse: false, title: 'Grouping Example', iconCls: 'icon-grid', renderTo: document.body });</code></pre> * @constructor * @param {Object} config */ Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, { /** * @cfg {Boolean} hideGroupedColumn True to hide the column that is currently grouped */ hideGroupedColumn:false, /** * @cfg {Boolean} showGroupName True to display the name for each set of grouped rows (defaults to true) */ showGroupName:true, /** * @cfg {Boolean} startCollapsed True to start all groups collapsed */ startCollapsed:false, /** * @cfg {Boolean} enableGrouping False to disable grouping functionality (defaults to true) */ enableGrouping:true, /** * @cfg {Boolean} enableGroupingMenu True to enable the grouping control in the column menu */ enableGroupingMenu:true, /** * @cfg {Boolean} enableNoGroups True to allow the user to turn off grouping */ enableNoGroups:true, /** * @cfg {String} emptyGroupText The text to display when there is an empty group value */ emptyGroupText : '(None)', /** * @cfg {Boolean} ignoreAdd True to skip refreshing the view when new rows are added (defaults to false) */ ignoreAdd: false, /** * @cfg {String} groupTextTpl The template used to render the group header. This is used to * format an object which contains the following properties: * <div class="mdetail-params"><ul> * <li><b>group</b> : String<p class="sub-desc">The <i>rendered</i> value of the group field. * By default this is the unchanged value of the group field. If a {@link #groupRenderer} * is specified, it is the result of a call to that.</p></li> * <li><b>gvalue</b> : Object<p class="sub-desc">The <i>raw</i> value of the group field.</p></li> * <li><b>text</b> : String<p class="sub-desc">The configured {@link #header} (If * {@link #showGroupName} is true) plus the <i>rendered</i>group field value.</p></li> * <li><b>groupId</b> : String<p class="sub-desc">A unique, generated ID which is applied to the * View Element which contains the group.</p></li> * <li><b>startRow</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li> * <li><b>rs</b> : Array<p class="sub-desc">.Contains a single element: The Record providing the data * for the row which caused group change.</p></li> * <li><b>cls</b> : String<p class="sub-desc">The generated class name string to apply to the group header Element.</p></li> * <li><b>style</b> : String<p class="sub-desc">The inline style rules to apply to the group header Element.</p></li> * </ul></div></p> * See {@link Ext.XTemplate} for information on how to format data using a template. */ groupTextTpl : '{text}', /** * @cfg {Function} groupRenderer The function used to format the grouping field value for * display in the group header. Should return a string value. This takes the following parameters: * <div class="mdetail-params"><ul> * <li><b>v</b> : Object<p class="sub-desc">The new value of the group field.</p></li> * <li><b>unused</b> : undefined<p class="sub-desc">Unused parameter.</p></li> * <li><b>r</b> : Ext.data.Record<p class="sub-desc">The Record providing the data * for the row which caused group change.</p></li> * <li><b>rowIndex</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li> * <li><b>colIndex</b> : Number<p class="sub-desc">The column index of the group field.</p></li> * <li><b>ds</b> : Ext.data.Store<p class="sub-desc">The Store which is providing the data Model.</p></li> * </ul></div></p> */ /** * @cfg {String} header The text with which to prefix the group field value in the group header line. */ // private gidSeed : 1000, // private initTemplates : function(){ Ext.grid.GroupingView.superclass.initTemplates.call(this); this.state = {}; var sm = this.grid.getSelectionModel(); sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect', this.onBeforeRowSelect, this); if(!this.startGroup){ this.startGroup = new Ext.XTemplate( '<div id="{groupId}" class="x-grid-group {cls}">', '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div>', this.groupTextTpl ,'</div></div>', '<div id="{groupId}-bd" class="x-grid-group-body">' ); } this.startGroup.compile(); this.endGroup = '</div></div>'; }, // private findGroup : function(el){ return Ext.fly(el).up('.x-grid-group', this.mainBody.dom); }, // private getGroups : function(){ return this.hasRows() ? this.mainBody.dom.childNodes : []; }, // private onAdd : function(){ if(this.enableGrouping && !this.ignoreAdd){ var ss = this.getScrollState(); this.refresh(); this.restoreScroll(ss); }else if(!this.enableGrouping){ Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments); } }, // private onRemove : function(ds, record, index, isUpdate){ Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments); var g = document.getElementById(record._groupId); if(g && g.childNodes[1].childNodes.length < 1){ Ext.removeNode(g); } this.applyEmptyText(); }, // private refreshRow : function(record){ if(this.ds.getCount()==1){ this.refresh(); }else{ this.isUpdating = true; Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments); this.isUpdating = false; } }, // private beforeMenuShow : function(){ var field = this.getGroupField(); var g = this.hmenu.items.get('groupBy'); if(g){ g.setDisabled(this.cm.config[this.hdCtxIndex].groupable === false); } var s = this.hmenu.items.get('showGroups'); if(s){ s.setDisabled(!field && this.cm.config[this.hdCtxIndex].groupable === false); s.setChecked(!!field, true); } }, // private renderUI : function(){ Ext.grid.GroupingView.superclass.renderUI.call(this); this.mainBody.on('mousedown', this.interceptMouse, this); if(this.enableGroupingMenu && this.hmenu){ this.hmenu.add('-',{ id:'groupBy', text: this.groupByText, handler: this.onGroupByClick, scope: this, iconCls:'x-group-by-icon' }); if(this.enableNoGroups){ this.hmenu.add({ id:'showGroups', text: this.showGroupsText, checked: true, checkHandler: this.onShowGroupsClick, scope: this }); } this.hmenu.on('beforeshow', this.beforeMenuShow, this); } }, // private onGroupByClick : function(){ this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex)); this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups }, // private onShowGroupsClick : function(mi, checked){ if(checked){ this.onGroupByClick(); }else{ this.grid.store.clearGrouping(); } }, /** * Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed. * @param {String} groupId The groupId assigned to the group (see getGroupId) * @param {Boolean} expanded (optional) */ toggleGroup : function(group, expanded){ this.grid.stopEditing(true); group = Ext.getDom(group); var gel = Ext.fly(group); expanded = expanded !== undefined ? expanded : gel.hasClass('x-grid-group-collapsed'); this.state[gel.dom.id] = expanded; gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed'); }, /** * Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed. * @param {Boolean} expanded (optional) */ toggleAllGroups : function(expanded){ var groups = this.getGroups(); for(var i = 0, len = groups.length; i < len; i++){ this.toggleGroup(groups[i], expanded); } }, /** * Expands all grouped rows. */ expandAllGroups : function(){ this.toggleAllGroups(true); }, /** * Collapses all grouped rows. */ collapseAllGroups : function(){ this.toggleAllGroups(false); }, // private interceptMouse : function(e){ var hd = e.getTarget('.x-grid-group-hd', this.mainBody); if(hd){ e.stopEvent(); this.toggleGroup(hd.parentNode); } }, // private getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){ var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v); if(g === ''){ g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText; } return g; }, // private getGroupField : function(){ return this.grid.store.getGroupState(); }, // private renderRows : function(){ var groupField = this.getGroupField(); var eg = !!groupField; // if they turned off grouping and the last grouped field is hidden if(this.hideGroupedColumn) { var colIndex = this.cm.findColumnIndex(groupField); if(!eg && this.lastGroupField !== undefined) { this.mainBody.update(''); this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false); delete this.lastGroupField; }else if (eg && this.lastGroupField === undefined) { this.lastGroupField = groupField; this.cm.setHidden(colIndex, true); }else if (eg && this.lastGroupField !== undefined && groupField !== this.lastGroupField) { this.mainBody.update(''); var oldIndex = this.cm.findColumnIndex(this.lastGroupField); this.cm.setHidden(oldIndex, false); this.lastGroupField = groupField; this.cm.setHidden(colIndex, true); } } return Ext.grid.GroupingView.superclass.renderRows.apply( this, arguments); }, // private doRender : function(cs, rs, ds, startRow, colCount, stripe){ if(rs.length < 1){ return ''; } var groupField = this.getGroupField(); var colIndex = this.cm.findColumnIndex(groupField); this.enableGrouping = !!groupField; if(!this.enableGrouping || this.isUpdating){ return Ext.grid.GroupingView.superclass.doRender.apply( this, arguments); } var gstyle = 'width:'+this.getTotalWidth()+';'; var gidPrefix = this.grid.getGridEl().id; var cfg = this.cm.config[colIndex]; var groupRenderer = cfg.groupRenderer || cfg.renderer; var prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : ''; var groups = [], curGroup, i, len, gid; for(i = 0, len = rs.length; i < len; i++){ var rowIndex = startRow + i; var r = rs[i], gvalue = r.data[groupField], g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds); if(!curGroup || curGroup.group != g){ gid = gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(g); // if state is defined use it, however state is in terms of expanded // so negate it, otherwise use the default. var isCollapsed = typeof this.state[gid] !== 'undefined' ? !this.state[gid] : this.startCollapsed; var gcls = isCollapsed ? 'x-grid-group-collapsed' : ''; curGroup = { group: g, gvalue: gvalue, text: prefix + g, groupId: gid, startRow: rowIndex, rs: [r], cls: gcls, style: gstyle }; groups.push(curGroup); }else{ curGroup.rs.push(r); } r._groupId = gid; } var buf = []; for(i = 0, len = groups.length; i < len; i++){ var g = groups[i]; this.doGroupStart(buf, g, cs, ds, colCount); buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call( this, cs, g.rs, ds, g.startRow, colCount, stripe); this.doGroupEnd(buf, g, cs, ds, colCount); } return buf.join(''); }, /** * Dynamically tries to determine the groupId of a specific value * @param {String} value * @return {String} The group id */ getGroupId : function(value){ var gidPrefix = this.grid.getGridEl().id; var groupField = this.getGroupField(); var colIndex = this.cm.findColumnIndex(groupField); var cfg = this.cm.config[colIndex]; var groupRenderer = cfg.groupRenderer || cfg.renderer; var gtext = this.getGroup(value, {data:{}}, groupRenderer, 0, colIndex, this.ds); return gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(value); }, // private doGroupStart : function(buf, g, cs, ds, colCount){ buf[buf.length] = this.startGroup.apply(g); }, // private doGroupEnd : function(buf, g, cs, ds, colCount){ buf[buf.length] = this.endGroup; }, // private getRows : function(){ if(!this.enableGrouping){ return Ext.grid.GroupingView.superclass.getRows.call(this); } var r = []; var g, gs = this.getGroups(); for(var i = 0, len = gs.length; i < len; i++){ g = gs[i].childNodes[1].childNodes; for(var j = 0, jlen = g.length; j < jlen; j++){ r[r.length] = g[j]; } } return r; }, // private updateGroupWidths : function(){ if(!this.enableGrouping || !this.hasRows()){ return; } var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.scrollOffset) +'px'; var gs = this.getGroups(); for(var i = 0, len = gs.length; i < len; i++){ gs[i].firstChild.style.width = tw; } }, // private onColumnWidthUpdated : function(col, w, tw){ this.updateGroupWidths(); }, // private onAllColumnWidthsUpdated : function(ws, tw){ this.updateGroupWidths(); }, // private onColumnHiddenUpdated : function(col, hidden, tw){ this.updateGroupWidths(); }, // private onLayout : function(){ this.updateGroupWidths(); }, // private onBeforeRowSelect : function(sm, rowIndex){ if(!this.enableGrouping){ return; } var row = this.getRow(rowIndex); if(row && !row.offsetParent){ var g = this.findGroup(row); this.toggleGroup(g, true); } }, /** * @cfg {String} groupByText Text displayed in the grid header menu for grouping by a column * (defaults to 'Group By This Field'). */ groupByText: 'Group By This Field', /** * @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping * (defaults to 'Show in Groups'). */ showGroupsText: 'Show in Groups' }); // private Ext.grid.GroupingView.GROUP_ID = 1000;
JavaScript
// private // This is a support class used internally by the Grid components Ext.grid.SplitDragZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.proxy = this.view.resizeProxy; Ext.grid.SplitDragZone.superclass.constructor.call(this, hd, "gridSplitters" + this.grid.getGridEl().id, { dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); this.scroll = false; }; Ext.extend(Ext.grid.SplitDragZone, Ext.dd.DDProxy, { fly: Ext.Element.fly, b4StartDrag : function(x, y){ this.view.headersDisabled = true; this.proxy.setHeight(this.view.mainWrap.getHeight()); var w = this.cm.getColumnWidth(this.cellIndex); var minw = Math.max(w-this.grid.minColumnWidth, 0); this.resetConstraints(); this.setXConstraint(minw, 1000); this.setYConstraint(0, 0); this.minX = x - minw; this.maxX = x + 1000; this.startPos = x; Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, handleMouseDown : function(e){ ev = Ext.EventObject.setEvent(e); var t = this.fly(ev.getTarget()); if(t.hasClass("x-grid-split")){ this.cellIndex = this.view.getCellIndex(t.dom); this.split = t.dom; this.cm = this.grid.colModel; if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } } }, endDrag : function(e){ this.view.headersDisabled = false; var endX = Math.max(this.minX, Ext.lib.Event.getPageX(e)); var diff = endX - this.startPos; this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); }, autoOffset : function(){ this.setDelta(0,0); } });
JavaScript
// private // This is a support class used internally by the Grid components Ext.grid.GridDragZone = function(grid, config){ this.view = grid.getView(); Ext.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config); if(this.view.lockedBody){ this.setHandleElId(Ext.id(this.view.mainBody.dom)); this.setOuterHandleElId(Ext.id(this.view.lockedBody.dom)); } this.scroll = false; this.grid = grid; this.ddel = document.createElement('div'); this.ddel.className = 'x-grid-dd-wrap'; }; Ext.extend(Ext.grid.GridDragZone, Ext.dd.DragZone, { ddGroup : "GridDD", getDragData : function(e){ var t = Ext.lib.Event.getTarget(e); var rowIndex = this.view.findRowIndex(t); if(rowIndex !== false){ var sm = this.grid.selModel; if(!sm.isSelected(rowIndex) || e.hasModifier()){ sm.handleMouseDown(this.grid, rowIndex, e); } return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()}; } return false; }, onInitDrag : function(e){ var data = this.dragData; this.ddel.innerHTML = this.grid.getDragDropText(); this.proxy.update(this.ddel); // fire start drag? }, afterRepair : function(){ this.dragging = false; }, getRepairXY : function(e, data){ return false; }, onEndDrag : function(data, e){ // fire end drag? }, onValidDrop : function(dd, e, id){ // fire drag drop? this.hideProxy(); }, beforeInvalidDrop : function(e, id){ } });
JavaScript
/** * @class Ext.Viewport * @extends Ext.Container * <p> 一个表示程序可视区域的特殊容器(浏览器可视区域) 。 * <p> 视窗渲染在document的body标签上,并且根据浏览器可视区域的大小自动调整并且管理窗口的大小变化。一个页面上只允许存在一个viewport。 * 所有的 {@link Ext.Panel 面板}增加到viewport,通过她的 {@link #items},或者通过她的子面板(子面板也都可以拥有自己的layout)的items,子面板的{@link #add}方法,这种设计让内部布局的优势非常明显。 * </p> * <p>Viewport 不支持滚动,所以如果子面板需要滚动支持可以使用{@link #autoScroll}配置。</p> * 展示一个经典的border布局的viewport程序示例 :<pre><code> new Ext.Viewport({ layout: 'border', defaults: { activeItem: 0, }, items: [{ region: 'north', html: '<h1 class="x-panel-header">Page Title</h1>', autoHeight: true, border: false, margins: '0 0 5 0' }, { region: 'west', collapsible: true, title: 'Navigation', xtype: 'treepanel', width: 200, autoScroll: true, split: true, loader: new Ext.tree.TreeLoader(), root: new Ext.tree.AsyncTreeNode({ expanded: true, children: [{ text: 'Menu Option 1', leaf: true }, { text: 'Menu Option 2', leaf: true }, { text: 'Menu Option 3', leaf: true }] }), rootVisible: false, listeners: { click: function(n) { Ext.Msg.alert('Navigation Tree Click', 'You clicked: "' + n.attributes.text + '"'); } } }, { region: 'center', xtype: 'tabpanel', items: { title: 'Default Tab', html: 'The first tab\'s content. Others may be added dynamically' } }, { region: 'south', title: 'Information', collapsible: true, html: 'Information goes here', split: true, height: 100, minHeight: 100 }] }); </code></pre> * @constructor * 创建一个新视区的对象 * @param {Object} config 配置项对象 */ Ext.Viewport = Ext.extend(Ext.Container, { /* * Privatize config options which, if used, would interfere with the * correct operation of the Viewport as the sole manager of the * layout of the document body. */ /** * @cfg {Mixed} applyTo @hide */ /** * @cfg {Boolean} allowDomMove @hide */ /** * @cfg {Boolean} hideParent @hide */ /** * @cfg {Mixed} renderTo @hide */ /** * @cfg {Boolean} hideParent @hide */ /** * @cfg {Number} height @hide */ /** * @cfg {Number} width @hide */ /** * @cfg {Boolean} autoHeight @hide */ /** * @cfg {Boolean} autoWidth @hide */ /** * @cfg {Boolean} deferHeight @hide */ /** * @cfg {Boolean} monitorResize @hide */ initComponent : function() { Ext.Viewport.superclass.initComponent.call(this); document.getElementsByTagName('html')[0].className += ' x-viewport'; this.el = Ext.getBody(); this.el.setHeight = Ext.emptyFn; this.el.setWidth = Ext.emptyFn; this.el.setSize = Ext.emptyFn; this.el.dom.scroll = 'no'; this.allowDomMove = false; this.autoWidth = true; this.autoHeight = true; Ext.EventManager.onWindowResize(this.fireResize, this); this.renderTo = this.el; }, fireResize : function(w, h){ this.fireEvent('resize', this, w, h, w, h); } }); Ext.reg('viewport', Ext.Viewport);
JavaScript
/** * @class Ext.WindowMgr * @extends Ext.WindowGroup * 缺省的全局window组,自动创建。 * 要单独处理多个z-order的window组,按情况另外建立{@link Ext.WindowGroup}的实例 * @singleton */ Ext.WindowMgr = new Ext.WindowGroup();
JavaScript
/** * @class Ext.Panel * @extends Ext.Container * 面板是一种为面向应用程序用户界面构建最佳的单元块,一种特定功能和结构化组件。 * 面板包含有底部和顶部的工具条,连同单独的头部、底部和body部分。 * 它提供内建都得可展开和可闭合的行为,连同多个内建的可制定的行为的工具按钮。 * 面板可简易地置入任意的容器或布局,而面板和渲染管线(rendering pipeline)则有框架完全控制。 * @constructor * @param {Object} config 配置项对象 */ Ext.Panel = Ext.extend(Ext.Container, { /** * 面板的头部元素 {@link Ext.Element Element}. 只读的。 * <p>此元素用于承载 {@link #title} 和 {@link #tools}</p> * @type Ext.Element * @property header */ /** * 面板的躯干元素 {@link Ext.Element Element} 用于承载HTML内容。 * 内容可由{@link #html} 的配置指定, 亦可通过配置{@link autoLoad}加载, * 通过面板的{@link #getUpdater Updater}亦是同样的原理。只读的。 * <p>注:若采用了上述的方法,那么面板则不能当作布局的容器嵌套子面板。</p> * <p>换句话说,若打算将面板用于布局的承载者,Body躯干元素就不能有任何加载或改动, * 它是由面板的局部(Panel's Layout)负责调控。 * @type Ext.Element * @property body */ /** * 面板的底部元素 @link Ext.Element Element}。只读的。 * <p>此元素用于承载{@link #buttons}</p> * @type Ext.Element * @property header */ /** * @cfg {Mixed} applyTo * 即applyTo代表一个在页面上已经存在的元素或该元素的id, * 该元素通过markup的方式来表示欲生成的组件的某些结构化信息, * Ext在创建一个组件时,会首先考虑使用applyTo元素中的存在的元素, * 你可以认为applyTo是组件在页面上的模板,与YUI中的markup模式很相似。 * 当你在 config中配置了applyTo属性后,renderTo属性将会被忽略。并且生成的组件将会被自动置去applyTo元素的父元素中。 * The id of the node, a DOM node or an existing Element corresponding to a DIV that is already present in * the document that specifies some panel-specific structural markup. When applyTo is used, constituent parts of * the panel can be specified by CSS class name within the main element, and the panel will automatically create those * components from that markup. Any required components not specified in the markup will be autogenerated if necessary. * The following class names are supported (baseCls will be replaced by {@link #baseCls}): * <ul><li>baseCls + '-header'</li> * <li>baseCls + '-header-text'</li> * <li>baseCls + '-bwrap'</li> * <li>baseCls + '-tbar'</li> * <li>baseCls + '-body'</li> * <li>baseCls + '-bbar'</li> * <li>baseCls + '-footer'</li></ul> * Using this config, a call to render() is not required. If applyTo is specified, any value passed for * {@link #renderTo} will be ignored and the target element's parent node will automatically be used as the panel's container. */ /** * @cfg {Object/Array} tbar * 面板顶部的工具条。此项可以是{@link Ext.Toolbar}的实例、工具条的配置对象,或由按钮配置项对象 * 构成的数组,以加入到工具条中。注意,此项属性渲染过后就不可用了, * 应使用{@link #getTopToolbar}的方法代替。 */ /** * @cfg {Object/Array} tbar * 面板底部的工具条。此项可以是{@link Ext.Toolbar}的实例、工具条的配置对象,或由按钮配置项对象 * 构成的数组,以加入到工具条中。注意,此项属性渲染过后就不可用了, * 应使用{@link #getBottomToolbar}的方法代替。 */ /** * @cfg {Boolean} header * True表示为显式建立头部元素,false则是跳过创建。缺省下,如不创建头部, * 将使用{@link #title} 的内容设置到头部去,如没指定title则不会。 * 如果设置好title,但头部设置为false,那么头部亦不会生成。 */ /** * @cfg {Boolean} footer * True表示为显式建立底部元素,false则是跳过创建。缺省下,就算不声明创建底部, * 若有一个或一个以上的按钮加入到面板的话,也创建底部,不指定按钮就不会生成。 */ /** * @cfg {String} title * 显示在面板头部的文本标题(默认为'')。如有指定了titile那么头部元素(head)会自动生成和显示, * 除非{@link #header}强制设为false。如果你不想在写配置时指定好title, * 不过想在后面才加入的话,你必须先指定一个非空的标题。(空白字符''亦可)或header:true * 这样才保证容器元素生成出来。 */ /** * @cfg {Array} buttons * 在面板底部加入按钮,{@link Ext.Button}配置的数组。 */ /** * @cfg {Object/String/Function} autoLoad * 一个特定的url反馈到Updater的{@link Ext.Updater#update}方法。<p> * 若autoLoad非null,面板在渲染后立即加载内容。同时该面板{@link #body}元素的默认URL属性就是这URL, * 所以可随时调用{@link Ext.Element#refresh refresh}的方法。</p> */ /** * @cfg {Boolean} frame * True表示为面板的边框外框可自定义的,false表示为边框可1px的点线(默认为false) */ /** * @cfg {Boolean} border * True表示为显示出面板body元素的边框,false则隐藏(缺省为true), * 默认下,边框是一套2px宽的内边框,但可在{@link #bodyBorder}中进一步设置。 */ /** * @cfg {Boolean} bodyBorder * True表示为显示出面板body元素的边框,false则隐藏(缺省为true), * 只有 {@link #border} == true时有效. 若 border == true and bodyBorder == false, 边框则为1px宽, * 可指定整个body元素的内置外观。 */ /** * @cfg {String/Object/Function} bodyStyle * 制定body元素的CSS样式。格式形如{@link Ext.Element#applyStyles}(缺省为null)。 */ /** * @cfg {String} iconCls * 一个能提供背景图片的CSS样式类,用于面板头部的图标:(默认为'')。 */ /** * @cfg {Boolean} collapsible * True表示为面板是可收缩的,并自动渲染一个展开/收缩的轮换按钮在头部工具条。 * false表示为保持面板为一个静止的尺寸(缺省为false)。 */ /** * @cfg {Array} tools * 一个按钮配置数组,加入到头部的工具条区域。每个工具配置可包含下列属性: * <div class="mdetail-params"><ul> * <li><b>id</b> : String<p class="sub-desc"><b>必须的。</b>要创建工具的类型。值可以是:<ul> * <li><tt>toggle</tt> (当{@link #collapsible}为<tt>true</tt>时默认创建)</li> * <li><tt>close</tt></li> * <li><tt>minimize</tt></li> * <li><tt>maximize</tt></li> * <li><tt>restore</tt></li> * <li><tt>gear</tt></li> * <li><tt>pin</tt></li> * <li><tt>unpin</tt></li> * <li><tt>right</tt></li> * <li><tt>left</tt></li> * <li><tt>up</tt></li> * <li><tt>down</tt></li> * <li><tt>refresh</tt></li> * <li><tt>minus</tt></li> * <li><tt>plus</tt></li> * <li><tt>help</tt></li> * <li><tt>search</tt></li> * <li><tt>save</tt></li> * </ul></div></p></li> * <li><b>handler</b> : Function<p class="sub-desc"><b>必须的。</b> 点击后执行的函数。 * 传入的参数有:<ul> * <li><b>event</b> : Ext.EventObject<p class="sub-desc">单击事件</p></li> * <li><b>toolEl</b> : Ext.Element<p class="sub-desc">工具元素(tool Element)</p></li> * <li><b>Panel</b> : Ext.Panel<p class="sub-desc">面板</p></li> * </ul></p></li> * <li><b>scope</b> : Object<p class="sub-desc">调用句柄的作用域</p></li> * <li><b>qtip</b> : String/Object<p class="sub-desc">提示字符串,或{@link Ext.QuickTip#register}的配置参数</p></li> * <li><b>hidden</b> : Boolean<p class="sub-desc">True表示为渲染为隐藏</p></li> * <li><b>on</b> : Object<p class="sub-desc">特定事件侦听器的配置对象,格式行如{@link #addListener}的参数</p></li> * </ul> * 用法举例: * <pre><code> tools:[{ id:'refresh', // hidden:true, handler: function(event, toolEl, panel){ // refresh logic } }] </code></pre> * 注意面板关闭时的轮换按钮(toggle tool)的实现是分离出去,这些工具按钮只提供视觉上的按钮。 * 所需的功能必须由句柄提供以实现相应的行为。 */ /** * @cfg {Boolean} hideCollapseTool * True表示为不出 展开/收缩的轮换按钮,当{@link #collapsible} = true,false就显示(默认为false)。 */ /** * @cfg {Boolean} titleCollapse * True表示为允许单击头部区域任何一个位置都可收缩面板(当{@link #collapsible} = true) * 反之只允许单击工具按钮(默认为false)。 */ /** * @cfg {Boolean} autoScroll * True表示为在面板body元素上,设置overflow:'auto'和出现滚动条 * false表示为裁剪所有溢出的内容(默认为false)。 */ /** * @cfg {Boolean} floating * True 表示为浮动此面板(带有自动填充和投影的绝对定位), * false表示为在其渲染的位置"就近"显示(默认为false)注意:默认情况下,设置为"浮动"会使得面板 * 在非正数的坐标上显示,以致不能正确显示,由于面板这时绝对定位的,必须精确地设置渲染后的位置 * (如:myPanel.setPosition(100,100);)而且,一个浮动面板是没有固定的宽度,(autoWidth:true), * 导致面板会填满与视图右方的区域。 * hidden:True表示为初始渲染即隐藏, * on:指定一个监听器,格式{add Listened},用法举例:刷新逻辑。 */ /** * @cfg {Boolean/String} shadow * True 表示为(或一个有效{@link Ext.Shadow#mode} 值) 在面板后显示投影效果,(默认为'sides'四边) * 注意此项只当floating = true时有效。 */ /** * @cfg {Number} shadowOffset * 投影偏移的象素值(默认为4) * 注意此项只当floating = true时有效. */ /** * @cfg {Boolean} shim * False表示为禁止用iframe填充,有些浏览器可能需要设置(默认为true) * 注意此项只当floating = true时有效. */ /** * @cfg {String/Object} html * 一段HTML片段,或 {@link Ext.DomHelper DomHelper} 作为面板body内容(默认为 ''). */ /** * @cfg {String} contentEl * 现有HTML节点的id,用作面板body的内容 (缺省为 ''). */ /** * @cfg {Object/Array} keys * KeyMap 的配置项对象 (格式形如: {@link Ext.KeyMap#addBinding} * 可用于将key分配到此面板 (缺省为 null). */ /** * @cfg {Boolean} draggable * True表示为激活此面板的拖动 (默认为false) 虽然 Ext.Panel.DD 是一个内部类并未归档的,但 * 亦可自定义拖放 (drag/drop) 的实现,具体做法是传入一个 Ext.Panel.DD 的配置代替 true 值。 */ /** * @cfg {String} baseCls * 作用在面板元素上的CSS样式类 (默认为 'x-panel'). */ baseCls : 'x-panel', /** * @cfg {String} collapsedCls * 当面板闭合时,面板元素的CSS样式类 (默认为 'x-panel-collapsed'). */ collapsedCls : 'x-panel-collapsed', /** * @cfg {Boolean} maskDisabled * True表示为当面板不可用时进行遮罩(默认为true)。 当面板禁用时,总是会告知下面的元素亦要禁用, * 但遮罩是另外一种方式同样达到禁用的效果。 */ maskDisabled: true, /** * @cfg {Boolean} animCollapse * True 表示为面板闭合过程附有动画效果 (默认为true,在类 {@link Ext.Fx} 可用的情况下). */ animCollapse: Ext.enableFx, /** * @cfg {Boolean} headerAsText * True表示为显示面板头部的标题 (默认为 true). */ headerAsText: true, /** * @cfg {String} buttonAlign * 在此面板上的按钮的对齐方式,有效值是'right,' 'left' and 'center' (默认为 'right'). */ buttonAlign: 'right', /** * @cfg {Boolean} collapsed * True 表示为渲染面板后即闭合 (默认为false). */ collapsed : false, /** * @cfg {Boolean} collapseFirst * True 表示为展开/闭合的轮换按钮出现在面板头部的左方,false表示为在右方 (默认为true). */ collapseFirst: true, /** * @cfg {Number} minButtonWidth * 此面板上按钮的最小宽度 (默认为75) */ minButtonWidth:75, /** * @cfg {String} elements * 面板渲染后,要初始化面板元素的列表,用逗号分隔开。 * 正常情况下,该列表会在面板读取配置的时候就自动生成,假设没有进行配置,但结构元素有更新渲染的情况下, * 就可根据指值得知结构元素是否已渲染的(例如,你打算在面板完成渲染后动态加入按钮或工具条)。 * 加入此列表中的这些元素后就在渲染好的面板中分配所需的载体(placeholders)。 * 有效值是:<ul> * <li><b>header</b></li> * <li><b>tbar</b> (top bar)</li> * <li><b>body</b></li> * <li><b>bbar</b> (bottom bar)</li> * <li><b>footer</b><li> * </ul> * 缺省为'body'. */ elements : 'body', // protected - these could be used to customize the behavior of the window, // but changing them would not be useful without further mofifications and // could lead to unexpected or undesirable results. toolTarget : 'header', collapseEl : 'bwrap', slideAnchor : 't', // private, notify box this class will handle heights deferHeight: true, // private expandDefaults: { duration:.25 }, // private collapseDefaults: { duration:.25 }, // private initComponent : function(){ Ext.Panel.superclass.initComponent.call(this); this.addEvents( /** * @event bodyresiz * 当面板的大小变化后触发。 * @param {Ext.Panel} p 调节大小的面板 * @param {Number} width 面板新宽度 * @param {Number} height 面板新高度 */ 'bodyresize', /** * @event titlechange * 当面板的标题有改动后触发。 * @param {Ext.Panel} p 标题被改动的那个面板 * @param {String} 新标题 */ 'titlechange', /** * @event collapse * 当面板被闭合后触发。 * @param {Ext.Panel} p 闭合的那个面板 */ 'collapse', /** * @event expand * 当面板被展开后触发。 * @param {Ext.Panel} p 展开的面板 */ 'expand', /** * @event beforecollapse * 当面板被闭合之前触发。若句柄返回false则取消闭合的动作。 * @param {Ext.Panel} p 正被闭合的面板 * @param {Boolean} animate True表示闭合时带有动画效果 */ 'beforecollapse', /** * @event beforeexpand * 当面板被展开之前触发。若句柄返回false则取消展开的动作。 * @param {Ext.Panel} p 正被展开的面板 * @param {Boolean} animate True表示闭合时带有动画效果 */ 'beforeexpand', /** * @event beforeclose * 当面板被关闭之前触发。 * 注意面板不直接支持“关闭”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。 * 若句柄返回false则取消关闭的动作。 * @param {Ext.Panel} p 正被关闭的面板 */ 'beforeclose', /** * @event beforeclose * 当面板被关闭后触发。 * 注意面板不直接支持“关闭”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。 * @param {Ext.Panel} p 已关闭的面板 */ 'close', /** * @event activate * 当面板视觉上被激活后触发。 * 注意面板不直接支持“激活”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。 * 另外在TabPanel控制下子组件也会触发activate和deactivate事件。 * @param {Ext.Panel} p 已活动的面板 */ 'activate', /** * @event activate * 当面板视觉上取消活动后触发。 * 注意面板不直接支持“取消活动”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。 * 另外在TabPanel控制下子组件也会触发activate和deactivate事件。 */ 'deactivate' ); // shortcuts if(this.tbar){ this.elements += ',tbar'; if(typeof this.tbar == 'object'){ this.topToolbar = this.tbar; } delete this.tbar; } if(this.bbar){ this.elements += ',bbar'; if(typeof this.bbar == 'object'){ this.bottomToolbar = this.bbar; } delete this.bbar; } if(this.header === true){ this.elements += ',header'; delete this.header; }else if(this.title && this.header !== false){ this.elements += ',header'; } if(this.footer === true){ this.elements += ',footer'; delete this.footer; } if(this.buttons){ var btns = this.buttons; /** * This Panel's Array of buttons as created from the <tt>buttons</tt> * config property. Read only. * @type Array * @property buttons */ this.buttons = []; for(var i = 0, len = btns.length; i < len; i++) { if(btns[i].render){ // button instance this.buttons.push(btns[i]); }else{ this.addButton(btns[i]); } } } if(this.autoLoad){ this.on('render', this.doAutoLoad, this, {delay:10}); } }, // private createElement : function(name, pnode){ if(this[name]){ pnode.appendChild(this[name].dom); return; } if(name === 'bwrap' || this.elements.indexOf(name) != -1){ if(this[name+'Cfg']){ this[name] = Ext.fly(pnode).createChild(this[name+'Cfg']); }else{ var el = document.createElement('div'); el.className = this[name+'Cls']; this[name] = Ext.get(pnode.appendChild(el)); } } }, // private onRender : function(ct, position){ Ext.Panel.superclass.onRender.call(this, ct, position); this.createClasses(); if(this.el){ // existing markup this.el.addClass(this.baseCls); this.header = this.el.down('.'+this.headerCls); this.bwrap = this.el.down('.'+this.bwrapCls); var cp = this.bwrap ? this.bwrap : this.el; this.tbar = cp.down('.'+this.tbarCls); this.body = cp.down('.'+this.bodyCls); this.bbar = cp.down('.'+this.bbarCls); this.footer = cp.down('.'+this.footerCls); this.fromMarkup = true; }else{ this.el = ct.createChild({ id: this.id, cls: this.baseCls }, position); } var el = this.el, d = el.dom; if(this.cls){ this.el.addClass(this.cls); } if(this.buttons){ this.elements += ',footer'; } // This block allows for maximum flexibility and performance when using existing markup // framing requires special markup if(this.frame){ el.insertHtml('afterBegin', String.format(Ext.Element.boxMarkup, this.baseCls)); this.createElement('header', d.firstChild.firstChild.firstChild); this.createElement('bwrap', d); // append the mid and bottom frame to the bwrap var bw = this.bwrap.dom; var ml = d.childNodes[1], bl = d.childNodes[2]; bw.appendChild(ml); bw.appendChild(bl); var mc = bw.firstChild.firstChild.firstChild; this.createElement('tbar', mc); this.createElement('body', mc); this.createElement('bbar', mc); this.createElement('footer', bw.lastChild.firstChild.firstChild); if(!this.footer){ this.bwrap.dom.lastChild.className += ' x-panel-nofooter'; } }else{ this.createElement('header', d); this.createElement('bwrap', d); // append the mid and bottom frame to the bwrap var bw = this.bwrap.dom; this.createElement('tbar', bw); this.createElement('body', bw); this.createElement('bbar', bw); this.createElement('footer', bw); if(!this.header){ this.body.addClass(this.bodyCls + '-noheader'); if(this.tbar){ this.tbar.addClass(this.tbarCls + '-noheader'); } } } if(this.border === false){ this.el.addClass(this.baseCls + '-noborder'); this.body.addClass(this.bodyCls + '-noborder'); if(this.header){ this.header.addClass(this.headerCls + '-noborder'); } if(this.footer){ this.footer.addClass(this.footerCls + '-noborder'); } if(this.tbar){ this.tbar.addClass(this.tbarCls + '-noborder'); } if(this.bbar){ this.bbar.addClass(this.bbarCls + '-noborder'); } } if(this.bodyBorder === false){ this.body.addClass(this.bodyCls + '-noborder'); } if(this.bodyStyle){ this.body.applyStyles(this.bodyStyle); } this.bwrap.enableDisplayMode('block'); if(this.header){ this.header.unselectable(); // for tools, we need to wrap any existing header markup if(this.headerAsText){ this.header.dom.innerHTML = '<span class="' + this.headerTextCls + '">'+this.header.dom.innerHTML+'</span>'; if(this.iconCls){ this.setIconClass(this.iconCls); } } } if(this.floating){ this.makeFloating(this.floating); } if(this.collapsible){ this.tools = this.tools ? this.tools.slice(0) : []; if(!this.hideCollapseTool){ this.tools[this.collapseFirst?'unshift':'push']({ id: 'toggle', handler : this.toggleCollapse, scope: this }); } if(this.titleCollapse && this.header){ this.header.on('click', this.toggleCollapse, this); this.header.setStyle('cursor', 'pointer'); } } if(this.tools){ var ts = this.tools; this.tools = {}; this.addTool.apply(this, ts); }else{ this.tools = {}; } if(this.buttons && this.buttons.length > 0){ // tables are required to maintain order and for correct IE layout var tb = this.footer.createChild({cls:'x-panel-btns-ct', cn: { cls:"x-panel-btns x-panel-btns-"+this.buttonAlign, html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>' }}, null, true); var tr = tb.getElementsByTagName('tr')[0]; for(var i = 0, len = this.buttons.length; i < len; i++) { var b = this.buttons[i]; var td = document.createElement('td'); td.className = 'x-panel-btn-td'; b.render(tr.appendChild(td)); } } if(this.tbar && this.topToolbar){ if(this.topToolbar instanceof Array){ this.topToolbar = new Ext.Toolbar(this.topToolbar); } this.topToolbar.render(this.tbar); } if(this.bbar && this.bottomToolbar){ if(this.bottomToolbar instanceof Array){ this.bottomToolbar = new Ext.Toolbar(this.bottomToolbar); } this.bottomToolbar.render(this.bbar); } }, /** * icon class if one has already been set. * 为该面板设置图标的样式类。此方法会覆盖当前现有的图标。 * @param {String} cls 新CSS样式类的名称 */ setIconClass : function(cls){ var old = this.iconCls; this.iconCls = cls; if(this.rendered){ if(this.frame){ this.header.addClass('x-panel-icon'); this.header.replaceClass(old, this.iconCls); }else{ var hd = this.header.dom; var img = hd.firstChild && String(hd.firstChild.tagName).toLowerCase() == 'img' ? hd.firstChild : null; if(img){ Ext.fly(img).replaceClass(old, this.iconCls); }else{ Ext.DomHelper.insertBefore(hd.firstChild, { tag:'img', src: Ext.BLANK_IMAGE_URL, cls:'x-panel-inline-icon '+this.iconCls }); } } } }, // private makeFloating : function(cfg){ this.floating = true; this.el = new Ext.Layer( typeof cfg == 'object' ? cfg : { shadow: this.shadow !== undefined ? this.shadow : 'sides', shadowOffset: this.shadowOffset, constrain:false, shim: this.shim === false ? false : undefined }, this.el ); }, /** * 返回面板顶部区域的工具条. * @return {Ext.Toolbar} toolbar对象 */ getTopToolbar : function(){ return this.topToolbar; }, /** * 返回面板底部区域的工具条. * @return {Ext.Toolbar} toolbar对象 */ getBottomToolbar : function(){ return this.bottomToolbar; }, /** * 为面板添加按钮。注意必须在渲染之前才可以调用该方法。最佳的方法是通过{@link #buttons}的配置项添加按钮。 * @param {String/Object} config 合法的{@link Ext.Button}配置项对象。若字符类型就表示这是按钮的提示文字。 * @param {Function} handler 按钮被按下时执行的函数,等同{@link Ext.Button#click} * @param {Object} scope 按钮触发时的事件处理函数所在作用域 * @return {Ext.Button} 已添加的按钮 */ addButton : function(config, handler, scope){ var bc = { handler: handler, scope: scope, minWidth: this.minButtonWidth, hideParent:true }; if(typeof config == "string"){ bc.text = config; }else{ Ext.apply(bc, config); } var btn = new Ext.Button(bc); if(!this.buttons){ this.buttons = []; } this.buttons.push(btn); return btn; }, // private addTool : function(){ if(!this[this.toolTarget]) { // no where to render tools! return; } if(!this.toolTemplate){ // initialize the global tool template on first use var tt = new Ext.Template( '<div class="x-tool x-tool-{id}">&#160;</div>' ); tt.disableFormats = true; tt.compile(); Ext.Panel.prototype.toolTemplate = tt; } for(var i = 0, a = arguments, len = a.length; i < len; i++) { var tc = a[i], overCls = 'x-tool-'+tc.id+'-over'; var t = this.toolTemplate.insertFirst(this[this.toolTarget], tc, true); this.tools[tc.id] = t; t.enableDisplayMode('block'); t.on('click', this.createToolHandler(t, tc, overCls, this)); if(tc.on){ t.on(tc.on); } if(tc.hidden){ t.hide(); } if(tc.qtip){ if(typeof tc.qtip == 'object'){ Ext.QuickTips.register(Ext.apply({ target: t.id }, tc.qtip)); } else { t.dom.qtip = tc.qtip; } } t.addClassOnOver(overCls); } }, // private onShow : function(){ if(this.floating){ return this.el.show(); } Ext.Panel.superclass.onShow.call(this); }, // private onHide : function(){ if(this.floating){ return this.el.hide(); } Ext.Panel.superclass.onHide.call(this); }, // private createToolHandler : function(t, tc, overCls, panel){ return function(e){ t.removeClass(overCls); e.stopEvent(); if(tc.handler){ tc.handler.call(tc.scope || t, e, t, panel); } }; }, // private afterRender : function(){ if(this.fromMarkup && this.height === undefined && !this.autoHeight){ this.height = this.el.getHeight(); } if(this.floating && !this.hidden && !this.initHidden){ this.el.show(); } if(this.title){ this.setTitle(this.title); } if(this.autoScroll){ this.body.dom.style.overflow = 'auto'; } if(this.html){ this.body.update(typeof this.html == 'object' ? Ext.DomHelper.markup(this.html) : this.html); delete this.html; } if(this.contentEl){ var ce = Ext.getDom(this.contentEl); Ext.fly(ce).removeClass(['x-hidden', 'x-hide-display']); this.body.dom.appendChild(ce); } if(this.collapsed){ this.collapsed = false; this.collapse(false); } Ext.Panel.superclass.afterRender.call(this); // do sizing calcs last this.initEvents(); }, // private getKeyMap : function(){ if(!this.keyMap){ this.keyMap = new Ext.KeyMap(this.el, this.keys); } return this.keyMap; }, // private initEvents : function(){ if(this.keys){ this.getKeyMap(); } if(this.draggable){ this.initDraggable(); } }, // private initDraggable : function(){ this.dd = new Ext.Panel.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable); }, // private beforeEffect : function(){ if(this.floating){ this.el.beforeAction(); } this.el.addClass('x-panel-animated'); }, // private afterEffect : function(){ this.syncShadow(); this.el.removeClass('x-panel-animated'); }, // private - wraps up an animation param with internal callbacks createEffect : function(a, cb, scope){ var o = { scope:scope, block:true }; if(a === true){ o.callback = cb; return o; }else if(!a.callback){ o.callback = cb; }else { // wrap it up o.callback = function(){ cb.call(scope); Ext.callback(a.callback, a.scope); }; } return Ext.applyIf(o, a); }, /** * 展开面板body, 显示内容. 触发 {@link #beforecollapse} 事件,如返回false则取消展开的动作. * @param {Boolean} animate True 表示为转换状态时出现动画, * (默认为面板 {@link #animCollapse} 的配置值) * @return {Ext.Panel} this */ collapse : function(animate){ if(this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforecollapse', this, animate) === false){ return; } var doAnim = animate === true || (animate !== false && this.animCollapse); this.beforeEffect(); this.onCollapse(doAnim, animate); return this; }, // private onCollapse : function(doAnim, animArg){ if(doAnim){ this[this.collapseEl].slideOut(this.slideAnchor, Ext.apply(this.createEffect(animArg||true, this.afterCollapse, this), this.collapseDefaults)); }else{ this[this.collapseEl].hide(); this.afterCollapse(); } }, // private afterCollapse : function(){ this.collapsed = true; this.el.addClass(this.collapsedCls); this.afterEffect(); this.fireEvent('collapse', this); }, /** * 展开面板的主体部分,显示全部。这会触发{@link #beforeexpand}的事件,若事件处理函数返回false那么这个方法将失效。 * @param {Boolean} animate True 表示为转换状态时出现动画, * (默认为面板 {@link #animCollapse} 的配置值) * @return {Ext.Panel} this */ expand : function(animate){ if(!this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforeexpand', this, animate) === false){ return; } var doAnim = animate === true || (animate !== false && this.animCollapse); this.el.removeClass(this.collapsedCls); this.beforeEffect(); this.onExpand(doAnim, animate); return this; }, // private onExpand : function(doAnim, animArg){ if(doAnim){ this[this.collapseEl].slideIn(this.slideAnchor, Ext.apply(this.createEffect(animArg||true, this.afterExpand, this), this.expandDefaults)); }else{ this[this.collapseEl].show(); this.afterExpand(); } }, // private afterExpand : function(){ this.collapsed = false; this.afterEffect(); this.fireEvent('expand', this); }, /** * 根据面板的当前状态,采取相应的 {@link #expand} 或 {@link #collapse}。 * @param {Boolean} animate True 表示为转换状态时出现动画, * (默认为面板 {@link #animCollapse} 的配置值) * @return {Ext.Panel} this */ toggleCollapse : function(animate){ this[this.collapsed ? 'expand' : 'collapse'](animate); return this; }, // private onDisable : function(){ if(this.rendered && this.maskDisabled){ this.el.mask(); } Ext.Panel.superclass.onDisable.call(this); }, // private onEnable : function(){ if(this.rendered && this.maskDisabled){ this.el.unmask(); } Ext.Panel.superclass.onEnable.call(this); }, // private onResize : function(w, h){ if(w !== undefined || h !== undefined){ if(!this.collapsed){ if(typeof w == 'number'){ this.body.setWidth( this.adjustBodyWidth(w - this.getFrameWidth())); }else if(w == 'auto'){ this.body.setWidth(w); } if(typeof h == 'number'){ this.body.setHeight( this.adjustBodyHeight(h - this.getFrameHeight())); }else if(h == 'auto'){ this.body.setHeight(h); } }else{ this.queuedBodySize = {width: w, height: h}; if(!this.queuedExpand && this.allowQueuedExpand !== false){ this.queuedExpand = true; this.on('expand', function(){ delete this.queuedExpand; this.onResize(this.queuedBodySize.width, this.queuedBodySize.height); this.doLayout(); }, this, {single:true}); } } this.fireEvent('bodyresize', this, w, h); } this.syncShadow(); }, // private adjustBodyHeight : function(h){ return h; }, // private adjustBodyWidth : function(w){ return w; }, // private onPosition : function(){ this.syncShadow(); }, // private onDestroy : function(){ if(this.tools){ for(var k in this.tools){ Ext.destroy(this.tools[k]); } } if(this.buttons){ for(var b in this.buttons){ Ext.destroy(this.buttons[b]); } } Ext.destroy( this.topToolbar, this.bottomToolbar ); Ext.Panel.superclass.onDestroy.call(this); }, /** * 返回面板框架元素的宽度 (不含body宽度) 要取的body宽度参阅 {@link #getInnerWidth}。 * @return {Number} The frame width */ getFrameWidth : function(){ var w = this.el.getFrameWidth('lr'); if(this.frame){ var l = this.bwrap.dom.firstChild; w += (Ext.fly(l).getFrameWidth('l') + Ext.fly(l.firstChild).getFrameWidth('r')); var mc = this.bwrap.dom.firstChild.firstChild.firstChild; w += Ext.fly(mc).getFrameWidth('lr'); } return w; }, /** * 返回面板框架元素的高度 (包括顶部/底部工具条的高度) 要取的body高度参阅{@link #getInnerHeight}。 * @return {Number} 框架高度 */ getFrameHeight : function(){ var h = this.el.getFrameWidth('tb'); h += (this.tbar ? this.tbar.getHeight() : 0) + (this.bbar ? this.bbar.getHeight() : 0); if(this.frame){ var hd = this.el.dom.firstChild; var ft = this.bwrap.dom.lastChild; h += (hd.offsetHeight + ft.offsetHeight); var mc = this.bwrap.dom.firstChild.firstChild.firstChild; h += Ext.fly(mc).getFrameWidth('tb'); }else{ h += (this.header ? this.header.getHeight() : 0) + (this.footer ? this.footer.getHeight() : 0); } return h; }, /** * 返回面板body元素的宽度 (不含任何框架元素) 要取的框架宽度参阅 {@link #getFrameWidth}. * @return {Number} body宽度 */ getInnerWidth : function(){ return this.getSize().width - this.getFrameWidth(); }, /** * 返回面板body元素的高度 (不包括任何框架元素的高度) 要取的框架高度参阅{@link #getFrameHeight}. * @return {Number} body高度 */ getInnerHeight : function(){ return this.getSize().height - this.getFrameHeight(); }, // private syncShadow : function(){ if(this.floating){ this.el.sync(true); } }, // private getLayoutTarget : function(){ return this.body; }, /** * 设置面板的标题文本,你也可以在这里指定面板的图片(CSS样式类)。 * @param {String} title 要设置的标题 * @param {String} (optional) iconCls 为该面板用户自定义的图标,这是一个CSS样式类的字符串。 */ setTitle : function(title, iconCls){ this.title = title; if(this.header && this.headerAsText){ this.header.child('span').update(title); } if(iconCls){ this.setIconClass(iconCls); } this.fireEvent('titlechange', this, title); return this; }, /** * 获取该面板的{@link Ext.Updater}。主要是为面板的主体部分(body)提过面向AJAX的内容更新。 * @return {Ext.Updater} Updater对象 */ getUpdater : function(){ return this.body.getUpdater(); }, /** * 利用XHR的访问加载远程的内容,立即显示在面板中 * @param {Object/String/Function} config 特定的配置项对象,可包含以下选项: <pre><code> panel.load({ url: "your-url.php", params: {param1: "foo", param2: "bar"}, // 或URL字符串,要已编码的 callback: yourFunction, scope: yourObject, // 回调的可选作用域 discardUrl: false, nocache: false, text: "Loading...", timeout: 30, scripts: false }); </code></pre> * 其中必填的属性是url。至于可选的属性有nocache、text与scripts,分别代表禁止缓存(disableCaching)、加载中的提示信息和是否对脚本敏感,都是关联到面板的Updater实例。 * @return {Ext.Panel} this */ load : function(){ var um = this.body.getUpdater(); um.update.apply(um, arguments); return this; }, // private beforeDestroy : function(){ Ext.Element.uncache( this.header, this.tbar, this.bbar, this.footer, this.body ); }, // private createClasses : function(){ this.headerCls = this.baseCls + '-header'; this.headerTextCls = this.baseCls + '-header-text'; this.bwrapCls = this.baseCls + '-bwrap'; this.tbarCls = this.baseCls + '-tbar'; this.bodyCls = this.baseCls + '-body'; this.bbarCls = this.baseCls + '-bbar'; this.footerCls = this.baseCls + '-footer'; }, // private createGhost : function(cls, useShim, appendTo){ var el = document.createElement('div'); el.className = 'x-panel-ghost ' + (cls ? cls : ''); if(this.header){ el.appendChild(this.el.dom.firstChild.cloneNode(true)); } Ext.fly(el.appendChild(document.createElement('ul'))).setHeight(this.bwrap.getHeight()); el.style.width = this.el.dom.offsetWidth + 'px';; if(!appendTo){ this.container.dom.appendChild(el); }else{ Ext.getDom(appendTo).appendChild(el); } if(useShim !== false && this.el.useShim !== false){ var layer = new Ext.Layer({shadow:false, useDisplay:true, constrain:false}, el); layer.show(); return layer; }else{ return new Ext.Element(el); } }, // private doAutoLoad : function(){ this.body.load( typeof this.autoLoad == 'object' ? this.autoLoad : {url: this.autoLoad}); } }); Ext.reg('panel', Ext.Panel);
JavaScript
/** * @class Ext.LoadMask * 一个简单的工具类,用于在加载数据时为元素做出类似于遮罩的效果。 * 对于有可用的{@link Ext.data.Store},可将效果与Store的加载达到同步,而mask本身会被缓存以备复用。 * 而对于其他元素,这个遮照类会替换元素本身的UpdateManager加载指示器,并在初始化完毕后销毁。 * @constructor * Create a new LoadMask * @param {Mixed} el 元素、DOM节点或id, * @param {Object} config 配置项对象 */ Ext.LoadMask = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(this.store){ this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.onLoad, this); this.removeMask = Ext.value(this.removeMask, false); }else{ var um = this.el.getUpdater(); um.showLoadIndicator = false; // disable the default indicator um.on('beforeupdate', this.onBeforeLoad, this); um.on('update', this.onLoad, this); um.on('failure', this.onLoad, this); this.removeMask = Ext.value(this.removeMask, true); } }; Ext.LoadMask.prototype = { /** * @cfg {Boolean} removeMask * True表示为一次性使用,即加载之后自动销毁(页面加载时有用),false表示为多次使用模版效果, * 保留这个mask(例如,页面上数据的加载)。默认为false。 */ /** * @cfg {String} msg * 加载信息中显示文字(默认为'Loading...') */ msg : 'Loading...', /** * @cfg {String} msgCls * 加载信息元素的样式(默认为"x-mask-loading") */ msgCls : 'x-mask-loading', /** * 只读。True表示为mask已被禁止,所以不会显示出来(默认为false)。 * @type Boolean */ disabled: false, /** * 禁用遮罩致使遮罩不会被显示 */ disable : function(){ this.disabled = true; }, /** * 启用遮罩以显示 */ enable : function(){ this.disabled = false; }, // private onLoad : function(){ this.el.unmask(this.removeMask); }, // private onBeforeLoad : function(){ if(!this.disabled){ this.el.mask(this.msg, this.msgCls); } }, show: function(){ this.onBeforeLoad(); }, hide: function(){ this.onLoad(); }, // private destroy : function(){ if(this.store){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.onLoad, this); }else{ var um = this.el.getUpdater(); um.un('beforeupdate', this.onBeforeLoad, this); um.un('update', this.onLoad, this); um.un('failure', this.onLoad, this); } } };
JavaScript
/** * @class Ext.Component * @extends Ext.util.Observable * <p>Base class for all Ext components. * 全体Ext组件的基类。 * Component下所有的子类均按照统一的Ext组件生命周期(lifeycle)执行运作,即创建、渲染和销毁(creation,rendering和destruction)。 * 并具有隐藏/显示和启用/禁用的基本行为特性。</p> * Component下的子类可被延时渲染(lazy-rendered)成为{@link Ext.Container}的一种,同时自动登记到{@link Ext.ComponentMgr}, * 这样便可在后面的代码使用{@link Ext#getCmp}获取组件的引用。 * 当需要以盒子模型(box model)的方式管理这些可视的器件(widgets), * 器件就必须从Component(或{@link Ext.BoxComponent})继承,渲染为一种布局。 * </p> * <p> * 每种component都有特定的类型,是Ext自身设置的类型。对xtype检查的相关方法如{@link #getXType}和{@link #isXType}。 * 这里是所有有效的xtypes列表:</p> * <pre> xtype 类Class ------------- ------------------ box Ext.BoxComponent button Ext.Button colorpalette Ext.ColorPalette component Ext.Component container Ext.Container cycle Ext.CycleButton dataview Ext.DataView datepicker Ext.DatePicker editor Ext.Editor editorgrid Ext.grid.EditorGridPanel grid Ext.grid.GridPanel paging Ext.PagingToolbar panel Ext.Panel progress Ext.ProgressBar splitbutton Ext.SplitButton tabpanel Ext.TabPanel treepanel Ext.tree.TreePanel viewport Ext.ViewPort window Ext.Window Toolbar components 工具条组件 --------------------------------------- toolbar Ext.Toolbar tbbutton Ext.Toolbar.Button tbfill Ext.Toolbar.Fill tbitem Ext.Toolbar.Item tbseparator Ext.Toolbar.Separator tbspacer Ext.Toolbar.Spacer tbsplit Ext.Toolbar.SplitButton tbtext Ext.Toolbar.TextItem Form components 表单组件 --------------------------------------- form Ext.FormPanel checkbox Ext.form.Checkbox combo Ext.form.ComboBox datefield Ext.form.DateField field Ext.form.Field fieldset Ext.form.FieldSet hidden Ext.form.Hidden htmleditor Ext.form.HtmlEditor numberfield Ext.form.NumberField radio Ext.form.Radio textarea Ext.form.TextArea textfield Ext.form.TextField timefield Ext.form.TimeField trigger Ext.form.TriggerField </pre> * @constructor * @param {Ext.Element/String/Object} config The configuration options. 配置项 * 如果传入的是一个元素,那么它将是内置的元素以及其id将用于组件的id。 * 如果传入的是一个字符串,那么就假设它是现有元素身上的id,也用于组件的id。 * 否则,那应该是一个标准的配置项对象,应用到组件身上。 */ Ext.Component = function(config){ config = config || {}; if(config.initialConfig){ if(config.isAction){ // actions this.baseAction = config; } config = config.initialConfig; // component cloning / action set up }else if(config.tagName || config.dom || typeof config == "string"){ // element object config = {applyTo: config, id: config.id || config}; } /** * 组件初始化配置项。只读的 * @type Object * @property initialConfig */ this.initialConfig = config; Ext.apply(this, config); this.addEvents( /** * @event disable * 当组件禁用后触发。 * @param {Ext.Component} this */ 'disable', /** * @event enable * 当组件启用后触发。 * @param {Ext.Component} this */ 'enable', /** * @event beforeshow * 当组件显示出来之前触发。如返回false则阻止显示。 * @param {Ext.Component} this */ 'beforeshow', /** * @event show * 当组件显示后触发。 * @param {Ext.Component} this */ 'show', /** * @event beforehide * 当组件将要隐藏的时候触发。如返回false则阻止隐藏。 * @param {Ext.Component} this */ 'beforehide', /** * @event hide * 当组件隐藏后触发。 * @param {Ext.Component} this */ 'hide', /** * @event beforerender * 当组件渲染之前触发。如返回false则阻止渲染。 * @param {Ext.Component} this */ 'beforerender', /** * @event render * 组件渲染之后触发。 * @param {Ext.Component} this */ 'render', /** * @event beforedestroy * 组件销毁之前触发。如返回false则停止销毁。 * @param {Ext.Component} this */ 'beforedestroy', /** * @event destroy * 组件销毁之后触发。 * @param {Ext.Component} this */ 'destroy', /** * @event beforestaterestore * 当组件的状态复原之前触发。如返回false则停止复原状态。 * @param {Ext.Component} this * @param {Object} state 保存状态的哈希表 */ 'beforestaterestore', /** * @event staterestore * 当组件的状态复原后触发。 * @param {Ext.Component} this * @param {Object} state 保存状态的哈希表 */ 'staterestore', /** * @event beforestatesave * 当组件的状态被保存到state provider之前触发。如返回false则停止保存。 * @param {Ext.Component} this * @param {Object} state 保存状态的哈希表 */ 'beforestatesave', /** * @event statesave * 当组件的状态被保存到state provider后触发。 * @param {Ext.Component} this * @param {Object} state 保存状态的哈希表 */ 'statesave' ); this.getId(); Ext.ComponentMgr.register(this); Ext.Component.superclass.constructor.call(this); if(this.baseAction){ this.baseAction.addComponent(this); } this.initComponent(); if(this.plugins){ if(this.plugins instanceof Array){ for(var i = 0, len = this.plugins.length; i < len; i++){ this.plugins[i].init(this); } }else{ this.plugins.init(this); } } if(this.stateful !== false){ this.initState(config); } if(this.applyTo){ this.applyToMarkup(this.applyTo); delete this.applyTo; }else if(this.renderTo){ this.render(this.renderTo); delete this.renderTo; } }; // private Ext.Component.AUTO_ID = 1000; Ext.extend(Ext.Component, Ext.util.Observable, { /** * @cfg {String} id * 唯一的组件id(默认为自动分配的id)。 */ /** * @cfg {String} xtype * The registered xtype to create. * 用于登记一个xtype。 * This config option is not used when passing * a config object into a constructor. * This config option is used only when * lazy instantiation is being used, and a child item of a Container is being * specified not as a fully instantiated Component, but as a <i>Component config * object</i>. * The xtype will be looked up at render time up to determine what * type of child Component to create.<br><br> * The predefined xtypes are listed {@link Ext.Component here}. * <br><br> * If you subclass Components to create your own Components, you may register * them using {@link Ext.ComponentMgr#registerType} in order to be able to * take advantage of lazy instantiation and rendering. */ /** * @cfg {String} cls * 一个可选添加的CSS样式类,加入到组件的元素上(默认为'')。 * 这为组件或组件的子节点加入标准CSS规则提供了方便。 */ /** * @cfg {String} style * 作用在组件元素上特定的样式。该值的有效格式应如{@link Ext.Element#applyStyles}。 */ /** * @cfg {String} cls * 一个可选添加的CSS样式类,加入到组件的容器上(默认为'')。 * 这为容器或容器的子节点加入标准CSS规则提供了方便。 */ /** * @cfg {Object/Array} plugins * 针对该组件自定义的功能,是对象或这些对象组成的数组。 * 一个有效的插件须保证带有一个init的方法以便接收属于Ext.Component类型的引用。 * 当一个组件被创建后,若发现由插件可用,组件会调用每个插件上的init方法,传入一个应用到插件本身。 * 这样,插件便能按照组件所提供的功能,调用到组件的方法或响应事件。 */ /** * @cfg {Mixed} applyTo * 节点的id,或是DOM节点,又或者是与DIV相当的现有元素,这些都是文档中已经存在的元素 * 当使用applyTo后,主元素所指定的id或CSS样式类将会作用于组件构成的部分, * 而被创建的组件将会尝试着根据这些markup构建它的子组件。 * 使用了这项配置后,不需要执行render()的方法。 * 若指定了applyTo,那么任何由{@link #renderTo}传入的值将会被忽略并使用目标元素的父级元素作为组件的容器。 */ /* * 译者:applyTo/renderTo-->容器定位选择的问题? * applyTo拿它的父元素作为container * renderTo该元素被用作容器 */ /** * @cfg {Mixed} renderTo * 容器渲染的那个节点的id,或是DOM节点,又或者是与DIV相当的现有元素。 * 使用了这项配置后,不需要执行render()的方法。 */ /* //internal - to be set by subclasses * @cfg {String} stateId * The unique id for this component to use for state management purposes (defaults to the component id). */ /* //internal - to be set by subclasses * @cfg {Array} stateEvents * An array of events that, when fired, should trigger this component to save its state (defaults to none). * These can be any types of events supported by this component, including browser or custom events (e.g., * ['click', 'customerchange']). */ /** * @cfg {String} disabledClass * 当组件被禁用时作用的CSS样式类(默认为"x-item-disabled")。 */ disabledClass : "x-item-disabled", /** * @cfg {Boolean} allowDomMove * 当渲染进行时能否移动Dom节点上的组件(默认为true)。 */ allowDomMove : true, /** * @cfg {Boolean} autoShow * True表示为在渲染的时候先检测一下有否关于隐藏的样式类(如:'x-hidden'或'x-hide-display'),有就移除隐藏的样式类。 * (缺省为false) */ autoShow : false, /** * @cfg {String} hideMode * 这个组件是怎么隐藏的。可支持的值有"visibility" (css中的visibility), "offsets"(负偏移位置)和 * "display"(css中的display)-默认为“display”。 */ hideMode: 'display', /** * @cfg {Boolean} hideParent * True表示为当隐藏/显示组件时对组件的容器亦一同隐藏/显示,false就只会隐藏/显示组件本身(默认为false)。 * 例如,可设置一个hide:true的隐藏按钮在window,如果按下就通知其父容器一起隐藏,这样做起来比较快捷省事。 */ hideParent: false, /** * 组件自身的{@link Ext.Container}(默认是undefined,只有在组件加入到容器时才会自动设置该属性)只读的。 * @type Ext.Container * @property ownerCt */ /** * True表示为组件是隐藏的。只读的 * @type Boolean * @property */ hidden : false, /** * True表示为组件已被禁止。只读的 * @type Boolean * @property */ disabled : false, /** * True表示为该组件已经渲染好了。只读的。 * @type Boolean * @property */ rendered : false, // private ctype : "Ext.Component", // private actionMode : "el", // private getActionEl : function(){ return this[this.actionMode]; }, /* // protected * Function to be implemented by Component subclasses to be part of standard component initialization flow (it is empty by default). * <pre><code> // Traditional constructor: Ext.Foo = function(config){ // call superclass constructor: Ext.Foo.superclass.constructor.call(this, config); this.addEvents({ // add events }); }; Ext.extend(Ext.Foo, Ext.Bar, { // class body } // initComponent replaces the constructor: Ext.Foo = Ext.extend(Ext.Bar, { initComponent : function(){ // call superclass initComponent Ext.Container.superclass.initComponent.call(this); this.addEvents({ // add events }); } } </code></pre> */ initComponent : Ext.emptyFn, /** * 如果这是延时加载的组件,就要执行这个渲染的方法到其容器的元素。 * @param {Mixed} container (可选的)该组件应该渲染到的元素。这一项不应是现有的元素。 * @param {String/Number} position (可选的) * 这个组件插入到容器的<b>之前</b>位置,可以是元素的ID或是DOM节点的索引(缺省是插入到容器的尾部) */ render : function(container, position){ if(!this.rendered && this.fireEvent("beforerender", this) !== false){ if(!container && this.el){ this.el = Ext.get(this.el); container = this.el.dom.parentNode; this.allowDomMove = false; } this.container = Ext.get(container); if(this.ctCls){ this.container.addClass(this.ctCls); } this.rendered = true; if(position !== undefined){ if(typeof position == 'number'){ position = this.container.dom.childNodes[position]; }else{ position = Ext.getDom(position); } } this.onRender(this.container, position || null); if(this.autoShow){ this.el.removeClass(['x-hidden','x-hide-' + this.hideMode]); } if(this.cls){ this.el.addClass(this.cls); delete this.cls; } if(this.style){ this.el.applyStyles(this.style); delete this.style; } this.fireEvent("render", this); this.afterRender(this.container); if(this.hidden){ this.hide(); } if(this.disabled){ this.disable(); } this.initStateEvents(); } return this; }, // private initState : function(config){ if(Ext.state.Manager){ var state = Ext.state.Manager.get(this.stateId || this.id); if(state){ if(this.fireEvent('beforestaterestore', this, state) !== false){ this.applyState(state); this.fireEvent('staterestore', this, state); } } } }, // private initStateEvents : function(){ if(this.stateEvents){ for(var i = 0, e; e = this.stateEvents[i]; i++){ this.on(e, this.saveState, this, {delay:100}); } } }, // private applyState : function(state, config){ if(state){ Ext.apply(this, state); } }, // private getState : function(){ return null; }, // private saveState : function(){ if(Ext.state.Manager){ var state = this.getState(); if(this.fireEvent('beforestatesave', this, state) !== false){ Ext.state.Manager.set(this.stateId || this.id, state); this.fireEvent('statesave', this, state); } } }, /** * 把这个组件应用到当前有效的markup。执行该函数后,无须调用render() * @param {String/HTMLElement} el */ applyToMarkup : function(el){ this.allowDomMove = false; this.el = Ext.get(el); this.render(this.el.dom.parentNode); }, /** * 加入CSS样式类到组件所在的元素。 * @param {string} cls 要加入的CSS样式类 */ addClass : function(cls){ if(this.el){ this.el.addClass(cls); }else{ this.cls = this.cls ? this.cls + ' ' + cls : cls; } }, /** * 移除CSS样式类到组件所属的元素。 * @param {string} cls 要移除的CSS样式类 */ removeClass : function(cls){ if(this.el){ this.el.removeClass(cls); }else if(this.cls){ this.cls = this.cls.split(' ').remove(cls).join(' '); } }, // private // default function is not really useful onRender : function(ct, position){ if(this.autoEl){ if(typeof this.autoEl == 'string'){ this.el = document.createElement(this.autoEl); }else{ var div = document.createElement('div'); Ext.DomHelper.overwrite(div, this.autoEl); this.el = div.firstChild; } } if(this.el){ this.el = Ext.get(this.el); if(this.allowDomMove !== false){ ct.dom.insertBefore(this.el.dom, position); } } }, // private getAutoCreate : function(){ var cfg = typeof this.autoCreate == "object" ? this.autoCreate : Ext.apply({}, this.defaultAutoCreate); if(this.id && !cfg.id){ cfg.id = this.id; } return cfg; }, // private afterRender : Ext.emptyFn, /** * 清除任何的事件的句柄,在DOM中移除组件的元素,从容器{@link Ext.Container}中移除本身(如果适合的话)和在{@link Ext.ComponentMgr}注销 * 销毁的方法一般由框架自动执行,通常不需要直接执行。 */ destroy : function(){ if(this.fireEvent("beforedestroy", this) !== false){ this.beforeDestroy(); if(this.rendered){ this.el.removeAllListeners(); this.el.remove(); if(this.actionMode == "container"){ this.container.remove(); } } this.onDestroy(); Ext.ComponentMgr.unregister(this); this.fireEvent("destroy", this); this.purgeListeners(); } }, // private beforeDestroy : Ext.emptyFn, // private onDestroy : Ext.emptyFn, /** * 返回所属的{@link Ext.Element}. * @return {Ext.Element} 元素 */ getEl : function(){ return this.el; }, /** * 返回该组件的id * @return {String} */ getId : function(){ return this.id || (this.id = "ext-comp-" + (++Ext.Component.AUTO_ID)); }, /** * 返回该组件的item id。 * @return {String} */ getItemId : function(){ return this.itemId || this.getId(); }, /** * 试着将焦点放到此项。 * @param {Boolean} selectText (可选的) true的话同时亦选中组件中的文本(尽可能) * @param {Boolean/Number} delay (可选的) 延时聚焦行为的毫秒数(true表示为10毫秒) * @return {Ext.Component} this */ focus : function(selectText, delay){ if(delay){ this.focus.defer(typeof delay == 'number' ? delay : 10, this, [selectText, false]); return; } if(this.rendered){ this.el.focus(); if(selectText === true){ this.el.dom.select(); } } return this; }, // private blur : function(){ if(this.rendered){ this.el.blur(); } return this; }, /** * 禁止该组件。 * @return {Ext.Component} this */ disable : function(){ if(this.rendered){ this.onDisable(); } this.disabled = true; this.fireEvent("disable", this); return this; }, // private onDisable : function(){ this.getActionEl().addClass(this.disabledClass); this.el.dom.disabled = true; }, /** * 启用该组件。 * @return {Ext.Component} this */ enable : function(){ if(this.rendered){ this.onEnable(); } this.disabled = false; this.fireEvent("enable", this); return this; }, // private onEnable : function(){ this.getActionEl().removeClass(this.disabledClass); this.el.dom.disabled = false; }, /** * 方便的函数用来控制组件禁用/可用。 * @param {Boolean} disabled */ setDisabled : function(disabled){ this[disabled ? "disable" : "enable"](); }, /** * 显示该组件。 * @return {Ext.Component} this */ show: function(){ if(this.fireEvent("beforeshow", this) !== false){ this.hidden = false; if(this.autoRender){ this.render(typeof this.autoRender == 'boolean' ? Ext.getBody() : this.autoRender); } if(this.rendered){ this.onShow(); } this.fireEvent("show", this); } return this; }, // private onShow : function(){ if(this.hideParent){ this.container.removeClass('x-hide-' + this.hideMode); }else{ this.getActionEl().removeClass('x-hide-' + this.hideMode); } }, /** * 隐藏该组件。 * @return {Ext.Component} this */ hide: function(){ if(this.fireEvent("beforehide", this) !== false){ this.hidden = true; if(this.rendered){ this.onHide(); } this.fireEvent("hide", this); } return this; }, // private onHide : function(){ if(this.hideParent){ this.container.addClass('x-hide-' + this.hideMode); }else{ this.getActionEl().addClass('x-hide-' + this.hideMode); } }, /** * 方便的函数用来控制组件显示/隐藏。 * @param {Boolean} visible true 时显示/false 时隐藏 * @return {Ext.Component} this */ setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } return this; }, /** * 该组件可见时返回true。 */ isVisible : function(){ return this.rendered && this.getActionEl().isVisible(); }, /** * 根据原始传入到该实例的配置项值,克隆一份组件。 * @param {Object} 一个新配置项对象,用于对克隆版本的属性进行重写。属性id应要重写,避免重复生成一个。 * @return {Ext.Component} clone 该组件的克隆copy */ cloneConfig : function(overrides){ overrides = overrides || {}; var id = overrides.id || Ext.id(); var cfg = Ext.applyIf(overrides, this.initialConfig); cfg.id = id; // prevent dup id return new this.constructor(cfg); }, /** * 获取{@link Ext.ComponentMgr}在已登记组件的xtypes。 * 全部可用的xtypes列表,可参考{@link Ext.Component}开头,用法举例: * <pre><code> var t = new Ext.form.TextField(); alert(t.getXType()); // alerts 'textfield' </code></pre> * @return {String} The xtype */ getXType : function(){ return this.constructor.xtype; }, /** * 测试这个组件是否属于某个指定的xtype。 * 这个方法既可测试该组件是否为某个xtype的子类,或直接是这个xtype的实例(shallow = true) * 全部可用的xtypes列表,可参考{@link Ext.Component}开头,用法举例: * <pre><code> var t = new Ext.form.TextField(); var isText = t.isXType('textfield'); // true var isBoxSubclass = t.isXType('box'); // true,textfield继承自BoxComponent var isBoxInstance = t.isXType('box', true); // false,非BoxComponent本身的实例 </code></pre> * @param {String} xtype 测试该组件的xtype * @param {Boolean} shallow (可选的) False表示为测试该组件是否为某个xtype的子类(缺省), * true就表示为测试该组件是否这个xtype本身的实例 */ isXType : function(xtype, shallow){ return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype; }, /** * 返回以斜杠分割的字符串,表示组件的xtype层次。 * 全部可用的xtypes列表,可参考{@link Ext.Component}开头,用法举例: * <pre><code> var t = new Ext.form.TextField(); alert(t.getXTypes()); // alerts 'component/box/field/textfield' </pre></code> * @return {String} xtype层次的字符串 */ getXTypes : function(){ var tc = this.constructor; if(!tc.xtypes){ var c = [], sc = this; while(sc && sc.constructor.xtype){ c.unshift(sc.constructor.xtype); sc = sc.constructor.superclass; } tc.xtypeChain = c; tc.xtypes = c.join('/'); } return tc.xtypes; } }); Ext.reg('component', Ext.Component);
JavaScript
/** * @class Ext.Resizable * @extends Ext.util.Observable * <p>在元素上应用拖动柄以使其支持缩放。拖动柄是嵌入在元素内部的且采用了绝对定位。某些元素, 如文本域或图片, 不支持这种做法。为了克服这种情况, 你可以把文本域打包在一个 Div 内, 并把 "resizeChild" 属性设为 true(或者指向元素的 ID), <b>或者</b>在配置项中设置 wrap 属性为 true, 元素就会被自动打包了。</p> * <p>下面是有效的拖动柄的值列表:</p> * <pre> 值 说明 ------ ------------------- 'n' 北(north) 's' 南(south) 'e' 东(east) 'w' 西(west) 'nw' 西北(northwest) 'sw' 西南(southwest) 'se' 东北(southeast) 'ne' 东南(northeast) 'all' 所有 </pre> * <p>下面是展示的是创建一个典型的 Resizable 对象的例子:</p> * <pre><code> var resizer = new Ext.Resizable("element-id", { handles: 'all', minWidth: 200, minHeight: 100, maxWidth: 500, maxHeight: 400, pinned: true }); resizer.on("resize", myHandler); </code></pre> * <p>想要隐藏某个缩放柄, 可以将它的CSS样式中的 display 属性设为 none, 或者通过脚本来实现:<br> * resizer.east.setDisplayed(false);</p> * @cfg {Boolean/String/Element} resizeChild 值为 true 时缩放首个子对象, 或者值为 id/element 时缩放指定对象(默认为 false) * @cfg {Array/String} adjustments 可以是字串 "auto" 或者形如 [width, height] 的数组, 其值会在执行缩放操作的时候被<b>加入</b>。(默认为 [0, 0]) * @cfg {Number} minWidth 元素允许的最小宽度(默认为 5) * @cfg {Number} minHeight 元素允许的最小高度(默认为 5) * @cfg {Number} maxWidth 元素允许的最大宽度(默认为 10000) * @cfg {Number} maxHeight 元素允许的最大高度(默认为 10000) * @cfg {Boolean} enabled 设为 false 可禁止缩放(默认为 true) * @cfg {Boolean} wrap 设为 true 则在需要的时候将元素用 div 打包(文本域和图片对象必须设置此属性, 默认为 false) * @cfg {Number} width 以像素表示的元素宽度(默认为 null) * @cfg {Number} height 以像素表示的元素高度(默认为 null) * @cfg {Boolean} animate 设为 true 则在缩放时展示动画效果(不可与 dynamic 同时使用, 默认为 false) * @cfg {Number} duration 当 animate = true 时动画持续的时间(默认为 .35) * @cfg {Boolean} dynamic 设为 true 则对元素进行实时缩放而不使用代理(默认为 false) * @cfg {String} handles 由要显示的缩放柄组成的字串(默认为 undefined) * @cfg {Boolean} multiDirectional <b>Deprecated</b>. 以前的添加多向缩放柄的方式, 建议使用 handles 属性。(默认为 false) * @cfg {Boolean} disableTrackOver 设为 true 则禁止鼠标跟踪。此属性仅在配置对象时可用。(默认为 false) * @cfg {String} easing 指定当 animate = true 时的动画效果(默认为 'easingOutStrong') * @cfg {Number} widthIncrement 以像素表示的宽度缩放增量(dynamic 属性必须为 true, 默认为 0) * @cfg {Number} heightIncrement 以像素表示的高度缩放增量(dynamic 属性必须为 true, 默认为 0) * @cfg {Boolean} pinned 设为 true 则保持缩放柄总是可见, false 则只在用户将鼠标经过 resizable 对象的边框时显示缩放柄。此属性仅在配置对象时可用。(默认为 false) * @cfg {Boolean} preserveRatio 设为 true 则在缩放时保持对象的原始长宽比(默认为 false) * @cfg {Boolean} transparent 设为 true 则将缩放柄设为透明。此属性仅在配置对象时可用。(默认为 false) * @cfg {Number} minX The minimum allowed page X for the element (仅用于向左缩放时, 默认为 0) * @cfg {Number} minY The minimum allowed page Y for the element (仅用于向上缩放时, 默认为 0) * @cfg {Boolean} draggable 便利的初始化拖移的方法(默认为 false) * @constructor * 创建一个 resizable 对象 * @param {Mixed} el 要缩放的对象的 id 或 element 对象 * @param {Object} config 配置项对象 */ Ext.Resizable = function(el, config){ this.el = Ext.get(el); if(config && config.wrap){ config.resizeChild = this.el; this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"}); this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap"; this.el.setStyle("overflow", "hidden"); this.el.setPositioning(config.resizeChild.getPositioning()); config.resizeChild.clearPositioning(); if(!config.width || !config.height){ var csize = config.resizeChild.getSize(); this.el.setSize(csize.width, csize.height); } if(config.pinned && !config.adjustments){ config.adjustments = "auto"; } } this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"}); this.proxy.unselectable(); this.proxy.enableDisplayMode('block'); Ext.apply(this, config); if(this.pinned){ this.disableTrackOver = true; this.el.addClass("x-resizable-pinned"); } // if the element isn't positioned, make it relative var position = this.el.getStyle("position"); if(position != "absolute" && position != "fixed"){ this.el.setStyle("position", "relative"); } if(!this.handles){ // no handles passed, must be legacy style this.handles = 's,e,se'; if(this.multiDirectional){ this.handles += ',n,w'; } } if(this.handles == "all"){ this.handles = "n s e w ne nw se sw"; } var hs = this.handles.split(/\s*?[,;]\s*?| /); var ps = Ext.Resizable.positions; for(var i = 0, len = hs.length; i < len; i++){ if(hs[i] && ps[hs[i]]){ var pos = ps[hs[i]]; this[pos] = new Ext.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent); } } // legacy this.corner = this.southeast; if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1){ this.updateBox = true; } this.activeHandle = null; if(this.resizeChild){ if(typeof this.resizeChild == "boolean"){ this.resizeChild = Ext.get(this.el.dom.firstChild, true); }else{ this.resizeChild = Ext.get(this.resizeChild, true); } } if(this.adjustments == "auto"){ var rc = this.resizeChild; var hw = this.west, he = this.east, hn = this.north, hs = this.south; if(rc && (hw || hn)){ rc.position("relative"); rc.setLeft(hw ? hw.el.getWidth() : 0); rc.setTop(hn ? hn.el.getHeight() : 0); } this.adjustments = [ (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0), (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1 ]; } if(this.draggable){ this.dd = this.dynamic ? this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id}); this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id); } // public events this.addEvents( "beforeresize", "resize" ); if(this.width !== null && this.height !== null){ this.resizeTo(this.width, this.height); }else{ this.updateChildSize(); } if(Ext.isIE){ this.el.dom.style.zoom = 1; } Ext.Resizable.superclass.constructor.call(this); }; Ext.extend(Ext.Resizable, Ext.util.Observable, { resizeChild : false, adjustments : [0, 0], minWidth : 5, minHeight : 5, maxWidth : 10000, maxHeight : 10000, enabled : true, animate : false, duration : .35, dynamic : false, handles : false, multiDirectional : false, disableTrackOver : false, easing : 'easeOutStrong', widthIncrement : 0, heightIncrement : 0, pinned : false, width : null, height : null, preserveRatio : false, transparent: false, minX: 0, minY: 0, draggable: false, /** * @cfg {Mixed} constrainTo 强制缩放到一个指定的元素 */ /** * @cfg {Ext.lib.Region} resizeRegion 强制缩放到一个指定区域 */ /** * @event beforeresize * 在缩放被实施之前触发。设置 enabled 为 false 可以取消缩放。 * @param {Ext.Resizable} this * @param {Ext.EventObject} e mousedown 事件 */ /** * @event resize * 缩放之后触发。 * @param {Ext.Resizable} this * @param {Number} width 新的宽度 * @param {Number} height 新的高度 * @param {Ext.EventObject} e mouseup 事件 */ /** * 执行手动缩放 * @param {Number} width * @param {Number} height */ resizeTo : function(width, height){ this.el.setSize(width, height); this.updateChildSize(); this.fireEvent("resize", this, width, height, null); }, // private startSizing : function(e, handle){ this.fireEvent("beforeresize", this, e); if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler if(!this.overlay){ this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"}, Ext.getBody()); this.overlay.unselectable(); this.overlay.enableDisplayMode("block"); this.overlay.on("mousemove", this.onMouseMove, this); this.overlay.on("mouseup", this.onMouseUp, this); } this.overlay.setStyle("cursor", handle.el.getStyle("cursor")); this.resizing = true; this.startBox = this.el.getBox(); this.startPoint = e.getXY(); this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0], (this.startBox.y + this.startBox.height) - this.startPoint[1]]; this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.overlay.show(); if(this.constrainTo) { var ct = Ext.get(this.constrainTo); this.resizeRegion = ct.getRegion().adjust( ct.getFrameWidth('t'), ct.getFrameWidth('l'), -ct.getFrameWidth('b'), -ct.getFrameWidth('r') ); } this.proxy.setStyle('visibility', 'hidden'); // workaround display none this.proxy.show(); this.proxy.setBox(this.startBox); if(!this.dynamic){ this.proxy.setStyle('visibility', 'visible'); } } }, // private onMouseDown : function(handle, e){ if(this.enabled){ e.stopEvent(); this.activeHandle = handle; this.startSizing(e, handle); } }, // private onMouseUp : function(e){ var size = this.resizeElement(); this.resizing = false; this.handleOut(); this.overlay.hide(); this.proxy.hide(); this.fireEvent("resize", this, size.width, size.height, e); }, // private updateChildSize : function(){ if(this.resizeChild){ var el = this.el; var child = this.resizeChild; var adj = this.adjustments; if(el.dom.offsetWidth){ var b = el.getSize(true); child.setSize(b.width+adj[0], b.height+adj[1]); } // Second call here for IE // The first call enables instant resizing and // the second call corrects scroll bars if they // exist if(Ext.isIE){ setTimeout(function(){ if(el.dom.offsetWidth){ var b = el.getSize(true); child.setSize(b.width+adj[0], b.height+adj[1]); } }, 10); } } }, // private snap : function(value, inc, min){ if(!inc || !value) return value; var newValue = value; var m = value % inc; if(m > 0){ if(m > (inc/2)){ newValue = value + (inc-m); }else{ newValue = value - m; } } return Math.max(min, newValue); }, // private resizeElement : function(){ var box = this.proxy.getBox(); if(this.updateBox){ this.el.setBox(box, false, this.animate, this.duration, null, this.easing); }else{ this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing); } this.updateChildSize(); if(!this.dynamic){ this.proxy.hide(); } return box; }, // private constrain : function(v, diff, m, mx){ if(v - diff < m){ diff = v - m; }else if(v - diff > mx){ diff = mx - v; } return diff; }, // private onMouseMove : function(e){ if(this.enabled){ try{// try catch so if something goes wrong the user doesn't get hung if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) { return; } //var curXY = this.startPoint; var curSize = this.curSize || this.startBox; var x = this.startBox.x, y = this.startBox.y; var ox = x, oy = y; var w = curSize.width, h = curSize.height; var ow = w, oh = h; var mw = this.minWidth, mh = this.minHeight; var mxw = this.maxWidth, mxh = this.maxHeight; var wi = this.widthIncrement; var hi = this.heightIncrement; var eventXY = e.getXY(); var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0])); var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1])); var pos = this.activeHandle.position; switch(pos){ case "east": w += diffX; w = Math.min(Math.max(mw, w), mxw); break; case "south": h += diffY; h = Math.min(Math.max(mh, h), mxh); break; case "southeast": w += diffX; h += diffY; w = Math.min(Math.max(mw, w), mxw); h = Math.min(Math.max(mh, h), mxh); break; case "north": diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; break; case "west": diffX = this.constrain(w, diffX, mw, mxw); x += diffX; w -= diffX; break; case "northeast": w += diffX; w = Math.min(Math.max(mw, w), mxw); diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; break; case "northwest": diffX = this.constrain(w, diffX, mw, mxw); diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; x += diffX; w -= diffX; break; case "southwest": diffX = this.constrain(w, diffX, mw, mxw); h += diffY; h = Math.min(Math.max(mh, h), mxh); x += diffX; w -= diffX; break; } var sw = this.snap(w, wi, mw); var sh = this.snap(h, hi, mh); if(sw != w || sh != h){ switch(pos){ case "northeast": y -= sh - h; break; case "north": y -= sh - h; break; case "southwest": x -= sw - w; break; case "west": x -= sw - w; break; case "northwest": x -= sw - w; y -= sh - h; break; } w = sw; h = sh; } if(this.preserveRatio){ switch(pos){ case "southeast": case "east": h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); w = ow * (h/oh); break; case "south": w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); break; case "northeast": w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); break; case "north": var tw = w; w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); x += (tw - w) / 2; break; case "southwest": h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); var tw = w; w = ow * (h/oh); x += tw - w; break; case "west": var th = h; h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); y += (th - h) / 2; var tw = w; w = ow * (h/oh); x += tw - w; break; case "northwest": var tw = w; var th = h; h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); w = ow * (h/oh); y += th - h; x += tw - w; break; } } this.proxy.setBounds(x, y, w, h); if(this.dynamic){ this.resizeElement(); } }catch(e){} } }, // private handleOver : function(){ if(this.enabled){ this.el.addClass("x-resizable-over"); } }, // private handleOut : function(){ if(!this.resizing){ this.el.removeClass("x-resizable-over"); } }, /** * 返回此组件绑定的 element 对象。 * @return {Ext.Element} */ getEl : function(){ return this.el; }, /** * 返回 resizeChild 属性指定的 element 对象(如果没有则返回 null)。 * @return {Ext.Element} */ getResizeChild : function(){ return this.resizeChild; }, /** * 销毁此 resizable对象。如果元素被打包且 removeEl 属性不为 true 则元素会保留。 * @param {Boolean} removeEl (可选项) 设为 true 则从 DOM 中删除此元素 */ destroy : function(removeEl){ this.proxy.remove(); if(this.overlay){ this.overlay.removeAllListeners(); this.overlay.remove(); } var ps = Ext.Resizable.positions; for(var k in ps){ if(typeof ps[k] != "function" && this[ps[k]]){ var h = this[ps[k]]; h.el.removeAllListeners(); h.el.remove(); } } if(removeEl){ this.el.update(""); this.el.remove(); } }, syncHandleHeight : function(){ var h = this.el.getHeight(true); if(this.west){ this.west.el.setHeight(h); } if(this.east){ this.east.el.setHeight(h); } } }); // private // hash to map config positions to true positions Ext.Resizable.positions = { n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast" }; // private Ext.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){ if(!this.tpl){ // only initialize the template if resizable is used var tpl = Ext.DomHelper.createTemplate( {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"} ); tpl.compile(); Ext.Resizable.Handle.prototype.tpl = tpl; } this.position = pos; this.rz = rz; this.el = this.tpl.append(rz.el.dom, [this.position], true); this.el.unselectable(); if(transparent){ this.el.setOpacity(0); } this.el.on("mousedown", this.onMouseDown, this); if(!disableTrackOver){ this.el.on("mouseover", this.onMouseOver, this); this.el.on("mouseout", this.onMouseOut, this); } }; // private Ext.Resizable.Handle.prototype = { afterResize : function(rz){ // do nothing }, // private onMouseDown : function(e){ this.rz.onMouseDown(this, e); }, // private onMouseOver : function(e){ this.rz.handleOver(this, e); }, // private onMouseOut : function(e){ this.rz.handleOut(this, e); } };
JavaScript
/** * @class Ext.DomHelper * 处理DOM或模板(Templates)的实用类。 * 能以JavaScript较清晰地编写HTML片段(HTML fragments)或DOM。 * 这是一个范例,产生五个子元素的无须列表,追加到当前元素'my-div':<br> <pre><code> var list = dh.append('my-div', { tag: 'ul', cls: 'my-list', children: [ {tag: 'li', id: 'item0', html: 'List Item 0'}, {tag: 'li', id: 'item1', html: 'List Item 1'}, {tag: 'li', id: 'item2', html: 'List Item 2'}, {tag: 'li', id: 'item3', html: 'List Item 3'}, {tag: 'li', id: 'item4', html: 'List Item 4'} ] }); </code></pre> * 更多资讯,请参阅 <a href="http://www.jackslocum.com/yui/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">BLOG和一些例子</a>. * @singleton */ Ext.DomHelper = function(){ var tempTableEl = null; var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i; var tableRe = /^table|tbody|tr|td$/i; // build as innerHTML where available /** @ignore */ var createHtml = function(o){ if(typeof o == 'string'){ return o; } var b = ""; if(!o.tag){ o.tag = "div"; } b += "<" + o.tag; for(var attr in o){ if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue; if(attr == "style"){ var s = o["style"]; if(typeof s == "function"){ s = s.call(); } if(typeof s == "string"){ b += ' style="' + s + '"'; }else if(typeof s == "object"){ b += ' style="'; for(var key in s){ if(typeof s[key] != "function"){ b += key + ":" + s[key] + ";"; } } b += '"'; } }else{ if(attr == "cls"){ b += ' class="' + o["cls"] + '"'; }else if(attr == "htmlFor"){ b += ' for="' + o["htmlFor"] + '"'; }else{ b += " " + attr + '="' + o[attr] + '"'; } } } if(emptyTags.test(o.tag)){ b += "/>"; }else{ b += ">"; var cn = o.children || o.cn; if(cn){ if(cn instanceof Array){ for(var i = 0, len = cn.length; i < len; i++) { b += createHtml(cn[i], b); } }else{ b += createHtml(cn, b); } } if(o.html){ b += o.html; } b += "</" + o.tag + ">"; } return b; }; // build as dom /** @ignore */ var createDom = function(o, parentNode){ var el = document.createElement(o.tag||'div'); var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute for(var attr in o){ if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else{ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } Ext.DomHelper.applyStyles(el, o.style); var cn = o.children || o.cn; if(cn){ if(cn instanceof Array){ for(var i = 0, len = cn.length; i < len; i++) { createDom(cn[i], el); } }else{ createDom(cn, el); } } if(o.html){ el.innerHTML = o.html; } if(parentNode){ parentNode.appendChild(el); } return el; }; var ieTable = function(depth, s, h, e){ tempTableEl.innerHTML = [s, h, e].join(''); var i = -1, el = tempTableEl; while(++i < depth){ el = el.firstChild; } return el; }; // kill repeat to save bytes var ts = '<table>', te = '</table>', tbs = ts+'<tbody>', tbe = '</tbody>'+te, trs = tbs + '<tr>', tre = '</tr>'+tbe; /** * @ignore * Nasty code for IE's broken table implementation */ var insertIntoTable = function(tag, where, el, html){ if(!tempTableEl){ tempTableEl = document.createElement('div'); } var node; var before = null; if(tag == 'td'){ if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD return; } if(where == 'beforebegin'){ before = el; el = el.parentNode; } else{ before = el.nextSibling; el = el.parentNode; } node = ieTable(4, trs, html, tre); } else if(tag == 'tr'){ if(where == 'beforebegin'){ before = el; el = el.parentNode; node = ieTable(3, tbs, html, tbe); } else if(where == 'afterend'){ before = el.nextSibling; el = el.parentNode; node = ieTable(3, tbs, html, tbe); } else{ // INTO a TR if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(4, trs, html, tre); } } else if(tag == 'tbody'){ if(where == 'beforebegin'){ before = el; el = el.parentNode; node = ieTable(2, ts, html, te); } else if(where == 'afterend'){ before = el.nextSibling; el = el.parentNode; node = ieTable(2, ts, html, te); } else{ if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(3, tbs, html, tbe); } } else{ // TABLE if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table return; } if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(2, ts, html, te); } el.insertBefore(node, before); return node; }; return { /** * True表示为强制使用DOM而非html片断 * @type Boolean */ useDom : false, /** * 返回元素的装饰(markup) * @param {Object} o DOM对象(包含子孙) * @return {String} */ markup : function(o){ return createHtml(o); }, /** * 把指定的样式应用到元素 * @param {String/HTMLElement} el 样式所应用的元素 * @param {String/Object/Function} styles 表示样式的特定格式字符串,如“width:100px”,或是对象的形式如{width:"100px"},或是能返回这些格式的函数 */ applyStyles : function(el, styles){ if(styles){ el = Ext.fly(el); if(typeof styles == "string"){ var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi; var matches; while ((matches = re.exec(styles)) != null){ el.setStyle(matches[1], matches[2]); } }else if (typeof styles == "object"){ for (var style in styles){ el.setStyle(style, styles[style]); } }else if (typeof styles == "function"){ Ext.DomHelper.applyStyles(el, styles.call()); } } }, /** * 插入HTML片断到Dom * @param {String} where 插入的html要放在元素的哪里 - beforeBegin, afterBegin, beforeEnd, afterEnd. * @param {HTMLElement} el 元素内容 * @param {String} html HTML片断 * @return {HTMLElement} 新节点 */ insertHtml : function(where, el, html){ where = where.toLowerCase(); if(el.insertAdjacentHTML){ if(tableRe.test(el.tagName)){ var rs; if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){ return rs; } } switch(where){ case "beforebegin": el.insertAdjacentHTML('BeforeBegin', html); return el.previousSibling; case "afterbegin": el.insertAdjacentHTML('AfterBegin', html); return el.firstChild; case "beforeend": el.insertAdjacentHTML('BeforeEnd', html); return el.lastChild; case "afterend": el.insertAdjacentHTML('AfterEnd', html); return el.nextSibling; } throw 'Illegal insertion point -> "' + where + '"'; } var range = el.ownerDocument.createRange(); var frag; switch(where){ case "beforebegin": range.setStartBefore(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el); return el.previousSibling; case "afterbegin": if(el.firstChild){ range.setStartBefore(el.firstChild); frag = range.createContextualFragment(html); el.insertBefore(frag, el.firstChild); return el.firstChild; }else{ el.innerHTML = html; return el.firstChild; } case "beforeend": if(el.lastChild){ range.setStartAfter(el.lastChild); frag = range.createContextualFragment(html); el.appendChild(frag); return el.lastChild; }else{ el.innerHTML = html; return el.lastChild; } case "afterend": range.setStartAfter(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el.nextSibling); return el.nextSibling; } throw 'Illegal insertion point -> "' + where + '"'; }, /** * 创建新的Dom元素并插入到el之前 * @param {String/HTMLElement/Element} el 元素内容 * @param {Object/String} o 指定的Dom对象(和子孙)或是裸HTML部分 * @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element * @return {HTMLElement/Ext.Element} 新节点 */ insertBefore : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "beforeBegin"); }, /** * 创建新的Dom元素并插入到el之后 * @param {String/HTMLElement/Element} el 元素内容 * @param {Object/String} o 指定的Dom对象(和子孙) * @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element * @return {HTMLElement/Ext.Element} 新节点 */ insertAfter : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling"); }, /** * 创建新的Dom元素并插入到el中,元素是第一个孩子。 * @param {String/HTMLElement/Element} el 元素内容 * @param {Object/String} o 指定的Dom对象(和子孙)或是原始的HTML部分 * @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element * @return {HTMLElement/Ext.Element} 新节点 */ insertFirst : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "afterBegin", "firstChild"); }, // private doInsert : function(el, o, returnElement, pos, sibling){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); (sibling === "firstChild" ? el : el.parentNode).insertBefore(newNode, sibling ? el[sibling] : el); }else{ var html = createHtml(o); newNode = this.insertHtml(pos, el, html); } return returnElement ? Ext.get(newNode, true) : newNode; }, /** * 创建新的Dom元素并加入到el中 * @param {String/HTMLElement/Element} el 元素内容 * @param {Object/String} o 指定的Dom对象(和子孙)或是原始的HTML部分 * @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element * @return {HTMLElement/Ext.Element} 新节点 */ append : function(el, o, returnElement){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); el.appendChild(newNode); }else{ var html = createHtml(o); newNode = this.insertHtml("beforeEnd", el, html); } return returnElement ? Ext.get(newNode, true) : newNode; }, /** * 创建新的Dom元素并覆盖el的内容 * @param {String/HTMLElement/Element} el 元素内容 * @param {Object/String} o 指定的Dom对象(和子孙)或是原始的HTML部分 * @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element * @return {HTMLElement/Ext.Element} 新节点 */ overwrite : function(el, o, returnElement){ el = Ext.getDom(el); el.innerHTML = createHtml(o); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; }, /** * 根据指定的Dom对象创建新的Ext.DomHelper.Template对象 * @param {Object} o 指定的Dom对象(连同子孙) * @return {Ext.DomHelper.Template} 新模板 */ createTemplate : function(o){ var html = createHtml(o); return new Ext.Template(html); } }; }();
JavaScript
/** * @class Ext.CompositeElement * 标准的复合类(composite class)。为集合中每个元素创建一个Ext.Element。 * <br><br> * <b>注意:尽管未全部罗列,该类支持全部Ext.Element的set/update方法。 * 集合里面的全部元素都会执行所有的Ext.Element动作。</b> * <br><br> * 所有的方法都返回<i>this</i>所以可写成链式的语法。 <pre><code> var els = Ext.select("#some-el div.some-class", true); //或者是从现有的元素直接选择 var el = Ext.get('some-el'); el.select('div.some-class', true); els.setWidth(100); // 所有的元素变为宽度100 els.hide(true); // 所有的元素渐隐。 // 或 els.setWidth(100).hide(true); </code></pre> */ Ext.CompositeElement = function(els){ this.elements = []; this.addElements(els); }; Ext.CompositeElement.prototype = { isComposite: true, addElements : function(els){ if(!els) return this; if(typeof els == "string"){ els = Ext.Element.selectorFunction(els); } var yels = this.elements; var index = yels.length-1; for(var i = 0, len = els.length; i < len; i++) { yels[++index] = Ext.get(els[i]); } return this; }, /** * 清除该composite,将传入一个选择符的元素加入到composite中。 * @param {String/Array} els CSS选择符,一个或多个元素组成的数组 * @return {CompositeElement} this */ fill : function(els){ this.elements = []; this.add(els); return this; }, /** * 传入一个选择符的参数,若匹配成功,则保存到该composite,其它的就会被过滤 * @param {String} selector CSS选择符字符串 * @return {CompositeElement} this */ filter : function(selector){ var els = []; this.each(function(el){ if(el.is(selector)){ els[els.length] = el.dom; } }); this.fill(els); return this; }, invoke : function(fn, args){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++) { Ext.Element.prototype[fn].apply(els[i], args); } return this; }, /** * 加入元素到这个composite. * @param {String/Array} els CSS选择符,一个或多个元素组成的数组 * @return {CompositeElement} this */ add : function(els){ if(typeof els == "string"){ this.addElements(Ext.Element.selectorFunction(els)); }else if(els.length !== undefined){ this.addElements(els); }else{ this.addElements([els]); } return this; }, /** * 传入一个Function类型的参数,在这个composite中每个元素中执行Function(带参数el, this, index)。 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的) <i>this</i> 指向的对象(默认为element) * @return {CompositeElement} this */ each : function(fn, scope){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++){ if(fn.call(scope || els[i], els[i], this, i) === false) { break; } } return this; }, /** * 根据指定的索引返回元素对象 * @param {Number} index * @return {Ext.Element} */ item : function(index){ return this.elements[index] || null; }, /** * 返回第一个元素 * @return {Ext.Element} */ first : function(){ return this.item(0); }, /** * 返回最后的元素 * @return {Ext.Element} */ last : function(){ return this.item(this.elements.length-1); }, /** * 返回该composite的元素的总数 * @return Number */ getCount : function(){ return this.elements.length; }, /** * 传入一个元素的参数,如果该composite里面有的话返回true * @return Boolean */ contains : function(el){ return this.indexOf(el) !== -1; }, /** * 传入一个元素的参数,返回元素第一次出现的位置。 * @return Boolean */ indexOf : function(el){ return this.elements.indexOf(Ext.get(el)); }, /** * 移除指定的元素。 * @param {Mixed} el 元素的ID,或是元素本身,也可以是该composite中的元素索引(Number类型),或是以上类型组成的数组。 * @param {Boolean} removeDom (可选的) True表示为DOM文档中的元素一并删除 * @return {CompositeElement} this */ removeElement : function(el, removeDom){ if(el instanceof Array){ for(var i = 0, len = el.length; i < len; i++){ this.removeElement(el[i]); } return this; } var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1 && this.elements[index]){ if(removeDom){ var d = this.elements[index]; if(d.dom){ d.remove(); }else{ Ext.removeNode(d); } } this.elements.splice(index, 1); } return this; }, /** * 传入一个元素,替换指定的元素。 * @param {Mixed} el 元素的ID,或是元素本身,也可以是该composite中的元素索引(Number类型),或是以上类型组成的数组。 * @param {String/HTMLElement/Element} replacement 元素的ID,或是元素本身 * @param {Boolean} removeDom (可选的) True表示为DOM文档中的元素一并删除 * @return {CompositeElement} this */ replaceElement : function(el, replacement, domReplace){ var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1){ if(domReplace){ this.elements[index].replaceWith(replacement); }else{ this.elements.splice(index, 1, Ext.get(replacement)) } } return this; }, /** * 移除所有元素。 */ clear : function(){ this.elements = []; } }; (function(){ Ext.CompositeElement.createCall = function(proto, fnName){ if(!proto[fnName]){ proto[fnName] = function(){ return this.invoke(fnName, arguments); }; } }; for(var fnName in Ext.Element.prototype){ if(typeof Ext.Element.prototype[fnName] == "function"){ Ext.CompositeElement.createCall(Ext.CompositeElement.prototype, fnName); } }; })();
JavaScript
//Notifies Element that fx methods are available Ext.enableFx = true; /** * @class Ext.Fx * <p>这是一个提供基础动画和视觉效果支持的类。<b>注意:</b>此类被引用后会自动应用于 {@link Ext.Element} 的接口, * 因此所有的效果必须通过 Element 对象来实现。反过来说,既然 Element 对象实际上并没有定义这些效果, * Ext.Fx 类<b>必须</b>被 Element 对象引用后才能使那些效果生效。</p><br/> * * <p>值得注意的是,虽然 Fx 的方法和许多非 Fx Element 对象的方法支持“方法链”,即他们返回 Element 对象本身作为方法的返回值, * 但是并非每次都能将两个对象混合在一个方法链中。Fx 的方法使用一个内部的效果队列以使每个效果能够在适当的时候按次序展现。 * 另一方面,对于非 Fx 的方法则没有这样的一个内部队列,它们总是立即生效。正因为如此,虽然可以在一个单链中混合调用 Fx 和非 Fx 的方法, * 但是并非总能得到预期的结果,而且必须小心处理类似的情况。</p><br/> * * <p>移动类的效果支持8个方向的定位锚,这意味着你可以选择 Element 对象所有8个不同的锚点中的任意一个来作为动画的起点或终点。 * 下面是所有支持的定位锚点位置:</p> <pre> 值 说明 ----- ----------------------------- tl 左上角 t 顶部中央 tr 右上角 l 左边中央 r 右边中央 bl 左下角 b 底部中央 br 右下角 </pre> * <b>尽管某些 Fx 方法可以接受特殊的自定义配置参数,然而下面的配置选项区域内显示了可供所有 Fx 方法使用的公共选项。</b> * @cfg {Function} callback 指定当效果完成时调用的函数 * @cfg {Object} scope 特效函数的作用域 * @cfg {String} easing 指定特效函数使用的合法的 Easing 值 * @cfg {String} afterCls 特效完成后应用的CSS样式类 * @cfg {Number} duration 以秒为单位设置的特效持续时间 * @cfg {Boolean} remove 特效完成后是否从 DOM 树中完全删除 Element 对象 * @cfg {Boolean} useDisplay 隐藏 Element 对象时是否使用 <i>display</i> CSS样式属性替代 <i>visibility</i>属性(仅仅应用于那些结束后隐藏 Element 对象的等效,其他的等效无效) * @cfg {String/Object/Function} afterStyle 特效完成后应用于 Element 对象的指定样式的字符串,例如:"width:100px",或者形如 {width:"100px"} 的对象,或者返回值为类似形式的函数 * @cfg {Boolean} block 当特效生效时是否阻塞队列中的其他特效 * @cfg {Boolean} concurrent 是否允许特效与队列中的下一个特效并行生效,或者确保他们在运行队列中 * @cfg {Boolean} stopFx 是否在当前特效完成后停止并删除后续(并发)的特效 */ Ext.Fx = { /** * 将元素滑入到视图中。作为可选参数传入的定位锚点将被设置为滑入特效的起始点。该函数会在需要的时候自动将元素与一个固定尺寸的容器封装起来。 * 有效的定位锚点可以参见 Fx 类的概述。 * 用法: *<pre><code> // 默认情况:将元素从顶部滑入 el.slideIn(); // 自定义:在2秒钟内将元素从右边滑入 el.slideIn('r', { duration: 2 }); // 常见的配置选项及默认值 el.slideIn('t', { easing: 'easeOut', duration: .5 }); </code></pre> * @param {String} anchor (可选)有效的 Fx 定位锚点之一(默认为顶部:'t') * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ slideIn : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "t"; // fix display to visibility this.fixDisplay(); // restore values after effect var r = this.getFxRestore(); var b = this.getBox(); // fixed size for slide this.setSize(b); // wrap if needed var wrap = this.fxWrap(r.pos, o, "hidden"); var st = this.dom.style; st.visibility = "visible"; st.position = "absolute"; // clear out temp styles after slide and unwrap var after = function(){ el.fxUnwrap(wrap, r.pos, o); st.width = r.width; st.height = r.height; el.afterFx(o); }; // time to calc the positions var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height}; switch(anchor.toLowerCase()){ case "t": wrap.setSize(b.width, 0); st.left = st.bottom = "0"; a = {height: bh}; break; case "l": wrap.setSize(0, b.height); st.right = st.top = "0"; a = {width: bw}; break; case "r": wrap.setSize(0, b.height); wrap.setX(b.right); st.left = st.top = "0"; a = {width: bw, points: pt}; break; case "b": wrap.setSize(b.width, 0); wrap.setY(b.bottom); st.left = st.top = "0"; a = {height: bh, points: pt}; break; case "tl": wrap.setSize(0, 0); st.right = st.bottom = "0"; a = {width: bw, height: bh}; break; case "bl": wrap.setSize(0, 0); wrap.setY(b.y+b.height); st.right = st.top = "0"; a = {width: bw, height: bh, points: pt}; break; case "br": wrap.setSize(0, 0); wrap.setXY([b.right, b.bottom]); st.left = st.top = "0"; a = {width: bw, height: bh, points: pt}; break; case "tr": wrap.setSize(0, 0); wrap.setX(b.x+b.width); st.left = st.bottom = "0"; a = {width: bw, height: bh, points: pt}; break; } this.dom.style.visibility = "visible"; wrap.show(); arguments.callee.anim = wrap.fxanim(a, o, 'motion', .5, 'easeOut', after); }); return this; }, /** * 将元素从视图中滑出。作为可选参数传入的定位锚点将被设置为滑出特效的结束点。特效结束后,元素会被隐藏(visibility = 'hidden'), * 但是块元素仍然会在 document 对象中占据空间。如果需要将元素从 DOM 树删除,则使用'remove'配置选项。 * 该函数会在需要的时候自动将元素与一个固定尺寸的容器封装起来。有效的定位锚点可以参见 Fx 类的概述。 * 用法: *<pre><code> // 默认情况:将元素从顶部滑出 el.slideOut(); // 自定义:在2秒钟内将元素从右边滑出 el.slideOut('r', { duration: 2 }); // 常见的配置选项及默认值 el.slideOut('t', { easing: 'easeOut', duration: .5, remove: false, useDisplay: false }); </code></pre> * @param {String} anchor (可选)有效的 Fx 定位锚点之一(默认为顶部:'t') * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ slideOut : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "t"; // restore values after effect var r = this.getFxRestore(); var b = this.getBox(); // fixed size for slide this.setSize(b); // wrap if needed var wrap = this.fxWrap(r.pos, o, "visible"); var st = this.dom.style; st.visibility = "visible"; st.position = "absolute"; wrap.setSize(b); var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.fxUnwrap(wrap, r.pos, o); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a, zero = {to: 0}; switch(anchor.toLowerCase()){ case "t": st.left = st.bottom = "0"; a = {height: zero}; break; case "l": st.right = st.top = "0"; a = {width: zero}; break; case "r": st.left = st.top = "0"; a = {width: zero, points: {to:[b.right, b.y]}}; break; case "b": st.left = st.top = "0"; a = {height: zero, points: {to:[b.x, b.bottom]}}; break; case "tl": st.right = st.bottom = "0"; a = {width: zero, height: zero}; break; case "bl": st.right = st.top = "0"; a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}}; break; case "br": st.left = st.top = "0"; a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}}; break; case "tr": st.left = st.bottom = "0"; a = {width: zero, height: zero, points: {to:[b.right, b.y]}}; break; } arguments.callee.anim = wrap.fxanim(a, o, 'motion', .5, "easeOut", after); }); return this; }, /** * 渐隐元素的同时还伴随着向各个方向缓慢地展开。特效结束后,元素会被隐藏(visibility = 'hidden'), * 但是块元素仍然会在 document 对象中占据空间。如果需要将元素从 DOM 树删除,则使用'remove'配置选项。 * 用法: *<pre><code> // 默认 el.puff(); // 常见的配置选项及默认值 el.puff({ easing: 'easeOut', duration: .5, remove: false, useDisplay: false }); </code></pre> * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ puff : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.clearOpacity(); this.show(); // restore values after effect var r = this.getFxRestore(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; st.fontSize = ''; el.afterFx(o); }; var width = this.getWidth(); var height = this.getHeight(); arguments.callee.anim = this.fxanim({ width : {to: this.adjustWidth(width * 2)}, height : {to: this.adjustHeight(height * 2)}, points : {by: [-(width * .5), -(height * .5)]}, opacity : {to: 0}, fontSize: {to:200, unit: "%"} }, o, 'motion', .5, "easeOut", after); }); return this; }, /** * 类似单击过后般地闪烁一下元素,然后从元素的中间开始收缩(类似于关闭电视机时的效果)。 * 特效结束后,元素会被隐藏(visibility = 'hidden'),但是块元素仍然会在 document 对象中占据空间。 * 如果需要将元素从 DOM 树删除,则使用'remove'配置选项。 * 用法: *<pre><code> // 默认 el.switchOff(); // 所有的配置选项及默认值 el.switchOff({ easing: 'easeIn', duration: .3, remove: false, useDisplay: false }); </code></pre> * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ switchOff : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.clearOpacity(); this.clip(); // restore values after effect var r = this.getFxRestore(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; el.afterFx(o); }; this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){ this.clearOpacity(); (function(){ this.fxanim({ height:{to:1}, points:{by:[0, this.getHeight() * .5]} }, o, 'motion', 0.3, 'easeIn', after); }).defer(100, this); }); }); return this; }, /** * 根据设置的颜色高亮显示 Element 对象(默认情况下应用于 background-color 属性,但是也可以通过"attr"配置选项来改变), * 然后渐隐为原始颜色。如果原始颜色不可用,你应该设置"endColor"配置选项以免动画结束后被清除。 * 用法: <pre><code> // 默认情况:高亮显示的背景颜色为黄色 el.highlight(); // 自定义:高亮显示前景字符颜色为蓝色并持续2秒 el.highlight("0000ff", { attr: 'color', duration: 2 }); // 常见的配置选项及默认值 el.highlight("ffff9c", { attr: "background-color", //可以是任何能够把值设置成颜色代码的 CSS 属性 endColor: (current color) or "ffffff", easing: 'easeIn', duration: 1 }); </code></pre> * @param {String} color (可选)高亮颜色。必须为不以 # 开头的6位16进制字符(默认为黄色:'ffff9c') * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ highlight : function(color, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ color = color || "ffff9c"; var attr = o.attr || "backgroundColor"; this.clearOpacity(); this.show(); var origColor = this.getColor(attr); var restoreColor = this.dom.style[attr]; var endColor = (o.endColor || origColor) || "ffffff"; var after = function(){ el.dom.style[attr] = restoreColor; el.afterFx(o); }; var a = {}; a[attr] = {from: color, to: endColor}; arguments.callee.anim = this.fxanim(a, o, 'color', 1, 'easeIn', after); }); return this; }, /** * 展示一个展开的波纹,伴随着渐隐的边框以突出显示 Element 对象。 * 用法: <pre><code> // 默认情况:一个淡蓝色的波纹 el.frame(); // 自定义:三个红色的波纹并持续3秒 el.frame("ff0000", 3, { duration: 3 }); // 常见的配置选项及默认值 el.frame("C3DAF9", 1, { duration: 1 //整个动画持续的时间(不是每个波纹持续的时间) // 注意:这里不能使用 Easing 选项在,即使被包含了也会被忽略 }); </code></pre> * @param {String} color (可选)边框的颜色。必须为不以 # 开头的6位16进制字符(默认为淡蓝色色:'C3DAF9') * @param {Number} count (可选)要显示的波纹的个数(默认为1) * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ frame : function(color, count, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ color = color || "#C3DAF9"; if(color.length == 6){ color = "#" + color; } count = count || 1; var duration = o.duration || 1; this.show(); var b = this.getBox(); var animFn = function(){ var proxy = Ext.getBody().createChild({ style:{ visbility:"hidden", position:"absolute", "z-index":"35000", // yee haw border:"0px solid " + color } }); var scale = Ext.isBorderBox ? 2 : 1; proxy.animate({ top:{from:b.y, to:b.y - 20}, left:{from:b.x, to:b.x - 20}, borderWidth:{from:0, to:10}, opacity:{from:1, to:0}, height:{from:b.height, to:(b.height + (20*scale))}, width:{from:b.width, to:(b.width + (20*scale))} }, duration, function(){ proxy.remove(); if(--count > 0){ animFn(); }else{ el.afterFx(o); } }); }; animFn.call(this); }); return this; }, /** * 在任何后续的等效开始之前创建一次暂停。如果队列中没有后续特效则没有效果。 * 用法: <pre><code> el.pause(1); </code></pre> * @param {Number} seconds 以秒为单位的暂停时间 * @return {Ext.Element} Element 对象 */ pause : function(seconds){ var el = this.getFxEl(); var o = {}; el.queueFx(o, function(){ setTimeout(function(){ el.afterFx(o); }, seconds * 1000); }); return this; }, /** * 将元素从透明渐变为不透明。结束时的透明度可以根据"endOpacity"选项来指定。 * 用法: <pre><code> // 默认情况:将可见度由 0 渐变到 100% el.fadeIn(); // 自定义:在2秒钟之内将可见度由 0 渐变到 75% el.fadeIn({ endOpacity: .75, duration: 2}); // 常见的配置选项及默认值 el.fadeIn({ endOpacity: 1, //可以是 0 到 1 之前的任意值(例如:.5) easing: 'easeOut', duration: .5 }); </code></pre> * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ fadeIn : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.setOpacity(0); this.fixDisplay(); this.dom.style.visibility = 'visible'; var to = o.endOpacity || 1; arguments.callee.anim = this.fxanim({opacity:{to:to}}, o, null, .5, "easeOut", function(){ if(to == 1){ this.clearOpacity(); } el.afterFx(o); }); }); return this; }, /** * 将元素从不透明渐变为透明。结束时的透明度可以根据"endOpacity"选项来指定。 * 用法: <pre><code> // 默认情况:将元素的可见度由当前值渐变到 0 el.fadeOut(); // 自定义:在2秒钟内将元素的可见度由当前值渐变到 25% el.fadeOut({ endOpacity: .25, duration: 2}); // 常见的配置选项及默认值 el.fadeOut({ endOpacity: 0, 可以是 0 到 1 之前的任意值(例如:.5) easing: 'easeOut', duration: .5 remove: false, useDisplay: false }); </code></pre> * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ fadeOut : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}}, o, null, .5, "easeOut", function(){ if(this.visibilityMode == Ext.Element.DISPLAY || o.useDisplay){ this.dom.style.display = "none"; }else{ this.dom.style.visibility = "hidden"; } this.clearOpacity(); el.afterFx(o); }); }); return this; }, /** * 以动画展示元素从开始的高度/宽度转换到结束的高度/宽度。 * 用法: <pre><code> // 将宽度和高度设置为 100x100 象素 el.scale(100, 100); // 常见的配置选项及默认值。如果给定值为 null,则高度和宽度默认被设置为元素已有的值。 el.scale( [element's width], [element's height], { easing: 'easeOut', duration: .35 }); </code></pre> * @param {Number} width 新的宽度(传递 undefined 则保持原始宽度) * @param {Number} height 新的高度(传递 undefined 则保持原始高度) * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ scale : function(w, h, o){ this.shift(Ext.apply({}, o, { width: w, height: h })); return this; }, /** * 以动画展示元素任意组合属性的改变,如元素的尺寸、位置坐标和(或)透明度。 * 如果以上属性中的任意一个没有在配置选项对象中指定则该属性不会发生改变。 * 为了使该特效生效,则必须在配置选项对象中设置至少一个新的尺寸、位置坐标或透明度属性。 * 用法: <pre><code> // 将元素水平地滑动到X坐标值为200的位置,同时还伴随着高度和透明度的改变 el.shift({ x: 200, height: 50, opacity: .8 }); // 常见的配置选项及默认值。 el.shift({ width: [element's width], height: [element's height], x: [element's x position], y: [element's y position], opacity: [element's opacity], easing: 'easeOut', duration: .35 }); </code></pre> * @param {Object} options 由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ shift : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity; if(w !== undefined){ a.width = {to: this.adjustWidth(w)}; } if(h !== undefined){ a.height = {to: this.adjustHeight(h)}; } if(x !== undefined || y !== undefined){ a.points = {to: [ x !== undefined ? x : this.getX(), y !== undefined ? y : this.getY() ]}; } if(op !== undefined){ a.opacity = {to: op}; } if(o.xy !== undefined){ a.points = {to: o.xy}; } arguments.callee.anim = this.fxanim(a, o, 'motion', .35, "easeOut", function(){ el.afterFx(o); }); }); return this; }, /** * 将元素从视图滑出并伴随着渐隐。作为可选参数传入的定位锚点将被设置为滑出特效的结束点。 * 用法: *<pre><code> // 默认情况:将元素向下方滑出并渐隐 el.ghost(); // 自定义:在2秒钟内将元素向右边滑出并渐隐 el.ghost('r', { duration: 2 }); // 常见的配置选项及默认值。 el.ghost('b', { easing: 'easeOut', duration: .5 remove: false, useDisplay: false }); </code></pre> * @param {String} anchor (可选)有效的 Fx 定位锚点之一(默认为底部:'b') * @param {Object} options (可选)由任何 Fx 的配置选项构成的对象 * @return {Ext.Element} Element 对象 */ ghost : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "b"; // restore values after effect var r = this.getFxRestore(); var w = this.getWidth(), h = this.getHeight(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a = {opacity: {to: 0}, points: {}}, pt = a.points; switch(anchor.toLowerCase()){ case "t": pt.by = [0, -h]; break; case "l": pt.by = [-w, 0]; break; case "r": pt.by = [w, 0]; break; case "b": pt.by = [0, h]; break; case "tl": pt.by = [-w, -h]; break; case "bl": pt.by = [-w, h]; break; case "br": pt.by = [w, h]; break; case "tr": pt.by = [w, -h]; break; } arguments.callee.anim = this.fxanim(a, o, 'motion', .5, "easeOut", after); }); return this; }, /** * 确保元素调用 syncFx 方法之后所有队列中的特效并发运行。它与 {@link #sequenceFx} 的作用是相反的。 * @return {Ext.Element} Element 对象 */ syncFx : function(){ this.fxDefaults = Ext.apply(this.fxDefaults || {}, { block : false, concurrent : true, stopFx : false }); return this; }, /** * 确保元素调用 sequenceFx 方法之后所有队列中的特效依次运行。它与 {@link #syncFx} 的作用是相反的。 * @return {Ext.Element} Element 对象 */ sequenceFx : function(){ this.fxDefaults = Ext.apply(this.fxDefaults || {}, { block : false, concurrent : false, stopFx : false }); return this; }, /* @private */ nextFx : function(){ var ef = this.fxQueue[0]; if(ef){ ef.call(this); } }, /** * 当元素拥有任何活动的或队列中的特效时返回 true,否则返回 false。 * @return {Boolean} 如果元素拥有特效为 true,否则为 false。 */ hasActiveFx : function(){ return this.fxQueue && this.fxQueue[0]; }, /** * 停止运行中的任何特效,如果元素的内部特效队列中还包含其他尚未开始的特效也一并清除。 * @return {Ext.Element} Element 对象 */ stopFx : function(){ if(this.hasActiveFx()){ var cur = this.fxQueue[0]; if(cur && cur.anim && cur.anim.isAnimated()){ this.fxQueue = [cur]; // clear out others cur.anim.stop(true); } } return this; }, /* @private */ beforeFx : function(o){ if(this.hasActiveFx() && !o.concurrent){ if(o.stopFx){ this.stopFx(); return true; } return false; } return true; }, /** * 如果元素的当前特效阻塞了特效队列以致于在当前特效完成前其他特效无法排队,则返回 true。如果元素没有阻塞队列则返回 false。 * 此方法一般用于保证由用户动作启动的特效在相同的特效重新启动之前能够顺利完成(例如:即使用户点击了很多次也只触发一个效果)。 * @return {Boolean} 如果阻塞返回 true,否则返回 false。 */ hasFxBlock : function(){ var q = this.fxQueue; return q && q[0] && q[0].block; }, /* @private */ queueFx : function(o, fn){ if(!this.fxQueue){ this.fxQueue = []; } if(!this.hasFxBlock()){ Ext.applyIf(o, this.fxDefaults); if(!o.concurrent){ var run = this.beforeFx(o); fn.block = o.block; this.fxQueue.push(fn); if(run){ this.nextFx(); } }else{ fn.call(this); } } return this; }, /* @private */ fxWrap : function(pos, o, vis){ var wrap; if(!o.wrap || !(wrap = Ext.get(o.wrap))){ var wrapXY; if(o.fixPosition){ wrapXY = this.getXY(); } var div = document.createElement("div"); div.style.visibility = vis; wrap = Ext.get(this.dom.parentNode.insertBefore(div, this.dom)); wrap.setPositioning(pos); if(wrap.getStyle("position") == "static"){ wrap.position("relative"); } this.clearPositioning('auto'); wrap.clip(); wrap.dom.appendChild(this.dom); if(wrapXY){ wrap.setXY(wrapXY); } } return wrap; }, /* @private */ fxUnwrap : function(wrap, pos, o){ this.clearPositioning(); this.setPositioning(pos); if(!o.wrap){ wrap.dom.parentNode.insertBefore(this.dom, wrap.dom); wrap.remove(); } }, /* @private */ getFxRestore : function(){ var st = this.dom.style; return {pos: this.getPositioning(), width: st.width, height : st.height}; }, /* @private */ afterFx : function(o){ if(o.afterStyle){ this.applyStyles(o.afterStyle); } if(o.afterCls){ this.addClass(o.afterCls); } if(o.remove === true){ this.remove(); } Ext.callback(o.callback, o.scope, [this]); if(!o.concurrent){ this.fxQueue.shift(); this.nextFx(); } }, /* @private */ getFxEl : function(){ // support for composite element fx return Ext.get(this.dom); }, /* @private */ fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); }, this ); opt.anim = anim; return anim; } }; //向后兼容 Ext.Fx.resize = Ext.Fx.scale; //被引用后,Ext.Fx 自动应用到 Element 对象,以便所有基础特效可以通过 Element API 直接使用 Ext.apply(Ext.Element.prototype, Ext.Fx);
JavaScript
/* * This is code is also distributed under MIT license for use * with jQuery and prototype JavaScript libraries. * 本代码与 jQuery、prototype JavaScript 类库同样遵循 MIT 授权协议发布与使用。 */ /** * @class Ext.DomQuery 根据编译请求提供高效的将选择符 / xpath 处理为可复用的函数的方法。可以添加新的伪类和匹配器。该类可以运行于 HTML 和 XML 文档之上(如果给出了一个内容节点)。 <p> DomQuery 提供大多数的<a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 选择符</a>,同时也支持某些自定义选择符和基本的 XPath。</p> <p> 下列所有的选择符、属性过滤器和伪类可以在任何命令中无限地组合使用。例如:“div.foo:nth-child(odd)[@foo=bar].bar:first”将是一个完全有效的选择符。命令中出现的节点过滤器将可以使你根据自己的文档结构对查询做出优化。 </p> <h4>元素选择符:</h4> <ul class="list"> <li> <b>*</b> 任意元素</li> <li> <b>E</b> 一个标签为 E 的元素</li> <li> <b>E F</b> 所有 E 元素的分支元素中含有标签为 F 的元素</li> <li> <b>E > F</b> 或 <b>E/F</b> 所有 E 元素的直系子元素中含有标签为 F 的元素</li> <li> <b>E + F</b> 所有标签为 F 并紧随着标签为 E 的元素之后的元素</li> <li> <b>E ~ F</b> 所有标签为 F 并与标签为 E 的元素是侧边的元素</li> </ul> <h4>属性选择符:</h4> <p>@ 与引号的使用是可选的。例如:div[@foo='bar'] 也是一个有效的属性选择符。</p> <ul class="list"> <li> <b>E[foo]</b> 拥有一个名为 “foo” 的属性</li> <li> <b>E[foo=bar]</b> 拥有一个名为 “foo” 且值为 “bar” 的属性</li> <li> <b>E[foo^=bar]</b> 拥有一个名为 “foo” 且值以 “bar” 开头的属性</li> <li> <b>E[foo$=bar]</b> 拥有一个名为 “foo” 且值以 “bar” 结尾的属性</li> <li> <b>E[foo*=bar]</b> 拥有一个名为 “foo” 且值包含字串 “bar” 的属性</li> <li> <b>E[foo%=2]</b> 拥有一个名为 “foo” 且值能够被2整除的属性</li> <li> <b>E[foo!=bar]</b> 拥有一个名为 “foo” 且值不为 “bar” 的属性</li> </ul> <h4>Pseudo Classes:</h4> <h4>伪类:</h4> <ul class="list"> <li> <b>E:first-child</b> E 元素为其父元素的第一个子元素</li> <li> <b>E:last-child</b> E 元素为其父元素的最后一个子元素</li> <li> <b>E:nth-child(<i>n</i>)</b> E 元素为其父元素的第 <i>n</i> 个子元素(由1开始的个数)</li> <li> <b>E:nth-child(odd)</b> E 元素为其父元素的奇数个数的子元素</li> <li> <b>E:nth-child(even)</b> E 元素为其父元素的偶数个数的子元素</li> <li> <b>E:only-child</b> E 元素为其父元素的唯一子元素</li> <li> <b>E:checked</b> E 元素为拥有一个名为“checked”且值为“true”的元素(例如:单选框或复选框)</li> <li> <b>E:first</b> 结果集中第一个 E 元素</li> <li> <b>E:last</b> 结果集中最后一个 E 元素</li> <li> <b>E:nth(<i>n</i>)</b> 结果集中第 <i>n</i> 个 E 元素(由1开始的个数)</li> <li> <b>E:odd</b> :nth-child(odd) 的简写</li> <li> <b>E:even</b> :nth-child(even) 的简写</li> <li> <b>E:contains(foo)</b> E 元素的 innerHTML 属性中包含“foo”字串</li> <li> <b>E:nodeValue(foo)</b> E 元素包含一个 textNode 节点且 nodeValue 等于“foo”</li> <li> <b>E:not(S)</b> 一个与简单选择符 S 不匹配的 E 元素</li> <li> <b>E:has(S)</b> 一个包含与简单选择符 S 相匹配的分支元素的 E 元素</li> <li> <b>E:next(S)</b> 下一个侧边元素为与简单选择符 S 相匹配的 E 元素</li> <li> <b>E:prev(S)</b> 上一个侧边元素为与简单选择符 S 相匹配的 E 元素</li> </ul> <h4>CSS 值选择符:</h4> <ul class="list"> <li> <b>E{display=none}</b> css 的“display”属性等于“none”</li> <li> <b>E{display^=none}</b> css 的“display”属性以“none”开始</li> <li> <b>E{display$=none}</b> css 的“display”属性以“none”结尾</li> <li> <b>E{display*=none}</b> css 的“display”属性包含字串“none”</li> <li> <b>E{display%=2}</b> css 的“display”属性能够被2整除</li> <li> <b>E{display!=none}</b> css 的“display”属性不等于“none”</li> </ul> * @singleton */ Ext.DomQuery = function(){ var cache = {}, simpleCache = {}, valueCache = {}; var nonSpace = /\S/; var trimRe = /^\s+|\s+$/g; var tplRe = /\{(\d+)\}/g; var modeRe = /^(\s?[\/>+~]\s?|\s|$)/; var tagTokenRe = /^(#)?([\w-\*]+)/; var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/; function child(p, index){ var i = 0; var n = p.firstChild; while(n){ if(n.nodeType == 1){ if(++i == index){ return n; } } n = n.nextSibling; } return null; }; function next(n){ while((n = n.nextSibling) && n.nodeType != 1); return n; }; function prev(n){ while((n = n.previousSibling) && n.nodeType != 1); return n; }; function children(d){ var n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } return this; }; function byClassName(c, a, v){ if(!v){ return c; } var r = [], ri = -1, cn; for(var i = 0, ci; ci = c[i]; i++){ if((' '+ci.className+' ').indexOf(v) != -1){ r[++ri] = ci; } } return r; }; function attrValue(n, attr){ if(!n.tagName && typeof n.length != "undefined"){ n = n[0]; } if(!n){ return null; } if(attr == "for"){ return n.htmlFor; } if(attr == "class" || attr == "className"){ return n.className; } return n.getAttribute(attr) || n[attr]; }; function getNodes(ns, mode, tagName){ var result = [], ri = -1, cs; if(!ns){ return result; } tagName = tagName || "*"; if(typeof ns.getElementsByTagName != "undefined"){ ns = [ns]; } if(!mode){ for(var i = 0, ni; ni = ns[i]; i++){ cs = ni.getElementsByTagName(tagName); for(var j = 0, ci; ci = cs[j]; j++){ result[++ri] = ci; } } }else if(mode == "/" || mode == ">"){ var utag = tagName.toUpperCase(); for(var i = 0, ni, cn; ni = ns[i]; i++){ cn = ni.children || ni.childNodes; for(var j = 0, cj; cj = cn[j]; j++){ if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ result[++ri] = cj; } } } }else if(mode == "+"){ var utag = tagName.toUpperCase(); for(var i = 0, n; n = ns[i]; i++){ while((n = n.nextSibling) && n.nodeType != 1); if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){ result[++ri] = n; } } }else if(mode == "~"){ for(var i = 0, n; n = ns[i]; i++){ while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName))); if(n){ result[++ri] = n; } } } return result; }; function concat(a, b){ if(b.slice){ return a.concat(b); } for(var i = 0, l = b.length; i < l; i++){ a[a.length] = b[i]; } return a; } function byTag(cs, tagName){ if(cs.tagName || cs == document){ cs = [cs]; } if(!tagName){ return cs; } var r = [], ri = -1; tagName = tagName.toLowerCase(); for(var i = 0, ci; ci = cs[i]; i++){ if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){ r[++ri] = ci; } } return r; }; function byId(cs, attr, id){ if(cs.tagName || cs == document){ cs = [cs]; } if(!id){ return cs; } var r = [], ri = -1; for(var i = 0,ci; ci = cs[i]; i++){ if(ci && ci.id == id){ r[++ri] = ci; return r; } } return r; }; function byAttribute(cs, attr, value, op, custom){ var r = [], ri = -1, st = custom=="{"; var f = Ext.DomQuery.operators[op]; for(var i = 0, ci; ci = cs[i]; i++){ var a; if(st){ a = Ext.DomQuery.getStyle(ci, attr); } else if(attr == "class" || attr == "className"){ a = ci.className; }else if(attr == "for"){ a = ci.htmlFor; }else if(attr == "href"){ a = ci.getAttribute("href", 2); }else{ a = ci.getAttribute(attr); } if((f && f(a, value)) || (!f && a)){ r[++ri] = ci; } } return r; }; function byPseudo(cs, name, value){ return Ext.DomQuery.pseudos[name](cs, value); }; // This is for IE MSXML which does not support expandos. // 此处用于兼容不支持扩展的 IE MSXML。 // IE runs the same speed using setAttribute, however FF slows way down // and Safari completely fails so they need to continue to use expandos. // IE 在运行 setAttribute 方法时速度相同,可是 FF 则要慢一些,而 Safari // 完全无法运行,所以他们只能继续使用扩展。 var isIE = window.ActiveXObject ? true : false; // this eval is stop the compressor from // renaming the variable to something shorter // 此处的 eval 用来阻止压缩程序将变量名变得更短 eval("var batch = 30803;"); var key = 30803; function nodupIEXml(cs){ var d = ++key; cs[0].setAttribute("_nodup", d); var r = [cs[0]]; for(var i = 1, len = cs.length; i < len; i++){ var c = cs[i]; if(!c.getAttribute("_nodup") != d){ c.setAttribute("_nodup", d); r[r.length] = c; } } for(var i = 0, len = cs.length; i < len; i++){ cs[i].removeAttribute("_nodup"); } return r; } function nodup(cs){ if(!cs){ return []; } var len = cs.length, c, i, r = cs, cj, ri = -1; if(!len || typeof cs.nodeType != "undefined" || len == 1){ return cs; } if(isIE && typeof cs[0].selectSingleNode != "undefined"){ return nodupIEXml(cs); } var d = ++key; cs[0]._nodup = d; for(i = 1; c = cs[i]; i++){ if(c._nodup != d){ c._nodup = d; }else{ r = []; for(var j = 0; j < i; j++){ r[++ri] = cs[j]; } for(j = i+1; cj = cs[j]; j++){ if(cj._nodup != d){ cj._nodup = d; r[++ri] = cj; } } return r; } } return r; } function quickDiffIEXml(c1, c2){ var d = ++key; for(var i = 0, len = c1.length; i < len; i++){ c1[i].setAttribute("_qdiff", d); } var r = []; for(var i = 0, len = c2.length; i < len; i++){ if(c2[i].getAttribute("_qdiff") != d){ r[r.length] = c2[i]; } } for(var i = 0, len = c1.length; i < len; i++){ c1[i].removeAttribute("_qdiff"); } return r; } function quickDiff(c1, c2){ var len1 = c1.length; if(!len1){ return c2; } if(isIE && c1[0].selectSingleNode){ return quickDiffIEXml(c1, c2); } var d = ++key; for(var i = 0; i < len1; i++){ c1[i]._qdiff = d; } var r = []; for(var i = 0, len = c2.length; i < len; i++){ if(c2[i]._qdiff != d){ r[r.length] = c2[i]; } } return r; } function quickId(ns, mode, root, id){ if(ns == root){ var d = root.ownerDocument || root; return d.getElementById(id); } ns = getNodes(ns, mode, "*"); return byId(ns, null, id); } return { getStyle : function(el, name){ return Ext.fly(el).getStyle(name); }, /** * 将一个 选择符 / xpath 查询编译为一个可利用的函数。返回的函数获得一个“root”参数(可选)作为查询的起点。 * @param {String} selector 选择符 / xpath 查询 * @param {String} type (可选)可以是“select”(默认)或“simple”以供简单选择符使用 * @return {Function} */ compile : function(path, type){ type = type || "select"; var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"]; var q = path, mode, lq; var tk = Ext.DomQuery.matchers; var tklen = tk.length; var mm; // accept leading mode switch var lmode = q.match(modeRe); if(lmode && lmode[1]){ fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; q = q.replace(lmode[1], ""); } // strip leading slashes while(path.substr(0, 1)=="/"){ path = path.substr(1); } while(q && lq != q){ lq = q; var tm = q.match(tagTokenRe); if(type == "select"){ if(tm){ if(tm[1] == "#"){ fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");'; }else{ fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");'; } q = q.replace(tm[0], ""); }else if(q.substr(0, 1) != '@'){ fn[fn.length] = 'n = getNodes(n, mode, "*");'; } }else{ if(tm){ if(tm[1] == "#"){ fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");'; }else{ fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");'; } q = q.replace(tm[0], ""); } } while(!(mm = q.match(modeRe))){ var matched = false; for(var j = 0; j < tklen; j++){ var t = tk[j]; var m = q.match(t.re); if(m){ fn[fn.length] = t.select.replace(tplRe, function(x, i){ return m[i]; }); q = q.replace(m[0], ""); matched = true; break; } } // prevent infinite loop on bad selector if(!matched){ throw 'Error parsing selector, parsing failed at "' + q + '"'; } } if(mm[1]){ fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";'; q = q.replace(mm[1], ""); } } fn[fn.length] = "return nodup(n);\n}"; eval(fn.join("")); return f; }, /** * 选择一组元素。 * @param {String} selector 选择符 / xpath 查询(可以是以逗号分隔的选择符列表) * @param {Node} root (可选)查询的起点(默认为:document)。 * @return {Array} */ select : function(path, root, type){ if(!root || root == document){ root = document; } if(typeof root == "string"){ root = document.getElementById(root); } var paths = path.split(","); var results = []; for(var i = 0, len = paths.length; i < len; i++){ var p = paths[i].replace(trimRe, ""); if(!cache[p]){ cache[p] = Ext.DomQuery.compile(p); if(!cache[p]){ throw p + " is not a valid selector"; } } var result = cache[p](root); if(result && result != document){ results = results.concat(result); } } if(paths.length > 1){ return nodup(results); } return results; }, /** * 选择单个元素。 * @param {String} selector 选择符 / xpath 查询 * @param {Node} root (可选)查询的起点(默认为:document)。 * @return {Element} */ selectNode : function(path, root){ return Ext.DomQuery.select(path, root)[0]; }, /** * 选择一个节点的值,可选择使用 defaultValue 替换掉 null。 * @param {String} selector 选择符 / xpath 查询 * @param {Node} root (可选)查询的起点(默认为:document)。 * @param {String} defaultValue */ selectValue : function(path, root, defaultValue){ path = path.replace(trimRe, ""); if(!valueCache[path]){ valueCache[path] = Ext.DomQuery.compile(path, "select"); } var n = valueCache[path](root); n = n[0] ? n[0] : n; var v = (n && n.firstChild ? n.firstChild.nodeValue : null); return ((v === null||v === undefined||v==='') ? defaultValue : v); }, /** * 取得一个经过处理的整形或浮点型的节点值。 * @param {String} selector 查询时使用的 XPath 或选择符 * @param {Node} root (可选)查询的起点(默认为 document)。 * @param {Number} defaultValue * @return {Number} */ selectNumber : function(path, root, defaultValue){ var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0); return parseFloat(v); }, /** * 如果所给的元素与简易选择符相匹配,则返回 true(例如:div.some-class 或者 span:first-child) * @param {String/HTMLElement/Array} el 元素 ID、元素本身、或元素数组 * @param {String} selector 测试用的简易选择符 * @return {Boolean} */ is : function(el, ss){ if(typeof el == "string"){ el = document.getElementById(el); } var isArray = (el instanceof Array); var result = Ext.DomQuery.filter(isArray ? el : [el], ss); return isArray ? (result.length == el.length) : (result.length > 0); }, /** * 将元素数组过滤成只包含匹配简易选择符的元素(例如:div.some-class 或者 span:first-child) * @param {Array} el 要过滤的元素数组 * @param {String} selector 测试用的简易选择符 * @param {Boolean} nonMatches 如果值为 true,将返回与选择符不匹配的元素,而不是匹配的元素 * @return {Array} */ filter : function(els, ss, nonMatches){ ss = ss.replace(trimRe, ""); if(!simpleCache[ss]){ simpleCache[ss] = Ext.DomQuery.compile(ss, "simple"); } var result = simpleCache[ss](els); return nonMatches ? quickDiff(result, els) : result; }, /** * 匹配的正则表达式和代码片断的集合。 */ matchers : [{ re: /^\.([\w-]+)/, select: 'n = byClassName(n, null, " {1} ");' }, { re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/, select: 'n = byPseudo(n, "{1}", "{2}");' },{ re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");' }, { re: /^#([\w-]+)/, select: 'n = byId(n, null, "{1}");' },{ re: /^@([\w-]+)/, select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};' } ], /** * 比较函数运算符集合。默认的运算符有:=、!=、^=、$=、*= 和 %=。 * 可以添加形如 <i>c</i>= 的运算符。其中 <i>c</i> 可以是除空格、&gt;和&lt;之外的任意字符。 */ operators : { "=" : function(a, v){ return a == v; }, "!=" : function(a, v){ return a != v; }, "^=" : function(a, v){ return a && a.substr(0, v.length) == v; }, "$=" : function(a, v){ return a && a.substr(a.length-v.length) == v; }, "*=" : function(a, v){ return a && a.indexOf(v) !== -1; }, "%=" : function(a, v){ return (a % v) == 0; }, "|=" : function(a, v){ return a && (a == v || a.substr(0, v.length+1) == v+'-'); }, "~=" : function(a, v){ return a && (' '+a+' ').indexOf(' '+v+' ') != -1; } }, /** * "pseudo class" 处理器集合。每一个处理器将传递当前节点集(数组形式)和参数(如果有)以供选择符使用。 */ pseudos : { "first-child" : function(c){ var r = [], ri = -1, n; for(var i = 0, ci; ci = n = c[i]; i++){ while((n = n.previousSibling) && n.nodeType != 1); if(!n){ r[++ri] = ci; } } return r; }, "last-child" : function(c){ var r = [], ri = -1, n; for(var i = 0, ci; ci = n = c[i]; i++){ while((n = n.nextSibling) && n.nodeType != 1); if(!n){ r[++ri] = ci; } } return r; }, "nth-child" : function(c, a) { var r = [], ri = -1; var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a); var f = (m[1] || 1) - 0, l = m[2] - 0; for(var i = 0, n; n = c[i]; i++){ var pn = n.parentNode; if (batch != pn._batch) { var j = 0; for(var cn = pn.firstChild; cn; cn = cn.nextSibling){ if(cn.nodeType == 1){ cn.nodeIndex = ++j; } } pn._batch = batch; } if (f == 1) { if (l == 0 || n.nodeIndex == l){ r[++ri] = n; } } else if ((n.nodeIndex + l) % f == 0){ r[++ri] = n; } } return r; }, "only-child" : function(c){ var r = [], ri = -1;; for(var i = 0, ci; ci = c[i]; i++){ if(!prev(ci) && !next(ci)){ r[++ri] = ci; } } return r; }, "empty" : function(c){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var cns = ci.childNodes, j = 0, cn, empty = true; while(cn = cns[j]){ ++j; if(cn.nodeType == 1 || cn.nodeType == 3){ empty = false; break; } } if(empty){ r[++ri] = ci; } } return r; }, "contains" : function(c, v){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if((ci.textContent||ci.innerText||'').indexOf(v) != -1){ r[++ri] = ci; } } return r; }, "nodeValue" : function(c, v){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(ci.firstChild && ci.firstChild.nodeValue == v){ r[++ri] = ci; } } return r; }, "checked" : function(c){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(ci.checked == true){ r[++ri] = ci; } } return r; }, "not" : function(c, ss){ return Ext.DomQuery.filter(c, ss, true); }, "any" : function(c, selectors){ var ss = selectors.split('|'); var r = [], ri = -1, s; for(var i = 0, ci; ci = c[i]; i++){ for(var j = 0; s = ss[j]; j++){ if(Ext.DomQuery.is(ci, s)){ r[++ri] = ci; break; } } } return r; }, "odd" : function(c){ return this["nth-child"](c, "odd"); }, "even" : function(c){ return this["nth-child"](c, "even"); }, "nth" : function(c, a){ return c[a-1] || []; }, "first" : function(c){ return c[0] || []; }, "last" : function(c){ return c[c.length-1] || []; }, "has" : function(c, ss){ var s = Ext.DomQuery.select; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(s(ss, ci).length > 0){ r[++ri] = ci; } } return r; }, "next" : function(c, ss){ var is = Ext.DomQuery.is; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var n = next(ci); if(n && is(n, ss)){ r[++ri] = ci; } } return r; }, "prev" : function(c, ss){ var is = Ext.DomQuery.is; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var n = prev(ci); if(n && is(n, ss)){ r[++ri] = ci; } } return r; } } }; }(); /** * 选定一个通过 CSS/XPath 选择符获取的 DOM 节点组成的数组。{@link Ext.DomQuery#select} 的简写方式 * @param {String} path 查询时使用的 XPath 或选择符 * @param {Node} root (可选)查询的起点(默认为 document)。 * @return {Array} * @member Ext * @method query */ Ext.query = Ext.DomQuery.select;
JavaScript
/** * @class Ext.Template * 将一段Html片段呈现为模板。可将模板编译以获取更高的性能。 * 针对格式化的函数的可用列表,请参阅{@link Ext.util.Format}.<br /> * 用法: <pre><code> var t = new Ext.Template( '&lt;div name="{id}"&gt;', '&lt;span class="{cls}"&gt;{name:trim} {value:ellipsis(10)}&lt;/span&gt;', '&lt;/div&gt;' ); t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'}); </code></pre> * @constructor * @param {String/Array} html HTML片断或是片断的数组(用于join(''))或多个参数(会执行join(''))。 */ Ext.Template = function(html){ var a = arguments; if(html instanceof Array){ html = html.join(""); }else if(a.length > 1){ var buf = []; for(var i = 0, len = a.length; i < len; i++){ if(typeof a[i] == 'object'){ Ext.apply(this, a[i]); }else{ buf[buf.length] = a[i]; } } html = buf.join(''); } /**@private*/ this.html = html; if(this.compiled){ this.compile(); } }; Ext.Template.prototype = { /** * 返回HTML片段,这块片断是由数据填充模板之后而成的。 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @return {String} HTML片段 */ applyTemplate : function(values){ if(this.compiled){ return this.compiled(values); } var useF = this.disableFormats !== true; var fm = Ext.util.Format, tpl = this; var fn = function(m, name, format, args){ if(format && useF){ if(format.substr(0, 5) == "this."){ return tpl.call(format.substr(5), values[name], values); }else{ if(args){ // quoted values are required for strings in compiled templates, // but for non compiled we need to strip them // quoted reversed for jsmin var re = /^\s*['"](.*)["']\s*$/; args = args.split(','); for(var i = 0, len = args.length; i < len; i++){ args[i] = args[i].replace(re, "$1"); } args = [values[name]].concat(args); }else{ args = [values[name]]; } return fm[format].apply(fm, args); } }else{ return values[name] !== undefined ? values[name] : ""; } }; return this.html.replace(this.re, fn); }, /** * 使得某段HTML可作用模板使用,也可将其编译 * @param {String} html * @param {Boolean} compile (可选的) ture表示为编译模板(默认为undefined) * @return {Ext.Template} this */ set : function(html, compile){ this.html = html; this.compiled = null; if(compile){ this.compile(); } return this; }, /** * Ture表示为禁止格式化功能(默认为false) * @type Boolean */ disableFormats : false, /** * 匹配模板变量的正则表达式。 * @type RegExp * @property */ re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, /** * 将模板编译成内置调用函数,消除刚才的正则表达式 * @return {Ext.Template} this */ compile : function(){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args){ if(format && useF){ args = args ? ',' + args : ""; if(format.substr(0, 5) != "this."){ format = "fm." + format + '('; }else{ format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } }else{ args= ''; format = "(values['" + name + "'] == undefined ? '' : "; } return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'"; }; var body; // branched to use + in gecko and [].join() in others if(Ext.isGecko){ body = "this.compiled = function(values){ return '" + this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) + "';};"; }else{ body = ["this.compiled = function(values){ return ['"]; body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, // private function used to call members call : function(fnName, value, allValues){ return this[fnName](value, allValues); }, /** * 填充模板的数据,形成为一个或多个新节点,作为首个子节点插入到e1。 * @param {Mixed} el 上下文的元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ insertFirst: function(el, values, returnElement){ return this.doInsert('afterBegin', el, values, returnElement); }, /** * 填充模板的数据,形成为一个或多个新节点,并位于el之前的位置插入。 * @param {Mixed} el 上下文的元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ insertBefore: function(el, values, returnElement){ return this.doInsert('beforeBegin', el, values, returnElement); }, /** * 填充模板的数据,形成为一个或多个新节点,并位于el之后的位置插入。 * @param {Mixed} el 上下文的元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ insertAfter : function(el, values, returnElement){ return this.doInsert('afterEnd', el, values, returnElement); }, /** * 填充模板的数据,形成为一个或多个新节点,并追加到e1。 * @param {Mixed} el 上下文的元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ append : function(el, values, returnElement){ return this.doInsert('beforeEnd', el, values, returnElement); }, doInsert : function(where, el, values, returnEl){ el = Ext.getDom(el); var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values)); return returnEl ? Ext.get(newNode, true) : newNode; }, /** * 填充模板的数据,形成为一个或多个新节点,对el的内容进行覆盖。 * @param {Mixed} el 正文元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element(默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ overwrite : function(el, values, returnElement){ el = Ext.getDom(el); el.innerHTML = this.applyTemplate(values); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; } }; /** * {@link #applyTemplate}的简写方式 * @method */ Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; /** * 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML. * @param {String/HTMLElement} DOM元素或某id * @param {Object} config 一个配置项对象 * @returns {Ext.Template} 创建好的模板 * @static */ Ext.Template.from = function(el, config){ el = Ext.getDom(el); return new Ext.Template(el.value || el.innerHTML, config || ''); };
JavaScript
/** * @class Number */ Ext.applyIf(Number.prototype, { /** * 检查当前数字是否属于某个期望的范围内。 * 若数字是在范围内的就返回数字,否则最小或最大的极限值,那个极限值取决于数字是倾向那一面(最大、最小)。 * 注意返回的极限值并不会影响当前的值。 * @param {Number} min 范围中最小的极限值 * @param {Number} max 范围中最大的极限值 * @return {Number} 若超出范围返回极限值,反正是值本身 */ constrain : function(min, max){ return Math.min(Math.max(this, min), max); } });
JavaScript
/** * @class Ext.Updater * @extends Ext.util.Observable * 为元素对象提供Ajax式更新。<br><br> * 用法:<br> * <pre><code> * //从Ext.Element对象上获取Updater * var el = Ext.get("foo"); * var mgr = el.getUpdater(); * mgr.update({ * url: "http://myserver.com/index.php", * params: { * param1: "foo", * param2: "bar" * } * }); * ... * mgr.formUpdate("myFormId", "http://myserver.com/index.php"); * <br> * //或直接声明(返回相同的UpdateManager实例) * var mgr = new Ext.Updater("myElementId"); * mgr.startAutoRefresh(60, "http://myserver.com/index.php"); * mgr.on("update", myFcnNeedsToKnow); * <br> //用快捷的方法在元素上直接访问 Ext.get("foo").load({ url: "bar.php", scripts: true, params: "param1=foo&amp;param2=bar", text: "Loading Foo..." }); * </code></pre> * @constructor * 直接创建新UpdateManager。 * @param {Mixed} el 被更新的元素 * @param {Boolean} forceNew (可选的) 默认下,构造器会检查传入之元素是否有UpdateManager,如果有的话它返回该实例,也会跳过检查(继承类时有用)。 */ Ext.Updater = function(el, forceNew){ el = Ext.get(el); if(!forceNew && el.updateManager){ return el.updateManager; } /** * 元素对象 * @type Ext.Element */ this.el = el; /** * 用于刷新的缓存url,如参数设置为false,每次调用update()都会重写该值。 * @type String */ this.defaultUrl = null; this.addEvents({ /** * @event beforeupdate * 在一个更新开始之前触发,如在事件句柄中返回false即意味着取消这次更新。 * @param {Ext.Element} el * @param {String/Object/Function} url * @param {String/Object} params */ "beforeupdate": true, /** * @event update * 当更新成功后触发 * @param {Ext.Element} el * @param {Object} oResponseObject response对象 */ "update": true, /** * @event failure * 当更新失败后触发 * @param {Ext.Element} el * @param {Object} oResponseObject response对象 */ "failure": true }); var d = Ext.Updater.defaults; /** * Blank page URL to use with SSL file uploads (Defaults to Ext.Updater.defaults.sslBlankUrl or "about:blank"). * @type String */ this.sslBlankUrl = d.sslBlankUrl; /** * Whether to append unique parameter on get request to disable caching (Defaults to Ext.Updater.defaults.disableCaching or false). * @type Boolean */ this.disableCaching = d.disableCaching; /** * Text for loading indicator (Defaults to Ext.Updater.defaults.indicatorText or '&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;'). * @type String */ this.indicatorText = d.indicatorText; /** * Whether to show indicatorText when loading (Defaults to Ext.Updater.defaults.showLoadIndicator or true). * @type String */ this.showLoadIndicator = d.showLoadIndicator; /** * Timeout for requests or form posts in seconds (Defaults to Ext.Updater.defaults.timeout or 30 seconds). * @type Number */ this.timeout = d.timeout; /** * True to process scripts in the output (Defaults to Ext.Updater.defaults.loadScripts (false)). * @type Boolean */ this.loadScripts = d.loadScripts; /** * Transaction object of current executing transaction */ this.transaction = null; /** * @private */ this.autoRefreshProcId = null; /** * Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments * @type Function */ this.refreshDelegate = this.refresh.createDelegate(this); /** * Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments * @type Function */ this.updateDelegate = this.update.createDelegate(this); /** * Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments * @type Function */ this.formUpdateDelegate = this.formUpdate.createDelegate(this); if(!this.renderer){ /** * The renderer for this Updater. Defaults to {@link Ext.Updater.BasicRenderer}. */ this.renderer = new Ext.Updater.BasicRenderer(); } Ext.Updater.superclass.constructor.call(this); }; Ext.extend(Ext.Updater, Ext.util.Observable, { /** * 获取当前UpdateManager所绑定的元素 * @return {Ext.Element} 元素 */ getEl : function(){ return this.el; }, /** * 发起一个的<b>异步</b>请求,然后根据响应的response更新元素。 * 如不指定使用GET,否则POST。 * @param {Object/String/Function} url (可选的)请求的url或是能够返回url的函数(默认为最后使用的url),也可以是一个对象,包含下列可选项: <pre><code> um.update({<br/> url: "your-url.php",<br/> params: {param1: "foo", param2: "bar"}, // 或是可URL编码的字符串<br/> callback: yourFunction,<br/> scope: yourObject, //(作用域可选) <br/> discardUrl: false, <br/> nocache: false,<br/> text: "加载中...",<br/> timeout: 30,<br/> scripts: false<br/> }); </code></pre> * 只有url的属性是必须的。 * 可选属性有nocache, text and scripts,分别是disableCaching,indicatorText和loadScripts的简写方式 * 它们用于设置UpdateManager实例相关的属性。 * @param {String/Object} params (可选的) 提交的参数,为可url编码的字符串"&param1=1&param2=2",也可以是对象的形式{param1: 1, param2: 2} * @param {Function} callback (可选的) Callback 事务完成后执行的回调(带参数oElement, bSuccess) * @param {Boolean} discardUrl (可选的) 默认情况下,完成更新后,最后一次使用的url会保存到defaultUrl属性 * 该参数为true的话,就不会保存。 */ /** * 发起一个的<b>异步</b>请求,然后根据响应的response更新元素。 * 如不指定使用GET,否则POST。<br><br> * <b>NB:</b> 根据异步请求远端服务器的特性,此函数执行后元素不会立即被更新。要处理返回的数据,使用回调选项,或指定<b><tt>update</tt></b>事件句柄 * @param {Object} options 一个配置项对象可以包含下列属性:<ul> * <li>url : <b>String/Function</b><p class="sub-desc">The URL to * request or a function which <i>returns</i> the URL.</p></li> * <li>method : <b>String</b><p class="sub-desc">The HTTP method to * use. Defaults to POST if params are present, or GET if not.</p></li> * <li>params : <b>String/Object/Function</b><p class="sub-desc">The * parameters to pass to the server. 传到服务器的参数。这可以字符串(未urlencoded亦可),或代表参数的对象,或返回对象的函数。</p></li> * <li><b>scripts</b> : Boolean<p class="sub-desc">If <tt>true</tt> * any &lt;script&gt; tags embedded in the response text will be extracted * and executed. If this option is specified, the callback will be * called <i>after</i> the execution of the scripts.</p></li> * * <li><b>callback</b> : Function<p class="sub-desc"> * 接收到服务器的响应后,执行的回调函数。该函数带下列的参数: * <ul> * <li><b>el</b> : Ext.Element<p class="sub-desc">被更新的元素</p></li> * <li><b>success</b> : Boolean<p class="sub-desc">True表示成功,false表示失败。</p></li> * <li><b>response</b> : XMLHttpRequest<p class="sub-desc">进行更新的那个XMLHttpRequest对象</p></li> * </ul> * </p> * </li> * * <li><b>scope</b> : Object<p class="sub-desc">The scope in which * to execute the callback 回调函数所在的作用域(<tt>this<tt>所指向的引用)。如果 * <tt>params</tt> 选项是一个函数,那么这个作用域也用于该函数。</p></li> * * <li><b>discardUrl</b> : Boolean<p class="sub-desc">If not passed * as <tt>false</tt> the URL of this request becomes the default URL for * this Updater object, and will be subsequently used in {@link #refresh} * calls.(可选的) 默认情况下,完成更新后,最后一次使用的url会保存到defaultUrl属性 * 该参数为true的话,就不会保存。</p></li> * <li><b>timeout</b> : Number<p class="sub-desc">The timeout to use * when waiting for a response.</p></li> * <li><b>nocache</b> : Boolean<p class="sub-desc">Only needed for GET * requests, this option causes an extra, generated parameter to be passed * to defeat caching.</p></li></ul> * <p> * For example: <pre><code> um.update({ url: "your-url.php", params: {param1: "foo", param2: "bar"}, // or a URL encoded string callback: yourFunction, scope: yourObject, //(optional scope) discardUrl: false, nocache: false, text: "Loading...", timeout: 30, scripts: false // Save time by avoiding RegExp execution. }); </code></pre> */ update : function(url, params, callback, discardUrl){ if(this.fireEvent("beforeupdate", this.el, url, params) !== false){ var method = this.method, cfg, callerScope; if(typeof url == "object"){ // must be config object cfg = url; url = cfg.url; params = params || cfg.params; callback = callback || cfg.callback; discardUrl = discardUrl || cfg.discardUrl; callerScope = cfg.scope; if(typeof cfg.method != "undefined"){method = cfg.method;}; if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;}; if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";}; if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;}; if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;}; } this.showLoading(); if(!discardUrl){ this.defaultUrl = url; } if(typeof url == "function"){ url = url.call(this); } method = method || (params ? "POST" : "GET"); if(method == "GET"){ url = this.prepareUrl(url); } var o = Ext.apply(cfg ||{}, { url : url, params: (typeof params == "function" && callerScope) ? params.createDelegate(callerScope) : params, success: this.processSuccess, failure: this.processFailure, scope: this, callback: undefined, timeout: (this.timeout*1000), argument: { "options": cfg, "url": url, "form": null, "callback": callback, "scope": callerScope || window, "params": params } }); this.transaction = Ext.Ajax.request(o); } }, /** * 执行表单的异步请求,然后根据响应response更新元素。 * 表单若有enctype="multipart/form-data"的属性,即被认为是文件上传。 * SSL文件上传应使用this.sslBlankUrl以阻止IE的安全警告。 * @param {String/HTMLElement} form 表单元素或表单id * @param {String} url (可选的) 表单提交的url。如忽略则采用表单的action属性 * @param {Boolean} reset (可选的) 完成更新后是否试着将表单复位 * @param {Function} callback (可选的) Callback 事务完成后 ,执行的回调,带下列参数 * <ul> * <li><b>el</b> : Ext.Element<p class="sub-desc">被更新的元素</p></li> * <li><b>success</b> : Boolean<p class="sub-desc">True表示成功,false表示失败。</p></li> * <li><b>response</b> : XMLHttpRequest<p class="sub-desc">进行更新的那个XMLHttpRequest对象</p></li> * </ul> */ formUpdate : function(form, url, reset, callback){ if(this.fireEvent("beforeupdate", this.el, form, url) !== false){ if(typeof url == "function"){ url = url.call(this); } form = Ext.getDom(form) this.transaction = Ext.Ajax.request({ form: form, url:url, success: this.processSuccess, failure: this.processFailure, scope: this, timeout: (this.timeout*1000), argument: { "url": url, "form": form, "callback": callback, "reset": reset } }); this.showLoading.defer(1, this); } }, /** * 根据最后一次使用的url,或属性defaultUrl,刷新元素。 * 如果未发现url,则立即返回。 * @param {Function} callback (可选的) Callback 事务完成后,执行的回调(带参数oElement, bSuccess) */ refresh : function(callback){ if(this.defaultUrl == null){ return; } this.update(this.defaultUrl, null, callback, true); }, /** * 设置该元素自动刷新。 * @param {Number} interval 更新频率(单位:秒) * @param {String/Function} url (可选的) 请求的url或是能够返回url的函数(默认为最后使用那个的url) * @param {String/Object} params (可选的) 提交的参数,为可url编码的字符串"&param1=1&param2=2",也可是对象的形式{param1: 1, param2: 2} * @param {Function} callback (可选的) Callback 事务完成后执行的回调(带参数oElement, bSuccess) * @param {Boolean} refreshNow (可选的) 是否立即执行更新,或等待下一次更新 */ startAutoRefresh : function(interval, url, params, callback, refreshNow){ if(refreshNow){ this.update(url || this.defaultUrl, params, callback, true); } if(this.autoRefreshProcId){ clearInterval(this.autoRefreshProcId); } this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000); }, /** * 停止该元素的自动刷新 */ stopAutoRefresh : function(){ if(this.autoRefreshProcId){ clearInterval(this.autoRefreshProcId); delete this.autoRefreshProcId; } }, isAutoRefreshing : function(){ return this.autoRefreshProcId ? true : false; }, /** * 把元素换成“加载中”的状态,可重写该方法执行自定义的动作。 */ showLoading : function(){ if(this.showLoadIndicator){ this.el.update(this.indicatorText); } }, /** * 加入查询字符串的唯一的参数,前提是disableCaching = true。 * @private */ prepareUrl : function(url){ if(this.disableCaching){ var append = "_dc=" + (new Date().getTime()); if(url.indexOf("?") !== -1){ url += "&" + append; }else{ url += "?" + append; } } return url; }, /** * @private */ processSuccess : function(response){ this.transaction = null; if(response.argument.form && response.argument.reset){ try{ // put in try/catch since some older FF releases had problems with this response.argument.form.reset(); }catch(e){} } if(this.loadScripts){ this.renderer.render(this.el, response, this, this.updateComplete.createDelegate(this, [response])); }else{ this.renderer.render(this.el, response, this); this.updateComplete(response); } }, updateComplete : function(response){ this.fireEvent("update", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback.call(response.argument.scope, this.el, true, response, response.argument.options); } }, /** * @private */ processFailure : function(response){ this.transaction = null; this.fireEvent("failure", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback.call(response.argument.scope, this.el, false, response, response.argument.options); } }, /** * 为这次更新设置内容渲染器。参阅{@link Ext.Updater.BasicRenderer#render}的更多资料。 * @param {Object} renderer 实现render()的对象 */ setRenderer : function(renderer){ this.renderer = renderer; }, getRenderer : function(){ return this.renderer; }, /** * 为这次更新设置defaultUrl * @param {String/Function} defaultUrl URL或是能返回的URL的函数 */ setDefaultUrl : function(defaultUrl){ this.defaultUrl = defaultUrl; }, /** * 取消执行事务 */ abort : function(){ if(this.transaction){ Ext.Ajax.abort(this.transaction); } }, /** * 当更新进行时返回true。 * @return {Boolean} */ isUpdating : function(){ if(this.transaction){ return Ext.Ajax.isLoading(this.transaction); } return false; } }); /** * @class Ext.Updater.defaults * UpdateManager组件中可定制的属性,这里是默认值集合。 */ Ext.Updater.defaults = { /** * 以秒为单位的请求超时时限(默认为30秒)。 * @type Number */ timeout : 30, /** * True表示为执行脚本(默认为false)。 * @type Boolean */ loadScripts : false, /** * 空白页的URL,通过SSL链接上传文件时使用(默认为“javascript:false”)。 * @type String */ sslBlankUrl : (Ext.SSL_SECURE_URL || "javascript:false"), /** * 是否添加一个唯一的参数以使接到请求时禁止缓存(默认为 false)。 * @type Boolean */ disableCaching : false, /** * 加载时是否显示“indicatorText”(默认为 true)。 * @type Boolean */ showLoadIndicator : true, /** * 加载指示器显示的内容(默认为'&lt;div class="loading-indicator"&gt;Loading...&lt;/div&gt;') * @type String */ indicatorText : '<div class="loading-indicator">Loading...</div>' }; /** * 静态的快捷方法。这个方法已经是过时的,推荐使用el.load({url:'foo.php', ...})。 *Usage: * <pre><code>Ext.Updater.updateElement("my-div", "stuff.php");</code></pre> * @param {Mixed} el The element to update * @param {String} url The url * @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs * @param {Object} options (optional) A config object with any of the Updater properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."} * @static * @deprecated * @member Ext.Updater */ Ext.Updater.updateElement = function(el, url, params, options){ var um = Ext.get(el).getUpdater(); Ext.apply(um, options); um.update(url, params, options ? options.callback : null); }; // alias for backwards compat Ext.Updater.update = Ext.Updater.updateElement; /** * @class Ext.Updater.BasicRenderer * 默认的内容渲染器。使用responseText更新元素的innerHTML属性。 */ Ext.Updater.BasicRenderer = function(){}; Ext.Updater.BasicRenderer.prototype = { /** * 当事务完成并准备更新元素的时候调用此方法。 * BasicRenderer 使用 responseText 更新元素的 innerHTML 属性。 * 如想要指定一个定制的渲染器(如:XML 或 JSON),使用“render(el, response)”方法创建一个对象, * 并通过setRenderer方法传递给UpdateManager。 * @param {Ext.Element} el 所渲染的元素 * @param {Object} response XMLHttpRequest对象 * @param {Updater} updateManager 调用的UpdateManager对象 * @param {Function} callback 如果loadScripts属性为true时,UpdateManager对象需要指定一个回调函数 */ render : function(el, response, updateManager, callback){ el.update(response.responseText, updateManager.loadScripts, callback); } }; Ext.UpdateManager = Ext.Updater;
JavaScript
/** * @class Ext.EventObject * 为了方便操作,在你定义的事件句柄上传入事件对象(Event Object),这个对象直接呈现了Yahoo! UI 事件功能。 * 同时也解决了自动null检查的不便。 * 举例: * <pre><code> fu<>nction handleClick(e){ // e它不是一个标准的事件对象,而是Ext.EventObject e.preventDefault(); var target = e.getTarget(); ... } var myDiv = Ext.get("myDiv"); myDiv.on("click", handleClick); //或者 Ext.EventManager.on("myDiv", 'click', handleClick); Ext.EventManager.addListener("myDiv", 'click', handleClick); </code></pre> * @singleton */ Ext.EventObject = function(){ var E = Ext.lib.Event; // safari keypress events for special keys return bad keycodes var safariKeys = { 63234 : 37, // left 63235 : 39, // right 63232 : 38, // up 63233 : 40, // down 63276 : 33, // page up 63277 : 34, // page down 63272 : 46, // delete 63273 : 36, // home 63275 : 35 // end }; // normalize button clicks var btnMap = Ext.isIE ? {1:0,4:1,2:2} : (Ext.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2}); Ext.EventObjectImpl = function(e){ if(e){ this.setEvent(e.browserEvent || e); } }; Ext.EventObjectImpl.prototype = { /** The normal browser event */ browserEvent : null, /** The button pressed in a mouse event */ button : -1, /** True表示事件触发时是有按下shift键的。True if the shift key was down during the event */ shiftKey : false, /** True表示事件触发时是有按下ctrl键的。True if the control key was down during the event */ ctrlKey : false, /** True表示事件触发时是有按下alt键的。True if the alt key was down during the event */ altKey : false, /** 键码常量 @type Number */ BACKSPACE : 8, /** 键码常量 @type Number */ TAB : 9, /** 键码常量 @type Number */ RETURN : 13, /** 键码常量 @type Number */ ENTER : 13, /** 键码常量 @type Number */ SHIFT : 16, /** 键码常量 @type Number */ CONTROL : 17, /** 键码常量 @type Number */ ESC : 27, /** 键码常量 @type Number */ SPACE : 32, /** 键码常量 @type Number */ PAGEUP : 33, /** 键码常量 @type Number */ PAGEDOWN : 34, /** 键码常量 @type Number */ END : 35, /** 键码常量 @type Number */ HOME : 36, /** 键码常量 @type Number */ LEFT : 37, /** 键码常量 @type Number */ UP : 38, /** 键码常量 @type Number */ RIGHT : 39, /** 键码常量 @type Number */ DOWN : 40, /** 键码常量 @type Number */ DELETE : 46, /** 键码常量 @type Number */ F5 : 116, /** @private */ setEvent : function(e){ if(e == this || (e && e.browserEvent)){ // already wrapped return e; } this.browserEvent = e; if(e){ // normalize buttons this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1); if(e.type == 'click' && this.button == -1){ this.button = 0; } this.type = e.type; this.shiftKey = e.shiftKey; // mac metaKey behaves like ctrlKey this.ctrlKey = e.ctrlKey || e.metaKey; this.altKey = e.altKey; // in getKey these will be normalized for the mac this.keyCode = e.keyCode; this.charCode = e.charCode; // cache the target for the delayed and or buffered events this.target = E.getTarget(e); // same for XY this.xy = E.getXY(e); }else{ this.button = -1; this.shiftKey = false; this.ctrlKey = false; this.altKey = false; this.keyCode = 0; this.charCode =0; this.target = null; this.xy = [0, 0]; } return this; }, /** * 停止事件(preventDefault和stopPropagation) */ stopEvent : function(){ if(this.browserEvent){ if(this.browserEvent.type == 'mousedown'){ Ext.EventManager.stoppedMouseDownEvent.fire(this); } E.stopEvent(this.browserEvent); } }, /** * 阻止浏览器默认行为处理事件 */ preventDefault : function(){ if(this.browserEvent){ E.preventDefault(this.browserEvent); } }, /** @private */ isNavKeyPress : function(){ var k = this.keyCode; k = Ext.isSafari ? (safariKeys[k] || k) : k; return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC; }, isSpecialKey : function(){ var k = this.keyCode; return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 || (k == 16) || (k == 17) || (k >= 18 && k <= 20) || (k >= 33 && k <= 35) || (k >= 36 && k <= 39) || (k >= 44 && k <= 45); }, /** * 取消事件上报 */ stopPropagation : function(){ if(this.browserEvent){ if(this.browserEvent.type == 'mousedown'){ Ext.EventManager.stoppedMouseDownEvent.fire(this); } E.stopPropagation(this.browserEvent); } }, /** * 获取事件的键盘代码 * @return {Number} */ getCharCode : function(){ return this.charCode || this.keyCode; }, /** * 返回一个常规化的事件键盘代码 * @return {Number} 键盘代码 */ getKey : function(){ var k = this.keyCode || this.charCode; return Ext.isSafari ? (safariKeys[k] || k) : k; }, /** * 获取事件X坐标。 * @return {Number} */ getPageX : function(){ return this.xy[0]; }, /** * 获取事件Y坐标。 * @return {Number} */ getPageY : function(){ return this.xy[1]; }, /** * 获取事件的时间。 * @return {Number} */ getTime : function(){ if(this.browserEvent){ return E.getTime(this.browserEvent); } return null; }, /** * 获取事件的页面坐标。 * @return {Array} xy值,格式[x, y] */ getXY : function(){ return this.xy; }, /** * 获取事件的目标对象。 * @param {String} selector (可选的) 一个简易的选择符,用于筛选目标或查找目标的父级元素 * @param {Number/String/HTMLElement/Element} maxDepth (可选的)搜索的最大深度(数字或是元素,默认为10||document.body) * @param {Boolean} returnEl (可选的) True表示为返回Ext.Element的对象而非DOM节点 * @return {HTMLelement} */ getTarget : function(selector, maxDepth, returnEl){ var t = Ext.get(this.target); return selector ? t.findParent(selector, maxDepth, returnEl) : (returnEl ? t : this.target); }, /** * 获取相关的目标对象。 * @return {HTMLElement} */ getRelatedTarget : function(){ if(this.browserEvent){ return E.getRelatedTarget(this.browserEvent); } return null; }, /** * 常规化鼠标滚轮的有限增量(跨浏览器) * @return {Number} The delta */ getWheelDelta : function(){ var e = this.browserEvent; var delta = 0; if(e.wheelDelta){ /* IE/Opera. */ delta = e.wheelDelta/120; }else if(e.detail){ /* Mozilla case. */ delta = -e.detail/3; } return delta; }, /** * 返回一个布尔值,表示当该事件执行的过程中,ctrl、alt、shift有否被按下。 * @return {Boolean} */ hasModifier : function(){ return ((this.ctrlKey || this.altKey) || this.shiftKey) ? true : false; }, /** * 返回true表示如果该事件的目标对象等于el,或是el的子元素 * @param {String/HTMLElement/Element} el * @param {Boolean} related (optional) (可选的)如果相关的target就是el而非target本身,返回true * @return {Boolean} */ within : function(el, related){ var t = this[related ? "getRelatedTarget" : "getTarget"](); return t && Ext.fly(el).contains(t); }, getPoint : function(){ return new Ext.lib.Point(this.xy[0], this.xy[1]); } }; return new Ext.EventObjectImpl(); }();
JavaScript
Ext = {version: '2.0'}; //为老版本浏览器提供 window["undefined"] = window["undefined"]; /** * @class Ext * Ext核心工具与函数 * @singleton */ /** * 复制所有参数config中的属性至参数obj(第一个参数为obj,第二个参数为config) * @param {Object} obj 接受方对象 * @param {Object} config 源对象 * @param {Object} defaults 默认对象,如果该参数存在,obj将会获取那些defaults有而config没有的属性 * @return {Object} returns obj * @member Ext apply */ Ext.apply = function(o, c, defaults){ if(defaults){ // no "this" reference for friendly out of scope calls Ext.apply(o, defaults); } if(o && c && typeof c == 'object'){ for(var p in c){ o[p] = c[p]; } } return o; }; (function(){ var idSeed = 0; var ua = navigator.userAgent.toLowerCase(); var isStrict = document.compatMode == "CSS1Compat", isOpera = ua.indexOf("opera") > -1, isSafari = (/webkit|khtml/).test(ua), isIE = !isOpera && ua.indexOf("msie") > -1, isIE7 = !isOpera && ua.indexOf("msie 7") > -1, isGecko = !isSafari && ua.indexOf("gecko") > -1, isBorderBox = isIE && !isStrict, isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1), isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1), isLinux = (ua.indexOf("linux") != -1), isSecure = window.location.href.toLowerCase().indexOf("https") === 0; // remove css image flicker if(isIE && !isIE7){ try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} } Ext.apply(Ext, { /** * 判断浏览器是否是 精确(Strict) 模式 * @type Boolean */ isStrict : isStrict, /** * 判断页面是否运行在SSL状态 * @type Boolean */ isSecure : isSecure, /** * 页面是否被完全读取,并可供使用 * @type Boolean */ isReady : false, /** * 是否定时清Ext.Elements缓存 (默认为是) * @type Boolean */ enableGarbageCollector : true, /** * 是否在清缓存后自动清除事件监听器 (默认为否) * 注意:前置条件是enableGarbageCollector:true * @type Boolean */ enableListenerCollection:false, /** * iframe与onReady所指向的连接为空白连接 * IE不可靠的内容警告 (默认为 javascript:false). * @type String */ SSL_SECURE_URL : "javascript:false", /** * 一个1*1的透明gif图片连接,用于内置图标和css背景 * 默认地址为 "http://extjs.com/s.gif",应用时应该设为自己的服务器连接). * @type String */ BLANK_IMAGE_URL : "http:/"+"/extjs.com/s.gif", /** * 可复用的空函数 * @property * @type Function */ emptyFn : function(){}, /** * 复制所有config的属性至obj,如果obj已有该属性,则不复制(第一个参数为obj,第二个参数为config) * @param {Object} obj 接受方对象 * @param {Object} config 源对象 * @return {Object} returns obj */ applyIf : function(o, c){ if(o && c){ for(var p in c){ if(typeof o[p] == "undefined"){ o[p] = c[p]; } } } return o; }, /** * 页面被初始化完毕后,在元素上绑定事件监听 * 事件名在'@'符号后 <pre><code> Ext.addBehaviors({ // 为id为foo的锚点元素增加onclick事件监听 '#foo a@click' : function(e, t){ // do something }, // 为多个元素增加mouseover事件监听 (在'@'前用逗号(,)分隔) '#foo a, #bar span.some-class@mouseover' : function(){ // do something } }); </code></pre> * @param {Object} obj 所绑定的事件及其行为 */ addBehaviors : function(o){ if(!Ext.isReady){ Ext.onReady(function(){ Ext.addBehaviors(o); }); return; } var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times for(var b in o){ var parts = b.split('@'); if(parts[1]){ // for Object prototype breakers var s = parts[0]; if(!cache[s]){ cache[s] = Ext.select(s); } cache[s].on(parts[1], o[b]); } } cache = null; }, /** * 对页面元素生成唯一id,如果该元素已存在id,则不会再生成 * @param {String/HTMLElement/Element} el (该参数可选) 将要生成id的元素 * @param {String} prefix (该参数可选) 该id的前缀(默认为 "ext-gen") * @return {String} 导出的Id. */ id : function(el, prefix){ prefix = prefix || "ext-gen"; el = Ext.getDom(el); var id = prefix + (++idSeed); return el ? (el.id ? el.id : (el.id = id)) : id; }, /** * 继承,并由传递的值决定是否覆盖原对象的属性 * 返回的对象中也增加了override()函数,用于覆盖实例的成员 * @param {Object} subclass 子类,用于继承(该类继承了父类所有属性,并最终返回该对象) * @param {Object} superclass 父类,被继承 * @param {Object} overrides (该参数可选) 一个对象,将它本身携带的属性对子类进行覆盖 * @method extend */ extend : function(){ // inline overrides var io = function(o){ for(var m in o){ this[m] = o[m]; } }; return function(sb, sp, overrides){ if(typeof sp == 'object'){ overrides = sp; sp = sb; sb = function(){sp.apply(this, arguments);}; } var F = function(){}, sbp, spp = sp.prototype; F.prototype = spp; sbp = sb.prototype = new F(); sbp.constructor=sb; sb.superclass=spp; if(spp.constructor == Object.prototype.constructor){ spp.constructor=sp; } sb.override = function(o){ Ext.override(sb, o); }; sbp.override = io; Ext.override(sb, overrides); return sb; }; }(), /** * 利用overrides重写origclass的方法,例 * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name. * Usage:<pre><code> Ext.override(MyClass, { newMethod1: function(){ // etc. }, newMethod2: function(foo){ // etc. } }); </code></pre> * @param {Object} origclass The class to override * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal * containing one or more methods. * @method override */ override : function(origclass, overrides){ if(overrides){ var p = origclass.prototype; for(var method in overrides){ p[method] = overrides[method]; } } }, /** * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage: * <pre><code> Ext.namespace('Company', 'Company.data'); Company.Widget = function() { ... } Company.data.CustomStore = function(config) { ... } </code></pre> * @param {String} namespace1 * @param {String} namespace2 * @param {String} etc * @method namespace */ namespace : function(){ var a=arguments, o=null, i, j, d, rt; for (i=0; i<a.length; ++i) { d=a[i].split("."); rt = d[0]; eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';'); for (j=1; j<d.length; ++j) { o[d[j]]=o[d[j]] || {}; o=o[d[j]]; } } }, /** * 将对象转化为一个编码后的URL连接 * 例如:Ext.urlEncode({foo: 1, bar: 2}); 将返回 "foo=1&bar=2". * 参数值可以是一个数组,数组下标将作为“健”,“值”则是数组所含内容 * (以下为译注)例:var myConn = Ext.urlEncode(['a','b','c']);将返回 "0=a&1=b&2=c" * @param {Object} o * @return {String} */ urlEncode : function(o){ if(!o){ return ""; } var buf = []; for(var key in o){ var ov = o[key], k = encodeURIComponent(key); var type = typeof ov; if(type == 'undefined'){ buf.push(k, "=&"); }else if(type != "function" && type != "object"){ buf.push(k, "=", encodeURIComponent(ov), "&"); }else if(ov instanceof Array){ if (ov.length) { for(var i = 0, len = ov.length; i < len; i++) { buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&"); } } else { buf.push(k, "=&"); } } } buf.pop(); return buf.join(""); }, /** * 将一个URL连接解码为一个对象 * 例如:Ext.urlDecode("foo=1&bar=2"); 将返回 {foo: 1, bar: 2} * 或: Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", true); 将返回 {foo: 1, bar: [2, 3, 4]}. * @param {String} string * @param {Boolean} overwrite (该参数可选) 如果该参数为true,在传递的字符串中如果有相同的键,值将会自动组装成一个数组(默认为false)。 * @return {Object} A literal with members */ urlDecode : function(string, overwrite){ if(!string || !string.length){ return {}; } var obj = {}; var pairs = string.split('&'); var pair, name, value; for(var i = 0, len = pairs.length; i < len; i++){ pair = pairs[i].split('='); name = decodeURIComponent(pair[0]); value = decodeURIComponent(pair[1]); if(overwrite !== true){ if(typeof obj[name] == "undefined"){ obj[name] = value; }else if(typeof obj[name] == "string"){ obj[name] = [obj[name]]; obj[name].push(value); }else{ obj[name].push(value); } }else{ obj[name] = value; } } return obj; }, /** * 迭代一个数组,数组中每个成员都将调用一次所传函数, 直到函数返回false才停止执行。 * 如果传递的数组并非一个真正的数组,所传递的函数只调用它一次。 * 译注:如果不是数组,就将该“数组”放入一个[]中,而且会返回一个隐藏的int参数,代表为该array调用function的次数。 * 该函数可被以下调用: (Object item, Number index, Array allItems). * @param {Array/NodeList/Mixed} 数组 * @param {Function} 函数 * @param {Object} 作用域 */ each : function(array, fn, scope){ if(typeof array.length == "undefined" || typeof array == "string"){ array = [array]; } for(var i = 0, len = array.length; i < len; i++){ if(fn.call(scope || array[i], array[i], i, array) === false){ return i; }; } }, // deprecated combine : function(){ var as = arguments, l = as.length, r = []; for(var i = 0; i < l; i++){ var a = as[i]; if(a instanceof Array){ r = r.concat(a); }else if(a.length !== undefined && !a.substr){ r = r.concat(Array.prototype.slice.call(a, 0)); }else{ r.push(a); } } return r; }, /** * 避免传递的字符串参数被正则表达式读取 * @param {String} str * @return {String} */ escapeRe : function(s) { return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1"); }, // internal callback : function(cb, scope, args, delay){ if(typeof cb == "function"){ if(delay){ cb.defer(delay, scope, args || []); }else{ cb.apply(scope, args || []); } } }, /** * 返回dom对象,参数可以是 string (id),dom node,或Ext.Element * @param {String/HTMLElement/Element) el * @return HTMLElement */ getDom : function(el){ if(!el || !document){ return null; } return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el); }, /** * 返回当前HTML文档的{@link Ext.Element}类型 * @return Ext.Element 文档 */ getDoc : function(){ return Ext.get(document); }, /** * 返回当前document.body的{@link Ext.Element}类型 * @return Ext.Element document.body */ getBody : function(){ return Ext.get(document.body || document.documentElement); }, /** * {@link Ext.ComponentMgr#get}的简写方式 * @param {String} id * @return Ext.Component */ getCmp : function(id){ return Ext.ComponentMgr.get(id); }, /** * 验证某个值是否数字的一个辅助方法,若不是,返回指定的缺省值。 * @param {Mixed} value 应该是一个数字,但其它的类型的值亦可适当地处理 * @param {Number} defaultValue 若传入的值是非数字所返回的缺省值 * @return {Number} 数字或缺省值 */ num : function(v, defaultValue){ if(typeof v != 'number'){ return defaultValue; } return v; }, /** * 尝试去移除每个传入的对象,包括DOM,事件侦听者,并呼叫他们的destroy方法(如果存在) * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the * DOM (if applicable) and calling their destroy functions (if available). This method is primarily * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be * passed into this function in a single call as separate arguments. * @param {Mixed} arg1 An {@link Ext.Element} or {@link Ext.Component} to destroy * @param {Mixed} (optional) arg2 * @param {Mixed} (optional) etc... */ destroy : function(){ for(var i = 0, a = arguments, len = a.length; i < len; i++) { var as = a[i]; if(as){ if(as.dom){ as.removeAllListeners(); as.remove(); continue; } if(typeof as.destroy == 'function'){ as.destroy(); } } } }, removeNode : isIE ? function(){ var d; return function(n){ if(n){ d = d || document.createElement('div'); d.appendChild(n); d.innerHTML = ''; } } }() : function(n){ if(n && n.parentNode){ n.parentNode.removeChild(n); } }, // inpired by a similar function in mootools library /** * 返回参数类型的详细信息 * 返回false,或是以下类型:<ul> * <li><b>string</b>: 如果传入的是字符串</li> * <li><b>number</b>: 如果输入的是数字</li> * <li><b>boolean</b>: 如果传入的是布尔值</li> * <li><b>function</b>: 如果传入的是函数</li> * <li><b>object</b>: 如果传入的是对象</li> * <li><b>array</b>: 如果传入的是数组</li> * <li><b>regexp</b>: 如果传入的是正则表达式</li> * <li><b>element</b>: 如果传入的是DOM Element</li> * <li><b>nodelist</b>: 如果传入的是DOM Node</li> * <li><b>textnode</b>: 如果传入的是DOM Text,且非空或空格</li> * <li><b>whitespace</b>: 如果传入的是DOM Text,且是空格</li> * @param {Mixed} object * @return {String} */ type : function(o){ if(o === undefined || o === null){ return false; } if(o.htmlElement){ return 'element'; } var t = typeof o; if(t == 'object' && o.nodeName) { switch(o.nodeType) { case 1: return 'element'; case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace'; } } if(t == 'object' || t == 'function') { switch(o.constructor) { case Array: return 'array'; case RegExp: return 'regexp'; } if(typeof o.length == 'number' && typeof o.item == 'function') { return 'nodelist'; } } return t; }, /** * 如果传入的值是null、undefined或空字符串,则返回true。(可选) * @param {Mixed} value 要验证的值 * @param {Boolean} allowBlank (可选) 如果该值为true,则空字符串不会当作空而返回true * @return {Boolean} */ isEmpty : function(v, allowBlank){ return v === null || v === undefined || (!allowBlank ? v === '' : false); }, value : function(v, defaultValue, allowBlank){ return Ext.isEmpty(v, allowBlank) ? defaultValue : v; }, /** @type Boolean */ isOpera : isOpera, /** @type Boolean */ isSafari : isSafari, /** @type Boolean */ isIE : isIE, /** @type Boolean */ isIE6 : isIE && !isIE7, /** @type Boolean */ isIE7 : isIE7, /** @type Boolean */ isGecko : isGecko, /** @type Boolean */ isBorderBox : isBorderBox, /** @type Boolean */ isLinux : isLinux, /** @type Boolean */ isWindows : isWindows, /** @type Boolean */ isMac : isMac, /** @type Boolean */ isAir : !!window.htmlControl, /** * Ext自动决定浮动元素是否应该被填充。 * @type Boolean */ useShims : ((isIE && !isIE7) || (isGecko && isMac)) }); // in intellij using keyword "namespace" causes parsing errors Ext.ns = Ext.namespace; })(); Ext.ns("Ext", "Ext.util", "Ext.grid", "Ext.dd", "Ext.tree", "Ext.data", "Ext.form", "Ext.menu", "Ext.state", "Ext.lib", "Ext.layout", "Ext.app", "Ext.ux");
JavaScript
/** * @class Array */ Ext.applyIf(Array.prototype, { /** * 检查对象是否存在于该数组。 * @param {Object} 要检查的对象 * @return {Number} 返回该对象在数组中的位置(不存在则返回-1)。 */ indexOf : function(o){ for (var i = 0, len = this.length; i < len; i++){ if(this[i] == o) return i; } return -1; }, /** * 删除数组中指定对象。如果该对象不在数组中,则不进行操作。 * @param {Object} o 要移除的对象 */ remove : function(o){ var index = this.indexOf(o); if(index != -1){ this.splice(index, 1); } return this; } });
JavaScript
/** * @class Ext.Element * Represents an Element in the DOM.<br><br> * Usage:<br> * 呈现DOM里面的一个元素。<br><br> * 用法:<br> <pre><code> var el = Ext.get("my-div"); // 或者是 getEl var el = getEl("my-div"); // 或者是一个 DOM element var el = Ext.get(myDivElement); </code></pre> * 使用Ext.get或是getEl()来代替调用构造函数,保证每次调用都是获取相同的对象而非构建新的一个。 * <br><br> * <b>动画</b><br /> * 操作DOM元素,很多情况下会用一些到动画效果(可选的)。 * 动画选项应该是布尔值(true )或是Object Literal 。动画选项有: <pre> 可选项 默认值 描述 --------- -------- --------------------------------------------- duration .35 动画持续的时间 easing easeOut The easing method callback none 当动画完成后执行的函数 scope this 回调函数的作用欲(可选的) duration .35 动画持续的时间(单位:秒) easing easeOut YUI的消除方法 callback none 动画完成之后执行的函数 scope this 回调函数的作用域 </pre> *另外,可通过配置项中的“anim“来获取动画对象,这样便可停止或操控这个动画效果。例子如下: <pre><code> var el = Ext.get("my-div"); // 没有动画 el.setWidth(100); // 默认动画 el.setWidth(100, true); // 对动画的一些设置 el.setWidth(100, { duration: 1, callback: this.foo, scope: this }); // 使用属性“anim”来获取动画对象 var opt = { duration: 1, callback: this.foo, scope: this }; el.setWidth(100, opt); ... if(opt.anim.isAnimated()){ opt.anim.stop(); } </code></pre> * <b> 组合(集合的)元素</b><br /> * 要处理一组的元素,参阅<a href="Ext.CompositeElement.html">Ext.CompositeElement</a> * @constructor 直接创建新元素 * @param {String/HTMLElement} element * @param {Boolean} forceNew (可选的) 构建函数默认会检查在Cache中是否已经有这个element的实例,并是否能返回一致的实例。设置这个布尔值会中止检查(扩展这个类时较有用)。 */ (function(){ var D = Ext.lib.Dom; var E = Ext.lib.Event; var A = Ext.lib.Anim; var propCache = {}; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; var view = document.defaultView; Ext.Element = function(element, forceNew){ var dom = typeof element == "string" ? document.getElementById(element) : element; if(!dom){ //无效的id/element return null; } var id = dom.id; if(forceNew !== true && id && Ext.Element.cache[id]){ // 元素对象已存在 return Ext.Element.cache[id]; } /** * DOM元素 * @type HTMLElement */ this.dom = dom; /** * DOM元素之ID * @property id */ this.id = id || Ext.id(dom); }; var El = Ext.Element; El.prototype = { /** * 元素默认的显示模式(默认为"") * @type String */ originalDisplay : "", visibilityMode : 1, /** * CSS值的单位。如不指定则默认为px。 * @type String */ defaultUnit : "px", /** * 设置元素的可见模式。 * 当调用setVisible()时,会确定可见模式究竟是“可见性visibility”的还是“显示display”的。 * @param visMode Element.VISIBILITY 或 Element.DISPLAY * @return {Ext.Element} this */ setVisibilityMode : function(visMode){ this.visibilityMode = visMode; return this; }, /** * 调用setVisibilityMode(Element.DISPLAY)的快捷方式 * @param {String} display (可选的)当可见时显示的内容 * @return {Ext.Element} this */ enableDisplayMode : function(display){ this.setVisibilityMode(El.DISPLAY); if(typeof display != "undefined") this.originalDisplay = display; return this; }, /** * 定位此节点并按照传入的简易选择符(如 div.some-class or span:first-child)查找父节点。 * @param {String} simpleSelector 要测试的简易选择符 * @param {Number/String/HTMLElement/Element} maxDepth (可选的) 搜索深度(MaxDepth),可以为number或元素(默认是 10 || document.body) * @param {Boolean} returnEl (可选的) True表示为返回Ext.Element对象,false的话返回DOM节点 * @return {HTMLElement} 匹配的DOM节点(null的话表示没有匹配结果) */ findParent : function(simpleSelector, maxDepth, returnEl){ var p = this.dom, b = document.body, depth = 0, dq = Ext.DomQuery, stopEl; maxDepth = maxDepth || 50; if(typeof maxDepth != "number"){ stopEl = Ext.getDom(maxDepth); maxDepth = 10; } while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){ if(dq.is(p, simpleSelector)){ return returnEl ? Ext.get(p) : p; } depth++; p = p.parentNode; } return null; }, /** * 按照简易选择符查找父节点。选择符如 div.some-class or span:first-child。 * @param {String} simpleSelector 要测试的简易选择符 * @param {Number/String/HTMLElement/Element} maxDepth (可选的) 搜索深度(MaxDepth),可以为number或元素(默认是 10 || document.body) * @param {Boolean} returnEl (可选的) True表示为返回Ext.Element对象代替DOM节点 * @return {HTMLElement} 匹配的DOM节点(null的话表示没有匹配结果) */ findParentNode : function(simpleSelector, maxDepth, returnEl){ var p = Ext.fly(this.dom.parentNode, '_internal'); return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; }, /** * 传入一个选择符的参数,按照选择符并沿着dom查找父节点。选择符应是简易的选择符,如 div.some-class or span:first-child。 * @param {String} simpleSelector 要测试的简易选择符 * @param {Number/String/HTMLElement/Element} maxDepth (可选的) 搜索深度(MaxDepth),可以为number或元素(默认是 10 || document.body) * @param {Boolean} returnEl (可选的) True:返回Ext.Element对象代替DOM节点 * @return {HTMLElement} 匹配的DOM节点(null的话表示没有匹配结果) */ up : function(simpleSelector, maxDepth){ return this.findParentNode(simpleSelector, maxDepth, true); }, /** * 如果这个元素就是传入的简易选择符参数(如 div.some-class或span:first-child,返回true。 * @param {String} ss 要测试的简易选择符 * @return {Boolean} true表示元素匹配选择符成功,否则返回false */ is : function(simpleSelector){ return Ext.DomQuery.is(this.dom, simpleSelector); }, /** * 在元素上执行动画 * @param {Object} args YUI之动画配置参数 * @param {Float} duration (可选的) 动画持续多久 (默认为 .35 秒) * @param {Function} onComplete (可选的) 动画完成后调用的函数 * @param {String} easing (可选的) 采用的“松开”方法 (默认为 'easeOut') * @param {String} animType (可选的) 默认为'run',可以是'color','motion',或'scroll' * @return {Ext.Element} this */ animate : function(args, duration, onComplete, easing, animType){ this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType); return this; }, /* * @私有的 内置动画调用 */ anim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); Ext.callback(opt.callback, opt.scope || this, [this, opt]); }, this ); opt.anim = anim; return anim; }, // private legacy anim prep // 私有的 legacy anim prep preanim : function(a, i){ return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]}); }, /** . * 移除无用的文本节点 * @param {Boolean} forceReclean (可选的)缺省地, * 元素会追踪自己是否已被清除了,所以你可以不断地调用这个方法 * 然而,如果你需要更新元素而且需要强制清除,你可以传入true的参数。 */ clean : function(forceReclean){ if(this.isCleaned && forceReclean !== true){ return this; } var ns = /\S/; var d = this.dom, n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !ns.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } this.isCleaned = true; return this; }, /** * 传入一个容器(container)参数,把元素滚动到容器的视图(View)。 * @param {String/HTMLElement/Element} container (可选的)滚动容器的元素(默认为document.body) * @param {Boolean} hscroll (可选的)false表示为禁止水平滚动 * @return {Ext.Element} this */ scrollIntoView : function(container, hscroll){ var c = Ext.getDom(container) || Ext.getBody().dom; var el = this.dom; var o = this.getOffsetsTo(c), l = o[0] + c.scrollLeft, t = o[1] + c.scrollTop, b = t+el.offsetHeight, r = l+el.offsetWidth; var ch = c.clientHeight; var ct = parseInt(c.scrollTop, 10); var cl = parseInt(c.scrollLeft, 10); var cb = ct + ch; var cr = cl + c.clientWidth; if(el.offsetHeight > ch || t < ct){ c.scrollTop = t; }else if(b > cb){ c.scrollTop = b-ch; } c.scrollTop = c.scrollTop; if(hscroll !== false){ if(el.offsetWidth > c.clientWidth || l < cl){ c.scrollLeft = l; }else if(r > cr){ c.scrollLeft = r-c.clientWidth; } c.scrollLeft = c.scrollLeft; } return this; }, scrollChildIntoView : function(child, hscroll){ Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll); }, /** * 测量元素其内容的实际高度,使元素之高度适合。 * 注:改函数使用setTimeout所以新高度或者不会立即有效。 * @param {Boolean} animate (可选的)变换(默认 false) * @param {Float} duration (可选的)动画持续时间(默认为0.35秒) * @param {Function} onComplete (可选的)动画完成后执行的函数 * @param {String} easing (可选的)采用清除的方法(默认为easeOut) * @return {Ext.Element} this */ autoHeight : function(animate, duration, onComplete, easing){ var oldHeight = this.getHeight(); this.clip(); this.setHeight(1); // 强迫裁剪 setTimeout(function(){ var height = parseInt(this.dom.scrollHeight, 10); if(!animate){ this.setHeight(height); this.unclip(); if(typeof onComplete == "function"){ onComplete(); } }else{ this.setHeight(oldHeight); // 恢复原始高度 this.setHeight(height, animate, duration, function(){ this.unclip(); if(typeof onComplete == "function") onComplete(); }.createDelegate(this), easing); } }.createDelegate(this), 0); return this; }, /** * 如果当前元素是传入元素的父级元素(ancestor)返回true, * @param {HTMLElement/String} el 要检查的元素 * @return {Boolean} true表示这个元素是传入元素的父级元素,否则返回false */ contains : function(el){ if(!el){return false;} return D.isAncestor(this.dom, el.dom ? el.dom : el); }, /** * 检查当前该元素是否都使用属性visibility和属性display来显示。 * @param {Boolean} deep (可选的)True表示为沿着DOM一路看父元素是否隐藏的。 * @return {Boolean} true表示该元素当前是可见的,否则返回false */ isVisible : function(deep) { var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none"); if(deep !== true || !vis){ return vis; } var p = this.dom.parentNode; while(p && p.tagName.toLowerCase() != "body"){ if(!Ext.fly(p, '_isVisible').isVisible()){ return false; } p = p.parentNode; } return true; }, /** * 传入一个CSS选择符的参数,然后基于该选择符为子节点创建一个{@link Ext.CompositeElement}组合元素。(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} unique true表示为为每个子元素创建唯一的Ext.Element(默认为false享元的普通对象flyweight object) * @return {CompositeElement/CompositeElementLite} 组合元素 */ select : function(selector, unique){ return El.select(selector, unique, this.dom); }, /** * 传入一个CSS选择符的参数,然后基于该选择符选取其子节点(选择符不应有id) * @param {String} selector CSS选择符 * @return {Array} 匹配节点之数组 */ query : function(selector, unique){ return Ext.DomQuery.select(selector, this.dom); }, /** * 传入一个CSS选择符的参数,然后基于该选择符,不限定深度,选取单个子节点(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} returnDom (可选的)true表示为返回DOM节点,false表示为返回Ext.Element(默认为false) * @return {HTMLElement/Ext.Element} Ext.Element的子孙(如returnDom = true则为DOM节点) */ child : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(selector, this.dom); return returnDom ? n : Ext.get(n); }, /** * 传入一个CSS选择符的参数,然后基于该选择符,"直接"选取单个子节点(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} returnDom (可选的)true表示为返回DOM节点,false表示为返回Ext.Element(默认为false) * @return {HTMLElement/Ext.Element} Ext.Element的子孙(如returnDom = true则为DOM节点) */ down : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(" > " + selector, this.dom); return returnDom ? n : Ext.get(n); }, /** * 为这个元素初始化{@link Ext.dd.DD}对象 * @param {String} DD对象隶属于的那个组(Group) * @param {Object} config DD之配置对象 * @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象 * @return {Ext.dd.DD} DD对象 */ initDD : function(group, config, overrides){ var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, /** * 为这个元素初始化{@link Ext.dd.DDProxy}对象 * @param {String} group DDProxy对象隶属于的那个组(Group) * @param {Object} config DDProxy之配置对象 * @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象 * @return {Ext.dd.DDProxy} DDProxy对象 */ initDDProxy : function(group, config, overrides){ var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, /** * 为这个元素初始化{@link Ext.dd.DDTarget}对象 * @param {String} group DDTarget对象隶属于的那个组(Group) * @param {Object} config DDTarget之配置对象 * @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象 * @return {Ext.dd.DDTarget} DDTarget对象 */ initDDTarget : function(group, config, overrides){ var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, /** * 设置元素可见性(参阅细节)。 * 如果visibilityMode 被设置成 Element.DISPLAY, * 那么它会使用display属性来隐藏元素,否则它会使用visibility。默认是使用 visibility属性。 * @param {Boolean} visible 元素是否可见的 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setVisible : function(visible, animate){ if(!animate || !A){ if(this.visibilityMode == El.DISPLAY){ this.setDisplayed(visible); }else{ this.fixDisplay(); this.dom.style.visibility = visible ? "visible" : "hidden"; } }else{ var dom = this.dom; var visMode = this.visibilityMode; if(visible){ this.setOpacity(.01); this.setVisible(true); } this.anim({opacity: { to: (visible?1:0) }}, this.preanim(arguments, 1), null, .35, 'easeIn', function(){ if(!visible){ if(visMode == El.DISPLAY){ dom.style.display = "none"; }else{ dom.style.visibility = "hidden"; } Ext.get(dom).setOpacity(1); } }); } return this; }, /** * 如果属性display不是"none"就返回true * @return {Boolean} */ isDisplayed : function() { return this.getStyle("display") != "none"; }, /** * 轮回元素visibility或display,取决于visibility mode。 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ toggle : function(animate){ this.setVisible(!this.isVisible(), this.preanim(arguments, 0)); return this; }, /** * 设置Css display属性。如果value为true,则使用originalDisplay。 * @param {Boolean} value 如果value为true,则使用originalDisplay。否则直接设置显示的字符串、 * @return {Ext.Element} this */ setDisplayed : function(value) { if(typeof value == "boolean"){ value = value ? this.originalDisplay : "none"; } this.setStyle("display", value); return this; }, /** * 使这个元素得到焦点。忽略任何已捕获的异常。 * @return {Ext.Element} this */ focus : function() { try{ this.dom.focus(); }catch(e){} return this; }, /** * 使这个元素失去焦点。忽略任何已捕获的异常。 * @return {Ext.Element} this */ blur : function() { try{ this.dom.blur(); }catch(e){} return this; }, /** * 为元素添加CSS类(CSS Class)。重复的类会被忽略。 * @param {String/Array} className 要加入的CSS类或者由类组成的数组 * @return {Ext.Element} this */ addClass : function(className){ if(className instanceof Array){ for(var i = 0, len = className.length; i < len; i++) { this.addClass(className[i]); } }else{ if(className && !this.hasClass(className)){ this.dom.className = this.dom.className + " " + className; } } return this; }, /** * 添加一个或多个className到这个元素,并移除其侧边(siblings)节点上所有的样式。 * @param {String} className 要加入的className,或者是由类组成的数组 * @return {Ext.Element} this */ radioClass : function(className){ var siblings = this.dom.parentNode.childNodes; for(var i = 0; i < siblings.length; i++) { var s = siblings[i]; if(s.nodeType == 1){ Ext.get(s).removeClass(className); } } this.addClass(className); return this; }, /** * 移除元素的CSS类 * @param {String/Array} className 要移除的CSS类或者由类组成的数组 * @return {Ext.Element} this */ removeClass : function(className){ if(!className || !this.dom.className){ return this; } if(className instanceof Array){ for(var i = 0, len = className.length; i < len; i++) { this.removeClass(className[i]); } }else{ if(this.hasClass(className)){ var re = this.classReCache[className]; if (!re) { re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g"); this.classReCache[className] = re; } this.dom.className = this.dom.className.replace(re, " "); } } return this; }, classReCache: {}, /** * 轮换(Toggles)--添加或移除指定的CSS类(如果已经存在的话便删除,否则就是新增加)。 * @param {String} className 轮换的CSS类 * @return {Ext.Element} this */ toggleClass : function(className){ if(this.hasClass(className)){ this.removeClass(className); }else{ this.addClass(className); } return this; }, /** * 检查某个CSS类是否存在这个元素的DOM节点上 * @param {String} className 要检查CSS类 * @return {Boolean} true表示为类是有的,否则为false */ hasClass : function(className){ return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1; }, /** * 在这个元素身上替换CSS类。如果旧的CSS名称不存在,新的就会加入。 * @param {String} oldClassName 要被替换之CSS类 * @param {String} newClassName 新CSS类 * @return {Ext.Element} this */ replaceClass : function(oldClassName, newClassName){ this.removeClass(oldClassName); this.addClass(newClassName); return this; }, /** * 给出一些CSS属性名,得到其值 * 如el.getStyles('color', 'font-size', 'width')会返回 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}. * @param {String} 样式一 * @param {String} 样式二 * @param {String} 等等.. * @return Object 样式对象 */ getStyles : function(){ var a = arguments, len = a.length, r = {}; for(var i = 0; i < len; i++){ r[a[i]] = this.getStyle(a[i]); } return r; }, /** * 常规化当前样式和计算样式。 * @param {String} property 返回值的那个样式属性。 * @return {String} 该元素样式属性的当前值。 */ getStyle : function(){ return view && view.getComputedStyle ? function(prop){ var el = this.dom, v, cs, camel; if(prop == 'float'){ prop = "cssFloat"; } if(v = el.style[prop]){ return v; } if(cs = view.getComputedStyle(el, "")){ if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } return cs[camel]; } return null; } : function(prop){ var el = this.dom, v, cs, camel; if(prop == 'opacity'){ if(typeof el.style.filter == 'string'){ var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i); if(m){ var fv = parseFloat(m[1]); if(!isNaN(fv)){ return fv ? fv / 100 : 0; } } } return 1; }else if(prop == 'float'){ prop = "styleFloat"; } if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(v = el.style[camel]){ return v; } if(cs = el.currentStyle){ return cs[camel]; } return null; }; }(), /** * 以打包的方式设置样式属性,也可以用一个对象参数包含多个样式。 * @param {String/Object} 要设置的样式属性,或是包含多个样式的对象 * @param {String} value (可选的)样式属性的值,如果第一个参数是对象,则这个参数为null * @return {Ext.Element} this */ setStyle : function(prop, value){ if(typeof prop == "string"){ var camel; if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(camel == 'opacity') { this.setOpacity(value); }else{ this.dom.style[camel] = value; } }else{ for(var style in prop){ if(typeof prop[style] != "function"){ this.setStyle(style, prop[style]); } } } return this; }, /** * {@link #setStyle}的另一个版本,能更灵活地设置样式属性 * @param {String/Object/Function} styles 表示样式的特定格式字符串,如“width:100px”,或是对象的形式如{width:"100px"},或是能返回这些格式的函数 * @return {Ext.Element} this */ applyStyles : function(style){ Ext.DomHelper.applyStyles(this.dom, style); return this; }, /** * 获取元素基于页面坐标的X位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回false)。 * @return {Number} 元素的X位置 */ getX : function(){ return D.getX(this.dom); }, /** * 获取元素基于页面坐标的Y位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回false)。 * @return {Number} 元素的Y位置 */ getY : function(){ return D.getY(this.dom); }, /** * 获取元素基于页面坐标当前的位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回false)。 * @return {Number} 元素的XY位置 */ getXY : function(){ return D.getXY(this.dom); }, getOffsetsTo : function(el){ var o = this.getXY(); var e = Ext.fly(el, '_internal').getXY(); return [o[0]-e[0],o[1]-e[1]]; }, /** * 设置元素基于页面坐标的X位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 元素的X位置 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setX : function(x, animate){ if(!animate || !A){ D.setX(this.dom, x); }else{ this.setXY([x, this.getY()], this.preanim(arguments, 1)); } return this; }, /** * 设置元素基于页面坐标的Y位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 元素的Y位置 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setY : function(y, animate){ if(!animate || !A){ D.setY(this.dom, y); }else{ this.setXY([this.getX(), y], this.preanim(arguments, 1)); } return this; }, /** * 直接使用CSS样式(代替{@link #setX}),设定元素的left位置。 * @param {String} left CSS属性left的值 * @return {Ext.Element} this */ setLeft : function(left){ this.setStyle("left", this.addUnits(left)); return this; }, /** * 直接使用CSS样式(代替{@link #setY}),设定元素的top位置。 * @param {String} top CSS属性top的值 * @return {Ext.Element} this */ setTop : function(top){ this.setStyle("top", this.addUnits(top)); return this; }, /** * 设置元素CSS Right的样式 * @param {String} bottom Bottom CSS属性值 * @return {Ext.Element} this */ setRight : function(right){ this.setStyle("right", this.addUnits(right)); return this; }, /** * 设置元素CSS Bottom的样式 * @param {String} bottom Bottom CSS属性值 * @return {Ext.Element} this */ setBottom : function(bottom){ this.setStyle("bottom", this.addUnits(bottom)); return this; }, /** * 设置元素在页面的坐标位置,不管这个元素如何定位。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Array} pos 对于新位置(基于页面坐标)包含X & Y [x, y]的值 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setXY : function(pos, animate){ if(!animate || !A){ D.setXY(this.dom, pos); }else{ this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion'); } return this; }, /** * 设置元素在页面的坐标位置,不管这个元素如何定位。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 新定位的X值(基于页面坐标) * @param {Number} y 新定位的Y值(基于页面坐标) * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setLocation : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, /** * 设置元素在页面的坐标位置,不管这个元素如何定位。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 新定位的X值(基于页面坐标) * @param {Number} y 新定位的Y值(基于页面坐标) * @param {Boolean/Object} animate (可选的) true :为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ moveTo : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, /** * 返回给出元素的区域。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @return {Region} A Ext.lib.Region 包含"top, left, bottom, right" 成员数据 */ getRegion : function(){ return D.getRegion(this.dom); }, /** * 返回元素的偏移(offset)高度 * @param {Boolean} contentHeight (可选的) true表示为获取减去边框和内补丁(borders & padding)的宽度 * @return {Number} 元素高度 */ getHeight : function(contentHeight){ var h = this.dom.offsetHeight || 0; h = contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb"); return h < 0 ? 0 : h; }, /** * 返回元素的偏移(offset)宽度 * @param {Boolean} contentWidth (可选的) true表示为获取减去边框和内补丁(borders & padding)的宽度 * @return {Number} 元素宽度 */ getWidth : function(contentWidth){ var w = this.dom.offsetWidth || 0; w = contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr"); return w < 0 ? 0 : w; }, /** * 当偏移值不可用时就模拟一个出来。该方法返回由padding或borders调整过的元素CSS高度,也可能是偏移的高度。 * 如果不用CSS设置高度而且是display:none的元素,有可能不能正常工作。 * @return {Number} */ getComputedHeight : function(){ var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight); if(!h){ h = parseInt(this.getStyle('height'), 10) || 0; if(!this.isBorderBox()){ h += this.getFrameWidth('tb'); } } return h; }, /** * 当偏移值不可用时就模拟一个出来。该方法返回由padding或borders调整过的元素CSS宽度,也可能是偏移的宽度。 * 如果不用CSS设置宽度而且是display:none的元素,有可能不能正常工作。 * @return {Number} */ getComputedWidth : function(){ var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth); if(!w){ w = parseInt(this.getStyle('width'), 10) || 0; if(!this.isBorderBox()){ w += this.getFrameWidth('lr'); } } return w; }, /** * 返回元素尺寸大小。 * @param {Boolean} contentSize (可选的) true表示为返回减去border和padding的宽度大小 * @return {Object} 包含元素大小尺寸的对象,如{width: (element width), height: (element height)} */ getSize : function(contentSize){ return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; }, getStyleSize : function(){ var w, h, d = this.dom, s = d.style; if(s.width && s.width != 'auto'){ w = parseInt(s.width, 10); if(Ext.isBorderBox){ w -= this.getFrameWidth('lr'); } } if(s.height && s.height != 'auto'){ h = parseInt(s.height, 10); if(Ext.isBorderBox){ h -= this.getFrameWidth('tb'); } } return {width: w || this.getWidth(true), height: h || this.getHeight(true)}; }, /** * 返回视图的高度和宽度。 * @return {Object} 包含视图大小尺寸的对象,如{width: (viewport width), height: (viewport height)} */ getViewSize : function(){ var d = this.dom, doc = document, aw = 0, ah = 0; if(d == doc || d == doc.body){ return {width : D.getViewWidth(), height: D.getViewHeight()}; }else{ return { width : d.clientWidth, height: d.clientHeight }; } }, /** * 返回“值的”属性值 * @param {Boolean} asNumber 表示为将值解析为数字 * @return {String/Number} */ getValue : function(asNumber){ return asNumber ? parseInt(this.dom.value, 10) : this.dom.value; }, adjustWidth : function(width){ if(typeof width == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ width -= (this.getBorderWidth("lr") + this.getPadding("lr")); } if(width < 0){ width = 0; } } return width; }, adjustHeight : function(height){ if(typeof height == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ height -= (this.getBorderWidth("tb") + this.getPadding("tb")); } if(height < 0){ height = 0; } } return height; }, /** * 设置元素的宽度 * @param {Number} width 新宽度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setWidth : function(width, animate){ width = this.adjustWidth(width); if(!animate || !A){ this.dom.style.width = this.addUnits(width); }else{ this.anim({width: {to: width}}, this.preanim(arguments, 1)); } return this; }, /** * 设置元素的高度 * @param {Number} height 新高度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setHeight : function(height, animate){ height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.height = this.addUnits(height); }else{ this.anim({height: {to: height}}, this.preanim(arguments, 1)); } return this; }, /** * 设置元素的大小尺寸。如果动画效果被打开,高度和宽度都会产生动画的变化效果。 * @param {Number} width 新宽度 * @param {Number} height 新高度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setSize : function(width, height, animate){ if(typeof width == "object"){ // in case of object from getSize() height = width.height; width = width.width; } width = this.adjustWidth(width); height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.width = this.addUnits(width); this.dom.style.height = this.addUnits(height); }else{ this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2)); } return this; }, /** * 一次过设置元素的位置和大小。如果动画效果被打开,高度和宽度都会产生动画的变化效果。 * @param {Number} x 新位置上的x值(基于页面的坐标) * @param {Number} y 新位置上的y值(基于页面的坐标) * @param {Number} width 新宽度 * @param {Number} height 新高度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setBounds : function(x, y, width, height, animate){ if(!animate || !A){ this.setSize(width, height); this.setLocation(x, y); }else{ width = this.adjustWidth(width); height = this.adjustHeight(height); this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}}, this.preanim(arguments, 4), 'motion'); } return this; }, /** * 设置元素的位置并调整大小到指定的位置。如果动画效果被打开,高度和宽度都会产生动画的变化效果。 * @param {Ext.lib.Region} region 要填充的区域 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setRegion : function(region, animate){ this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1)); return this; }, /** * 为该组件加入事件句柄(event handler)。跟简写方式{@link #on}是一样的。 * 通常你会更多的使用元素本身{@link Ext.Element#removeListener}的方法。 * @param {String/HTMLElement} eventName 侦听事件的类型 * @param {Function} handler 句柄,事件执行的方法 * @param {Object} scope (可选的) 句柄函数执行时所在的作用域。句柄函数“this”的上下文。 * @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会下来的属性:<ul> * <li>scope {Object} 句柄函数执行时所在的作用域。句柄函数“this”的上下文。</li> * <li>delegate {String} 一个简易选择符,用于过滤目标,或是查找目标的子孙。</li> * <li>stopEvent {Boolean} true表示为阻止事件。即停止传播、阻止默认动作。</li> * <li>preventDefault {Boolean} true表示为阻止默认动作</li> * <li>stopPropagation {Boolean} true表示为阻止事件传播</li> * <li>normalized {Boolean} false表示对句柄函数传入一个浏览器对象代替Ext.EventObject</li> * <li>delay {Number} 触发事件后开始执行句柄的延时时间(invocation:the act of making a particular function start),单位:毫秒</li> * <li>single {Boolean} true代表为下次事件触发加入一个要处理的句柄,然后再移除本身。</li> * <li>buffer {Number} 指定一个毫秒数,会将句柄安排到{@link Ext.util.DelayedTask}延时之后才执行 . * 如果事件在那个事件再次触发,则原句柄将<em>不会</em> 被启用,但是新句柄会安排在其位置。</li> * </ul><br> * <p>参阅{@link Ext.Element#addListener}的例子已了解如何使用这些选项。</p> * <p> * <b>Combining Options</b><br> * In the following examples, the shorthand form {@link #on} is used rather than the more verbose * addListener. The two are equivalent. Using the options argument, it is possible to combine different * types of listeners:<br> * <br> * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)<div style="margin: 5px 20px 20px;"> * Code:<pre><code> el.on('click', this.onClick, this, { single: true, delay: 100, stopEvent : true, forumId: 4 });</code></pre> * <p> * <b>Attaching multiple handlers in 1 call</b><br> * The method also allows for a single argument to be passed which is a config object containing properties * which specify multiple handlers. * <p> * Code:<pre><code> el.on({ 'click' : { fn: this.onClick, scope: this, delay: 100 }, 'mouseover' : { fn: this.onMouseOver, scope: this }, 'mouseout' : { fn: this.onMouseOut, scope: this } });</code></pre> * <p> * Or a shorthand syntax:<br> * Code:<pre><code> el.on({ 'click' : this.onClick, 'mouseover' : this.onMouseOver, 'mouseout' : this.onMouseOut, scope: this });</code></pre> */ addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); }, /** * 从这个元素上移除事件句柄(event handler),跟简写方式{@link #un}是一样的。 * 举例: * <pre><code> el.removeListener('click', this.handlerFn); //或 el.un('click', this.handlerFn); </code></pre> * @param {String} eventName 要移除事件的类型 * @param {Function} fn 事件执行的方法 * @return {Ext.Element} this */ removeListener : function(eventName, fn){ Ext.EventManager.removeListener(this.dom, eventName, fn); return this; }, /** * 在该元素身上移除所有已加入的侦听器 * @return {Ext.Element} this */ removeAllListeners : function(){ E.purgeElement(this.dom); return this; }, /** * 创建此元素的事件句柄,由此元素接替另外的对象触发和处理事件。 * @param {String} eventName 要接替的事件名称 * @param {Object} object 任何继承自{@link Ext.util.Observable}的对象用于在上下文里触发接替的事件 */ relayEvent : function(eventName, observable){ this.on(eventName, function(e){ observable.fireEvent(eventName, e); }); }, /** * 设置元素透明度 * @param {Float} opacity 新的透明度。 0 = 透明, .5 = 50% 可见, 1 =完全可见, 等等 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setOpacity : function(opacity, animate){ if(!animate || !A){ var s = this.dom.style; if(Ext.isIE){ s.zoom = 1; s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") + (opacity == 1 ? "" : " alpha(opacity=" + opacity * 100 + ")"); }else{ s.opacity = opacity; } }else{ this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn'); } return this; }, /** * 获取X坐标 * @param {Boolean} local true表示为获取局部CSS位置代替页面坐标 */ getLeft : function(local){ if(!local){ return this.getX(); }else{ return parseInt(this.getStyle("left"), 10) || 0; } }, /** * 获取元素的右X坐标 (元素X位置 + 元素宽度) * @param {Boolean} local True :获取局部CSS位置代替页面坐标 * @return {Number} */ getRight : function(local){ if(!local){ return this.getX() + this.getWidth(); }else{ return (this.getLeft(true) + this.getWidth()) || 0; } }, /** * 获取顶部Y坐标 * @param {Boolean} local :获取局部CSS位置代替页面坐标 * @return {Number} */ getTop : function(local) { if(!local){ return this.getY(); }else{ return parseInt(this.getStyle("top"), 10) || 0; } }, /** * 获取元素的底部Y坐标 (元素Y位置 + 元素宽度) * @param {Boolean} local True :获取局部CSS位置代替页面坐标 * @return {Number} */ getBottom : function(local){ if(!local){ return this.getY() + this.getHeight(); }else{ return (this.getTop(true) + this.getHeight()) || 0; } }, /** * 初始化元素的定位。 * 如果不传入一个特定的定位,而又还没定位的话,将会使这个元素 相对(relative)定位 * @param {String} pos (可选的) 使用 "relative", "absolute" 或 "fixed"的定位 * @param {Number} zIndex (可选的) z-Index值 * @param {Number} x (可选的)设置页面 X方向位置 * @param {Number} y (可选的) 设置页面 Y方向位置 */ position : function(pos, zIndex, x, y){ if(!pos){ if(this.getStyle('position') == 'static'){ this.setStyle('position', 'relative'); } }else{ this.setStyle("position", pos); } if(zIndex){ this.setStyle("z-index", zIndex); } if(x !== undefined && y !== undefined){ this.setXY([x, y]); }else if(x !== undefined){ this.setX(x); }else if(y !== undefined){ this.setY(y); } }, /** * 当文档加载后清除位置并复位到默认 * @param {String} value (可选的) 用于 left,right,top,bottom的值, 默认为 '' (空白字符串). 你可使用 'auto'. * @return {Ext.Element} this */ clearPositioning : function(value){ value = value ||''; this.setStyle({ "left": value, "right": value, "top": value, "bottom": value, "z-index": "", "position" : "static" }); return this; }, /** * 获取一个包含CSS定位的对象 * 有用的技巧:连同setPostioning一起,可在更新执行之前,先做一个快照(snapshot),之后便可恢复该元素。 * @return {Object} */ getPositioning : function(){ var l = this.getStyle("left"); var t = this.getStyle("top"); return { "position" : this.getStyle("position"), "left" : l, "right" : l ? "" : this.getStyle("right"), "top" : t, "bottom" : t ? "" : this.getStyle("bottom"), "z-index" : this.getStyle("z-index") }; }, /** * 获取指定边(side(s))的 border(s)宽度 * @param {String} side可以是 t, l, r, b或是任何组合 * 例如,传入lr的参数会得到(l)eft padding +(r)ight padding * @return {Number} 四边的padding之和 */ getBorderWidth : function(side){ return this.addStyles(side, El.borders); }, /** * 获取指定边(side(s))的padding宽度 * @param {String} side 可以是 t, l, r, b或是任何组合 * 例如,传入lr的参数会得到(l)eft padding +(r)ight padding * @return {Number} 四边的padding之和 */ getPadding : function(side){ return this.addStyles(side, El.paddings); }, /** * 由getPositioning()返回的对象去设置定位 * @param {Object} posCfg * @return {Ext.Element} this */ setPositioning : function(pc){ this.applyStyles(pc); if(pc.right == "auto"){ this.dom.style.right = ""; } if(pc.bottom == "auto"){ this.dom.style.bottom = ""; } return this; }, fixDisplay : function(){ if(this.getStyle("display") == "none"){ this.setStyle("visibility", "hidden"); this.setStyle("display", this.originalDisplay); if(this.getStyle("display") == "none"){ this.setStyle("display", "block"); } } }, /** * 快速设置left和top(采用默认单位) * @param {String} left CSS的left属性值 * @param {String} top TCSS的top属性值 * @return {Ext.Element} this */ setLeftTop : function(left, top){ this.dom.style.left = this.addUnits(left); this.dom.style.top = this.addUnits(top); return this; }, /** * 移动这个元素到相对于当前的位置。 * @param {String} direction 允许的值:"l","left" - "r","right" - "t","top","up" - "b","bottom","down". * @param {Number} distance 元素移动有多远(像素) * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ move : function(direction, distance, animate){ var xy = this.getXY(); direction = direction.toLowerCase(); switch(direction){ case "l": case "left": this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2)); break; case "r": case "right": this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2)); break; case "t": case "top": case "up": this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2)); break; case "b": case "bottom": case "down": this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2)); break; } return this; }, /** * 保存当前的溢出(overflow),然后进行裁剪元素的溢出部分 - 使用 {@link #unclip}来移除 * @return {Ext.Element} this */ clip : function(){ if(!this.isClipped){ this.isClipped = true; this.originalClip = { "o": this.getStyle("overflow"), "x": this.getStyle("overflow-x"), "y": this.getStyle("overflow-y") }; this.setStyle("overflow", "hidden"); this.setStyle("overflow-x", "hidden"); this.setStyle("overflow-y", "hidden"); } return this; }, /** * 在调用clip()之前,返回原始的裁剪部分(溢出的) * @return {Ext.Element} this */ unclip : function(){ if(this.isClipped){ this.isClipped = false; var o = this.originalClip; if(o.o){this.setStyle("overflow", o.o);} if(o.x){this.setStyle("overflow-x", o.x);} if(o.y){this.setStyle("overflow-y", o.y);} } return this; }, /** * 返回X、Y坐标,由元素已标记好的位置(anchor position)指定。 * @param {String} anchor (可选的) 指定的标记位置(默认为 "c")。参阅 {@link #alignTo}可支持的标记好的位置(anchor position)之细节。 * @param {Object} size (可选的) 用于计算标记位置的对象 * {width: (目标宽度), height: (目标高度)} (默认为元素当前大小) * @param {Boolean} local (可选的) true表示为获取局部的(元素相对的 top/left) 标记的位置而非页面坐标 * @return {Array} [x, y] 包含元素X、Y坐标的数组 */ getAnchorXY : function(anchor, local, s){ //Passing a different size is useful for pre-calculating anchors, //especially for anchored animations that change the el size. var w, h, vp = false; if(!s){ var d = this.dom; if(d == document.body || d == document){ vp = true; w = D.getViewWidth(); h = D.getViewHeight(); }else{ w = this.getWidth(); h = this.getHeight(); } }else{ w = s.width; h = s.height; } var x = 0, y = 0, r = Math.round; switch((anchor || "tl").toLowerCase()){ case "c": x = r(w*.5); y = r(h*.5); break; case "t": x = r(w*.5); y = 0; break; case "l": x = 0; y = r(h*.5); break; case "r": x = w; y = r(h*.5); break; case "b": x = r(w*.5); y = h; break; case "tl": x = 0; y = 0; break; case "bl": x = 0; y = h; break; case "br": x = w; y = h; break; case "tr": x = w; y = 0; break; } if(local === true){ return [x, y]; } if(vp){ var sc = this.getScroll(); return [x + sc.left, y + sc.top]; } //Add the element's offset xy //加入元素的xy偏移 var o = this.getXY(); return [x+o[0], y+o[1]]; }, /** * 获取该元素对齐另一个元素时候的x,y坐标。参阅 {@link #alignTo}了解可支持的位置值。 * @param {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @return {Array} [x, y] */ getAlignToXY : function(el, p, o){ el = Ext.get(el); if(!el || !el.dom){ throw "Element.alignToXY with an element that doesn't exist"; } var d = this.dom; var c = false; var p1 = "", p2 = ""; o = o || [0,0]; if(!p){ p = "tl-bl"; }else if(p == "?"){ p = "tl-bl?"; }else if(p.indexOf("-") == -1){ p = "tl-" + p; } p = p.toLowerCase(); var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/); if(!m){ throw "Element.alignTo with an invalid alignment " + p; } p1 = m[1]; p2 = m[2]; c = !!m[3]; var a1 = this.getAnchorXY(p1, true); var a2 = el.getAnchorXY(p2, false); var x = a2[0] - a1[0] + o[0]; var y = a2[1] - a1[1] + o[1]; if(c){ var w = this.getWidth(), h = this.getHeight(), r = el.getRegion(); var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5; var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1); var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1); var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t")); var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r")); var doc = document; var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5; var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5; if((x+w) > dw + scrollX){ x = swapX ? r.left-w : dw+scrollX-w; } if(x < scrollX){ x = swapX ? r.right : scrollX; } if((y+h) > dh + scrollY){ y = swapY ? r.top-h : dh+scrollY-h; } if (y < scrollY){ y = swapY ? r.bottom : scrollY; } } return [x,y]; }, getConstrainToXY : function(){ var os = {top:0, left:0, bottom:0, right: 0}; return function(el, local, offsets, proposedXY){ el = Ext.get(el); offsets = offsets ? Ext.applyIf(offsets, os) : os; var vw, vh, vx = 0, vy = 0; if(el.dom == document.body || el.dom == document){ vw = Ext.lib.Dom.getViewWidth(); vh = Ext.lib.Dom.getViewHeight(); }else{ vw = el.dom.clientWidth; vh = el.dom.clientHeight; if(!local){ var vxy = el.getXY(); vx = vxy[0]; vy = vxy[1]; } } var s = el.getScroll(); vx += offsets.left + s.left; vy += offsets.top + s.top; vw -= offsets.right; vh -= offsets.bottom; var vr = vx+vw; var vb = vy+vh; var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth, h = this.dom.offsetHeight; var moved = false; if((x + w) > vr){ x = vr - w; moved = true; } if((y + h) > vb){ y = vb - h; moved = true; } if(x < vx){ x = vx; moved = true; } if(y < vy){ y = vy; moved = true; } return moved ? [x, y] : false; }; }(), adjustForConstraints : function(xy, parent, offsets){ return this.getConstrainToXY(parent || document, false, offsets, xy) || xy; }, /** * 对齐元素到另外一个元素的指定的标记。如果这个元素是document,对齐到视图 * 位置参数是可选的, 可指定为下列格式: * <ul> * <li><b>空白</b>: 默认为 aligning the element"s top-left corner to * the target"s bottom-left corner ("tl-bl").</li> * <li><b>有一个锚点()One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point. * The element being aligned will position its top-left corner (tl) to * that point. <i>This method has been * deprecated in favor of the newer two anchor syntax below</i>.</li> * <li><b>有两个锚点</b>: * If two values from the table below are passed separated by a dash, * the first value is used as the * element"s anchor point, and the second value is used as the target"s anchor point.</li> * </ul> * 下列可支持的锚点位置: <pre> 值 描述 ----- ----------------------------- tl The top left corner (default) t The center of the top edge tr The top right corner l The center of the left edge c In the center of the element r The center of the right edge bl The bottom left corner b The center of the bottom edge br The bottom right corner </pre> Example Usage: 使用范例: <pre><code> // align el to other-el using the default positioning ("tl-bl", non-constrained) el.alignTo("other-el"); // align the top left corner of el with the top right corner of other-el (constrained to viewport) el.alignTo("other-el", "tr?"); // align the bottom right corner of el with the center left edge of other-el el.alignTo("other-el", "br-l?"); // align the center of el with the bottom left corner of other-el and // adjust the x position by -6 pixels (and the y position by 0) el.alignTo("other-el", "c-bl", [-6, 0]); </code></pre> * @param {Mixed} element The element to align to. * @param {String} position The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * @param {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ alignTo : function(element, position, offsets, animate){ var xy = this.getAlignToXY(element, position, offsets); this.setXY(xy, this.preanim(arguments, 3)); return this; }, /** * 标记一个元素到另外一个元素,并当window resiz时重新对齐。 * @param {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @param {Boolean/Number} monitorScroll (可选的) true表示为监视body滚动并重新定位。如果该参数是一个数字,即意味有缓冲延时(默认为 50ms) * @param {Function} callback 动画完成后执行的函数 * @return {Ext.Element} this */ anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){ var action = function(){ this.alignTo(el, alignment, offsets, animate); Ext.callback(callback, this); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); // align immediately return this; }, /** * Clears any opacity settings from this element. Required in some cases for IE. * 清除这个元素的透明度设置。IE有时候会用到 * @return {Ext.Element} this */ clearOpacity : function(){ if (window.ActiveXObject) { if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){ this.dom.style.filter = ""; } } else { this.dom.style.opacity = ""; this.dom.style["-moz-opacity"] = ""; this.dom.style["-khtml-opacity"] = ""; } return this; }, /** * 隐藏此元素 -使用display mode 来决定用 "display" 抑或 "visibility"。 参阅 {@link #setVisible}. * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ hide : function(animate){ this.setVisible(false, this.preanim(arguments, 0)); return this; }, /** * 显示此元素 -使用display mode 来决定用 "display" 抑或 "visibility"。 参阅 {@link #setVisible}. * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ show : function(animate){ this.setVisible(true, this.preanim(arguments, 0)); return this; }, /** * @私有的 测试某个尺寸是否有单位,否则加入默认单位。 */ addUnits : function(size){ return Ext.Element.addUnits(size, this.defaultUnit); }, /** * 更新该元素的innerHTML,遇到脚本可以执行。 * @param {String} html 新的HTML * @param {Boolean} loadScripts (可选的) true表示为遇到脚本要执行 * @param {Function} callback 当更新完成后,你加载一个同步脚本,得知更新完成。 * @return {Ext.Element} this */ update : function(html, loadScripts, callback){ if(typeof html == "undefined"){ html = ""; } if(loadScripts !== true){ this.dom.innerHTML = html; if(typeof callback == "function"){ callback(); } return this; } var id = Ext.id(); var dom = this.dom; html += '<span id="' + id + '"></span>'; E.onAvailable(id, function(){ var hd = document.getElementsByTagName("head")[0]; var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig; var srcRe = /\ssrc=([\'\"])(.*?)\1/i; var typeRe = /\stype=([\'\"])(.*?)\1/i; var match; while(match = re.exec(html)){ var attrs = match[1]; var srcMatch = attrs ? attrs.match(srcRe) : false; if(srcMatch && srcMatch[2]){ var s = document.createElement("script"); s.src = srcMatch[2]; var typeMatch = attrs.match(typeRe); if(typeMatch && typeMatch[2]){ s.type = typeMatch[2]; } hd.appendChild(s); }else if(match[2] && match[2].length > 0){ if(window.execScript) { window.execScript(match[2]); } else { window.eval(match[2]); } } } var el = document.getElementById(id); if(el){Ext.removeNode(el);} if(typeof callback == "function"){ callback(); } }); dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, ""); return this; }, /** * 直接访问Updater的{@link Ext.Updater#update}方法(相同的参数) * @param {String/Function} url 针对该请求的url或是能返回url的函数 * @param {String/Object} params(可选的)作为url一部分的参数,可以是已编码的字符串"param1=1&amp;param2=2",或是一个对象{param1: 1, param2: 2} * @param {Function} callback (可选的)请求往返完成后的回调,调用时有参数(oElement, bSuccess) * @param {Boolean} discardUrl (可选的)默认情况下你执行一次更新后,最后一次url会保存到defaultUrl。如果true的话,将不会保存。 * @return {Ext.Element} this */ load : function(){ var um = this.getUpdater(); um.update.apply(um, arguments); return this; }, /** * 获取这个元素的UpdateManager * @return {Ext.UpdateManager} The Updater */ getUpdater : function(){ if(!this.updateManager){ this.updateManager = new Ext.Updater(this); } return this.updateManager; }, /** * 禁止该元素的文本可被选择(可跨浏览器)。 * @return {Ext.Element} this */ unselectable : function(){ this.dom.unselectable = "on"; this.swallowEvent("selectstart", true); this.applyStyles("-moz-user-select:none;-khtml-user-select:none;"); this.addClass("x-unselectable"); return this; }, /** * 计算该元素的x,y到屏幕中心的值 * @return {Array} The x, y values [x, y] */ getCenterXY : function(){ return this.getAlignToXY(document, 'c-c'); }, /** * 在视图或其他元素中,居中元素。 * @param {String/HTMLElement/Ext.Element} centerIn (可选的)视图或其他元素 */ center : function(centerIn){ this.alignTo(centerIn || document, 'c-c'); return this; }, /** * 测试不同的CSS规则/浏览器以确定该元素是否使用Border Box * @return {Boolean} */ isBorderBox : function(){ return noBoxAdjust[this.dom.tagName.toLowerCase()] || Ext.isBorderBox; }, /** * 返回一个BOX {x, y, width, height},可用于匹配其他元素的大小/位置。 * @param {Boolean} contentBox (可选的)true表示为返回元素内容的BOX。 * @param {Boolean} local (可选的) true表示为返回元素的left和top代替页面的x/y。 * @return {Object} */ getBox : function(contentBox, local){ var xy; if(!local){ xy = this.getXY(); }else{ var left = parseInt(this.getStyle("left"), 10) || 0; var top = parseInt(this.getStyle("top"), 10) || 0; xy = [left, top]; } var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx; if(!contentBox){ bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h}; }else{ var l = this.getBorderWidth("l")+this.getPadding("l"); var r = this.getBorderWidth("r")+this.getPadding("r"); var t = this.getBorderWidth("t")+this.getPadding("t"); var b = this.getBorderWidth("b")+this.getPadding("b"); bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)}; } bx.right = bx.x + bx.width; bx.bottom = bx.y + bx.height; return bx; }, /** * 传入的“side”的参数,统计边框和内补丁(padding & borders)的宽度并返回该值。 * 参阅getBorderWidth()以得到更多sides的资料 * @param {String} sides * @return {Number} */ getFrameWidth : function(sides, onlyContentBox){ return onlyContentBox && Ext.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides)); }, /** * 设置元素之Box。使用getBox() 在其他对象身上获取box对象。 * 如果动画为true,那么高度和宽度都会同时出现动画效果。 * @param {Object} box 填充的Box {x, y, width, height} * @param {Boolean} adjust (可选的) 是否自动调整由box-mode问题引起的高度和宽度设置 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setBox : function(box, adjust, animate){ var w = box.width, h = box.height; if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){ w -= (this.getBorderWidth("lr") + this.getPadding("lr")); h -= (this.getBorderWidth("tb") + this.getPadding("tb")); } this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2)); return this; }, /** * 强制浏览器重新渲染该元素 * @return {Ext.Element} this */ repaint : function(){ var dom = this.dom; this.addClass("x-repaint"); setTimeout(function(){ Ext.get(dom).removeClass("x-repaint"); }, 1); return this; }, /** * 返回该元素的top、left、right 和 bottom 属性,以表示margin(外补丁)。 * 若有sides参数传入,即返回已计算好的sides宽度。 * @param {String} sides (可选的) 任何 l, r, t, b的组合,以获取该 sides的统计。 * @return {Object/Number} */ getMargins : function(side){ if(!side){ return { top: parseInt(this.getStyle("margin-top"), 10) || 0, left: parseInt(this.getStyle("margin-left"), 10) || 0, bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0, right: parseInt(this.getStyle("margin-right"), 10) || 0 }; }else{ return this.addStyles(side, El.margins); } }, addStyles : function(sides, styles){ var val = 0, v, w; for(var i = 0, len = sides.length; i < len; i++){ v = this.getStyle(styles[sides.charAt(i)]); if(v){ w = parseInt(v, 10); if(w){ val += (w >= 0 ? w : -1 * w); } } } return val; }, /** * 创建代理(Proxy),即元素的元素 * @param {String/Object} config 代理元素的类名称或是DomHelper配置项对象 * @param {String/HTMLElement} renderTo (可选的) 成为代理的元素或是元素ID (默认为 document.body) * @param {Boolean} matchBox (可选的) true表示为立即和代理对齐和设置大小 (默认为 false) * @return {Ext.Element} 新代理元素 */ createProxy : function(config, renderTo, matchBox){ config = typeof config == "object" ? config : {tag : "div", cls: config}; var proxy; if(renderTo){ proxy = Ext.DomHelper.append(renderTo, config, true); }else { proxy = Ext.DomHelper.insertBefore(this.dom, config, true); } if(matchBox){ proxy.setBox(this.getBox()); } return proxy; }, /** * 在元素身上遮上一个蒙板(mask),以禁止用户操作。须core.css。 * 这个方法只能用于接受子节点(child nodes)的元素。 * @param {String} msg (可选的) 蒙板显示的信息 * @param {String} msgCls (可选的) 信息元素的CSS类 * @return {Element} 信息元素 */ mask : function(msg, msgCls){ if(this.getStyle("position") == "static"){ this.setStyle("position", "relative"); } if(this._maskMsg){ this._maskMsg.remove(); } if(this._mask){ this._mask.remove(); } this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true); this.addClass("x-masked"); this._mask.setDisplayed(true); if(typeof msg == 'string'){ this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true); var mm = this._maskMsg; mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg"; mm.dom.firstChild.innerHTML = msg; mm.setDisplayed(true); mm.center(this); } if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ this._mask.setSize(this.dom.clientWidth, this.getHeight()); } return this._mask; }, /** * 移除之前的蒙板。 * 如果removeEl是true,则蒙板会被摧毁,否则放在缓存cache中。 */ unmask : function(){ if(this._mask){ if(this._maskMsg){ this._maskMsg.remove(); delete this._maskMsg; } this._mask.remove(); delete this._mask; } this.removeClass("x-masked"); }, /** * 返回true表示为这个元素应用了蒙板。 * @return {Boolean} */ isMasked : function(){ return this._mask && this._mask.isVisible(); }, /** * 创建一个iframe垫片来使得select和其他windowed对象在该元素显示之下。 * @return {Ext.Element} 新垫片元素 */ createShim : function(){ var el = document.createElement('iframe'); el.frameBorder = 'no'; el.className = 'ext-shim'; if(Ext.isIE && Ext.isSecure){ el.src = Ext.SSL_SECURE_URL; } var shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); shim.autoBoxAdjust = false; return shim; }, /** * 从DOM里面移除该元素,并从缓存中删除。 */ remove : function(){ Ext.removeNode(this.dom); delete El.cache[this.dom.id]; }, /** * 设置事件句柄,当鼠标在此元素之上作用的Css样式类。自动过滤因mouseout事件引起在子元素上的轻移(Flicker) * @param {Function} overFn * @param {Function} outFn * @param {Object} scope (可选的) * @return {Ext.Element} this */ hover : function(overFn, outFn, scope){ var preOverFn = function(e){ if(!e.within(this, true)){ overFn.apply(scope || this, arguments); } }; var preOutFn = function(e){ if(!e.within(this, true)){ outFn.apply(scope || this, arguments); } }; this.on("mouseover", preOverFn, this.dom); this.on("mouseout", preOutFn, this.dom); return this; }, /** * 设置事件句柄,当此鼠标位于元素上方时作用的CSS样式类。 * @param {String} className * @param {Boolean} preventFlicker (可选的) 如果为true,会阻止因mouseout事件引起在子元素上的轻移(Flicker) * @return {Ext.Element} this */ addClassOnOver : function(className, preventFlicker){ this.hover( function(){ Ext.fly(this, '_internal').addClass(className); }, function(){ Ext.fly(this, '_internal').removeClass(className); } ); return this; }, /** * 设置事件句柄,当此元素得到焦点(focus)时作用的CSS样式类。 * @param {String} className * @return {Ext.Element} this */ addClassOnFocus : function(className){ this.on("focus", function(){ Ext.fly(this, '_internal').addClass(className); }, this.dom); this.on("blur", function(){ Ext.fly(this, '_internal').removeClass(className); }, this.dom); return this; }, /** * 当鼠标在该元素上面按下接着松开(即单击效果),设置event handlers来添加和移除css类。 * @param {String} className * @return {Ext.Element} this */ addClassOnClick : function(className){ var dom = this.dom; this.on("mousedown", function(){ Ext.fly(dom, '_internal').addClass(className); var d = Ext.getDoc(); var fn = function(){ Ext.fly(dom, '_internal').removeClass(className); d.removeListener("mouseup", fn); }; d.on("mouseup", fn); }); return this; }, /** * 事件上报(bubbling)的过程中停止特定的事件,阻止默认动作(可选的)。 * @param {String} eventName * @param {Boolean} preventDefault (可选的)true表示阻止默认动作 * @return {Ext.Element} this */ swallowEvent : function(eventName, preventDefault){ var fn = function(e){ e.stopPropagation(); if(preventDefault){ e.preventDefault(); } }; if(eventName instanceof Array){ for(var i = 0, len = eventName.length; i < len; i++){ this.on(eventName[i], fn); } return this; } this.on(eventName, fn); return this; }, /** * 获取此节点的父级元素 * @param {String} selector (optional) 通过简易选择符来查找下一个侧边节点 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 下一个侧边节点或null */ parent : function(selector, returnDom){ return this.matchNode('parentNode', 'parentNode', selector, returnDom); }, /** * 获取下一个侧边节点,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找下一个侧边节点 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 下一个侧边节点或null */ next : function(selector, returnDom){ return this.matchNode('nextSibling', 'nextSibling', selector, returnDom); }, /** * 获取上一个侧边节点,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找上一个侧边节点 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 上一个侧边节点或null */ prev : function(selector, returnDom){ return this.matchNode('previousSibling', 'previousSibling', selector, returnDom); }, /** * 获取第一个子元素,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找第一个子元素 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 第一个子元素或null */ first : function(selector, returnDom){ return this.matchNode('nextSibling', 'firstChild', selector, returnDom); }, /** * 获取最后一个子元素,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找最后一个元素 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 最后一个元素或null */ last : function(selector, returnDom){ return this.matchNode('previousSibling', 'lastChild', selector, returnDom); }, matchNode : function(dir, start, selector, returnDom){ var n = this.dom[start]; while(n){ if(n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))){ return !returnDom ? Ext.get(n) : n; } n = n[dir]; } return null; }, /** * 传入一个或多个元素,加入到该元素 * @param {String/HTMLElement/Array/Element/CompositeElement} el * @return {Ext.Element} this */ appendChild: function(el){ el = Ext.get(el); el.appendTo(this); return this; }, /** * 传入一个DomHelper配置项对象的参数,将其创建并加入其到该元素; * 可选地,可指定在其子元素(哪个子元素由参数传入)之前的地方插入。 * @param {Object} config DomHelper元素配置项对象 * @param {HTMLElement} insertBefore (可选的) 该元素的子元素 * @param {Boolean} returnDom (可选的) true表示为返回标准的DOM节点而非一个Ext.Element类型的元素 * @return {Ext.Element} 新的子元素 */ createChild: function(config, insertBefore, returnDom){ config = config || {tag:'div'}; if(insertBefore){ return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true); } return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); }, /** * 传入元素的参数,将该元素加入到传入的元素 * @param {String/HTMLElement/Element} el 新父元素 * @return {Ext.Element} this */ appendTo: function(el){ el = Ext.getDom(el); el.appendChild(this.dom); return this; }, /** * 传入元素的参数,将该元素的DOM插入其之前 * @param {String/HTMLElement/Element} el 在它前面插入的那个元素 * @return {Ext.Element} this */ insertBefore: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el); return this; }, /** * 传入元素的参数,将该元素的DOM插入其之后 * @param {String/HTMLElement/Element} el 在它后面插入的那个元素 * @return {Ext.Element} this */ insertAfter: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el.nextSibling); return this; }, /** * 插入(或创建)一个元素(或DomHelper配置项对象)作为该元素的第一个子元素 * @param {String/HTMLElement/Element/Object} el 可以是id;或是插入的元素;或是要创建和插入的DomHelper配置项对象 * @return {Ext.Element} 新子元素 */ insertFirst: function(el, returnDom){ el = el || {}; if(typeof el == 'object' && !el.nodeType){ // dh config return this.createChild(el, this.dom.firstChild, returnDom); }else{ el = Ext.getDom(el); this.dom.insertBefore(el, this.dom.firstChild); return !returnDom ? Ext.get(el) : el; } }, /** * 插入(或创建)一个元素(或DomHelper配置项对象)作为该元素的侧边节点。 * @param {String/HTMLElement/Element/Object} el 可以是id;或是插入的元素;或是要创建和插入的DomHelper配置项对象 * @param {String} where (可选的) 'before' 或 'after' 默认为before * @param {Boolean} returnDom (可选的) true表示返回没加工过的DOM元素而非Ext.Element * @return {Ext.Element} 被插入的元素 */ insertSibling: function(el, where, returnDom){ var rt; if(el instanceof Array){ for(var i = 0, len = el.length; i < len; i++){ rt = this.insertSibling(el[i], where, returnDom); } return rt; } where = where ? where.toLowerCase() : 'before'; el = el || {}; var refNode = where == 'before' ? this.dom : this.dom.nextSibling; if(typeof el == 'object' && !el.nodeType){ // dh config if(where == 'after' && !this.dom.nextSibling){ rt = Ext.DomHelper.append(this.dom.parentNode, el, !returnDom); }else{ rt = Ext.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom); } }else{ rt = this.dom.parentNode.insertBefore(Ext.getDom(el), refNode); if(!returnDom){ rt = Ext.get(rt); } } return rt; }, /** * 创建和打包(warp)该元素和其他元素 * @param {Object} config (可选的) 包裹元素(null的话则是一个空白的div)的DomHelper配置项对象 * @param {Boolean} returnDom (可选的) true表示为返回没加工过的DOM元素,而非Ext.Element * @return {/HTMLElementElement} 刚创建好的包裹元素 */ wrap: function(config, returnDom){ if(!config){ config = {tag: "div"}; } var newEl = Ext.DomHelper.insertBefore(this.dom, config, !returnDom); newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); return newEl; }, /** * 用于当前这个元素替换传入的元素 * @param {Mixed} el 要替换的元素 * @return {Ext.Element} this */ replace: function(el){ el = Ext.get(el); this.insertBefore(el); el.remove(); return this; }, /** * 用传入的元素替换这个元素。 * @param {Mixed/Object} el 新元素或是要创建的DomHelper配置项对象 * @return {Ext.Element} this */ replaceWith: function(el){ if(typeof el == 'object' && !el.nodeType){ // dh config el = this.insertSibling(el, 'before'); }else{ el = Ext.getDom(el); this.dom.parentNode.insertBefore(el, this.dom); } El.uncache(this.id); this.dom.parentNode.removeChild(this.dom); this.dom = el; this.id = Ext.id(el); El.cache[this.id] = this; return this; }, /** * 插入HTML片断到这个元素 * @param {String} where 要插入的html放在元素的哪里 - beforeBegin, afterBegin, beforeEnd, afterEnd. * @param {String} html HTML片断 * @param {Boolean} returnEl true表示为返回一个Ext.Element * @return {HTMLElement} 被插入之节点(或最近的,如果超过一处插入的话) */ insertHtml : function(where, html, returnEl){ var el = Ext.DomHelper.insertHtml(where, this.dom, html); return returnEl ? Ext.get(el) : el; }, /** * 传入属性(attributes)的参数,使之成为该元素的属性(一个样式的属性可以是字符串,对象或函数function) * @param {Object} o 属性对象 * @param {Boolean} useSet (可选的) false表示为用expandos来重写默认的setAttribute * @return {Ext.Element} this */ set : function(o, useSet){ var el = this.dom; useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet; for(var attr in o){ if(attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else if(o.hasOwnProperty(attr)){ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } if(o.style){ Ext.DomHelper.applyStyles(el, o.style); } return this; }, /** * 构建KeyMap的快捷方式 * @param {Number/Array/Object/String} key 可侦听代码的数值、key代码的数组的字串符,或者是像这样的object: {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)} * @param {Function} fn 调用的函数 * @param {Object} scope (可选的) 函数的作用域 * @return {Ext.KeyMap} 创建好的KeyMap */ addKeyListener : function(key, fn, scope){ var config; if(typeof key != "object" || key instanceof Array){ config = { key: key, fn: fn, scope: scope }; }else{ config = { key : key.key, shift : key.shift, ctrl : key.ctrl, alt : key.alt, fn: fn, scope: scope }; } return new Ext.KeyMap(this, config); }, /** * 为该元素创建一个KeyMap * @param {Object} config KeyMap配置项。参阅 {@link Ext.KeyMap} * @return {Ext.KeyMap} 创建好的KeyMap */ addKeyMap : function(config){ return new Ext.KeyMap(this, config); }, /** * 返回true表示为该元素是可滚动的 * @return {Boolean} */ isScrollable : function(){ var dom = this.dom; return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; }, /** * 滚动该元素到指定的滚动点(scroll point)。 * 它不会边界检查所以若果你滚动到一个不合理的值时它也会试着去做。 * 要自动检查边界,请使用scroll()。 * @param {String} side 即可 "left" 对应scrollLeft的值,也可以 "top" 对于scrollTop的值. * @param {Number} value 新滚动值 * @param {Boolean/Object} animate (可选的) true表示为默认动画,或有一个标准元素动画配置的对象 * @return {Element} this */ scrollTo : function(side, value, animate){ var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop"; if(!animate || !A){ this.dom[prop] = value; }else{ var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value]; this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll'); } return this; }, /** * 滚动该元素到指定的方向。须确认元素可滚动的范围,以免滚动超出元素可滚动的范围。 * @param {String} direction 可能出现的值: "l","left" - "r","right" - "t","top","up" - "b","bottom","down". * @param {Number} distance 元素滚动有多远(像素) * @param {Boolean/Object} animate (可选的) true表示为默认动画,或有一个标准元素动画配置的对象 * @return {Boolean} true表示为滚动是轮换的;false表示为元素能滚动其最远的 */ scroll : function(direction, distance, animate){ if(!this.isScrollable()){ return; } var el = this.dom; var l = el.scrollLeft, t = el.scrollTop; var w = el.scrollWidth, h = el.scrollHeight; var cw = el.clientWidth, ch = el.clientHeight; direction = direction.toLowerCase(); var scrolled = false; var a = this.preanim(arguments, 2); switch(direction){ case "l": case "left": if(w - l > cw){ var v = Math.min(l + distance, w-cw); this.scrollTo("left", v, a); scrolled = true; } break; case "r": case "right": if(l > 0){ var v = Math.max(l - distance, 0); this.scrollTo("left", v, a); scrolled = true; } break; case "t": case "top": case "up": if(t > 0){ var v = Math.max(t - distance, 0); this.scrollTo("top", v, a); scrolled = true; } break; case "b": case "bottom": case "down": if(h - t > ch){ var v = Math.min(t + distance, h-ch); this.scrollTo("top", v, a); scrolled = true; } break; } return scrolled; }, /** * 传入一个页面坐标的参数,将其翻译到元素的CSS left/top值。 * @param {Number/Array} x 页面x or 数组 [x, y] * @param {Number} y 页面 y * @param {Object} 包含left、top属性的对象,如 {left: (值), top: (值)} */ translatePoints : function(x, y){ if(typeof x == 'object' || x instanceof Array){ y = x[1]; x = x[0]; } var p = this.getStyle('position'); var o = this.getXY(); var l = parseInt(this.getStyle('left'), 10); var t = parseInt(this.getStyle('top'), 10); if(isNaN(l)){ l = (p == "relative") ? 0 : this.dom.offsetLeft; } if(isNaN(t)){ t = (p == "relative") ? 0 : this.dom.offsetTop; } return {left: (x - o[0] + l), top: (y - o[1] + t)}; }, /** * 返回元素当前滚动的位置。 * @return {Object} 包含滚动位置的对象,格式如 {left: (scrollLeft), top: (scrollTop)} */ getScroll : function(){ var d = this.dom, doc = document; if(d == doc || d == doc.body){ var l, t; if(Ext.isIE && Ext.isStrict){ l = doc.documentElement.scrollLeft || (doc.body.scrollLeft || 0); t = doc.documentElement.scrollTop || (doc.body.scrollTop || 0); }else{ l = window.pageXOffset || (doc.body.scrollLeft || 0); t = window.pageYOffset || (doc.body.scrollTop || 0); } return {left: l, top: t}; }else{ return {left: d.scrollLeft, top: d.scrollTop}; } }, /** * 为指定的CSS属性返回CSS颜色。RGB、三位数(像#fff)和有效值都被转换到标准六位十六进制的颜色 * @param {String} attr CSS属性 * @param {String} defaultValue 当找不到有效的颜色时所用的默认值 * @param {String} prefix (可选的) 默认为 #。应用到YUI颜色动画时须为空白字串符 */ getColor : function(attr, defaultValue, prefix){ var v = this.getStyle(attr); if(!v || v == "transparent" || v == "inherit") { return defaultValue; } var color = typeof prefix == "undefined" ? "#" : prefix; if(v.substr(0, 4) == "rgb("){ var rvs = v.slice(4, v.length -1).split(","); for(var i = 0; i < 3; i++){ var h = parseInt(rvs[i]); var s = h.toString(16); if(h < 16){ s = "0" + s; } color += s; } } else { if(v.substr(0, 1) == "#"){ if(v.length == 4) { for(var i = 1; i < 4; i++){ var c = v.charAt(i); color += c + c; } }else if(v.length == 7){ color += v.substr(1); } } } return(color.length > 5 ? color.toLowerCase() : defaultValue); }, /** * 将指定的元素打包到一个特定的样式/markup块,渲染成为斜纹背景、圆角和四边投影的灰色容器。 * 用法举例:<pre><code> // 基本box打包 Ext.get("foo").boxWrap(); Ext.get("foo").boxWrap().addClass("x-box-blue"); </pre></code> * @param {String} class (可选的)一个CSS基类,应用到包裹元素(默认为'x-box')。 * 注意有许多依赖该CSS规则来产生整体的效果。 * 所以你提供一个交替的基样式,必须保证你所提供的都是所需的规则。 * @return {Ext.Element} this */ boxWrap : function(cls){ cls = cls || 'x-box'; var el = Ext.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls))); el.child('.'+cls+'-mc').dom.appendChild(this.dom); return el; }, /** * 在DOM节点中的某个元素,返回其一个命名空间属性的值。 * @param {String} namespace 要查找属性所在的命名空间 * @param {String} name 属性名称 * @return {String} 属性值 */ getAttributeNS : Ext.isIE ? function(ns, name){ var d = this.dom; var type = typeof d[ns+":"+name]; if(type != 'undefined' && type != 'unknown'){ return d[ns+":"+name]; } return d[name]; } : function(ns, name){ var d = this.dom; return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name]; }, getTextWidth : function(text, min, max){ return (Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width).constrain(min || 0, max || 1000000); } }; var ep = El.prototype; /** * 加入一个事件句柄(addListener的简写方式) * @param {String} eventName 加入事件的类型 * @param {Function} fn 事件执行的方法 * @param {Object} scope (可选的)函数之作用域 (这个元素) * @param {Object} options (可选的)标准的{@link #addListener} 配置项对象 * @member Ext.Element * @method on */ ep.on = ep.addListener; // backwards compat ep.mon = ep.addListener; ep.getUpdateManager = ep.getUpdater; /** * 从这个元素上移除一个event handler({@link #removeListener}的简写方式) * @param {String} eventName 要移除事件的类型 * @param {Function} fn 事件执行的方法 * @return {Ext.Element} this * @member Ext.Element * @method un */ ep.un = ep.removeListener; /** * true表示为自动调整由box-mode问题引起的高度和宽度设置(默认true)。 */ ep.autoBoxAdjust = true; // private El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i; // private El.addUnits = function(v, defaultUnit){ if(v === "" || v == "auto"){ return v; } if(v === undefined){ return ''; } if(typeof v == "number" || !El.unitPattern.test(v)){ return v + (defaultUnit || 'px'); } return v; }; El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>'; /** * 显示模式(Visibility mode)的常量 - 使用Visibility来隐藏元素 * @static * @property Element.VISIBILITY */ El.VISIBILITY = 1; /** * 显示模式(Visibility mode)的常量 - 使用Display来隐藏元素 * @static * @property Element.DISPLAY */ El.DISPLAY = 2; El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"}; El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"}; El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"}; El.cache = {}; var docEl; /** * 获取元素对象的静态方法。 * 如果是相同的对象的话,只是从缓存中提取。 * Automatically fixes if an object was recreated with the same id via AJAX or DOM. * @param {Mixed} el 节点的id,一个DOM节点或是已存在的元素。, * @return {Element} 元素对象 * @static */ El.get = function(el){ var ex, elm, id; if(!el){ return null; } if(typeof el == "string"){ // element id if(!(elm = document.getElementById(el))){ return null; } if(ex = El.cache[el]){ ex.dom = elm; }else{ ex = El.cache[el] = new El(elm); } return ex; }else if(el.tagName){ if(!(id = el.id)){ id = Ext.id(el); } if(ex = El.cache[id]){ ex.dom = el; }else{ ex = El.cache[id] = new El(el); } return ex; }else if(el instanceof El){ if(el != docEl){ el.dom = document.getElementById(el.id) || el.dom; El.cache[el.id] = el; } return el; }else if(el.isComposite){ return el; }else if(el instanceof Array){ return El.select(el); }else if(el == document){ if(!docEl){ var f = function(){}; f.prototype = El.prototype; docEl = new f(); docEl.dom = document; } return docEl; } return null; }; El.uncache = function(el){ for(var i = 0, a = arguments, len = a.length; i < len; i++) { if(a[i]){ delete El.cache[a[i].id || a[i]]; } } }; El.garbageCollect = function(){ if(!Ext.enableGarbageCollector){ clearInterval(El.collectorThread); return; } for(var eid in El.cache){ var el = El.cache[eid], d = el.dom; if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){ delete El.cache[eid]; if(d && Ext.enableListenerCollection){ E.purgeElement(d); } } } } El.collectorThreadId = setInterval(El.garbageCollect, 30000); var flyFn = function(){}; flyFn.prototype = El.prototype; var _cls = new flyFn(); // dom is optional El.Flyweight = function(dom){ this.dom = dom; }; El.Flyweight.prototype = _cls; El.Flyweight.prototype.isFlyweight = true; El._flyweights = {}; /** * 获取共享元的元素,传入的节点会成为活动元素。 * 不保存该元素的引用(reference)-可由其它代码重写dom节点。 * @param {String/HTMLElement} el Dom节点或id * @param {String} named (可选的) 为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。 * @static * @return {Element} 共享的Element对象(null表示为找不到元素) */ El.fly = function(el, named){ named = named || '_global'; el = Ext.getDom(el); if(!el){ return null; } if(!El._flyweights[named]){ El._flyweights[named] = new El.Flyweight(); } El._flyweights[named].dom = el; return El._flyweights[named]; }; /** * 获取元素对象的静态方法。 * 如果是相同的对象的话,只是从缓存中提取。 * @param {String/HTMLElement/Element} el 节点的id,一个DOM节点或是已存在的元素。, * @return {Element} Element对象 * @member Ext * @method get */ Ext.get = El.get; /** * 获取共享元的元素,传入的节点会成为活动元素。 * 不保存该元素的引用(reference)-可由其它代码重写dom节点。 * {@link Ext.Element#fly}的简写方式。 * @param {String/HTMLElement} el Dom节点或id * @param {String} named (可选的)为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。 * @static * @return {Element} 共享的Element对象 * @member Ext * @method fly */ Ext.fly = El.fly; var noBoxAdjust = Ext.isStrict ? { select:1 } : { input:1, select:1, textarea:1 }; if(Ext.isIE || Ext.isGecko){ noBoxAdjust['button'] = 1; } Ext.EventManager.on(window, 'unload', function(){ delete El.cache; delete El._flyweights; }); })();
JavaScript
/** * @class Ext.CompositeElementLite * @extends Ext.CompositeElement * 享元的组合类(Flyweight composite class)。为相同的元素操作可复用Ext.Element <pre><code> var els = Ext.select("#some-el div.some-class"); // 或者是从现有的元素直接选择 var el = Ext.get('some-el'); el.select('div.some-class'); els.setWidth(100); // 所有的元素变为宽度100 els.hide(true); // 所有的元素渐隐 // 或 els.setWidth(100).hide(true); </code></pre><br><br> * <b>注意:尽管未全部罗列,该类支持全部Ext.Element的set/update方法。 * 集合里面的全部元素都会执行全体的Ext.Element动作。</b> */ Ext.CompositeElementLite = function(els){ Ext.CompositeElementLite.superclass.constructor.call(this, els); this.el = new Ext.Element.Flyweight(); }; Ext.extend(Ext.CompositeElementLite, Ext.CompositeElement, { addElements : function(els){ if(els){ if(els instanceof Array){ this.elements = this.elements.concat(els); }else{ var yels = this.elements; var index = yels.length-1; for(var i = 0, len = els.length; i < len; i++) { yels[++index] = els[i]; } } } return this; }, invoke : function(fn, args){ var els = this.elements; var el = this.el; for(var i = 0, len = els.length; i < len; i++) { el.dom = els[i]; Ext.Element.prototype[fn].apply(el, args); } return this; }, /** * 根据指定的索引,返回DOM元素对象的享元元素 * @param {Number} index * @return {Ext.Element} */ item : function(index){ if(!this.elements[index]){ return null; } this.el.dom = this.elements[index]; return this.el; }, // 修正享元的作用域 addListener : function(eventName, handler, scope, opt){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++) { Ext.EventManager.on(els[i], eventName, handler, scope || els[i], opt); } return this; }, /** * 传入一个Function类型的参数,在该composite中每个元素中执行Function(带参数el, this, index)。 * <b>传入的元素是享元(共享的)Ext.Element实例,所以你需要引用dom节点的话,使用el.dom。</b> * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的) <i>this</i> 指向的对象(默认为element) * @return {CompositeElement} this */ each : function(fn, scope){ var els = this.elements; var el = this.el; for(var i = 0, len = els.length; i < len; i++){ el.dom = els[i]; if(fn.call(scope || el, el, this, i) === false){ break; } } return this; }, indexOf : function(el){ return this.elements.indexOf(Ext.getDom(el)); }, replaceElement : function(el, replacement, domReplace){ var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1){ replacement = Ext.getDom(replacement); if(domReplace){ var d = this.elements[index]; d.parentNode.insertBefore(replacement, d); Ext.removeNode(d); } this.elements.splice(index, 1, replacement); } return this; } }); Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener; if(Ext.DomQuery){ Ext.Element.selectorFunction = Ext.DomQuery.select; } Ext.Element.select = function(selector, unique, root){ var els; if(typeof selector == "string"){ els = Ext.Element.selectorFunction(selector, root); }else if(selector.length !== undefined){ els = selector; }else{ throw "Invalid selector"; } if(unique === true){ return new Ext.CompositeElement(els); }else{ return new Ext.CompositeElementLite(els); } }; /** * 传入一个CSS选择符的参数,基于该选择符选取多个元素合成为一个元素,以看待单个元素的方式工作。 * @param {String/Array} selector CSS选择符或元素数组 * @param {Boolean} unique True表示为为每个子元素创建唯一的 Ext.Element(默认为false,享元的普通对象flyweight object) * @param {HTMLElement/String} root (可选的)查询时的根元素或元素的id * @return {CompositeElementLite/CompositeElement} * @member Ext * @method select */ Ext.select = Ext.Element.select;
JavaScript
/** * @class Function * 这个函数可用于任何Function对象(任何javascript函数)。 */ Ext.apply(Function.prototype, { /** * 创建一个回调函数,该回调传递参数的形式为:arguments[0], arguments[1], arguments[2], ... * 对于任何函数来说都是可以直接调用的。 * 例如: <code>myFunction.createCallback(myarg, myarg2)</code> * 将创建一个函数,要求有2个参数 * @return {Function} 新产生的函数 */ createCallback : function(/*args...*/){ // make args available, in function below var args = arguments; var method = this; return function() { return method.apply(window, args); }; }, /** * 创建一个委派对象 (回调) ,该对象的作用域指向obj * 对于任何函数来说都是可以直接调用的。 * 例如:<code>this.myFunction.createDelegate(this)</code> * 将创建一个函数,该函数的作用域会自动指向 this。 * (译注:这是一个极其有用的函数,既创建一个即带参数又没有执行的函数,封装事件时很有价值) * @param {Object} obj (该参数可选) 自定义的作用域对象 * @param {Array} args (该参数可选) 覆盖原函数的参数。(默认为该函数的arguments) * @param {Boolean/Number} appendArgs (该参数可选) 如果该参数为true,将args加载到该函数的后面,如果该参数为数字类型,则args将插入到所指定的位置 * @return {Function} 新产生的函数 */ createDelegate : function(obj, args, appendArgs){ var method = this; return function() { var callArgs = args || arguments; if(appendArgs === true){ callArgs = Array.prototype.slice.call(arguments, 0); callArgs = callArgs.concat(args); }else if(typeof appendArgs == "number"){ callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first var applyArgs = [appendArgs, 0].concat(args); // create method call params Array.prototype.splice.apply(callArgs, applyArgs); // splice them in } return method.apply(obj || window, callArgs); }; }, /** * 延迟调用该函数。 * @param {Number} 延迟时间,以毫秒为记 (如果是0则立即执行) * @param {Object} obj (该参数可选) 该函数作用域 * @param {Array} args (该参数可选) 覆盖原函数的参数。(默认为该函数的arguments) * @param {Boolean/Number} appendArgs (该参数可选) 如果该参数为true,将args加载到该函数的后面, * 如果该参数为数字类型,则args将插入到所指定的位置 * @return {Number} The timeout id that can be used with clearTimeout */ defer : function(millis, obj, args, appendArgs){ var fn = this.createDelegate(obj, args, appendArgs); if(millis){ return setTimeout(fn, millis); } fn(); return 0; }, /** * 创建一个组合函数,调用次序为:原函数 + 参数中的函数。 * 该函数返回了原函数执行的结果(也就是返回了原函数的返回值) * 在参数中传递的函数fcn,它的参数也是原函数的参数。 * @param {Function} fcn 将要进行组合的函数 * @param {Object} scope (该参数可选) fcn的作用域 (默认指向原函数或window) * @return {Function} 新产生的函数 */ createSequence : function(fcn, scope){ if(typeof fcn != "function"){ return this; } var method = this; return function() { var retval = method.apply(this || window, arguments); fcn.apply(scope || this || window, arguments); return retval; }; }, /** * 创建一个拦截器函数。 传递的参数fcn被原函数之前调用。 如果fcn的返回值为false,则原函数不会被调用。 * 在返回函数中,将返回原函数的返回值。 * 参数fcn会被调用,fcn被调用时会被传入原函数的参数。 * @param {Function} fcn 在原函数被调用前调用的函数 * @param {Object} scope (可选的)fcn的作用域(默认指向原函数或window) * @return {Function} 新产生的函数 */ createInterceptor : function(fcn, scope){ if(typeof fcn != "function"){ return this; } var method = this; return function() { fcn.target = this; fcn.method = method; if(fcn.apply(scope || this || window, arguments) === false){ return; } return method.apply(this || window, arguments); }; } });
JavaScript
/** * @class Ext.Element * Represents an Element in the DOM.<br><br> * Usage:<br> * 呈现DOM里面的一个元素。<br><br> * 用法:<br> <pre><code> var el = Ext.get("my-div"); // or with getEl // 或者是 getEl var el = getEl("my-div"); // or with a DOM element // 或者是一个 DOM element var el = Ext.get(myDivElement); </code></pre> * Using Ext.get() or getEl() instead of calling the constructor directly ensures you get the same object * each call instead of constructing a new one.<br><br> * <b>Animations</b><br /> * Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter * should either be a boolean (true) or an object literal with animation options. Note that the supported Element animation * options are a subset of the {@link Ext.Fx} animation options specific to Fx effects. The Element animation options are: * * 使用Ext.get或是getEl()来代替调用构造函数,保证每次调用都是获取相同的对象而非构建新的一个。 * <br><br> * <b>动画</b><br /> * 操作DOM元素,很多情况下会用一些到动画效果(可选的)。 * 动画选项应该是布尔值(true )或是Object Literal 。动画选项有: <pre> Option Default Description 可选项 默认值 描述 --------- -------- --------------------------------------------- duration .35 动画持续的时间 easing easeOut The easing method callback none 当动画完成后执行的函数 scope this 回调函数的作用欲(可选的) duration .35 动画持续的时间(单位:秒) easing easeOut YUI的消除方法 callback none 动画完成之后执行的函数 scope this 回调函数的作用域 </pre> * Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or * manipulate the animation. Here's an example: *另外,可通过配置项中的“anim“来获取动画对象,这样便可停止或操控这个动画效果。例子如下: <pre><code> var el = Ext.get("my-div"); // no animation // 没有动画 el.setWidth(100); // default animation // 默认动画 el.setWidth(100, true); // animation with some options set // 对动画的一些设置 el.setWidth(100, { duration: 1, callback: this.foo, scope: this }); // using the "anim" property to get the Anim object // 使用属性“anim”来获取动画对象 var opt = { duration: 1, callback: this.foo, scope: this }; el.setWidth(100, opt); ... if(opt.anim.isAnimated()){ opt.anim.stop(); } </code></pre> * <b> Composite (Collections of) Elements</b><br /> * For working with collections of Elements, see {@link Ext.CompositeElement} * @constructor Create a new Element directly. * @param {String/HTMLElement} element * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class). * * <b> 组合(集合的)元素</b><br /> * 要处理一组的元素,参阅<a href="Ext.CompositeElement.html">Ext.CompositeElement</a> * @constructor 直接创建新元素 * @param {String/HTMLElement} element * @param {Boolean} forceNew (可选的) 构建函数默认会检查在Cache中是否已经有这个element的实例,并是否能返回一致的实例。设置这个布尔值会中止检查(扩展这个类时较有用)。 */ (function(){ var D = Ext.lib.Dom; var E = Ext.lib.Event; var A = Ext.lib.Anim; // local style camelizing for speed var propCache = {}; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; var view = document.defaultView; Ext.Element = function(element, forceNew){ var dom = typeof element == "string" ? document.getElementById(element) : element; if(!dom){ // invalid id/element //无效的id/element return null; } var id = dom.id; if(forceNew !== true && id && Ext.Element.cache[id]){ // element object already exists // 元素对象已存在 return Ext.Element.cache[id]; } /** * DOM元素 * @type HTMLElement */ this.dom = dom; /** * DOM元素之ID * @type String */ this.id = id || Ext.id(dom); }; var El = Ext.Element; El.prototype = { /** * 元素默认的显示模式(默认为"") * @type String */ originalDisplay : "", visibilityMode : 1, /** * CSS值的单位。如不指定则默认为px。 * @type String */ defaultUnit : "px", /** * 设置元素的可见模式。 * 当调用setVisible()时,会确定可见模式究竟是“可见性visibility”的还是“显示display”的。 * @param visMode Element.VISIBILITY 或 Element.DISPLAY * @return {Ext.Element} this */ setVisibilityMode : function(visMode){ this.visibilityMode = visMode; return this; }, /** * 调用setVisibilityMode(Element.DISPLAY)的快捷方式 * @param {String} display (可选的)当可见时显示的内容 * @return {Ext.Element} this */ enableDisplayMode : function(display){ this.setVisibilityMode(El.DISPLAY); if(typeof display != "undefined") this.originalDisplay = display; return this; }, /** * Looks at this node and then at parent nodes for * a match of the passed simple selector (e.g. div.some-class or span:first-child) * @param {String} selector The simple selector to test * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body) * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node * @return {HTMLElement} The matching DOM node (or null if no match was found) * / * /** * 定位此节点并按照传入的简易选择符(如 div.some-class or span:first-child)查找父节点。 * @param {String} simpleSelector 要测试的简易选择符 * @param {Number/String/HTMLElement/Element} maxDepth (可选的) 搜索深度(MaxDepth),可以为number或元素(默认是 10 || document.body) * @param {Boolean} returnEl (可选的) True表示为返回Ext.Element对象,false的话返回DOM节点 * @return {HTMLElement} 匹配的DOM节点(null的话表示没有匹配结果) */ findParent : function(simpleSelector, maxDepth, returnEl){ var p = this.dom, b = document.body, depth = 0, dq = Ext.DomQuery, stopEl; maxDepth = maxDepth || 50; if(typeof maxDepth != "number"){ stopEl = Ext.getDom(maxDepth); maxDepth = 10; } while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){ if(dq.is(p, simpleSelector)){ return returnEl ? Ext.get(p) : p; } depth++; p = p.parentNode; } return null; }, /** * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child) * @param {String} selector The simple selector to test * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body) * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node * @return {HTMLElement} The matching DOM node (or null if no match was found) */ /** * 按照简易选择符查找父节点。选择符如 div.some-class or span:first-child。 * @param {String} simpleSelector 要测试的简易选择符 * @param {Number/String/HTMLElement/Element} maxDepth (可选的) 搜索深度(MaxDepth),可以为number或元素(默认是 10 || document.body) * @param {Boolean} returnEl (可选的) True表示为返回Ext.Element对象代替DOM节点 * @return {HTMLElement} 匹配的DOM节点(null的话表示没有匹配结果) */ findParentNode : function(simpleSelector, maxDepth, returnEl){ var p = Ext.fly(this.dom.parentNode, '_internal'); return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; }, /** * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child). * This is a shortcut for findParentNode() that always returns an Ext.Element. * @param {String} selector The simple selector to test * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body) * @return {Ext.Element} The matching DOM node (or null if no match was found) * 传入一个选择符的参数,按照选择符并沿着dom查找父节点。选择符应是简易的选择符,如 div.some-class or span:first-child。 * @param {String} simpleSelector 要测试的简易选择符 * @param {Number/String/HTMLElement/Element} maxDepth (可选的) 搜索深度(MaxDepth),可以为number或元素(默认是 10 || document.body) * @param {Boolean} returnEl (可选的) True:返回Ext.Element对象代替DOM节点 * @return {HTMLElement} 匹配的DOM节点(null的话表示没有匹配结果) */ up : function(simpleSelector, maxDepth){ return this.findParentNode(simpleSelector, maxDepth, true); }, /** * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child) * @param {String} selector The simple selector to test * @return {Boolean} True if this element matches the selector, else false * 返回true,如果这个元素就是传入的简易选择符参数(如 div.some-class或span:first-child) * @param {String} ss 要测试的简易选择符 * @return {Boolean} true表示元素匹配选择符成功,否则返回false */ is : function(simpleSelector){ return Ext.DomQuery.is(this.dom, simpleSelector); }, /** * Perform animation on this element. * @param {Object} args The animation control args * @param {Float} duration (optional) How long the animation lasts in seconds (defaults to .35) * @param {Function} onComplete (optional) Function to call when animation completes * @param {String} easing (optional) Easing method to use (defaults to 'easeOut') * @param {String} animType (optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll' * @return {Ext.Element} this * 在元素上执行动画 * @param {Object} args YUI之动画配置参数 * @param {Float} duration (可选的) 动画持续多久 (默认为 .35 秒) * @param {Function} onComplete (可选的) 动画完成后调用的函数 * @param {String} easing (可选的) 采用的“松开”方法 (默认为 'easeOut') * @param {String} animType (可选的) 默认为'run'。 可以是'color', 'motion', 或 'scroll' * @return {Ext.Element} this */ animate : function(args, duration, onComplete, easing, animType){ this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType); return this; }, /* * @private Internal animation call * @私有的 内置动画调用 */ anim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); Ext.callback(opt.callback, opt.scope || this, [this, opt]); }, this ); opt.anim = anim; return anim; }, // private legacy anim prep // 私有的 legacy anim prep preanim : function(a, i){ return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]}); }, /** * Removes worthless text nodes * @param {Boolean} forceReclean (optional) By default the element * keeps track if it has been cleaned already so * you can call this over and over. However, if you update the element and * need to force a reclean, you can pass true. * 移除无用的文本节点 * @param {Boolean} forceReclean (可选的)缺省地, * 元素会追踪自己是否已被清除了,所以你可以不断地调用这个方法 * 然而,如果你需要更新元素而且需要强制清除,你可以传入true的参数。 */ clean : function(forceReclean){ if(this.isCleaned && forceReclean !== true){ return this; } var ns = /\S/; var d = this.dom, n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !ns.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } this.isCleaned = true; return this; }, /** * Scrolls this element into view within the passed container. * @param {Mixed} container (optional) The container element to scroll (defaults to document.body) * @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true) * @return {Ext.Element} this * * 传入一个容器(container)参数,把元素滚动到容器的视图(View)。 * @param {String/HTMLElement/Element} container (可选的)滚动容器的元素(默认为document.body) * @param {Boolean} hscroll (可选的)false表示为禁止水平滚动 * @return {Ext.Element} this */ scrollIntoView : function(container, hscroll){ var c = Ext.getDom(container) || Ext.getBody().dom; var el = this.dom; var o = this.getOffsetsTo(c), l = o[0] + c.scrollLeft, t = o[1] + c.scrollTop, b = t+el.offsetHeight, r = l+el.offsetWidth; var ch = c.clientHeight; var ct = parseInt(c.scrollTop, 10); var cl = parseInt(c.scrollLeft, 10); var cb = ct + ch; var cr = cl + c.clientWidth; if(el.offsetHeight > ch || t < ct){ c.scrollTop = t; }else if(b > cb){ c.scrollTop = b-ch; } c.scrollTop = c.scrollTop; // corrects IE, other browsers will ignore if(hscroll !== false){ if(el.offsetWidth > c.clientWidth || l < cl){ c.scrollLeft = l; }else if(r > cr){ c.scrollLeft = r-c.clientWidth; } c.scrollLeft = c.scrollLeft; } return this; }, // private scrollChildIntoView : function(child, hscroll){ Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll); }, /** * Measures the element's content height and updates height to match. Note: this function uses setTimeout so * the new height may not be available immediately. * @param {Boolean} animate (optional) Animate the transition (defaults to false) * @param {Float} duration (optional) Length of the animation in seconds (defaults to .35) * @param {Function} onComplete (optional) Function to call when animation completes * @param {String} easing (optional) Easing method to use (defaults to easeOut) * @return {Ext.Element} this * * 测量元素其内容的实际高度,使元素之高度适合。 * 注:改函数使用setTimeout所以新高度或者不会立即有效。 * @param {Boolean} animate (可选的)变换(默认 false) * @param {Float} duration (可选的)动画持续时间(默认为0.35秒) * @param {Function} onComplete (可选的)动画完成后执行的函数 * @param {String} easing (可选的)采用清除的方法(默认为easeOut) * @return {Ext.Element} this */ autoHeight : function(animate, duration, onComplete, easing){ var oldHeight = this.getHeight(); this.clip(); this.setHeight(1); // force clipping // 强迫裁剪 setTimeout(function(){ var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari if(!animate){ this.setHeight(height); this.unclip(); if(typeof onComplete == "function"){ onComplete(); } }else{ this.setHeight(oldHeight); // restore original height // 恢复原始高度 this.setHeight(height, animate, duration, function(){ this.unclip(); if(typeof onComplete == "function") onComplete(); }.createDelegate(this), easing); } }.createDelegate(this), 0); return this; }, /** * Returns true if this element is an ancestor of the passed element * @param {HTMLElement/String} el The element to check * @return {Boolean} True if this element is an ancestor of el, else false * * 返回true,如果这个元素是传入元素的父级元素(ancestor) * @param {HTMLElement/String} el 要检查的元素 * @return {Boolean} true表示这个元素是传入元素的父级元素,否则返回false */ contains : function(el){ if(!el){return false;} return D.isAncestor(this.dom, el.dom ? el.dom : el); }, /** * Checks whether the element is currently visible using both visibility and display properties. * @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false) * @return {Boolean} True if the element is currently visible, else false * * 检查当前该元素是否都使用属性visibility和属性display来显示。 * @param {Boolean} deep (可选的)True表示为沿着DOM一路看父元素是否隐藏的。 * @return {Boolean} true表示该元素当前是可见的,否则返回false */ isVisible : function(deep) { var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none"); if(deep !== true || !vis){ return vis; } var p = this.dom.parentNode; while(p && p.tagName.toLowerCase() != "body"){ if(!Ext.fly(p, '_isVisible').isVisible()){ return false; } p = p.parentNode; } return true; }, /** * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @param {Boolean} unique (optional) True to create a unique Ext.Element for each child (defaults to false, which creates a single shared flyweight object) * @return {CompositeElement/CompositeElementLite} The composite element * * 传入一个CSS选择符的参数,然后基于该选择符为子节点创建一个{@link Ext.CompositeElement}组合元素。(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} unique true表示为为每个子元素创建唯一的Ext.Element(默认为false享元的普通对象flyweight object) * @return {CompositeElement/CompositeElementLite} 组合元素 */ select : function(selector, unique){ return El.select(selector, unique, this.dom); }, /** * Selects child nodes based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @return {Array} An array of the matched nodes * * 传入一个CSS选择符的参数,然后基于该选择符选取其子节点(选择符不应有id) * @param {String} selector CSS选择符 * @return {Array} 匹配节点之数组 */ query : function(selector, unique){ return Ext.DomQuery.select(selector, this.dom); }, /** * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false) * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true) * * 传入一个CSS选择符的参数,然后基于该选择符,不限定深度,选取单个子节点(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} returnDom (可选的)true表示为返回DOM节点,false表示为返回Ext.Element(默认为false) * @return {HTMLElement/Ext.Element} Ext.Element的子孙(如returnDom = true则为DOM节点) */ child : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(selector, this.dom); return returnDom ? n : Ext.get(n); }, /** * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false) * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true) * * 传入一个CSS选择符的参数,然后基于该选择符,"直接"选取单个子节点(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} returnDom (可选的)true表示为返回DOM节点,false表示为返回Ext.Element(默认为false) * @return {HTMLElement/Ext.Element} Ext.Element的子孙(如returnDom = true则为DOM节点) */ down : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(" > " + selector, this.dom); return returnDom ? n : Ext.get(n); }, /** * Initializes a {@link Ext.dd.DD} drag drop object for this element. * @param {String} group The group the DD object is member of * @param {Object} config The DD config object * @param {Object} overrides An object containing methods to override/implement on the DD object * @return {Ext.dd.DD} The DD object * * 为这个元素初始化{@link Ext.dd.DD}对象 * @param {String} DD对象隶属于的那个组(Group) * @param {Object} config DD之配置对象 * @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象 * @return {Ext.dd.DD} DD对象 */ initDD : function(group, config, overrides){ var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, /** * Initializes a {@link Ext.dd.DDProxy} object for this element. * @param {String} group The group the DDProxy object is member of * @param {Object} config The DDProxy config object * @param {Object} overrides An object containing methods to override/implement on the DDProxy object * @return {Ext.dd.DDProxy} The DDProxy object * * 为这个元素初始化{@link Ext.dd.DDProxy}对象 * @param {String} group DDProxy对象隶属于的那个组(Group) * @param {Object} config DDProxy之配置对象 * @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象 * @return {Ext.dd.DDProxy} DDProxy对象 */ initDDProxy : function(group, config, overrides){ var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, /** * Initializes a {@link Ext.dd.DDTarget} object for this element. * @param {String} group The group the DDTarget object is member of * @param {Object} config The DDTarget config object * @param {Object} overrides An object containing methods to override/implement on the DDTarget object * @return {Ext.dd.DDTarget} The DDTarget object * * 为这个元素初始化{@link Ext.dd.DDTarget}对象 * @param {String} group DDTarget对象隶属于的那个组(Group) * @param {Object} config DDTarget之配置对象 * @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象 * @return {Ext.dd.DDTarget} DDTarget对象 */ initDDTarget : function(group, config, overrides){ var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, /** * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property. * @param {Boolean} visible Whether the element is visible * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * * 设置元素可见性(参阅细节)。 * 如果visibilityMode 被设置成 Element.DISPLAY, * 那么它会使用display属性来隐藏元素,否则它会使用visibility。默认是使用 visibility属性。 * @param {Boolean} visible 元素是否可见的 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setVisible : function(visible, animate){ if(!animate || !A){ if(this.visibilityMode == El.DISPLAY){ this.setDisplayed(visible); }else{ this.fixDisplay(); this.dom.style.visibility = visible ? "visible" : "hidden"; } }else{ // closure for composites var dom = this.dom; var visMode = this.visibilityMode; if(visible){ this.setOpacity(.01); this.setVisible(true); } this.anim({opacity: { to: (visible?1:0) }}, this.preanim(arguments, 1), null, .35, 'easeIn', function(){ if(!visible){ if(visMode == El.DISPLAY){ dom.style.display = "none"; }else{ dom.style.visibility = "hidden"; } Ext.get(dom).setOpacity(1); } }); } return this; }, /** * Returns true if display is not "none" * @return {Boolean} * * 如果属性display不是"none"就返回true * @return {Boolean} */ isDisplayed : function() { return this.getStyle("display") != "none"; }, /** * Toggles the element's visibility or display, depending on visibility mode. * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * * 轮回元素visibility或display,取决于visibility mode。 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ toggle : function(animate){ this.setVisible(!this.isVisible(), this.preanim(arguments, 0)); return this; }, /** * Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true. * @param {Mixed} value Boolean value to display the element using its default display, or a string to set the display directly. * @return {Ext.Element} this * * 设置Css display属性。如果value为true,则使用originalDisplay。 * @param {Boolean} value 如果value为true,则使用originalDisplay。否则直接设置显示的字符串、 * @return {Ext.Element} this */ setDisplayed : function(value) { if(typeof value == "boolean"){ value = value ? this.originalDisplay : "none"; } this.setStyle("display", value); return this; }, /** * Tries to focus the element. Any exceptions are caught and ignored. * @return {Ext.Element} this * * 使这个元素得到焦点。忽略任何已捕获的异常。 * @return {Ext.Element} this */ focus : function() { try{ this.dom.focus(); }catch(e){} return this; }, /** * Tries to blur the element. Any exceptions are caught and ignored. * @return {Ext.Element} this * * 使这个元素失去焦点。忽略任何已捕获的异常。 * @return {Ext.Element} this */ blur : function() { try{ this.dom.blur(); }catch(e){} return this; }, /** * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out. * @param {String/Array} className The CSS class to add, or an array of classes * @return {Ext.Element} this * * 为元素添加CSS类(CSS Class)。重复的类会被忽略。 * @param {String/Array} className 要加入的CSS类或者由类组成的数组 * @return {Ext.Element} this */ addClass : function(className){ if(className instanceof Array){ for(var i = 0, len = className.length; i < len; i++) { this.addClass(className[i]); } }else{ if(className && !this.hasClass(className)){ this.dom.className = this.dom.className + " " + className; } } return this; }, /** * Adds one or more CSS classes to this element and removes the same class(es) from all siblings. * @param {String/Array} className The CSS class to add, or an array of classes * @return {Ext.Element} this * * 添加一个或多个className到这个元素,并移除其侧边(siblings)节点上所有的样式。 * @param {String} className 要加入的className,或者是由类组成的数组 * @return {Ext.Element} this */ radioClass : function(className){ var siblings = this.dom.parentNode.childNodes; for(var i = 0; i < siblings.length; i++) { var s = siblings[i]; if(s.nodeType == 1){ Ext.get(s).removeClass(className); } } this.addClass(className); return this; }, /** * Removes one or more CSS classes from the element. * @param {String/Array} className The CSS class to remove, or an array of classes * @return {Ext.Element} this * * 移除元素的CSS类 * @param {String/Array} className 要移除的CSS类或者由类组成的数组 * @return {Ext.Element} this */ removeClass : function(className){ if(!className || !this.dom.className){ return this; } if(className instanceof Array){ for(var i = 0, len = className.length; i < len; i++) { this.removeClass(className[i]); } }else{ if(this.hasClass(className)){ var re = this.classReCache[className]; if (!re) { re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g"); this.classReCache[className] = re; } this.dom.className = this.dom.className.replace(re, " "); } } return this; }, // private classReCache: {}, /** * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it). * @param {String} className The CSS class to toggle * @return {Ext.Element} this * * 轮换(Toggles)--添加或移除指定的CSS类(如果已经存在的话便删除,否则就是新增加)。 * @param {String} className 轮换的CSS类 * @return {Ext.Element} this */ toggleClass : function(className){ if(this.hasClass(className)){ this.removeClass(className); }else{ this.addClass(className); } return this; }, /** * Checks if the specified CSS class exists on this element's DOM node. * @param {String} className The CSS class to check for * @return {Boolean} True if the class exists, else false * * 检查某个CSS类是否存在这个元素的DOM节点上 * @param {String} className 要检查CSS类 * @return {Boolean} true表示为类是有的,否则为false */ hasClass : function(className){ return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1; }, /** * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added. * @param {String} oldClassName The CSS class to replace * @param {String} newClassName The replacement CSS class * @return {Ext.Element} this * * 在这个元素身上替换CSS类。如果旧的CSS名称不存在,新的就会加入。 * @param {String} oldClassName 要被替换之CSS类 * @param {String} newClassName 新CSS类 * @return {Ext.Element} this */ replaceClass : function(oldClassName, newClassName){ this.removeClass(oldClassName); this.addClass(newClassName); return this; }, /** * 给出一些CSS属性名,得到其值 * 如 el.getStyles('color', 'font-size', 'width')会返回 * {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}. * @param {String} arg1 样式一 * @param {String} arg2 样式二 * @param {String} args 等等.. * @return {Object} 样式对象 */ getStyles : function(){ var a = arguments, len = a.length, r = {}; for(var i = 0; i < len; i++){ r[a[i]] = this.getStyle(a[i]); } return r; }, /** * Normalizes currentStyle and computedStyle. * @param {String} property The style property whose value is returned. * @return {String} The current value of the style property for this element. * * 常规化当前样式和计算样式。 * @param {String} property 返回值的那个样式属性。 * @return {String} 该元素样式属性的当前值。 */ getStyle : function(){ return view && view.getComputedStyle ? function(prop){ var el = this.dom, v, cs, camel; if(prop == 'float'){ prop = "cssFloat"; } if(v = el.style[prop]){ return v; } if(cs = view.getComputedStyle(el, "")){ if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } return cs[camel]; } return null; } : function(prop){ var el = this.dom, v, cs, camel; if(prop == 'opacity'){ if(typeof el.style.filter == 'string'){ var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i); if(m){ var fv = parseFloat(m[1]); if(!isNaN(fv)){ return fv ? fv / 100 : 0; } } } return 1; }else if(prop == 'float'){ prop = "styleFloat"; } if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(v = el.style[camel]){ return v; } if(cs = el.currentStyle){ return cs[camel]; } return null; }; }(), /** * Wrapper for setting style properties, * also takes single object parameter of multiple styles. * @param {String/Object} property The style property to be set, or an object of multiple styles. * @param {String} value (optional) The value to apply to the given property, or null if an object was passed. * @return {Ext.Element} this * * 以打包的方式设置样式属性,也可以用一个对象参数包含多个样式。 * @param {String/Object} 要设置的样式属性,或是包含多个样式的对象 * @param {String} value (可选的)样式属性的值,如果第一个参数是对象,则这个参数为null * @return {Ext.Element} this */ setStyle : function(prop, value){ if(typeof prop == "string"){ var camel; if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(camel == 'opacity') { this.setOpacity(value); }else{ this.dom.style[camel] = value; } }else{ for(var style in prop){ if(typeof prop[style] != "function"){ this.setStyle(style, prop[style]); } } } return this; }, /** * More flexible version of {@link #setStyle} for setting style properties. * @param {String/Object/Function} styles A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or * a function which returns such a specification. * @return {Ext.Element} this * {@link #setStyle}的另一个版本,能更灵活地设置样式属性 * @param {String/Object/Function} styles 表示样式的特定格式字符串,如“width:100px”,或是对象的形式如{width:"100px"},或是能返回这些格式的函数 * @return {Ext.Element} this */ applyStyles : function(style){ Ext.DomHelper.applyStyles(this.dom, style); return this; }, /** * Gets the current X position of the element based on page coordinates. * Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @return {Number} The X position of the element * * 获取元素基于页面坐标的X位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回false)。 * @return {Number} 元素的X位置 */ getX : function(){ return D.getX(this.dom); }, /** * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @return {Number} The Y position of the element * * 获取元素基于页面坐标的Y位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回false)。 * @return {Number} 元素的Y位置 */ getY : function(){ return D.getY(this.dom); }, /** * Gets the current position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @return {Array} The XY position of the element * * 获取元素基于页面坐标当前的位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回false)。 * @return {Number} 元素的XY位置 */ getXY : function(){ return D.getXY(this.dom); }, /** * Returns the offsets of this element from the passed element. Both element must be part of the DOM tree and not have display:none to have page coordinates. * @param {Mixed} element The element to get the offsets from. * @return {Array} The XY page offsets (e.g. [100, -200]) */ getOffsetsTo : function(el){ var o = this.getXY(); var e = Ext.fly(el, '_internal').getXY(); return [o[0]-e[0],o[1]-e[1]]; }, /** * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Number} The X position of the element * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * * 设置元素基于页面坐标的X位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 元素的X位置 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setX : function(x, animate){ if(!animate || !A){ D.setX(this.dom, x); }else{ this.setXY([x, this.getY()], this.preanim(arguments, 1)); } return this; }, /** * Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Number} The Y position of the element * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * * 设置元素基于页面坐标的Y位置。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 元素的Y位置 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setY : function(y, animate){ if(!animate || !A){ D.setY(this.dom, y); }else{ this.setXY([this.getX(), y], this.preanim(arguments, 1)); } return this; }, /** * Sets the element's left position directly using CSS style (instead of {@link #setX}). * @param {String} left The left CSS property value * @return {Ext.Element} this * * 直接使用CSS样式(代替{@link #setX}),设定元素的left位置。 * @param {String} left CSS属性left的值 * @return {Ext.Element} this */ setLeft : function(left){ this.setStyle("left", this.addUnits(left)); return this; }, /** * Sets the element's top position directly using CSS style (instead of {@link #setY}). * @param {String} top The top CSS property value * @return {Ext.Element} this * * 直接使用CSS样式(代替{@link #setY}),设定元素的top位置。 * @param {String} top CSS属性top的值 * @return {Ext.Element} this */ setTop : function(top){ this.setStyle("top", this.addUnits(top)); return this; }, /** * Sets the element's CSS right style. * @param {String} right The right CSS property value * @return {Ext.Element} this * * 设置元素CSS Right的样式 * @param {String} bottom Bottom CSS属性值 * @return {Ext.Element} this */ setRight : function(right){ this.setStyle("right", this.addUnits(right)); return this; }, /** * Sets the element's CSS bottom style. * @param {String} bottom The bottom CSS property value * @return {Ext.Element} this * * 设置元素CSS Bottom的样式 * @param {String} bottom Bottom CSS属性值 * @return {Ext.Element} this */ setBottom : function(bottom){ this.setStyle("bottom", this.addUnits(bottom)); return this; }, /** * Sets the position of the element in page coordinates, regardless of how the element is positioned. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based) * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * 设置元素在页面的坐标位置,不管这个元素如何定位。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Array} pos 对于新位置(基于页面坐标)包含X & Y [x, y]的值 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setXY : function(pos, animate){ if(!animate || !A){ D.setXY(this.dom, pos); }else{ this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion'); } return this; }, /** * Sets the position of the element in page coordinates, regardless of how the element is positioned. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Number} x X value for new position (coordinates are page-based) * @param {Number} y Y value for new position (coordinates are page-based) * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * 设置元素在页面的坐标位置,不管这个元素如何定位。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 新定位的X值(基于页面坐标) * @param {Number} y 新定位的Y值(基于页面坐标) * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setLocation : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, /** * Sets the position of the element in page coordinates, regardless of how the element is positioned. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Number} x X value for new position (coordinates are page-based) * @param {Number} y Y value for new position (coordinates are page-based) * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this * 设置元素在页面的坐标位置,不管这个元素如何定位。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @param {Number} x 新定位的X值(基于页面坐标) * @param {Number} y 新定位的Y值(基于页面坐标) * @param {Boolean/Object} animate (可选的) true :为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ moveTo : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, /** * Returns the region of the given element. * The element must be part of the DOM tree to have a region (display:none or elements not appended return false). * @return {Region} A Ext.lib.Region containing "top, left, bottom, right" member data. * 返回给出元素的区域。 * 元素必须是DOM树中的一部分,才拥有页面坐标(display:none或未加入的elements返回 false)。 * @return {Region} A Ext.lib.Region 包含"top, left, bottom, right" 成员数据 */ getRegion : function(){ return D.getRegion(this.dom); }, /** * Returns the offset height of the element * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding * @return {Number} The element's height * 返回元素的偏移(offset)高度 * @param {Boolean} contentHeight (可选的) true表示为获取减去边框和内补丁(borders & padding)的宽度 * @return {Number} 元素高度 */ getHeight : function(contentHeight){ var h = this.dom.offsetHeight || 0; h = contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb"); return h < 0 ? 0 : h; }, /** * Returns the offset width of the element * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding * @return {Number} The element's width * 返回元素的偏移(offset)宽度 * @param {Boolean} contentWidth (可选的) true表示为获取减去边框和内补丁(borders & padding)的宽度 * @return {Number} 元素宽度 */ getWidth : function(contentWidth){ var w = this.dom.offsetWidth || 0; w = contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr"); return w < 0 ? 0 : w; }, /** * Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders * when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements * if a height has not been set using CSS. * @return {Number} */ /** * 当偏移值不可用时就模拟一个出来。该方法返回由padding或borders调整过的元素CSS高度,也可能是偏移的高度。 * 如果不用CSS设置高度而且是display:none的元素,有可能不能正常工作。 * @return {Number} */ getComputedHeight : function(){ var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight); if(!h){ h = parseInt(this.getStyle('height'), 10) || 0; if(!this.isBorderBox()){ h += this.getFrameWidth('tb'); } } return h; }, /** * Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders * when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements * if a width has not been set using CSS. * @return {Number} */ /** * 当偏移值不可用时就模拟一个出来。该方法返回由padding或borders调整过的元素CSS宽度,也可能是偏移的宽度。 * 如果不用CSS设置宽度而且是display:none的元素,有可能不能正常工作。 * @return {Number} */ getComputedWidth : function(){ var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth); if(!w){ w = parseInt(this.getStyle('width'), 10) || 0; if(!this.isBorderBox()){ w += this.getFrameWidth('lr'); } } return w; }, /** * Returns the size of the element. * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding * @return {Object} An object containing the element's size {width: (element width), height: (element height)} * 返回元素尺寸大小。 * @param {Boolean} contentSize (可选的) true表示为返回减去border和padding的宽度大小 * @return {Object} 包含元素大小尺寸的对象,如{width: (element width), height: (element height)} */ getSize : function(contentSize){ return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; }, getStyleSize : function(){ var w, h, d = this.dom, s = d.style; if(s.width && s.width != 'auto'){ w = parseInt(s.width, 10); if(Ext.isBorderBox){ w -= this.getFrameWidth('lr'); } } if(s.height && s.height != 'auto'){ h = parseInt(s.height, 10); if(Ext.isBorderBox){ h -= this.getFrameWidth('tb'); } } return {width: w || this.getWidth(true), height: h || this.getHeight(true)}; }, /** * Returns the width and height of the viewport. * @return {Object} An object containing the viewport's size {width: (viewport width), height: (viewport height)} * 返回视图的高度和宽度。 * @return {Object} 包含视图大小尺寸的对象,如{width: (viewport width), height: (viewport height)} */ getViewSize : function(){ var d = this.dom, doc = document, aw = 0, ah = 0; if(d == doc || d == doc.body){ return {width : D.getViewWidth(), height: D.getViewHeight()}; }else{ return { width : d.clientWidth, height: d.clientHeight }; } }, /** * Returns the value of the "value" attribute * @param {Boolean} asNumber true to parse the value as a number * @return {String/Number} * 返回“值的”属性值 * @param {Boolean} asNumber 表示为将值解析为数字 * @return {String/Number} */ getValue : function(asNumber){ return asNumber ? parseInt(this.dom.value, 10) : this.dom.value; }, // private adjustWidth : function(width){ if(typeof width == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ width -= (this.getBorderWidth("lr") + this.getPadding("lr")); } if(width < 0){ width = 0; } } return width; }, // private adjustHeight : function(height){ if(typeof height == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ height -= (this.getBorderWidth("tb") + this.getPadding("tb")); } if(height < 0){ height = 0; } } return height; }, /** * Set the width of the element * @param {Number} width The new width * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * 设置元素的宽度 * @param {Number} width 新宽度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setWidth : function(width, animate){ width = this.adjustWidth(width); if(!animate || !A){ this.dom.style.width = this.addUnits(width); }else{ this.anim({width: {to: width}}, this.preanim(arguments, 1)); } return this; }, /** * Set the height of the element * @param {Number} height The new height * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * 设置元素的高度 * @param {Number} height 新高度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setHeight : function(height, animate){ height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.height = this.addUnits(height); }else{ this.anim({height: {to: height}}, this.preanim(arguments, 1)); } return this; }, /** * Set the size of the element. If animation is true, both width an height will be animated concurrently. * @param {Number} width The new width * @param {Number} height The new height * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * 设置元素的大小尺寸。如果动画效果被打开,高度和宽度都会产生动画的变化效果。 * @param {Number} width 新宽度 * @param {Number} height 新高度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setSize : function(width, height, animate){ if(typeof width == "object"){ // in case of object from getSize() height = width.height; width = width.width; } width = this.adjustWidth(width); height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.width = this.addUnits(width); this.dom.style.height = this.addUnits(height); }else{ this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2)); } return this; }, /** * Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently. * @param {Number} x X value for new position (coordinates are page-based) * @param {Number} y Y value for new position (coordinates are page-based) * @param {Number} width The new width * @param {Number} height The new height * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * 一次过设置元素的位置和大小。如果动画效果被打开,高度和宽度都会产生动画的变化效果。 * @param {Number} x 新位置上的x值(基于页面的坐标) * @param {Number} y 新位置上的y值(基于页面的坐标) * @param {Number} width 新宽度 * @param {Number} height 新高度 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setBounds : function(x, y, width, height, animate){ if(!animate || !A){ this.setSize(width, height); this.setLocation(x, y); }else{ width = this.adjustWidth(width); height = this.adjustHeight(height); this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}}, this.preanim(arguments, 4), 'motion'); } return this; }, /** * Sets the element's position and size the the specified region. If animation is true then width, height, x and y will be animated concurrently. * @param {Ext.lib.Region} region The region to fill * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * * 设置元素的位置并调整大小到指定的位置。如果动画效果被打开,高度和宽度都会产生动画的变化效果。 * @param {Ext.lib.Region} region 要填充的区域 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setRegion : function(region, animate){ this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1)); return this; }, /** * 为该组件加入事件句柄(event handler)。跟简写方式{@link #on}是一样的。 * 通常你会更多的使用元素本身{@link Ext.Element#removeListener}的方法。 * @param {String/HTMLElement} eventName 侦听事件的类型 * @param {Function} handler 句柄,事件执行的方法 * @param {Object} scope (可选的) 句柄函数执行时所在的作用域。句柄函数“this”的上下文。 */ addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); }, /** * 从这个元素上移除事件句柄(event handler),跟简写方式{@link #un}是一样的。 * 举例: * <pre><code> el.removeListener('click', this.handlerFn); //或 el.un('click', this.handlerFn); </code></pre> * @param {String} eventName 要移除事件的类型 * @param {Function} fn 事件执行的方法 * @return {Ext.Element} this */ removeListener : function(eventName, fn){ Ext.EventManager.removeListener(this.dom, eventName, fn); return this; }, /** * Removes all previous added listeners from this element * * 在该元素身上移除所有已加入的侦听器 * @return {Ext.Element} this */ removeAllListeners : function(){ E.purgeElement(this.dom); return this; }, /** * Create an event handler on this element * 创建此元素的事件句柄,由此元素接替另外的对象触发和处理事件。 * such that when the event fires and is handled by this element, * it will be relayed to another object * (i.e., fired again as if it originated from that object instead). * @param {String} eventName 要接替的事件名称 * @param {Object} object 任何继承自{@link Ext.util.Observable}的对象用于在上下文里触发接替的事件 */ relayEvent : function(eventName, observable){ this.on(eventName, function(e){ observable.fireEvent(eventName, e); }); }, /** * Set the opacity of the element * @param {Float} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * 设置元素透明度 * @param {Float} opacity 新的透明度。 0 = 透明, .5 = 50% 可见, 1 =完全可见, 等等 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setOpacity : function(opacity, animate){ if(!animate || !A){ var s = this.dom.style; if(Ext.isIE){ s.zoom = 1; s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") + (opacity == 1 ? "" : " alpha(opacity=" + opacity * 100 + ")"); }else{ s.opacity = opacity; } }else{ this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn'); } return this; }, /** * Gets the left X coordinate * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} * * 获取X坐标 * @param {Boolean} local true表示为获取局部CSS位置代替页面坐标 * @return {Number} */ getLeft : function(local){ if(!local){ return this.getX(); }else{ return parseInt(this.getStyle("left"), 10) || 0; } }, /** * Gets the right X coordinate of the element (element X position + element width) * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} * * 获取元素的右X坐标 (元素X位置 + 元素宽度) * @param {Boolean} local True :获取局部CSS位置代替页面坐标 * @return {Number} */ getRight : function(local){ if(!local){ return this.getX() + this.getWidth(); }else{ return (this.getLeft(true) + this.getWidth()) || 0; } }, /** * Gets the top Y coordinate * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} * * 获取顶部Y坐标 * @param {Boolean} local :获取局部CSS位置代替页面坐标 * @return {Number} */ getTop : function(local) { if(!local){ return this.getY(); }else{ return parseInt(this.getStyle("top"), 10) || 0; } }, /** * Gets the bottom Y coordinate of the element (element Y position + element height) * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} * * 获取元素的底部Y坐标 (元素Y位置 + 元素宽度) * @param {Boolean} local True :获取局部CSS位置代替页面坐标 * @return {Number} */ getBottom : function(local){ if(!local){ return this.getY() + this.getHeight(); }else{ return (this.getTop(true) + this.getHeight()) || 0; } }, /** * Initializes positioning on this element. If a desired position is not passed, it will make the * the element positioned relative IF it is not already positioned. * @param {String} pos (optional) Positioning to use "relative", "absolute" or "fixed" * @param {Number} zIndex (optional) The zIndex to apply * @param {Number} x (optional) Set the page X position * @param {Number} y (optional) Set the page Y position * * 初始化元素的定位。 * 如果不传入一个特定的定位,而又还没定位的话,将会使这个元素 相对(relative)定位 * @param {String} pos (可选的) 使用 "relative", "absolute" 或 "fixed"的定位 * @param {Number} zIndex (可选的) z-Index值 * @param {Number} x (可选的)设置页面 X方向位置 * @param {Number} y (可选的) 设置页面 Y方向位置 */ position : function(pos, zIndex, x, y){ if(!pos){ if(this.getStyle('position') == 'static'){ this.setStyle('position', 'relative'); } }else{ this.setStyle("position", pos); } if(zIndex){ this.setStyle("z-index", zIndex); } if(x !== undefined && y !== undefined){ this.setXY([x, y]); }else if(x !== undefined){ this.setX(x); }else if(y !== undefined){ this.setY(y); } }, /** * Clear positioning back to the default when the document was loaded * @param {String} value (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'. * @return {Ext.Element} this * * 当文档加载后清除位置并复位到默认 * @param {String} value (可选的) 用于 left,right,top,bottom的值, 默认为 '' (空白字符串). 你可使用 'auto'. * @return {Ext.Element} this */ clearPositioning : function(value){ value = value ||''; this.setStyle({ "left": value, "right": value, "top": value, "bottom": value, "z-index": "", "position" : "static" }); return this; }, /** * Gets an object with all CSS positioning properties. Useful along with setPostioning to get * snapshot before performing an update and then restoring the element. * @return {Object} * * 获取一个包含CSS定位的对象 * 有用的技巧:连同setPostioning一起,可在更新执行之前,先做一个快照(snapshot),之后便可恢复该元素。 * @return {Object} */ getPositioning : function(){ var l = this.getStyle("left"); var t = this.getStyle("top"); return { "position" : this.getStyle("position"), "left" : l, "right" : l ? "" : this.getStyle("right"), "top" : t, "bottom" : t ? "" : this.getStyle("bottom"), "z-index" : this.getStyle("z-index") }; }, /** * Gets the width of the border(s) for the specified side(s) * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, * passing lr would get the border (l)eft width + the border (r)ight width. * @return {Number} The width of the sides passed added together * * 获取指定边(side(s))的 border(s)宽度 * @param {String} side可以是 t, l, r, b或是任何组合 * 例如,传入lr的参数会得到(l)eft padding +(r)ight padding * @return {Number} 四边的padding之和 */ getBorderWidth : function(side){ return this.addStyles(side, El.borders); }, /** * Gets the width of the padding(s) for the specified side(s) * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, * passing lr would get the padding (l)eft + the padding (r)ight. * @return {Number} The padding of the sides passed added together * 获取指定边(side(s))的padding宽度 * @param {String} side 可以是 t, l, r, b或是任何组合 * 例如,传入lr的参数会得到(l)eft padding +(r)ight padding * @return {Number} 四边的padding之和 */ getPadding : function(side){ return this.addStyles(side, El.paddings); }, /** * Set positioning with an object returned by getPositioning(). * * 由getPositioning()返回的对象去设置定位 * @param {Object} posCfg * @return {Ext.Element} this */ setPositioning : function(pc){ this.applyStyles(pc); if(pc.right == "auto"){ this.dom.style.right = ""; } if(pc.bottom == "auto"){ this.dom.style.bottom = ""; } return this; }, // private fixDisplay : function(){ if(this.getStyle("display") == "none"){ this.setStyle("visibility", "hidden"); this.setStyle("display", this.originalDisplay); // first try reverting to default if(this.getStyle("display") == "none"){ // if that fails, default to block this.setStyle("display", "block"); } } }, /** * Quick set left and top adding default units * * 快速设置left和top(采用默认单位) * @param {String} left CSS的left属性值 * @param {String} top TCSS的top属性值 * @return {Ext.Element} this */ setLeftTop : function(left, top){ this.dom.style.left = this.addUnits(left); this.dom.style.top = this.addUnits(top); return this; }, /** * Move this element relative to its current position. * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down". * @param {Number} distance How far to move the element in pixels * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * 移动这个元素到相对于当前的位置。 * @param {String} direction 可能出现的值: "l","left" - "r","right" - "t","top","up" - "b","bottom","down". * @param {Number} distance 元素移动有多远(像素) * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ move : function(direction, distance, animate){ var xy = this.getXY(); direction = direction.toLowerCase(); switch(direction){ case "l": case "left": this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2)); break; case "r": case "right": this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2)); break; case "t": case "top": case "up": this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2)); break; case "b": case "bottom": case "down": this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2)); break; } return this; }, /** * Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove * @return {Ext.Element} this * * 保存当前的溢出(overflow),然后进行裁剪元素的溢出部分 - 使用 {@link #unclip}来移除 * @return {Ext.Element} this */ clip : function(){ if(!this.isClipped){ this.isClipped = true; this.originalClip = { "o": this.getStyle("overflow"), "x": this.getStyle("overflow-x"), "y": this.getStyle("overflow-y") }; this.setStyle("overflow", "hidden"); this.setStyle("overflow-x", "hidden"); this.setStyle("overflow-y", "hidden"); } return this; }, /** * Return clipping (overflow) to original clipping before clip() was called * * 在调用clip()之前,返回原始的裁剪部分(溢出的) * @return {Ext.Element} this */ unclip : function(){ if(this.isClipped){ this.isClipped = false; var o = this.originalClip; if(o.o){this.setStyle("overflow", o.o);} if(o.x){this.setStyle("overflow-x", o.x);} if(o.y){this.setStyle("overflow-y", o.y);} } return this; }, /** * Gets the x,y coordinates specified by the anchor position on the element. * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} * for details on supported anchor positions. * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead * of page coordinates * @param {Object} size (optional) An object containing the size to use for calculating anchor position * {width: (target width), height: (target height)} (defaults to the element's current size) * @return {Array} [x, y] An array containing the element's x and y coordinates * 返回X、Y坐标,由元素已标记好的位置(anchor position)指定。 * @param {String} anchor (可选的) 指定的标记位置(默认为 "c")。参阅 {@link #alignTo}可支持的标记好的位置(anchor position)之细节。 * @param {Object} size (可选的) 用于计算标记位置的对象 * {width: (目标宽度), height: (目标高度)} (默认为元素当前大小) * @param {Boolean} local (可选的) true表示为获取局部的(元素相对的 top/left) 标记的位置而非页面坐标 * @return {Array} [x, y] 包含元素X、Y坐标的数组 */ getAnchorXY : function(anchor, local, s){ //Passing a different size is useful for pre-calculating anchors, //especially for anchored animations that change the el size. var w, h, vp = false; if(!s){ var d = this.dom; if(d == document.body || d == document){ vp = true; w = D.getViewWidth(); h = D.getViewHeight(); }else{ w = this.getWidth(); h = this.getHeight(); } }else{ w = s.width; h = s.height; } var x = 0, y = 0, r = Math.round; switch((anchor || "tl").toLowerCase()){ case "c": x = r(w*.5); y = r(h*.5); break; case "t": x = r(w*.5); y = 0; break; case "l": x = 0; y = r(h*.5); break; case "r": x = w; y = r(h*.5); break; case "b": x = r(w*.5); y = h; break; case "tl": x = 0; y = 0; break; case "bl": x = 0; y = h; break; case "br": x = w; y = h; break; case "tr": x = w; y = 0; break; } if(local === true){ return [x, y]; } if(vp){ var sc = this.getScroll(); return [x + sc.left, y + sc.top]; } //Add the element's offset xy //加入元素的xy偏移 var o = this.getXY(); return [x+o[0], y+o[1]]; }, /** * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the * supported position values. * @param {Mixed} element The element to align to. * @param {String} position The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @return {Array} [x, y] * 获取该元素对齐另一个元素时候的x,y坐标。参阅 {@link #alignTo}了解可支持的位置值。 * @param {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @return {Array} [x, y] */ getAlignToXY : function(el, p, o){ el = Ext.get(el); if(!el || !el.dom){ throw "Element.alignToXY with an element that doesn't exist"; } var d = this.dom; var c = false; //constrain to viewport //constrain to viewport视图的约束 var p1 = "", p2 = ""; o = o || [0,0]; if(!p){ p = "tl-bl"; }else if(p == "?"){ p = "tl-bl?"; }else if(p.indexOf("-") == -1){ p = "tl-" + p; } p = p.toLowerCase(); var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/); if(!m){ throw "Element.alignTo with an invalid alignment " + p; } p1 = m[1]; p2 = m[2]; c = !!m[3]; //Subtract the aligned el's internal xy from the target's offset xy //plus custom offset to get the aligned el's new offset xy var a1 = this.getAnchorXY(p1, true); var a2 = el.getAnchorXY(p2, false); var x = a2[0] - a1[0] + o[0]; var y = a2[1] - a1[1] + o[1]; if(c){ //constrain the aligned el to viewport if necessary var w = this.getWidth(), h = this.getHeight(), r = el.getRegion(); // 5px of margin for ie var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5; //If we are at a viewport boundary and the aligned el is anchored on a target border that is //perpendicular to the vp border, allow the aligned el to slide on that border, //otherwise swap the aligned el to the opposite border of the target. var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1); var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1); var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t")); var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r")); var doc = document; var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5; var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5; if((x+w) > dw + scrollX){ x = swapX ? r.left-w : dw+scrollX-w; } if(x < scrollX){ x = swapX ? r.right : scrollX; } if((y+h) > dh + scrollY){ y = swapY ? r.top-h : dh+scrollY-h; } if (y < scrollY){ y = swapY ? r.bottom : scrollY; } } return [x,y]; }, // private getConstrainToXY : function(){ var os = {top:0, left:0, bottom:0, right: 0}; return function(el, local, offsets, proposedXY){ el = Ext.get(el); offsets = offsets ? Ext.applyIf(offsets, os) : os; var vw, vh, vx = 0, vy = 0; if(el.dom == document.body || el.dom == document){ vw = Ext.lib.Dom.getViewWidth(); vh = Ext.lib.Dom.getViewHeight(); }else{ vw = el.dom.clientWidth; vh = el.dom.clientHeight; if(!local){ var vxy = el.getXY(); vx = vxy[0]; vy = vxy[1]; } } var s = el.getScroll(); vx += offsets.left + s.left; vy += offsets.top + s.top; vw -= offsets.right; vh -= offsets.bottom; var vr = vx+vw; var vb = vy+vh; var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth, h = this.dom.offsetHeight; // only move it if it needs it var moved = false; // first validate right/bottom if((x + w) > vr){ x = vr - w; moved = true; } if((y + h) > vb){ y = vb - h; moved = true; } // then make sure top/left isn't negative if(x < vx){ x = vx; moved = true; } if(y < vy){ y = vy; moved = true; } return moved ? [x, y] : false; }; }(), // private adjustForConstraints : function(xy, parent, offsets){ return this.getConstrainToXY(parent || document, false, offsets, xy) || xy; }, /** * Aligns this element with another element relative to the specified anchor points. If the other element is the * document it aligns it to the viewport. * The position parameter is optional, and can be specified in any one of the following formats: * <ul> * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li> * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point. * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been * deprecated in favor of the newer two anchor syntax below</i>.</li> * <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the * element's anchor point, and the second value is used as the target's anchor point.</li> * </ul> * 对齐元素到另外一个元素的指定的标记。如果这个元素是document,对齐到视图 * 位置参数是可选的, 可指定为下列格式: * <ul> * <li><b>空白</b>: 默认为 aligning the element"s top-left corner to * the target"s bottom-left corner ("tl-bl").</li> * <li><b>有一个锚点()One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point. * The element being aligned will position its top-left corner (tl) to * that point. <i>This method has been * deprecated in favor of the newer two anchor syntax below</i>.</li> * <li><b>有两个锚点</b>: * If two values from the table below are passed separated by a dash, * the first value is used as the * element"s anchor point, and the second value is used as the target"s anchor point.</li> * </ul> * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than * that specified in order to enforce the viewport constraints. * Following are all of the supported anchor positions: * 下列可支持的锚点位置: <pre> Value Description 值 描述 ----- ----------------------------- tl The top left corner (default) t The center of the top edge tr The top right corner l The center of the left edge c In the center of the element r The center of the right edge bl The bottom left corner b The center of the bottom edge br The bottom right corner </pre> Example Usage: 使用范例: <pre><code> // align el to other-el using the default positioning ("tl-bl", non-constrained) el.alignTo("other-el"); // align the top left corner of el with the top right corner of other-el (constrained to viewport) el.alignTo("other-el", "tr?"); // align the bottom right corner of el with the center left edge of other-el el.alignTo("other-el", "br-l?"); // align the center of el with the bottom left corner of other-el and // adjust the x position by -6 pixels (and the y position by 0) el.alignTo("other-el", "c-bl", [-6, 0]); </code></pre> * @param {Mixed} element The element to align to. * @param {String} position The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * @param {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ alignTo : function(element, position, offsets, animate){ var xy = this.getAlignToXY(element, position, offsets); this.setXY(xy, this.preanim(arguments, 3)); return this; }, /** * Anchors an element to another element and realigns it when the window is resized. * @param {Mixed} element The element to align to. * @param {String} position The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter * is a number, it is used as the buffer delay (defaults to 50ms). * @param {Function} callback The function to call after the animation finishes * @return {Ext.Element} this * 标记一个元素到另外一个元素,并当window resiz时重新对齐。 * @param {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @param {Boolean/Number} monitorScroll (可选的) true表示为监视body滚动并重新定位。如果该参数是一个数字,即意味有缓冲延时(默认为 50ms) * @param {Function} callback 动画完成后执行的函数 * @return {Ext.Element} this */ anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){ var action = function(){ this.alignTo(el, alignment, offsets, animate); Ext.callback(callback, this); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); // align immediately return this; }, /** * Clears any opacity settings from this element. Required in some cases for IE. * 清除这个元素的透明度设置。IE有时候会用到 * @return {Ext.Element} this */ clearOpacity : function(){ if (window.ActiveXObject) { if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){ this.dom.style.filter = ""; } } else { this.dom.style.opacity = ""; this.dom.style["-moz-opacity"] = ""; this.dom.style["-khtml-opacity"] = ""; } return this; }, /** * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * 隐藏此元素 -使用display mode 来决定用 "display" 抑或 "visibility"。 参阅 {@link #setVisible}. * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ hide : function(animate){ this.setVisible(false, this.preanim(arguments, 0)); return this; }, /** * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * 显示此元素 -使用display mode 来决定用 "display" 抑或 "visibility"。 参阅 {@link #setVisible}. * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ show : function(animate){ this.setVisible(true, this.preanim(arguments, 0)); return this; }, /** * @private Test if size has a unit, otherwise appends the default * @私有的 测试某个尺寸是否有单位,否则加入默认单位。 */ addUnits : function(size){ return Ext.Element.addUnits(size, this.defaultUnit); }, /** * Update the innerHTML of this element, optionally searching for and processing scripts * @param {String} html The new HTML * @param {Boolean} loadScripts (optional) True to look for and process scripts (defaults to false) * @param {Function} callback (optional) For async script loading you can be notified when the update completes * @return {Ext.Element} this * * 更新该元素的innerHTML,遇到脚本可以执行。 * @param {String} html 新的HTML * @param {Boolean} loadScripts (可选的) true表示为遇到脚本要执行 * @param {Function} callback 当更新完成后,你加载一个同步脚本,得知更新完成。 * @return {Ext.Element} this */ update : function(html, loadScripts, callback){ if(typeof html == "undefined"){ html = ""; } if(loadScripts !== true){ this.dom.innerHTML = html; if(typeof callback == "function"){ callback(); } return this; } var id = Ext.id(); var dom = this.dom; html += '<span id="' + id + '"></span>'; E.onAvailable(id, function(){ var hd = document.getElementsByTagName("head")[0]; var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig; var srcRe = /\ssrc=([\'\"])(.*?)\1/i; var typeRe = /\stype=([\'\"])(.*?)\1/i; var match; while(match = re.exec(html)){ var attrs = match[1]; var srcMatch = attrs ? attrs.match(srcRe) : false; if(srcMatch && srcMatch[2]){ var s = document.createElement("script"); s.src = srcMatch[2]; var typeMatch = attrs.match(typeRe); if(typeMatch && typeMatch[2]){ s.type = typeMatch[2]; } hd.appendChild(s); }else if(match[2] && match[2].length > 0){ if(window.execScript) { window.execScript(match[2]); } else { window.eval(match[2]); } } } var el = document.getElementById(id); if(el){Ext.removeNode(el);} if(typeof callback == "function"){ callback(); } }); dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, ""); return this; }, /** * Direct access to the Updater {@link Ext.Updater#update} method (takes the same parameters). * @param {String/Function} url The url for this request or a function to call to get the url * @param {String/Object} params (optional) The parameters to pass as either a url encoded string "param1=1&amp;param2=2" or an object {param1: 1, param2: 2} * @param {Function} callback (optional) Callback when transaction is complete - called with signature (oElement, bSuccess) * @param {Boolean} discardUrl (optional) By default when you execute an update the defaultUrl is changed to the last used url. If true, it will not store the url. * @return {Ext.Element} this * * 直接访问Updater的{@link Ext.Updater#update}方法(相同的参数) * @param {String/Function} url 针对该请求的url或是能返回url的函数 * @param {String/Object} params(可选的)作为url一部分的参数,可以是已编码的字符串"param1=1&amp;param2=2",或是一个对象{param1: 1, param2: 2} * @param {Function} callback (可选的)请求往返完成后的回调,调用时有参数(oElement, bSuccess) * @param {Boolean} discardUrl (可选的)默认情况下你执行一次更新后,最后一次url会保存到defaultUrl。如果true的话,将不会保存。 * @return {Ext.Element} this */ load : function(){ var um = this.getUpdater(); um.update.apply(um, arguments); return this; }, /** * Gets this element's Updater * @return {Ext.Updater} The Updater * * 获取这个元素的UpdateManager * @return {Ext.UpdateManager} The Updater */ getUpdater : function(){ if(!this.updateManager){ this.updateManager = new Ext.Updater(this); } return this.updateManager; }, /** * Disables text selection for this element (normalized across browsers) * 禁止该元素的文本可被选择(可跨浏览器)。 * @return {Ext.Element} this */ unselectable : function(){ this.dom.unselectable = "on"; this.swallowEvent("selectstart", true); this.applyStyles("-moz-user-select:none;-khtml-user-select:none;"); this.addClass("x-unselectable"); return this; }, /** * Calculates the x, y to center this element on the screen * * 计算该元素的x,y到屏幕中心的值 * @return {Array} The x, y values [x, y] */ getCenterXY : function(){ return this.getAlignToXY(document, 'c-c'); }, /** * Centers the Element in either the viewport, or another Element. * @param {Mixed} centerIn (optional) The element in which to center the element. * * 在视图或其他元素中,居中元素。 * @param {String/HTMLElement/Ext.Element} centerIn (可选的)视图或其他元素 */ center : function(centerIn){ this.alignTo(centerIn || document, 'c-c'); return this; }, /** * Tests various css rules/browsers to determine if this element uses a border box * @return {Boolean} * 测试不同的CSS规则/浏览器以确定该元素是否使用Border Box * @return {Boolean} */ isBorderBox : function(){ return noBoxAdjust[this.dom.tagName.toLowerCase()] || Ext.isBorderBox; }, /** * Return a box {x, y, width, height} that can be used to set another elements * size/location to match this element. * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned. * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y. * @return {Object} box An object in the format {x, y, width, height} * * 返回一个BOX {x, y, width, height},可用于匹配其他元素的大小/位置。 * @param {Boolean} contentBox (可选的)true表示为返回元素内容的BOX。 * @param {Boolean} local (可选的) true表示为返回元素的left和top代替页面的x/y。 * @return {Object} */ getBox : function(contentBox, local){ var xy; if(!local){ xy = this.getXY(); }else{ var left = parseInt(this.getStyle("left"), 10) || 0; var top = parseInt(this.getStyle("top"), 10) || 0; xy = [left, top]; } var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx; if(!contentBox){ bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h}; }else{ var l = this.getBorderWidth("l")+this.getPadding("l"); var r = this.getBorderWidth("r")+this.getPadding("r"); var t = this.getBorderWidth("t")+this.getPadding("t"); var b = this.getBorderWidth("b")+this.getPadding("b"); bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)}; } bx.right = bx.x + bx.width; bx.bottom = bx.y + bx.height; return bx; }, /** * Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth() * for more information about the sides. * * 传入的“side”的参数,统计边框和内补丁(padding & borders)的宽度并返回该值。 * 参阅getBorderWidth()以得到更多sides的资料 * @param {String} sides * @return {Number} */ getFrameWidth : function(sides, onlyContentBox){ return onlyContentBox && Ext.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides)); }, /** * Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently. * @param {Object} box The box to fill {x, y, width, height} * @param {Boolean} adjust (optional) Whether to adjust for box-model issues automatically * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this * * 设置元素之Box。使用getBox() 在其他对象身上获取box对象。 * 如果动画为true,那么高度和宽度都会同时出现动画效果。 * @param {Object} box 填充的Box {x, y, width, height} * @param {Boolean} adjust (可选的) 是否自动调整由box-mode问题引起的高度和宽度设置 * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ setBox : function(box, adjust, animate){ var w = box.width, h = box.height; if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){ w -= (this.getBorderWidth("lr") + this.getPadding("lr")); h -= (this.getBorderWidth("tb") + this.getPadding("tb")); } this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2)); return this; }, /** * Forces the browser to repaint this element * * 强制浏览器重新渲染该元素 * @return {Ext.Element} this */ repaint : function(){ var dom = this.dom; this.addClass("x-repaint"); setTimeout(function(){ Ext.get(dom).removeClass("x-repaint"); }, 1); return this; }, /** * Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed, * then it returns the calculated width of the sides (see getPadding) * @param {String} sides (optional) Any combination of l, r, t, b to get the sum of those sides * @return {Object/Number} * * 返回该元素的top、left、right 和 bottom 属性,以表示margin(外补丁)。 * 若有sides参数传入,即返回已计算好的sides宽度。 * @param {String} sides (可选的) 任何 l, r, t, b的组合,以获取该 sides的统计。 * @return {Object/Number} */ getMargins : function(side){ if(!side){ return { top: parseInt(this.getStyle("margin-top"), 10) || 0, left: parseInt(this.getStyle("margin-left"), 10) || 0, bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0, right: parseInt(this.getStyle("margin-right"), 10) || 0 }; }else{ return this.addStyles(side, El.margins); } }, // private addStyles : function(sides, styles){ var val = 0, v, w; for(var i = 0, len = sides.length; i < len; i++){ v = this.getStyle(styles[sides.charAt(i)]); if(v){ w = parseInt(v, 10); if(w){ val += (w >= 0 ? w : -1 * w); } } } return val; }, /** * Creates a proxy element of this element * @param {String/Object} config The class name of the proxy element or a DomHelper config object * @param {String/HTMLElement} renderTo (optional) The element or element id to render the proxy to (defaults to document.body) * @param {Boolean} matchBox (optional) True to align and size the proxy to this element now (defaults to false) * @return {Ext.Element} The new proxy element * * 创建代理(Proxy),即元素的元素 * @param {String/Object} config 代理元素的类名称或是DomHelper配置项对象 * @param {String/HTMLElement} renderTo (可选的) 成为代理的元素或是元素ID (默认为 document.body) * @param {Boolean} matchBox (可选的) true表示为立即和代理对齐和设置大小 (默认为 false) * @return {Ext.Element} 新代理元素 */ createProxy : function(config, renderTo, matchBox){ config = typeof config == "object" ? config : {tag : "div", cls: config}; var proxy; if(renderTo){ proxy = Ext.DomHelper.append(renderTo, config, true); }else { proxy = Ext.DomHelper.insertBefore(this.dom, config, true); } if(matchBox){ proxy.setBox(this.getBox()); } return proxy; }, /** * Puts a mask over this element to disable user interaction. Requires core.css. * This method can only be applied to elements which accept child nodes. * @param {String} msg (optional) A message to display in the mask * @param {String} msgCls (optional) A css class to apply to the msg element * @return {Element} The mask element * * 在元素身上遮上一个蒙板(mask),以禁止用户操作。须core.css。 * 这个方法只能用于接受子节点(child nodes)的元素。 * @param {String} msg (可选的) 蒙板显示的信息 * @param {String} msgCls (可选的) 信息元素的CSS类 * @return {Element} 信息元素 */ mask : function(msg, msgCls){ if(this.getStyle("position") == "static"){ this.setStyle("position", "relative"); } if(this._maskMsg){ this._maskMsg.remove(); } if(this._mask){ this._mask.remove(); } this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true); this.addClass("x-masked"); this._mask.setDisplayed(true); if(typeof msg == 'string'){ this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true); var mm = this._maskMsg; mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg"; mm.dom.firstChild.innerHTML = msg; mm.setDisplayed(true); mm.center(this); } if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically this._mask.setSize(this.dom.clientWidth, this.getHeight()); } return this._mask; }, /** * Removes a previously applied mask. * * 移除之前的蒙板。 * 如果removeEl是true,则蒙板会被摧毁,否则放在缓存cache中。 */ unmask : function(){ if(this._mask){ if(this._maskMsg){ this._maskMsg.remove(); delete this._maskMsg; } this._mask.remove(); delete this._mask; } this.removeClass("x-masked"); }, /** * Returns true if this element is masked * * 返回true表示为这个元素应用了蒙板。 * @return {Boolean} */ isMasked : function(){ return this._mask && this._mask.isVisible(); }, /** * Creates an iframe shim for this element to keep selects and other windowed objects from * showing through. * @return {Ext.Element} The new shim element * * 创建一个iframe垫片来使得select和其他windowed对象在该元素显示之下。 * @return {Ext.Element} 新垫片元素 */ createShim : function(){ var el = document.createElement('iframe'); el.frameBorder = 'no'; el.className = 'ext-shim'; if(Ext.isIE && Ext.isSecure){ el.src = Ext.SSL_SECURE_URL; } var shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); shim.autoBoxAdjust = false; return shim; }, /** * Removes this element from the DOM and deletes it from the cache * 从DOM里面移除该元素,并从缓存中删除。 */ remove : function(){ Ext.removeNode(this.dom); delete El.cache[this.dom.id]; }, /** * Sets up event handlers to call the passed functions when the mouse is over this element. * Automatically filters child element mouse events. * @param {Function} overFn * @param {Function} outFn * @param {Object} scope (optional) * @return {Ext.Element} this * * 设置事件句柄,当鼠标在此元素之上作用的Css样式类。自动过滤因mouseout事件引起在子元素上的轻移(Flicker) * @param {Function} overFn * @param {Function} outFn * @param {Object} scope (可选的) * @return {Ext.Element} this */ hover : function(overFn, outFn, scope){ var preOverFn = function(e){ if(!e.within(this, true)){ overFn.apply(scope || this, arguments); } }; var preOutFn = function(e){ if(!e.within(this, true)){ outFn.apply(scope || this, arguments); } }; this.on("mouseover", preOverFn, this.dom); this.on("mouseout", preOutFn, this.dom); return this; }, /** * Sets up event handlers to add and remove a css class when the mouse is over this element * * 设置事件句柄,当此鼠标位于元素上方时作用的CSS样式类。 * @param {String} className * @param {Boolean} preventFlicker (可选的) 如果为true,会阻止因mouseout事件引起在子元素上的轻移(Flicker) * @return {Ext.Element} this */ addClassOnOver : function(className, preventFlicker){ this.hover( function(){ Ext.fly(this, '_internal').addClass(className); }, function(){ Ext.fly(this, '_internal').removeClass(className); } ); return this; }, /** * Sets up event handlers to add and remove a css class when this element has the focus * * 设置事件句柄,当此元素得到焦点(focus)时作用的CSS样式类。 * @param {String} className * @return {Ext.Element} this */ addClassOnFocus : function(className){ this.on("focus", function(){ Ext.fly(this, '_internal').addClass(className); }, this.dom); this.on("blur", function(){ Ext.fly(this, '_internal').removeClass(className); }, this.dom); return this; }, /** * Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect) * 当鼠标在该元素上面按下接着松开(即单击效果),设置event handlers来添加和移除css类。 * @param {String} className * @return {Ext.Element} this */ addClassOnClick : function(className){ var dom = this.dom; this.on("mousedown", function(){ Ext.fly(dom, '_internal').addClass(className); var d = Ext.getDoc(); var fn = function(){ Ext.fly(dom, '_internal').removeClass(className); d.removeListener("mouseup", fn); }; d.on("mouseup", fn); }); return this; }, /** * Stops the specified event from bubbling and optionally prevents the default action * @param {String} eventName * @param {Boolean} preventDefault (optional) true to prevent the default action too * @return {Ext.Element} this * * 事件上报(bubbling)的过程中停止特定的事件,阻止默认动作(可选的)。 * @param {String} eventName * @param {Boolean} preventDefault (可选的)true表示阻止默认动作 * @return {Ext.Element} this */ swallowEvent : function(eventName, preventDefault){ var fn = function(e){ e.stopPropagation(); if(preventDefault){ e.preventDefault(); } }; if(eventName instanceof Array){ for(var i = 0, len = eventName.length; i < len; i++){ this.on(eventName[i], fn); } return this; } this.on(eventName, fn); return this; }, /** * Gets the parent node for this element, optionally chaining up trying to match a selector * 获取此节点的父级元素 * @param {String} selector (optional) 通过简易选择符来查找下一个侧边节点 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 下一个侧边节点或null */ parent : function(selector, returnDom){ return this.matchNode('parentNode', 'parentNode', selector, returnDom); }, /** * Gets the next sibling, skipping text nodes * 获取下一个侧边节点,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找下一个侧边节点 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 下一个侧边节点或null */ next : function(selector, returnDom){ return this.matchNode('nextSibling', 'nextSibling', selector, returnDom); }, /** * Gets the previous sibling, skipping text nodes * 获取上一个侧边节点,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找上一个侧边节点 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 上一个侧边节点或null */ prev : function(selector, returnDom){ return this.matchNode('previousSibling', 'previousSibling', selector, returnDom); }, /** * Gets the first child, skipping text nodes * 获取第一个子元素,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找第一个子元素 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 第一个子元素或null */ first : function(selector, returnDom){ return this.matchNode('nextSibling', 'firstChild', selector, returnDom); }, /** * 获取最后一个子元素,跳过文本节点 * @param {String} selector (optional) 通过简易选择符来查找最后一个元素 * @param {Boolean} returnDom (optional) True表示返回原始的dom节点而非Ext.Element * @return {Ext.Element/HTMLElement} 最后一个元素或null */ last : function(selector, returnDom){ return this.matchNode('previousSibling', 'lastChild', selector, returnDom); }, matchNode : function(dir, start, selector, returnDom){ var n = this.dom[start]; while(n){ if(n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))){ return !returnDom ? Ext.get(n) : n; } n = n[dir]; } return null; }, /** * Appends the passed element(s) to this element * 传入一个或多个元素,加入到该元素 * @param {String/HTMLElement/Array/Element/CompositeElement} el * @return {Ext.Element} this */ appendChild: function(el){ el = Ext.get(el); el.appendTo(this); return this; }, /** * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element. * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be * automatically generated with the specified attributes. * @param {HTMLElement} insertBefore (optional) a child element of this element * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element * @return {Ext.Element} The new child element * 传入一个DomHelper配置项对象的参数,将其创建并加入其到该元素; * 可选地,可指定在其子元素(哪个子元素由参数传入)之前的地方插入。 * @param {Object} config DomHelper元素配置项对象 * @param {HTMLElement} insertBefore (可选的) 该元素的子元素 * @param {Boolean} returnDom (可选的) true表示为返回DOM节点代替创建一个元素 * @return {Ext.Element} 新的子元素 */ createChild: function(config, insertBefore, returnDom){ config = config || {tag:'div'}; if(insertBefore){ return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true); } return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); }, /** * Appends this element to the passed element * @param {Mixed} el The new parent element * @return {Ext.Element} this * * 传入元素的参数,将该元素加入到传入的元素 * @param {String/HTMLElement/Element} el 新父元素 * @return {Ext.Element} this */ appendTo: function(el){ el = Ext.getDom(el); el.appendChild(this.dom); return this; }, /** * Inserts this element before the passed element in the DOM * @param {Mixed} el The element to insert before * @return {Ext.Element} this * * 传入元素的参数,将该元素的DOM插入其之前 * @param {String/HTMLElement/Element} el 在它前面插入的那个元素 * @return {Ext.Element} this */ insertBefore: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el); return this; }, /** * Inserts this element after the passed element in the DOM * @param {Mixed} el The element to insert after * @return {Ext.Element} this * * 传入元素的参数,将该元素的DOM插入其之后 * @param {String/HTMLElement/Element} el 在它后面插入的那个元素 * @return {Ext.Element} this */ insertAfter: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el.nextSibling); return this; }, /** * Inserts (or creates) an element (or DomHelper config) as the first child of the this element * @param {Mixed/Object} el The id or element to insert or a DomHelper config to create and insert * @return {Ext.Element} The new child * * 插入(或创建)一个元素(或DomHelper配置项对象)作为该元素的第一个子元素 * @param {String/HTMLElement/Element/Object} el 可以是id;或是插入的元素;或是要创建和插入的DomHelper配置项对象 * @return {Ext.Element} 新子元素 */ insertFirst: function(el, returnDom){ el = el || {}; if(typeof el == 'object' && !el.nodeType){ // dh config return this.createChild(el, this.dom.firstChild, returnDom); }else{ el = Ext.getDom(el); this.dom.insertBefore(el, this.dom.firstChild); return !returnDom ? Ext.get(el) : el; } }, /** * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element * @param {Mixed/Object/Array} el The id, element to insert or a DomHelper config to create and insert *or* an array of any of those. * @param {String} where (optional) 'before' or 'after' defaults to before * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element * @return {Ext.Element} the inserted Element * * 插入(或创建)一个元素(或DomHelper配置项对象)作为该元素的侧边节点。 * @param {String/HTMLElement/Element/Object} el 可以是id;或是插入的元素;或是要创建和插入的DomHelper配置项对象 * @param {String} where (可选的) 'before' 或 'after' 默认为before * @param {Boolean} returnDom (可选的) true表示返回没加工过的DOM元素而非Ext.Element * @return {Ext.Element} 被插入的元素 */ insertSibling: function(el, where, returnDom){ var rt; if(el instanceof Array){ for(var i = 0, len = el.length; i < len; i++){ rt = this.insertSibling(el[i], where, returnDom); } return rt; } where = where ? where.toLowerCase() : 'before'; el = el || {}; var refNode = where == 'before' ? this.dom : this.dom.nextSibling; if(typeof el == 'object' && !el.nodeType){ // dh config if(where == 'after' && !this.dom.nextSibling){ rt = Ext.DomHelper.append(this.dom.parentNode, el, !returnDom); }else{ rt = Ext.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom); } }else{ rt = this.dom.parentNode.insertBefore(Ext.getDom(el), refNode); if(!returnDom){ rt = Ext.get(rt); } } return rt; }, /** * Creates and wraps this element with another element * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element * @return {HTMLElement/Element} The newly created wrapper element * * 创建和打包(warp)该元素和其他元素 * @param {Object} config (可选的) 包裹元素(null的话则是一个空白的div)的DomHelper配置项对象 * @param {Boolean} returnDom (可选的) true表示为返回没加工过的DOM元素,而非Ext.Element * @return {/HTMLElementElement} 刚创建好的包裹元素 */ wrap: function(config, returnDom){ if(!config){ config = {tag: "div"}; } var newEl = Ext.DomHelper.insertBefore(this.dom, config, !returnDom); newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); return newEl; }, /** * Replaces the passed element with this element * @param {Mixed} el The element to replace * @return {Ext.Element} this * * 用于当前这个元素替换传入的元素 * @param {Mixed} el 要替换的元素 * @return {Ext.Element} this */ replace: function(el){ el = Ext.get(el); this.insertBefore(el); el.remove(); return this; }, /** * Replaces this element with the passed element * * 用传入的元素替换这个元素。 * @param {Mixed/Object} el 新元素或是要创建的DomHelper配置项对象 * @return {Ext.Element} this */ replaceWith: function(el){ if(typeof el == 'object' && !el.nodeType){ // dh config el = this.insertSibling(el, 'before'); }else{ el = Ext.getDom(el); this.dom.parentNode.insertBefore(el, this.dom); } El.uncache(this.id); this.dom.parentNode.removeChild(this.dom); this.dom = el; this.id = Ext.id(el); El.cache[this.id] = this; return this; }, /** * Inserts an html fragment into this element * @param {String} where Where to insert the html in relation to the this element - beforeBegin, afterBegin, beforeEnd, afterEnd. * @param {String} html The HTML fragment * @param {Boolean} returnEl True to return an Ext.Element * @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted) * * 插入HTML片断到这个元素 * @param {String} where 要插入的html放在元素的哪里 - beforeBegin, afterBegin, beforeEnd, afterEnd. * @param {String} html HTML片断 * @param {Boolean} returnEl true表示为返回一个Ext.Element * @return {HTMLElement} 被插入之节点(或最近的,如果超过一处插入的话) */ insertHtml : function(where, html, returnEl){ var el = Ext.DomHelper.insertHtml(where, this.dom, html); return returnEl ? Ext.get(el) : el; }, /** * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function) * @param {Object} o The object with the attributes * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos. * @return {Ext.Element} this * * 传入属性(attributes)的参数,使之成为该元素的属性(一个样式的属性可以是字符串,对象或函数function) * @param {Object} o 属性对象 * @param {Boolean} useSet (可选的) false表示为用expandos来重写默认的setAttribute * @return {Ext.Element} this */ set : function(o, useSet){ var el = this.dom; useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet; for(var attr in o){ if(attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else if(o.hasOwnProperty(attr)){ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } if(o.style){ Ext.DomHelper.applyStyles(el, o.style); } return this; }, /** * Convenience method for constructing a KeyMap * @param {Number/Array/Object/String} key Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options: * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)} * @param {Function} fn The function to call * @param {Object} scope (optional) The scope of the function * @return {Ext.KeyMap} The KeyMap created * * 构建KeyMap的快捷方式 * @param {Number/Array/Object/String} key 可侦听代码的数值、key代码的数组的字串符,或者是像这样的object: {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)} * @param {Function} fn 调用的函数 * @param {Object} scope (可选的) 函数的作用域 * @return {Ext.KeyMap} 创建好的KeyMap */ addKeyListener : function(key, fn, scope){ var config; if(typeof key != "object" || key instanceof Array){ config = { key: key, fn: fn, scope: scope }; }else{ config = { key : key.key, shift : key.shift, ctrl : key.ctrl, alt : key.alt, fn: fn, scope: scope }; } return new Ext.KeyMap(this, config); }, /** * Creates a KeyMap for this element * @param {Object} config The KeyMap config. See {@link Ext.KeyMap} for more details * @return {Ext.KeyMap} The KeyMap created * * 为该元素创建一个KeyMap * @param {Object} config KeyMap配置项。参阅 {@link Ext.KeyMap} * @return {Ext.KeyMap} 创建好的KeyMap */ addKeyMap : function(config){ return new Ext.KeyMap(this, config); }, /** * Returns true if this element is scrollable. * @return {Boolean} * * 返回true表示为该元素是可滚动的 * @return {Boolean} */ isScrollable : function(){ var dom = this.dom; return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; }, /** * Scrolls this element the specified scroll point. It does NOT do bounds checking so if you scroll to a weird value it will try to do it. For auto bounds checking, use scroll(). * @param {String} side Either "left" for scrollLeft values or "top" for scrollTop values. * @param {Number} value The new scroll value * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Element} this * * 滚动该元素到指定的滚动点(scroll point)。 * 它不会边界检查所以若果你滚动到一个不合理的值时它也会试着去做。 * 要自动检查边界,请使用scroll()。 * @param {String} side 即可 "left" 对应scrollLeft的值,也可以 "top" 对于scrollTop的值. * @param {Number} value 新滚动值 * @param {Boolean/Object} animate (可选的) true表示为默认动画,或有一个标准元素动画配置的对象 * @return {Element} this */ scrollTo : function(side, value, animate){ var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop"; if(!animate || !A){ this.dom[prop] = value; }else{ var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value]; this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll'); } return this; }, /** * Scrolls this element the specified direction. Does bounds checking to make sure the scroll is * within this element's scrollable range. * @param {String} direction Possible values are: "l","left" - "r","right" - "t","top","up" - "b","bottom","down". * @param {Number} distance How far to scroll the element in pixels * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Boolean} Returns true if a scroll was triggered or false if the element * was scrolled as far as it could go. * 滚动该元素到指定的方向。须确认元素可滚动的范围,以免滚动超出元素可滚动的范围。 * @param {String} direction 可能出现的值: "l","left" - "r","right" - "t","top","up" - "b","bottom","down". * @param {Number} distance 元素滚动有多远(像素) * @param {Boolean/Object} animate (可选的) true表示为默认动画,或有一个标准元素动画配置的对象 * @return {Boolean} true表示为滚动是轮换的;false表示为元素能滚动其最远的 */ scroll : function(direction, distance, animate){ if(!this.isScrollable()){ return; } var el = this.dom; var l = el.scrollLeft, t = el.scrollTop; var w = el.scrollWidth, h = el.scrollHeight; var cw = el.clientWidth, ch = el.clientHeight; direction = direction.toLowerCase(); var scrolled = false; var a = this.preanim(arguments, 2); switch(direction){ case "l": case "left": if(w - l > cw){ var v = Math.min(l + distance, w-cw); this.scrollTo("left", v, a); scrolled = true; } break; case "r": case "right": if(l > 0){ var v = Math.max(l - distance, 0); this.scrollTo("left", v, a); scrolled = true; } break; case "t": case "top": case "up": if(t > 0){ var v = Math.max(t - distance, 0); this.scrollTo("top", v, a); scrolled = true; } break; case "b": case "bottom": case "down": if(h - t > ch){ var v = Math.min(t + distance, h-ch); this.scrollTo("top", v, a); scrolled = true; } break; } return scrolled; }, /** * Translates the passed page coordinates into left/top css values for this element * @param {Number/Array} x The page x or an array containing [x, y] * @param {Number} y The page y * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)} * 传入一个页面坐标的参数,将其翻译到元素的CSS left/top值。 * @param {Number/Array} x 页面x or 数组 [x, y] * @param {Number} y 页面 y * @param {Object} 包含left、top属性的对象,如 {left: (值), top: (值)} */ translatePoints : function(x, y){ if(typeof x == 'object' || x instanceof Array){ y = x[1]; x = x[0]; } var p = this.getStyle('position'); var o = this.getXY(); var l = parseInt(this.getStyle('left'), 10); var t = parseInt(this.getStyle('top'), 10); if(isNaN(l)){ l = (p == "relative") ? 0 : this.dom.offsetLeft; } if(isNaN(t)){ t = (p == "relative") ? 0 : this.dom.offsetTop; } return {left: (x - o[0] + l), top: (y - o[1] + t)}; }, /** * Returns the current scroll position of the element. * @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)} * * 返回元素当前滚动的位置。 * @return {Object} 包含滚动位置的对象,格式如 {left: (scrollLeft), top: (scrollTop)} */ getScroll : function(){ var d = this.dom, doc = document; if(d == doc || d == doc.body){ var l, t; if(Ext.isIE && Ext.isStrict){ l = doc.documentElement.scrollLeft || (doc.body.scrollLeft || 0); t = doc.documentElement.scrollTop || (doc.body.scrollTop || 0); }else{ l = window.pageXOffset || (doc.body.scrollLeft || 0); t = window.pageYOffset || (doc.body.scrollTop || 0); } return {left: l, top: t}; }else{ return {left: d.scrollLeft, top: d.scrollTop}; } }, /** * Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values * are convert to standard 6 digit hex color. * @param {String} attr The css attribute * @param {String} defaultValue The default value to use when a valid color isn't found * @param {String} prefix (optional) defaults to #. Use an empty string when working with * color anims. * * 为指定的CSS属性返回CSS颜色。RGB、三位数(像#fff)和有效值都被转换到标准六位十六进制的颜色 * @param {String} attr CSS属性 * @param {String} defaultValue 当找不到有效的颜色时所用的默认值 * @param {String} prefix (可选的) 默认为 #。应用到YUI颜色动画时须为空白字串符 */ getColor : function(attr, defaultValue, prefix){ var v = this.getStyle(attr); if(!v || v == "transparent" || v == "inherit") { return defaultValue; } var color = typeof prefix == "undefined" ? "#" : prefix; if(v.substr(0, 4) == "rgb("){ var rvs = v.slice(4, v.length -1).split(","); for(var i = 0; i < 3; i++){ var h = parseInt(rvs[i]); var s = h.toString(16); if(h < 16){ s = "0" + s; } color += s; } } else { if(v.substr(0, 1) == "#"){ if(v.length == 4) { for(var i = 1; i < 4; i++){ var c = v.charAt(i); color += c + c; } }else if(v.length == 7){ color += v.substr(1); } } } return(color.length > 5 ? color.toLowerCase() : defaultValue); }, /** * Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a * gradient background, rounded corners and a 4-way shadow. Example usage: * <pre><code> // Basic box wrap Ext.get("foo").boxWrap(); // You can also add a custom class and use CSS inheritance rules to customize the box look. // 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example // for how to create a custom box wrap style. Ext.get("foo").boxWrap().addClass("x-box-blue"); </pre></code> * @param {String} class (optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box'). * Note that there are a number of CSS rules that are dependent on this name to make the overall effect work, * so if you supply an alternate base class, make sure you also supply all of the necessary rules. * @return {Ext.Element} this * 将指定的元素打包到一个特定的样式/markup块,渲染成为斜纹背景、圆角和四边投影的灰色容器。 * 用法举例:<pre><code> // 基本box打包 Ext.get("foo").boxWrap(); // You can also add a custom class and use CSS inheritance rules to customize the box look. // 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example // for how to create a custom box wrap style. Ext.get("foo").boxWrap().addClass("x-box-blue"); </pre></code> * @param {String} class (可选的)一个CSS基类,应用到包裹元素(默认为'x-box')。 * 注意有许多依赖该CSS规则来产生整体的效果。 * 所以你提供一个交替的基样式,必须保证你所提供的都是所需的规则。 * @return {Ext.Element} this */ boxWrap : function(cls){ cls = cls || 'x-box'; var el = Ext.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls))); el.child('.'+cls+'-mc').dom.appendChild(this.dom); return el; }, /** * Returns the value of a namespaced attribute from the element's underlying DOM node. * @param {String} namespace The namespace in which to look for the attribute * @param {String} name The attribute name * @return {String} The attribute value * * 在DOM节点中的某个元素,返回其一个命名空间属性的值。 * @param {String} namespace 要查找属性所在的命名空间 * @param {String} name 属性名称 * @return {String} 属性值 */ getAttributeNS : Ext.isIE ? function(ns, name){ var d = this.dom; var type = typeof d[ns+":"+name]; if(type != 'undefined' && type != 'unknown'){ return d[ns+":"+name]; } return d[name]; } : function(ns, name){ var d = this.dom; return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name]; }, getTextWidth : function(text, min, max){ return (Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width).constrain(min || 0, max || 1000000); } }; var ep = El.prototype; /** * Appends an event handler (shorthand for {@link #addListener}). * @param {String} eventName The type of event to handle * @param {Function} fn The handler function the event invokes * @param {Object} scope (optional) The scope (this element) of the handler function * @param {Object} options (optional) An object containing standard {@link #addListener} options * @member Ext.Element * @method on * * 加入一个事件句柄(addListener的简写方式) * @param {String} eventName 加入事件的类型 * @param {Function} fn 事件执行的方法 * @param {Object} scope (可选的)函数之作用域 (这个元素) * @param {Object} options (可选的)标准的{@link #addListener} 配置项对象 * @member Ext.Element * @method on */ ep.on = ep.addListener; // backwards compat ep.mon = ep.addListener; ep.getUpdateManager = ep.getUpdater; /** * Removes an event handler from this element (shorthand for {@link #removeListener}). * @param {String} eventName the type of event to remove * @param {Function} fn the method the event invokes * * 从这个元素上移除一个event handler({@link #removeListener}的简写方式) * @param {String} eventName 要移除事件的类型 * @param {Function} fn 事件执行的方法 * @return {Ext.Element} this * @member Ext.Element * @method un */ ep.un = ep.removeListener; /** * true to automatically adjust width and height settings for box-model issues (default to true) * true表示为自动调整由box-mode问题引起的高度和宽度设置(默认true)。 */ ep.autoBoxAdjust = true; // private El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i; // private El.addUnits = function(v, defaultUnit){ if(v === "" || v == "auto"){ return v; } if(v === undefined){ return ''; } if(typeof v == "number" || !El.unitPattern.test(v)){ return v + (defaultUnit || 'px'); } return v; }; // special markup used throughout Ext when box wrapping elements El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>'; /** * Visibility mode constant - Use visibility to hide element * 显示模式(Visibility mode)的常量 - 使用Visibility来隐藏元素 * @static * @type Number */ El.VISIBILITY = 1; /** * Visibility mode constant - Use display to hide element * 显示模式(Visibility mode)的常量 - 使用Display来隐藏元素 * @static * @type Number */ El.DISPLAY = 2; El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"}; El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"}; El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"}; /** * @private */ El.cache = {}; var docEl; /** * Static method to retrieve Element objects. * Uses simple caching to consistently return the same object. * Automatically fixes if an object was recreated with the same id via AJAX or DOM. * @param {Mixed} el The id of the node, a DOM Node or an existing Element. * @return {Element} The Element object (or null if no matching element was found) * @static * 获取元素对象的静态方法。 * 如果是相同的对象的话,只是从缓存中提取。 * Automatically fixes if an object was recreated with the same id via AJAX or DOM. * @param {Mixed} el 节点的id,一个DOM节点或是已存在的元素。, * @return {Element} 元素对象 * @static */ El.get = function(el){ var ex, elm, id; if(!el){ return null; } if(typeof el == "string"){ // element id if(!(elm = document.getElementById(el))){ return null; } if(ex = El.cache[el]){ ex.dom = elm; }else{ ex = El.cache[el] = new El(elm); } return ex; }else if(el.tagName){ // dom element if(!(id = el.id)){ id = Ext.id(el); } if(ex = El.cache[id]){ ex.dom = el; }else{ ex = El.cache[id] = new El(el); } return ex; }else if(el instanceof El){ if(el != docEl){ el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid, // catch case where it hasn't been appended El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it } return el; }else if(el.isComposite){ return el; }else if(el instanceof Array){ return El.select(el); }else if(el == document){ // create a bogus element object representing the document object if(!docEl){ var f = function(){}; f.prototype = El.prototype; docEl = new f(); docEl.dom = document; } return docEl; } return null; }; // private El.uncache = function(el){ for(var i = 0, a = arguments, len = a.length; i < len; i++) { if(a[i]){ delete El.cache[a[i].id || a[i]]; } } }; // private // Garbage collection - uncache elements/purge listeners on orphaned elements // so we don't hold a reference and cause the browser to retain them El.garbageCollect = function(){ if(!Ext.enableGarbageCollector){ clearInterval(El.collectorThread); return; } for(var eid in El.cache){ var el = El.cache[eid], d = el.dom; // ------------------------------------------------------- // Determining what is garbage: // ------------------------------------------------------- // !d // dom node is null, definitely garbage // ------------------------------------------------------- // !d.parentNode // no parentNode == direct orphan, definitely garbage // ------------------------------------------------------- // !d.offsetParent && !document.getElementById(eid) // display none elements have no offsetParent so we will // also try to look it up by it's id. However, check // offsetParent first so we don't do unneeded lookups. // This enables collection of elements that are not orphans // directly, but somewhere up the line they have an orphan // parent. // ------------------------------------------------------- if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){ delete El.cache[eid]; if(d && Ext.enableListenerCollection){ E.purgeElement(d); } } } } El.collectorThreadId = setInterval(El.garbageCollect, 30000); var flyFn = function(){}; flyFn.prototype = El.prototype; var _cls = new flyFn(); // dom is optional El.Flyweight = function(dom){ this.dom = dom; }; El.Flyweight.prototype = _cls; El.Flyweight.prototype.isFlyweight = true; El._flyweights = {}; /** * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element - * the dom node can be overwritten by other code. * @param {String/HTMLElement} el The dom node or id * @param {String} named (optional) Allows for creation of named reusable flyweights to * prevent conflicts (e.g. internally Ext uses "_internal") * 获取共享元的元素,传入的节点会成为活动元素。 * 不保存该元素的引用(reference)-可由其它代码重写dom节点。 * @param {String/HTMLElement} el Dom节点或id * @param {String} named (可选的) 为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。 * @static * @return {Element} 共享的Element对象(null表示为找不到元素) */ El.fly = function(el, named){ named = named || '_global'; el = Ext.getDom(el); if(!el){ return null; } if(!El._flyweights[named]){ El._flyweights[named] = new El.Flyweight(); } El._flyweights[named].dom = el; return El._flyweights[named]; }; /** * Static method to retrieve Element objects. Uses simple caching to consistently return the same object. * Automatically fixes if an object was recreated with the same id via AJAX or DOM. * Shorthand of {@link Ext.Element#get} * @param {Mixed} el The id of the node, a DOM Node or an existing Element. * @return {Element} The Element object * * 获取元素对象的静态方法。 * 如果是相同的对象的话,只是从缓存中提取。 * @param {String/HTMLElement/Element} el 节点的id,一个DOM节点或是已存在的元素。, * @return {Element} Element对象 * @member Ext * @method get */ Ext.get = El.get; /** * Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element - * the dom node can be overwritten by other code. * Shorthand of {@link Ext.Element#fly} * @param {String/HTMLElement} el The dom node or id * @param {String} named (optional) Allows for creation of named reusable flyweights to * prevent conflicts (e.g. internally Ext uses "_internal") * @static * @return {Element} The shared Element object * * 获取共享元的元素,传入的节点会成为活动元素。 * 不保存该元素的引用(reference)-可由其它代码重写dom节点。 * {@link Ext.Element#fly}的简写方式。 * @param {String/HTMLElement} el Dom节点或id * @param {String} named (可选的)为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。 * @static * @return {Element} 共享的Element对象 * @member Ext * @method fly */ Ext.fly = El.fly; // speedy lookup for elements never to box adjust var noBoxAdjust = Ext.isStrict ? { select:1 } : { input:1, select:1, textarea:1 }; if(Ext.isIE || Ext.isGecko){ noBoxAdjust['button'] = 1; } Ext.EventManager.on(window, 'unload', function(){ delete El.cache; delete El._flyweights; }); })();
JavaScript
/** * @class String * 将javascript的String原型对象进行修改,增加工具的方法。 */ Ext.applyIf(String, { /* * 避免传入 ' 与 \ * @param {String} str * @return {String} */ escape : function(string) { return string.replace(/('|\\)/g, "\\$1"); }, /** * 在字符串左边填充指定字符。这对于统一字符或日期标准格式非常有用。 * 例如: * <pre><code> var s = String.leftPad('123', 5, '0'); // s 现在是:'00123' </code></pre> * @param {String} 源字符串 * @param {Number} 源+填充字符串的总长度 * @param {String} 填充字符串(默认是" ") * @return {String} 填充后的字符串 * @static */ leftPad : function (val, size, ch) { var result = new String(val); if(ch === null || ch === undefined || ch === '') { ch = " "; } while (result.length < size) { result = ch + result; } return result; }, /** * 定义带标记的字符串,并用自定义字符替换标记。 * 每个标记必须是唯一的,而且必须要像{0},{1}...{n}这样自增长。 * 例如: * <pre><code> var cls = 'my-class', text = 'Some text'; var s = String.format('<div class="{0}">{1}</div>', cls, text); // s now contains the string: '<div class="my-class">Some text</div>' </code></pre> * @param {String} 带标记的字符串 * @param {String} 第一个值,替换{0} * @param {String} 第二个值,替换{1}...等等(可以有任意多个) * @return {String} 转化过的字符串 * @static */ format : function(format){ var args = Array.prototype.slice.call(arguments, 1); return format.replace(/\{(\d+)\}/g, function(m, i){ return args[i]; }); } }); /** * 比较并交换字符串的值。 * 参数中的第一个值与当前字符串对象比较,如果相等则返回传入的第一个参数,否则返回第二个参数。 * 注意:这个方法返回新值,但并不改变现有字符串。 * <pre><code> // alternate sort directions sort = sort.toggle('ASC', 'DESC'); // instead of conditional logic: sort = (sort == 'ASC' ? 'DESC' : 'ASC'); </code></pre> * @param {String} 第一个参数,与函数相等则返回 * @param {String} 传入的第二个参数,不等返回 * @return {String} 新值 */ String.prototype.toggle = function(value, other){ return this == value ? other : value; }; /** * 检验数字大小。 * 传入两个数字,一小一大,如果当前数字小于传入的小数字,则返回小的;如果该数字大于大的,则返回大的;如果在中间,则返回该数字本身 * 注意:这个方法返回新数字,但并不改变现有数字 * @param {Number} 小数 * @param {Number} 大数 * @return {Number} 大小数字,或其本身 */ String.prototype.trim = function(){ var re = /^\s+|\s+$/g; return function(){ return this.replace(re, ""); }; }();
JavaScript
/** * @class Ext.state.CookieProvider * @extends Ext.state.Provider * 通过cookies保存state的Provider之默认实现。 * <br />用法: <pre><code> var cp = new Ext.state.CookieProvider({ path: "/cgi-bin/", expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30天 domain: "extjs.com" }) Ext.state.Manager.setProvider(cp); </code></pre> * @constructor * 创建一个新的CookieProvider * @param {Object} config 配置项对象 */ Ext.state.CookieProvider = function(config){ Ext.state.CookieProvider.superclass.constructor.call(this); this.path = "/"; this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days this.domain = null; this.secure = false; Ext.apply(this, config); this.state = this.readCookies(); }; /** * @cfg {String} domain cookie保存的域名。 注意你在某个页面一旦设置好,将不能够再指定其它的域名,但可以是子域名, * 或者就是它本身如“extjs.com”,这样可以在不同子域名下访问cookies。 * 默认为null使用相同的域名(包括www如www.extjs.com) **/ /** * @cfg {Boolean} secure * True表示为网站使用SSL加密(默认false) */ /** * @cfg {String} path 激活cookie之路径(默认是根目录”/“,对该网站下所有的页面激活) */ /** * @cfg {Date} expires 过期的日子(默认七日之后) */ Ext.extend(Ext.state.CookieProvider, Ext.state.Provider, { // private set : function(name, value){ if(typeof value == "undefined" || value === null){ this.clear(name); return; } this.setCookie(name, value); Ext.state.CookieProvider.superclass.set.call(this, name, value); }, // private clear : function(name){ this.clearCookie(name); Ext.state.CookieProvider.superclass.clear.call(this, name); }, // private readCookies : function(){ var cookies = {}; var c = document.cookie + ";"; var re = /\s?(.*?)=(.*?);/g; var matches; while((matches = re.exec(c)) != null){ var name = matches[1]; var value = matches[2]; if(name && name.substring(0,3) == "ys-"){ cookies[name.substr(3)] = this.decodeValue(value); } } return cookies; }, // private setCookie : function(name, value){ document.cookie = "ys-"+ name + "=" + this.encodeValue(value) + ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : ""); }, // private clearCookie : function(name){ document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : ""); } });
JavaScript
/** * @class Ext.state.Provider * 为State Provider的实现提供一个抽象基类。 * 该类对<b>某些类型</b>的变量提供了编码、解码方法,包括日期和定义Provider的接口。 */ Ext.state.Provider = function(){ /** * @event statechange * 当state发生改变时触发 * @param {Provider} this 该state提供者 * @param {String} key 已改名的那个键 * @param {String} value 已编码的state值 */ this.addEvents("statechange"); this.state = {}; Ext.state.Provider.superclass.constructor.call(this); }; Ext.extend(Ext.state.Provider, Ext.util.Observable, { /** * 返回当前的键值(value for a key) * @param {String} name 键名称 * @param {Mixed} defaultValue 若键值找不到的情况下,返回的默认值 * @return {Mixed} State数据 */ get : function(name, defaultValue){ return typeof this.state[name] == "undefined" ? defaultValue : this.state[name]; }, /** * 清除某个state的值 * @param {String} name 键名称 */ clear : function(name){ delete this.state[name]; this.fireEvent("statechange", this, name, null); }, /** * 设置键值 * @param {String} name 键名称 * @param {Mixed} value 设置值 */ set : function(name, value){ this.state[name] = value; //console.log(value); this.fireEvent("statechange", this, name, value); }, /** * 对之前用过的 {@link #encodeValue}字符串解码。 * @param {String} value 要解码的值 * @return {Mixed} 已解码的值 */ decodeValue : function(cookie){ var re = /^(a|n|d|b|s|o)\:(.*)$/; var matches = re.exec(unescape(cookie)); if(!matches || !matches[1]) return; // non state cookie var type = matches[1]; var v = matches[2]; switch(type){ case "n": return parseFloat(v); case "d": return new Date(Date.parse(v)); case "b": return (v == "1"); case "a": var all = []; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ all.push(this.decodeValue(values[i])); } return all; case "o": var all = {}; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ var kv = values[i].split("="); all[kv[0]] = this.decodeValue(kv[1]); } return all; default: return v; } }, /** * 针对某些类型的编码,可用 {@link #decodeValue}解码。 * @param {Mixed} value 要编码的值 * @return {String} 以编码值 */ encodeValue : function(v){ var enc; if(typeof v == "number"){ enc = "n:" + v; }else if(typeof v == "boolean"){ enc = "b:" + (v ? "1" : "0"); }else if(v instanceof Date){ enc = "d:" + v.toGMTString(); }else if(v instanceof Array){ var flat = ""; for(var i = 0, len = v.length; i < len; i++){ flat += this.encodeValue(v[i]); if(i != len-1) flat += "^"; } enc = "a:" + flat; }else if(typeof v == "object"){ var flat = ""; for(var key in v){ if(typeof v[key] != "function" && v[key] !== undefined){ flat += key + "=" + this.encodeValue(v[key]) + "^"; } } enc = "o:" + flat.substring(0, flat.length-1); }else{ enc = "s:" + v; } return escape(enc); } });
JavaScript
/** * @class Ext.state.Manager * 这是个全局state管理器。默认情况下,所有的组件都能“感知state”该类以获得state信息,无须传入一个自定义state provider。 * 要实现这个类,必须在应用程序初始化时连同provider一起初始。 <pre><code> // 在你的初始化函数中 init : function(){ Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); ... //假设这是 {@link Ext.BorderLayout} var layout = new Ext.BorderLayout(...); layout.restoreState(); // 或者{Ext.BasicDialog} var dialog = new Ext.BasicDialog(...); dialog.restoreState(); </code></pre> * @singleton */ Ext.state.Manager = function(){ var provider = new Ext.state.Provider(); return { /** * 针对应用程序配置默认的state provider * @param {Provider} stateProvider 要设置的state provider */ setProvider : function(stateProvider){ provider = stateProvider; }, /** * 返回当前的键值(value for a key) * @param {String} name 键名称 * @param {Mixed} defaultValue 若键值找不到的情况下,返回的默认值 * @return {Mixed} State数据 */ get : function(key, defaultValue){ return provider.get(key, defaultValue); }, /** * 设置键值 * @param {String} name 键名称 * @param {Mixed} value 设置值 */ set : function(key, value){ provider.set(key, value); }, /** * 清除某个state的值 * @param {String} name 键名称 */ clear : function(key){ provider.clear(key); }, /** *获取当前已配置的state provider * @return {Provider} state provider */ getProvider : function(){ return provider; } }; }();
JavaScript
/** * @class Ext.util.CSS * 操控CSS规则的工具类 * @singleton */ Ext.util.CSS = function(){ var rules = null; var doc = document; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; return { /** * 动态生成样式表。用style标签围绕样式后加入到文档头部中。 * @param {String} cssText 包含css的文本 * @return {StyleSheet} */ createStyleSheet : function(cssText, id){ var ss; var head = doc.getElementsByTagName("head")[0]; var rules = doc.createElement("style"); rules.setAttribute("type", "text/css"); if(id){ rules.setAttribute("id", id); } if(Ext.isIE){ head.appendChild(rules); ss = rules.styleSheet; ss.cssText = cssText; }else{ try{ rules.appendChild(doc.createTextNode(cssText)); }catch(e){ rules.cssText = cssText; } head.appendChild(rules); ss = rules.styleSheet ? rules.styleSheet : (rules.sheet || doc.styleSheets[doc.styleSheets.length-1]); } this.cacheStyleSheet(ss); return ss; }, /** * 由id移除样式或连接 * @param {String} id 标签的ID */ removeStyleSheet : function(id){ var existing = doc.getElementById(id); if(existing){ existing.parentNode.removeChild(existing); } }, /** * 动态交换现有的样式,指向新的一个 * @param {String} id 要移除的现有链接标签的ID * @param {String} url 要包含新样式表的href */ swapStyleSheet : function(id, url){ this.removeStyleSheet(id); var ss = doc.createElement("link"); ss.setAttribute("rel", "stylesheet"); ss.setAttribute("type", "text/css"); ss.setAttribute("id", id); ss.setAttribute("href", url); doc.getElementsByTagName("head")[0].appendChild(ss); }, /** * 如果动态地加入样式表,刷新样式cache。 * @return {Object} 由选择器索引的样式对象(hash) */ refreshCache : function(){ return this.getRules(true); }, // private cacheStyleSheet : function(ss){ if(!rules){ rules = {}; } try{// try catch for cross domain access issue var ssRules = ss.cssRules || ss.rules; for(var j = ssRules.length-1; j >= 0; --j){ rules[ssRules[j].selectorText] = ssRules[j]; } }catch(e){} }, /** * 获取文档内的所有的CSS rules * @param {Boolean} refreshCache true:刷新内置缓存 * @return {Object} 由选择器索引的样式对象(hash) */ getRules : function(refreshCache){ if(rules == null || refreshCache){ rules = {}; var ds = doc.styleSheets; for(var i =0, len = ds.length; i < len; i++){ try{ this.cacheStyleSheet(ds[i]); }catch(e){} } } return rules; }, /** * 由选择符获取不同的CSS规则 * @param {String/Array} selector 选择符支持数组,在匹配第一个结果后立刻停止继续寻找 * @param {Boolean} refreshCache true表示为如果你最近有更新或新加样式的话,就刷新内置缓存 * @return {CSSRule} 找到的CSS rule或null(找不到) */ getRule : function(selector, refreshCache){ var rs = this.getRules(refreshCache); if(!(selector instanceof Array)){ return rs[selector]; } for(var i = 0; i < selector.length; i++){ if(rs[selector[i]]){ return rs[selector[i]]; } } return null; }, /** * 更新样式属性 * @param {String/Array} selector 选择符支持数组,在匹配第一个结果后立刻停止继续寻找 * @param {String} property css属性 * @param {String} value 属性的新值 * @return {Boolean} true:如果样式找到并更新 */ updateRule : function(selector, property, value){ if(!(selector instanceof Array)){ var rule = this.getRule(selector); if(rule){ rule.style[property.replace(camelRe, camelFn)] = value; return true; } }else{ for(var i = 0; i < selector.length; i++){ if(this.updateRule(selector[i], property, value)){ return true; } } } return false; } }; }();
JavaScript
/** * @class Ext.util.Format *可复用的数据格式化函数。 * @singleton */ Ext.util.Format = function(){ var trimRe = /^\s+|\s+$/g; return { /** * 对大于指定长度部分的字符串,进行裁剪,增加省略号(“...”)的显示 * @param {String} value 要裁剪的字符串 * @param {Number} length 允许长度 * @return {String} 转换后的文本 */ ellipsis : function(value, len){ if(value && value.length > len){ return value.substr(0, len-3)+"..."; } return value; }, /** * 检查一个值是否为underfined,若是的话转换为空值 * @param {Mixed} value 要检查的值 * @return {Mixed} 转换成功为空白字符串,否则为原来的值 */ undef : function(value){ return value !== undefined ? value : ""; }, /** * 检查一个值(引用的)是否为空,若是则转换到缺省值。 * @param {Mixed} value 要检查的引用值 * @param {String} defaultValue 默认赋予的值(默认为"") * @return {String} */ defaultValue : function(value, defaultValue){ return value !== undefined && value !== '' ? value : defaultValue; }, /** * 转义(&, <, >, and ') 为能在HTML显示的字符 * @param {String} value 要编码的字符串 * @return {String} 编码后的文本 */ htmlEncode : function(value){ return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); }, /** * 将(&, <, >, and ')字符从HTML显示的格式还原 * @param {String} value 解码的字符串 * @return {String} 编码后的文本 */ htmlDecode : function(value){ return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"'); }, /** * 裁剪一段文本的前后多余的空格 * @param {String} value 要裁剪的文本 * @return {String} 裁剪后的文本 */ trim : function(value){ return String(value).replace(trimRe, ""); }, /** * 返回一个从指定位置开始的指定长度的子字符串。 * @param {String} value 原始文本 * @param {Number} start 所需的子字符串的起始位置 * @param {Number} length 在返回的子字符串中应包括的字符个数。 * @return {String} 指定长度的子字符串 */ substr : function(value, start, length){ return String(value).substr(start, length); }, /** * 返回一个字符串,该字符串中的字母被转换为小写字母。 * @param {String} value 要转换的字符串 * @return {String} 转换后的字符串 */ lowercase : function(value){ return String(value).toLowerCase(); }, /** * 返回一个字符串,该字符串中的字母被转换为大写字母。 * @param {String} value 要转换的字符串 * @return {String} 转换后的字符串 */ uppercase : function(value){ return String(value).toUpperCase(); }, /** * 返回一个字符串,该字符串中的第一个字母转化为大写字母,剩余的为小写。 * @param {String} value 要转换的字符串 * @return {String} 转换后的字符串 */ capitalize : function(value){ return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase(); }, // private call : function(value, fn){ if(arguments.length > 2){ var args = Array.prototype.slice.call(arguments, 2); args.unshift(value); return eval(fn).apply(window, args); }else{ return eval(fn).call(window, value); } }, /** * 格式化数字到美元货币 * @param {Number/String} value 要格式化的数字 * @return {String} 已格式化的货币 */ usMoney : function(v){ v = (Math.round((v-0)*100))/100; v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v); v = String(v); var ps = v.split('.'); var whole = ps[0]; var sub = ps[1] ? '.'+ ps[1] : '.00'; var r = /(\d+)(\d{3})/; while (r.test(whole)) { whole = whole.replace(r, '$1' + ',' + '$2'); } v = whole + sub; if(v.charAt(0) == '-'){ return '-$' + v.substr(1); } return "$" + v; }, /** * 将某个值解析成为一个特定格式的日期。 * @param {Mixed} value 要格式化的值 * @param {String} format (可选的)任何有效的日期字符串(默认为“月/日/年”) * @return {Function} 日期格式函数 */ date : function(v, format){ if(!v){ return ""; } if(!(v instanceof Date)){ v = new Date(Date.parse(v)); } return v.dateFormat(format || "m/d/Y"); }, /** * 返回一个函数,该函数的作用是渲染日期格式,便于复用。 * @param {String} format 任何有效的日期字符串 * @return {Function} 日期格式函数 */ dateRenderer : function(format){ return function(v){ return Ext.util.Format.date(v, format); }; }, // private stripTagsRE : /<\/?[^>]+>/gi, /** * 剥去所有HTML标签 * @param {Mixed} value 要剥去的文本 * @return {String} 剥去后的HTML标签 */ stripTags : function(v){ return !v ? v : String(v).replace(this.stripTagsRE, ""); }, stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, /** * 剥去所有脚本(Script)标签 * @param {Mixed} value 要剥去的文本 * @return {String} 剥去后的HTML标签 */ stripScripts : function(v){ return !v ? v : String(v).replace(this.stripScriptsRe, ""); }, /** * 对文件大小进行简单的格式化(xxx bytes、xxx KB、xxx MB) * @param {Number/String} size 要格式化的数值 * @return {String} 已格式化的值 */ fileSize : function(size){ if(size < 1024) { return size + " bytes"; } else if(size < 1048576) { return (Math.round(((size*10) / 1024))/10) + " KB"; } else { return (Math.round(((size*10) / 1048576))/10) + " MB"; } }, math : function(){ var fns = {}; return function(v, a){ if(!fns[a]){ fns[a] = new Function('v', 'return v ' + a + ';'); } return fns[a](v); } }() }; }();
JavaScript
/** * @class Ext.util.DelayedTask * 提供快捷的方法执行setTimeout,新的超时时限会取消旧的超时时限. * 例如验证表单的时候,键盘按下(keypress)那一瞬,就可用上该类(不会立即验证表单,稍作延时)。 * keypress事件会稍作停顿之后(某个时间)才继续执行、 * @constructor 该构建器无须参数 * @param {Function} fn (optional) 默认超时的函数。 * @param {Object} scope (optional) 默认超时的作用域 * @param {Array} args (optional) 默认参数数组 */ Ext.util.DelayedTask = function(fn, scope, args){ var id = null, d, t; var call = function(){ var now = new Date().getTime(); if(now - t >= d){ clearInterval(id); id = null; fn.apply(scope, args || []); } }; /** * 取消所有待定的超时(any pending timeout),并重新排列(queues)。 * @param {Number} delay 延迟毫秒数 * @param {Function} newFn (optional) 重写传入到构建器的函数 * @param {Object} newScope (optional) 重写传入到构建器的作用域 * @param {Array} newArgs (optional) 重写传入到构建器的参数 */ this.delay = function(delay, newFn, newScope, newArgs){ if(id && delay != d){ this.cancel(); } d = delay; t = new Date().getTime(); fn = newFn || fn; scope = newScope || scope; args = newArgs || args; if(!id){ id = setInterval(call, d); } }; /** * 取消最后的排列超时 */ this.cancel = function(){ if(id){ clearInterval(id); id = null; } }; };
JavaScript
/** * @class Ext.util.Observable * 一个抽象基类(Abstract base class),为事件机制的管理提供一个公共接口。子类应有一个"events"属性来定义所有的事件。<br> * 例如: * <pre><code> Employee = function(name){ this.name = name; this.addEvents({ "fired" : true, "quit" : true }); } Ext.extend(Employee, Ext.util.Observable); </code></pre> */ Ext.util.Observable = function(){ /** * @cfg {Object} listeners * 一个配置项对象,可方便在该对象初始化时便加入多个事件处理函数。 * 这应该是一个如{@link #addListener}有效的配置项对象,即可一次过加入多个事件处理函数。 */ if(this.listeners){ this.on(this.listeners); delete this.listeners; } }; Ext.util.Observable.prototype = { /** * 触发指定的事件,并将欲执行的处理函数的参数传入。(应该至少要有事件的名称) * @param {String} eventName 事件名称 * @param {Object...} args 传入事件处理函数(Event Handlers)的参数 * @return {Boolean} 如果有处理函数返回true或者false */ fireEvent : function(){ if(this.eventsSuspended !== true){ var ce = this.events[arguments[0].toLowerCase()]; if(typeof ce == "object"){ return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1)); } } return true; }, // private filterOptRe : /^(?:scope|delay|buffer|single)$/, /** * 加入一个事件处理函数。{@link #on}是其简写方式。 * Appends an event handler to this element. The shorthand version {@link #on} is equivalent. * @param {String} eventName 事件处理函数的名称The type of event to handle * @param {Function} fn 事件处理函数。该函数会送入以下的参数:The handler function the event invokes. This function is passed * the following parameters:<ul> * <li>evt : EventObject<div class="sub-desc">用于描述这次事件{@link Ext.EventObject EventObject}的事件对象The {@link Ext.EventObject EventObject} describing the event.</div></li> * <li>t : Element<div class="sub-desc">事件源对象,类型是{@link Ext.Element Element} The {@link Ext.Element Element} which was the target of the event. * 注意该项可能会选项<tt>delegate</tt>筛选而发生变化Note that this may be filtered by using the <tt>delegate</tt> option.</div></li> * <li>o : Object<div class="sub-desc">调用addListener时送入的选项对象The options object from the addListener call.</div></li> * </ul> * @param {Object} scope (可选的) 事件处理函数执行时所在的作用域。处理函数“this”的上下文。(optional) The scope (The <tt>this</tt> reference) of the handler function. Defaults * to this Element. * @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会下来的属性:(optional) An object containing handler configuration properties. * This may contain any of the following properties:<ul> * <li>scope {Object} : 事件处理函数执行时所在的作用域。处理函数“this”的上下文环境。The scope in which to execute the handler function. The handler function's "this" context.</li> * <li>delegate {String} : 一个简易选择符,用于过滤目标,或是查找目标的子孙。A simple selector to filter the target or look for a descendant of the target</li> * <li>stopEvent {Boolean} : true表示为阻止事件。即停止传播、阻止默认动作。True to stop the event. That is stop propagation, and prevent the default action.</li> * <li>preventDefault {Boolean} : true表示为阻止默认动作True to prevent the default action</li> * <li>stopPropagation {Boolean} : true表示为阻止事件传播True to prevent event propagation</li> * <li>normalized {Boolean} : false表示对处理函数送入一个原始、未封装过的浏览器对象而非标准的Ext.EventObjectFalse to pass a browser event to the handler function instead of an Ext.EventObject</li> * <li>delay {Number} : 触发事件后处理函数延时执行的时间The number of milliseconds to delay the invocation of the handler after te event fires.</li> * <li>single {Boolean} : true代表为下次事件触发加入一个要处理的函数,然后再移除本身。True to add a handler to handle just the next firing of the event, and then remove itself.</li> * <li>buffer {Number} : 若指定一个毫秒数会把该处理函数安排到{@link Ext.util.DelayedTask}延时之后才执行。 * 如果事件在那个事件再次触发,则原句柄将<em>不会</em> 被启用,但是新句柄会安排在其位置。Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed * by the specified number of milliseconds. If the event fires again within that time, the original * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li> * </ul><br> * <p> * <b>不同配搭方式的选项Combining Options</b><br> * In the following examples, the shorthand form {@link #on} is used rather than the more verbose * addListener. The two are equivalent. * 下面的例子,使用的是{@link #on}的简写方式。和addListener是等价的。 * 利用参数选项,可以组合成不同类型的侦听器: * Using the options argument, it is possible to combine different * types of listeners:<br> * <br> * 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId)的一次性侦听器。这些事件设置在处理函数(也就是第三个的参数)中也可以找到的。 * A normalized, delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the * options object. The options object is available as the third parameter in the handler function.<div style="margin: 5px 20px 20px;"> * 代码:Code:<pre><code> el.on('click', this.onClick, this, { single: true, delay: 100, stopEvent : true, forumId: 4 });</code></pre></p> * <p> * <b>多个处理函数一次性登记Attaching multiple handlers in 1 call</b><br> * 这样的话,可允许多个事件处理函数都共享一个配置事件的配置项对象。The method also allows for a single argument to be passed which is a config object containing properties * which specify multiple handlers.</p> * <p> * 代码:Code:<pre><code> el.on({ 'click' : { fn: this.onClick, scope: this, delay: 100 }, 'mouseover' : { fn: this.onMouseOver, scope: this }, 'mouseout' : { fn: this.onMouseOut, scope: this } });</code></pre></p> * <p> * 或者是简写的语法:Or a shorthand syntax:<br> * Code:<pre><code> el.on({ 'click' : this.onClick, 'mouseover' : this.onMouseOver, 'mouseout' : this.onMouseOut, scope: this });</code></pre></p> */ addListener : function(eventName, fn, scope, o){ if(typeof eventName == "object"){ o = eventName; for(var e in o){ if(this.filterOptRe.test(e)){ continue; } if(typeof o[e] == "function"){ // shared options this.addListener(e, o[e], o.scope, o); }else{ // individual options this.addListener(e, o[e].fn, o[e].scope, o[e]); } } return; } o = (!o || typeof o == "boolean") ? {} : o; eventName = eventName.toLowerCase(); var ce = this.events[eventName] || true; if(typeof ce == "boolean"){ ce = new Ext.util.Event(this, eventName); this.events[eventName] = ce; } ce.addListener(fn, scope, o); }, /** * 移除侦听器 * @param {String} eventName 侦听事件的类型 * @param {Function} handler 移除的处理函数 * @param {Object} scope (可选的)处理函数之作用域 */ removeListener : function(eventName, fn, scope){ var ce = this.events[eventName.toLowerCase()]; if(typeof ce == "object"){ ce.removeListener(fn, scope); } }, /** * 从这个对象身上移除所有的侦听器 */ purgeListeners : function(){ for(var evt in this.events){ if(typeof this.events[evt] == "object"){ this.events[evt].clearListeners(); } } }, relayEvents : function(o, events){ var createHandler = function(ename){ return function(){ return this.fireEvent.apply(this, Ext.combine(ename, Array.prototype.slice.call(arguments, 0))); }; }; for(var i = 0, len = events.length; i < len; i++){ var ename = events[i]; if(!this.events[ename]){ this.events[ename] = true; }; o.on(ename, createHandler(ename), this); } }, /** * 定义观察者的事件。 * @param {Object} object 定义的事件对象 */ addEvents : function(o){ if(!this.events){ this.events = {}; } if(typeof o == 'string'){ for(var i = 0, a = arguments, v; v = a[i]; i++){ if(!this.events[a[i]]){ o[a[i]] = true; } } }else{ Ext.applyIf(this.events, o); } }, /** * 查询该对象是否有指定事件的侦听器 * @param {String} eventName 查询事件之名称 * @return {Boolean} True表示为事件正在被侦听 */ hasListener : function(eventName){ var e = this.events[eventName]; return typeof e == "object" && e.listeners.length > 0; }, /** * 暂停触发所有的事件(参阅{@link #resumeEvents}) */ suspendEvents : function(){ this.eventsSuspended = true; }, /** * 重新触发事件(参阅{@link #suspendEvents}) */ resumeEvents : function(){ this.eventsSuspended = false; }, // these are considered experimental // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call // private getMethodEvent : function(method){ if(!this.methodEvents){ this.methodEvents = {}; } var e = this.methodEvents[method]; if(!e){ e = {}; this.methodEvents[method] = e; e.originalFn = this[method]; e.methodName = method; e.before = []; e.after = []; var returnValue, v, cancel; var obj = this; var makeCall = function(fn, scope, args){ if((v = fn.apply(scope || obj, args)) !== undefined){ if(typeof v === 'object'){ if(v.returnValue !== undefined){ returnValue = v.returnValue; }else{ returnValue = v; } if(v.cancel === true){ cancel = true; } }else if(v === false){ cancel = true; }else { returnValue = v; } } } this[method] = function(){ returnValue = v = undefined; cancel = false; var args = Array.prototype.slice.call(arguments, 0); for(var i = 0, len = e.before.length; i < len; i++){ makeCall(e.before[i].fn, e.before[i].scope, args); if(cancel){ return returnValue; } } if((v = e.originalFn.apply(obj, args)) !== undefined){ returnValue = v; } for(var i = 0, len = e.after.length; i < len; i++){ makeCall(e.after[i].fn, e.after[i].scope, args); if(cancel){ return returnValue; } } return returnValue; }; } return e; }, // adds an "interceptor" called before the original method beforeMethod : function(method, fn, scope){ var e = this.getMethodEvent(method); e.before.push({fn: fn, scope: scope}); }, // adds a "sequence" called after the original method afterMethod : function(method, fn, scope){ var e = this.getMethodEvent(method); e.after.push({fn: fn, scope: scope}); }, removeMethodListener : function(method, fn, scope){ var e = this.getMethodEvent(method); for(var i = 0, len = e.before.length; i < len; i++){ if(e.before[i].fn == fn && e.before[i].scope == scope){ e.before.splice(i, 1); return; } } for(var i = 0, len = e.after.length; i < len; i++){ if(e.after[i].fn == fn && e.after[i].scope == scope){ e.after.splice(i, 1); return; } } } }; /** * 为该元素添加事件处理函数(event handler),addListener的简写方式 * @param {String} eventName 侦听事件的类型 * @param {Object} scope (可选的) 执行处理函数的作用域 * @param {Function} handler 事件涉及的方法 * @param {Object} options (可选的) */ Ext.util.Observable.prototype.on = Ext.util.Observable.prototype.addListener; /** * 移除侦听器 * @param {String} eventName 侦听事件的类型 * @param {Function} handler 事件涉及的方法 * @param {Object} scope (可选的)处理函数的作用域 */ Ext.util.Observable.prototype.un = Ext.util.Observable.prototype.removeListener; /** * 开始捕捉特定的观察者。 * 在事件触发<b>之前</b>,所有的事件会以“事件名称+标准签名”的形式传入到函数(传入的参数是function类型)。 * 如果传入的函数执行后返回false,则接下的事件将不会触发。 * @param {Observable} o 要捕捉的观察者 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的)函数作用域 */ Ext.util.Observable.capture = function(o, fn, scope){ o.fireEvent = o.fireEvent.createInterceptor(fn, scope); }; /** * 从Observable身上移除<b>所有</b>已加入的捕捉captures。 * @param {Observable} o 要释放的观察者 * @static */ Ext.util.Observable.releaseCapture = function(o){ o.fireEvent = Ext.util.Observable.prototype.fireEvent; }; (function(){ var createBuffered = function(h, o, scope){ var task = new Ext.util.DelayedTask(); return function(){ task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0)); }; }; var createSingle = function(h, e, fn, scope){ return function(){ e.removeListener(fn, scope); return h.apply(scope, arguments); }; }; var createDelayed = function(h, o, scope){ return function(){ var args = Array.prototype.slice.call(arguments, 0); setTimeout(function(){ h.apply(scope, args); }, o.delay || 10); }; }; Ext.util.Event = function(obj, name){ this.name = name; this.obj = obj; this.listeners = []; }; Ext.util.Event.prototype = { addListener : function(fn, scope, options){ scope = scope || this.obj; if(!this.isListening(fn, scope)){ var l = this.createListener(fn, scope, options); if(!this.firing){ this.listeners.push(l); }else{ // if we are currently firing this event, don't disturb the listener loop this.listeners = this.listeners.slice(0); this.listeners.push(l); } } }, createListener : function(fn, scope, o){ o = o || {}; scope = scope || this.obj; var l = {fn: fn, scope: scope, options: o}; var h = fn; if(o.delay){ h = createDelayed(h, o, scope); } if(o.single){ h = createSingle(h, this, fn, scope); } if(o.buffer){ h = createBuffered(h, o, scope); } l.fireFn = h; return l; }, findListener : function(fn, scope){ scope = scope || this.obj; var ls = this.listeners; for(var i = 0, len = ls.length; i < len; i++){ var l = ls[i]; if(l.fn == fn && l.scope == scope){ return i; } } return -1; }, isListening : function(fn, scope){ return this.findListener(fn, scope) != -1; }, removeListener : function(fn, scope){ var index; if((index = this.findListener(fn, scope)) != -1){ if(!this.firing){ this.listeners.splice(index, 1); }else{ this.listeners = this.listeners.slice(0); this.listeners.splice(index, 1); } return true; } return false; }, clearListeners : function(){ this.listeners = []; }, fire : function(){ var ls = this.listeners, scope, len = ls.length; if(len > 0){ this.firing = true; var args = Array.prototype.slice.call(arguments, 0); for(var i = 0; i < len; i++){ var l = ls[i]; if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){ this.firing = false; return false; } } this.firing = false; } return true; } }; })();
JavaScript
/** * @class Ext.util.JSON * Douglas Crockford的json.js之修改版本 该版本没有“入侵”Object对象的prototype * http://www.json.org/js.html * @singleton */ Ext.util.JSON = new (function(){ var useHasOwn = {}.hasOwnProperty ? true : false; // crashes Safari in some instances //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/; var pad = function(n) { return n < 10 ? "0" + n : n; }; var m = { "\b": '\\b', "\t": '\\t', "\n": '\\n', "\f": '\\f', "\r": '\\r', '"' : '\\"', "\\": '\\\\' }; var encodeString = function(s){ if (/["\\\x00-\x1f]/.test(s)) { return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if(c){ return c; } c = b.charCodeAt(); return "\\u00" + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + s + '"'; }; var encodeArray = function(o){ var a = ["["], b, i, l = o.length, v; for (i = 0; i < l; i += 1) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if (b) { a.push(','); } a.push(v === null ? "null" : Ext.util.JSON.encode(v)); b = true; } } a.push("]"); return a.join(""); }; var encodeDate = function(o){ return '"' + o.getFullYear() + "-" + pad(o.getMonth() + 1) + "-" + pad(o.getDate()) + "T" + pad(o.getHours()) + ":" + pad(o.getMinutes()) + ":" + pad(o.getSeconds()) + '"'; }; /** * 对一个对象,数组,或是其它值编码 * @param {Mixed} o 要编码的变量 * @return {String} JSON字符串 */ this.encode = function(o){ if(typeof o == "undefined" || o === null){ return "null"; }else if(o instanceof Array){ return encodeArray(o); }else if(o instanceof Date){ return encodeDate(o); }else if(typeof o == "string"){ return encodeString(o); }else if(typeof o == "number"){ return isFinite(o) ? String(o) : "null"; }else if(typeof o == "boolean"){ return String(o); }else { var a = ["{"], b, i, v; for (i in o) { if(!useHasOwn || o.hasOwnProperty(i)) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if(b){ a.push(','); } a.push(this.encode(i), ":", v === null ? "null" : this.encode(v)); b = true; } } } a.push("}"); return a.join(""); } }; /** * 将JSON字符串解码(解析)成为对象。如果JSON是无效的,该函数抛出一个“语法错误”。 * @param {String} json JSON字符串 * @return {Object} 对象 */ this.decode = function(json){ return eval("(" + json + ')'); }; })(); /** * {@link Ext.util.JSON#encode}的简写方式 * @member Ext encode * @method */ Ext.encode = Ext.util.JSON.encode; /** * {@link Ext.util.JSON#decode}的简写方式 * @member Ext decode * @method */ Ext.decode = Ext.util.JSON.decode;
JavaScript
/** * @class Ext.KeyMap * Ext.KeyMap类负责在某一元素上,键盘和用户动作(Actions)之间的映射。 * 构建器可接收由{@link #addBinding}定义的相同配置项对象。 * 如果你绑定了一个KeyMap的回调函数,KeyMap会在该回调函数上提供下列参数(String key, Ext.EventObject e) * 如果匹配的是组合键,回调函数也只会执行一次) * KepMap能够实现以字符串来表示key<br /> * 一个key可用于多个动作。 * 用法: <pre><code> // 映射key(由keycode指定) var map = new Ext.KeyMap("my-element", { key: 13, // 或者是 Ext.EventObject.ENTER fn: myHandler, scope: myObject }); // 映射组合键(由字符串指定) var map = new Ext.KeyMap("my-element", { key: "a\r\n\t", fn: myHandler, scope: myObject }); // 映射多个动作的组合键(由字符串和code数组指定) var map = new Ext.KeyMap("my-element", [ { key: [10,13], fn: function(){ alert("Return was pressed"); } }, { key: "abc", fn: function(){ alert('a, b or c was pressed'); } }, { key: "\t", ctrl:true, shift:true, fn: function(){ alert('Control + shift + tab was pressed.'); } } ]); </code></pre> * <b>一个KeyMap开始激活</b> * @constructor * @param {Mixed} el 绑定的元素 * @param {Object} config T配置项 * @param {String} eventName (可选地)绑定的事件(默认“keydown”) */ Ext.KeyMap = function(el, config, eventName){ this.el = Ext.get(el); this.eventName = eventName || "keydown"; this.bindings = []; if(config){ this.addBinding(config); } this.enable(); }; Ext.KeyMap.prototype = { /** * 如果让KeyMap来处理key,设置true的话,则停止事件上报(event from bubbling),并阻拦默认浏览器动作(默认为false) * @type Boolean */ stopEvent : false, /** * 新增该KeyMap的新绑定。下列配置项(对象的属性)均被支持: * <pre> 属性 类型 描述 ---------- --------------- ---------------------------------------------------------------------- key String/Array 进行处理的单个keycode或keycodes组成的数组 shift Boolean True:只有shift按下的的同时处理key (默认false) ctrl Boolean True:只有ctrl按下的的同时处理key (默认false) handler Function 当KeyMap找到预期的组合键时所执行的函数 alt Boolean True:只有alt按下的的同时处理key (默认false) fn Function 当组合键按下后回调函数 scope Object 回调函数的作用域 </pre> * * 用法: * <pre><code> // 创建一个KeyMap var map = new Ext.KeyMap(document, { key: Ext.EventObject.ENTER, fn: handleKey, scope: this }); //对现有的KeyMap延迟再绑定 map.addBinding({ key: 'abc', shift: true, fn: handleKey, scope: this }); </code></pre> * @param {Object} config 单个KeyMap配置 */ addBinding : function(config){ if(config instanceof Array){ for(var i = 0, len = config.length; i < len; i++){ this.addBinding(config[i]); } return; } var keyCode = config.key, shift = config.shift, ctrl = config.ctrl, alt = config.alt, fn = config.fn || config.handler, scope = config.scope; if(typeof keyCode == "string"){ var ks = []; var keyString = keyCode.toUpperCase(); for(var j = 0, len = keyString.length; j < len; j++){ ks.push(keyString.charCodeAt(j)); } keyCode = ks; } var keyArray = keyCode instanceof Array; var handler = function(e){ if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){ var k = e.getKey(); if(keyArray){ for(var i = 0, len = keyCode.length; i < len; i++){ if(keyCode[i] == k){ if(this.stopEvent){ e.stopEvent(); } fn.call(scope || window, k, e); return; } } }else{ if(k == keyCode){ if(this.stopEvent){ e.stopEvent(); } fn.call(scope || window, k, e); } } } }; this.bindings.push(handler); }, /** * 加入单个键侦听器的简写方式 * @param {Number/Array/Object} key 既可是key code,也可以是key codes的集合,或者是下列的对象 * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)} * @param {Function} fn 调用的函数 * @param {Object} scope (optional) 函数的作用域 */ on : function(key, fn, scope){ var keyCode, shift, ctrl, alt; if(typeof key == "object" && !(key instanceof Array)){ keyCode = key.key; shift = key.shift; ctrl = key.ctrl; alt = key.alt; }else{ keyCode = key; } this.addBinding({ key: keyCode, shift: shift, ctrl: ctrl, alt: alt, fn: fn, scope: scope }) }, // private handleKeyDown : function(e){ if(this.enabled){ //以防万一 var b = this.bindings; for(var i = 0, len = b.length; i < len; i++){ b[i].call(this, e); } } }, /** KeyMap是已激活的话返回true * @return {Boolean} */ isEnabled : function(){ return this.enabled; }, /** * 激活KeyMap */ enable: function(){ if(!this.enabled){ this.el.on(this.eventName, this.handleKeyDown, this); this.enabled = true; } }, /** * 禁止该KeyMap */ disable: function(){ if(this.enabled){ this.el.removeListener(this.eventName, this.handleKeyDown, this); this.enabled = false; } } };
JavaScript
/** * @class Ext.KeyNav * <p> * 为跨浏览器的键盘方向键加上一层快捷的包装器(wrapper)。 * KeyNav允许你为某个功能绑定方向键,按下的时候即调用该功能。 * KeyNav允许你对方向键进行函数调用的绑定,即按下相应的键便立即执行函数,轻松实现了对任意UI组件的键盘事件控制</p> * <p>下列是全部有可能会出现的键(已实现的): enter, left, right, up, down, tab, esc, * pageUp, pageDown, del, home, end。 举例:</p> <pre><code> var nav = new Ext.KeyNav("my-element", { "left" : function(e){ this.moveLeft(e.ctrlKey); }, "right" : function(e){ this.moveRight(e.ctrlKey); }, "enter" : function(e){ this.save(); }, scope : this }); </code></pre> * @constructor * @param {Mixed} el 绑定的元素 * @param {Object} config 配置项 */ Ext.KeyNav = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(!this.disabled){ this.disabled = true; this.enable(); } }; Ext.KeyNav.prototype = { /** * @cfg {Boolean} disabled * True表示为禁止该KeyNav的实例(默认为false) */ disabled : false, /** * @cfg {String} defaultEventAction * 当KeyNav拦截某键之后,所调用的{@link Ext.EventObject}方法。该值可以是 * {@link Ext.EventObject#stopEvent}, {@link Ext.EventObject#preventDefault}与 * {@link Ext.EventObject#stopPropagation}(默认为“stopEvent”) */ defaultEventAction: "stopEvent", /** * @cfg {Boolean} forceKeyDown * 以keydown事件代替keypress(默认为false)。 * 由于IE上按下special键不能有效触发keypress事件,所以IE上会自动设置为true。 * 然而将该项规定为true的话,则表示所以浏览器上都以以keydown事件代替keypress */ forceKeyDown : false, // private prepareEvent : function(e){ var k = e.getKey(); var h = this.keyToHandler[k]; //if(h && this[h]){ // e.stopPropagation(); //} if(Ext.isSafari && h && k >= 37 && k <= 40){ e.stopEvent(); } }, // private relay : function(e){ var k = e.getKey(); var h = this.keyToHandler[k]; if(h && this[h]){ if(this.doRelay(e, this[h], h) !== true){ e[this.defaultEventAction](); } } }, // private doRelay : function(e, h, hname){ return h.call(this.scope || this, e); }, // possible handlers enter : false, left : false, right : false, up : false, down : false, tab : false, esc : false, pageUp : false, pageDown : false, del : false, home : false, end : false, // quick lookup hash keyToHandler : { 37 : "left", 39 : "right", 38 : "up", 40 : "down", 33 : "pageUp", 34 : "pageDown", 46 : "del", 36 : "home", 35 : "end", 13 : "enter", 27 : "esc", 9 : "tab" }, /** * 激活这个KeyNav */ enable: function(){ if(this.disabled){ // ie won't do special keys on keypress, no one else will repeat keys with keydown // the EventObject will normalize Safari automatically if(this.forceKeyDown || Ext.isIE || Ext.isAir){ this.el.on("keydown", this.relay, this); }else{ this.el.on("keydown", this.prepareEvent, this); this.el.on("keypress", this.relay, this); } this.disabled = false; } }, /** * 禁用这个KeyNav */ disable: function(){ if(!this.disabled){ if(this.forceKeyDown || Ext.isIE || Ext.isAir){ this.el.un("keydown", this.relay); }else{ this.el.un("keydown", this.prepareEvent); this.el.un("keypress", this.relay); } this.disabled = true; } } };
JavaScript
/** * @class Ext.util.MixedCollection * 一个负责维护数字下标(numeric indexes)和键值(key)的集合类,并暴露了一些事件。 * @constructor * @param {Boolean} allowFunctions True表示为允许加入函数的引用到集合内(默认为false) * @param {Function} keyFn 对于一个在该Mixed集合中已保存类型的item,可用这个函数返回对应item的键值。 * 执行MixedCollection方法时不需要特定传入一个key参数便可查找出键值。传入这个参数等同于实现了{@link #getKey}方法。 */ Ext.util.MixedCollection = function(allowFunctions, keyFn){ this.items = []; this.map = {}; this.keys = []; this.length = 0; this.addEvents( /** * @event clear * 当集合被清除后触发。 */ "clear", /** * @event add * 当item被加入到集合之后触发。 * @param {Number} index 加入item的索引 * @param {Object} o 加入的item * @param {String} key 加入item的键名称 */ "add", /** * @event replace * 集合中的item被替换后触发。 * @param {String} key 新加入item的键名称 * @param {Object} old 被替换之item * @param {Object} new 新item. */ "replace", /** * @event remove * 当item被移除集合时触发。 * @param {Object} o 被移除的item * @param {String} key (可选的)被移除的item的键名称 */ "remove", "sort" ); this.allowFunctions = allowFunctions === true; if(keyFn){ this.getKey = keyFn; } Ext.util.MixedCollection.superclass.constructor.call(this); }; Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, { allowFunctions : false, /** * 加入一个item到集合中。 * @param {String} key item的键名称 * @param {Object} o 加入的item * @return {Object} 已加入的item */ add : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } if(typeof key == "undefined" || key === null){ this.length++; this.items.push(o); this.keys.push(null); }else{ var old = this.map[key]; if(old){ return this.replace(key, o); } this.length++; this.items.push(o); this.map[key] = o; this.keys.push(key); } this.fireEvent("add", this.length-1, o, key); return o; }, /** * 如果你执行getKey的方法,MixedCollection有一个通用的方法来取得keys。 * 默认的实现只是简单地返回<tt style="font-weight:bold;">item.id</tt>, * 不过你可以按照下面的例子自定义一个实现,以返回另外一个值 <pre><code> // 一般方式 var mc = new Ext.util.MixedCollection(); mc.add(someEl.dom.id, someEl); mc.add(otherEl.dom.id, otherEl); //等等 // 使用getKey var mc = new Ext.util.MixedCollection(); mc.getKey = function(el){ return el.dom.id; }; mc.add(someEl); mc.add(otherEl); // 或通过构造器 var mc = new Ext.util.MixedCollection(false, function(el){ return el.dom.id; }); mc.add(someEl); mc.add(otherEl); </code></pre> * @param o {Object} 根据item找到key * @return {Object} 传入item的key */ getKey : function(o){ return o.id; }, /** * 替换集合中的item。完成后触发{@link #replace}事件。 * @param {String} key 要替换item所关联的那个key,或是item。 * @param o {Object} o (可选的)如果传入的第一个参数是key,那么item就是key的键名称。 * @return {Object} 新的item。 */ replace : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } var old = this.item(key); if(typeof key == "undefined" || key === null || typeof old == "undefined"){ return this.add(key, o); } var index = this.indexOfKey(key); this.items[index] = o; this.map[key] = o; this.fireEvent("replace", key, old, o); return o; }, /** * 将数组中或是对象中的所有元素加入到集合中。 * @param {Object/Array} objs 对象中包含的所有属性,或是数组中所有的值,都分别逐一加入集合中。 */ addAll : function(objs){ if(arguments.length > 1 || objs instanceof Array){ var args = arguments.length > 1 ? arguments : objs; for(var i = 0, len = args.length; i < len; i++){ this.add(args[i]); } }else{ for(var key in objs){ if(this.allowFunctions || typeof objs[key] != "function"){ this.add(key, objs[key]); } } } }, /** * 在集合中执行每个Item的指定函数。函数执行时,会有下列的参数: * <div class="mdetail-params"><ul> * <li><b>item</b> : Mixed<p class="sub-desc">集合中的item</p></li> * <li><b>index</b> : Number<p class="sub-desc">item的索引</p></li> * <li><b>length</b> : Number<p class="sub-desc">集合中的items的总数</p></li> * </ul></div> * 那个函数应该要返回一个布尔值。若函数返回false便终止枚举。 * @param {Function} fn 每个item要执行的函数 * @param {Object} scope (optional) 函数执行时的作用域 */ each : function(fn, scope){ var items = [].concat(this.items); // each safe for removal for(var i = 0, len = items.length; i < len; i++){ if(fn.call(scope || items[i], items[i], i, len) === false){ break; } } }, /** * 传入一个函数类型的参数,然后在集合中的每个Item执行。key和其相关的item都作为头两个参数传入。 * @param {Function} fn 每个item要执行的函数。 * @param {Object} scope (可选的)执行函数的作用域 */ eachKey : function(fn, scope){ for(var i = 0, len = this.keys.length; i < len; i++){ fn.call(scope || window, this.keys[i], this.items[i], i, len); } }, /** * 根据传入的函数,执行该函数若返回true便说明这是要找到的那个item。 * @param {Function} fn 每个item要执行的查询函数。 * @param {Object} scope (可选的)执行函数的作用域 * @return {Object} 根据规则函数在集合中第一个找到的item */ find : function(fn, scope){ for(var i = 0, len = this.items.length; i < len; i++){ if(fn.call(scope || window, this.items[i], this.keys[i])){ return this.items[i]; } } return null; }, /** * 指定集合中的某个索引然后插入一个Item * @param {Number} index 要插入item的索引。 * @param {String} key 包含新item的key名称,或item本身 * @param {Object} o (可选的) 如果第二个参数是key,新item * @return {Object}以插入的item */ insert : function(index, key, o){ if(arguments.length == 2){ o = arguments[1]; key = this.getKey(o); } if(index >= this.length){ return this.add(key, o); } this.length++; this.items.splice(index, 0, o); if(typeof key != "undefined" && key != null){ this.map[key] = o; } this.keys.splice(index, 0, key); this.fireEvent("add", index, o, key); return o; }, /** * 从集合中移除Item * @param {Object} o 移除的item * @return {Object} 被移除的Item */ remove : function(o){ return this.removeAt(this.indexOf(o)); }, /** * 从集合中移除由index指定的Item。完成后触发{@link #remove}事件。 * @param {Number} index 移除item的索引 * @return {Object} 被移除的item或是false就代表没有移除。 */ removeAt : function(index){ if(index < this.length && index >= 0){ this.length--; var o = this.items[index]; this.items.splice(index, 1); var key = this.keys[index]; if(typeof key != "undefined"){ delete this.map[key]; } this.keys.splice(index, 1); this.fireEvent("remove", o, key); return o; } return false; }, /** * 根据传入参数key,从集合中移除相关的item * @param {String} key 要移除item的key * @return {Object} 被移除的item或是false就代表没有移除。 */ removeKey : function(key){ return this.removeAt(this.indexOfKey(key)); }, /** * 返回集合中的item总数。 * @return {Number} item总数 */ getCount : function(){ return this.length; }, /** * 传入一个对象,返回它的索引。 * @param {Object} o 要寻找索引的item * @return {Number} item的索引。返回-1表示找不到。 */ indexOf : function(o){ return this.items.indexOf(o); }, /** * 传入一个Key,返回它的索引。 * @param {String} key 寻找索引的key * @return {Number} key的索引 */ indexOfKey : function(key){ return this.keys.indexOf(key); }, /** * 根据key或索引(index)返回item。key的优先权高于索引。 * 这个方法相当于先调用{@link #key},如不匹配在调用{@link #itemAt}。 * @param {String/Number} key或者是item的索引 * @return {Object} 传入key所关联的item */ item : function(key){ var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key]; return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype! }, /** * 根据索引找到item * @param {Number} index item的索引index * @return {Object} 指定索引的item */ itemAt : function(index){ return this.items[index]; }, /** * 根据key找到item * @param {String/Number} key item的key * @return {Object} key所关联的item */ key : function(key){ return this.map[key]; }, /** * 若在集合中找到传入的item,则返回true。 * @param {Object} o 要在集合中查找的对象 * @return {Boolean} True表示为在集合中找到该item */ contains : function(o){ return this.indexOf(o) != -1; }, /** * 若在集合中找到传入的key,则返回true。 * @param {Object} o 要在集合中查找的对象 * @return {Boolean} True表示为在集合中找到该key */ containsKey : function(key){ return typeof this.map[key] != "undefined"; }, /** * 清除集合中所有item */ clear : function(){ this.length = 0; this.items = []; this.keys = []; this.map = {}; this.fireEvent("clear"); }, /** * 返回集合中第一个item * @return {Object} 集合中第一个item */ first : function(){ return this.items[0]; }, /** * 返回集合中最后一个item * @return {Object} 集合中最后一个item */ last : function(){ return this.items[this.length-1]; }, // private _sort : function(property, dir, fn){ var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1; fn = fn || function(a, b){ return a-b; }; var c = [], k = this.keys, items = this.items; for(var i = 0, len = items.length; i < len; i++){ c[c.length] = {key: k[i], value: items[i], index: i}; } c.sort(function(a, b){ var v = fn(a[property], b[property]) * dsc; if(v == 0){ v = (a.index < b.index ? -1 : 1); } return v; }); for(var i = 0, len = c.length; i < len; i++){ items[i] = c[i].value; k[i] = c[i].key; } this.fireEvent("sort", this); }, /** * 按传入的函数排列集合 * @param {String} 方向(可选的) "ASC" 或 "DESC" * @param {Function} fn(可选的) 一个供参照的function */ sort : function(dir, fn){ this._sort("value", dir, fn); }, /** * 按key顺序排列集合 * @param {String} 方向(可选的) "ASC" 或 "DESC" * @param {Function} fn(可选的) 一个参照的function (默认为非敏感字符串) */ keySort : function(dir, fn){ this._sort("key", dir, fn || function(a, b){ var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase(); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }); }, /** * 返回这个集合中的某个范围内的items * @param {Number} startIndex (可选的) 默认为 0 * @param {Number} endIndex (可选的) 默认为最后的item * @return {Array} items数组 */ getRange : function(start, end){ var items = this.items; if(items.length < 1){ return []; } start = start || 0; end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1); var r = []; if(start <= end){ for(var i = start; i <= end; i++) { r[r.length] = items[i]; } }else{ for(var i = start; i >= end; i--) { r[r.length] = items[i]; } } return r; }, /** * 由指定的属性过滤集合中的<i>对象</i>。 * 返回以过滤后的新集合 * @param {String} property 你对象身上的属性 * @param {String/RegExp} value 也可以是属性开始的值或对于这个属性的正则表达式 * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning * @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False). * @return {MixedCollection} 过滤后的新对象 */ filter : function(property, value, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return this.clone(); } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.filterBy(function(o){ return o && value.test(o[property]); }); }, /** * 由函数过滤集合中的<i>对象</i>。 * 返回以过滤后的<i>新</i>集合 * 传入的函数会被集合中每个对象执行。如果函数返回true,则value会被包含否则会被过滤、 * @param {Function} fn 被调用的函数,会接收o(object)和k (the key)参数 * @param {Object} scope (可选的)函数的作用域(默认为 this) * @return {MixedCollection} 过滤后的新对象 */ filterBy : function(fn, scope){ var r = new Ext.util.MixedCollection(); r.getKey = this.getKey; var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ r.add(k[i], it[i]); } } return r; }, /** * 由指定的属性/值查找集合中的第一个匹配对象。 * 这个对象是过滤后的<i>新</i>集合 * @param {String} property 当前对象下的属性名称 * @param {String/RegExp} value 代表属性值的字符串,也可以是一个正则表达式以测试属性。y. * @param {Number} start (可选的)从第几个字符开始搜索(默认为0) * @param {Boolean} anyMatch (可选的)True表示为匹配字符串的任意一部分,不只是开始的部分 * @param {Boolean} caseSensitive (可选的)True表示为打开大小写敏感 * @return {Number} 匹配的索引或-1 */ findIndex : function(property, value, start, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return -1; } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.findIndexBy(function(o){ return o && value.test(o[property]); }, null, start); }, /** * 由函数过滤集合中的<i>对象</i>。 * 返回以过滤后的<i>新</i>集合 * 传入的函数会被集合中每个对象执行。如果函数返回true,则value会被包含否则会被过滤、 * @param {Function} fn 被调用的函数,会接收o(object)和k (the key)参数 * @param {Object} scope (可选的)函数的作用域(默认为 this) * @param {Number} start (可选的)从第几个字符开始搜索(默认为0) * @return {MixedCollection} 匹配的索引或-1 */ findIndexBy : function(fn, scope, start){ var k = this.keys, it = this.items; for(var i = (start||0), len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } if(typeof start == 'number' && start > 0){ for(var i = 0; i < start; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } } return -1; }, // private createValueMatcher : function(value, anyMatch, caseSensitive){ if(!value.exec){ // not a regex value = String(value); value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), caseSensitive ? '' : 'i'); } return value; }, /** * 创建该集合的浅表副本shallow copy(shallow copy) * @return {MixedCollection} */ clone : function(){ var r = new Ext.util.MixedCollection(); var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ r.add(k[i], it[i]); } r.getKey = this.getKey; return r; } }); /** * 根据key或索引返回item。key的优先权高于索引。 * @method * @param {String/Number} key 或者是item的索引 * @return {Object} 传入key所关联的item */ Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;
JavaScript
/** * @class Ext.util.TextMetrics * 为一段文字提供一个精确象素级的测量,以便可以得到某段文字的高度和宽度。 * @singleton */ Ext.util.TextMetrics = function(){ var shared; return { /** * 测量指定文字尺寸 * @param {String/HTMLElement} el 元素,DOM节点或ID,使得被渲染之文字获得新的CSS样式。 * @param {String} text 欲测量的文字 * @param {Number} fixedWidth (optional) 如果文字是多行的,您必须先设置好一个宽度。 * 以便正确的测出高度。 * @return {Object} 由文字尺寸组成的对象 {width: (width), height: (height)} */ measure : function(el, text, fixedWidth){ if(!shared){ shared = Ext.util.TextMetrics.Instance(el, fixedWidth); } shared.bind(el); shared.setFixedWidth(fixedWidth || 'auto'); return shared.getSize(text); }, /** * 返回一个唯一的TextMetrics实例,直接绑定到某个元素和复用, * 这样会减少在每个测量上初始样式属性的多次调用。 * @param {String/HTMLElement} el 将实例绑定到的元素,DOM节点或ID * @param {Number} fixedWidth (optional) 如果文字是多行的,您必须先设置好一个宽度。 * 以便正确地测出高度。 * @return {Ext.util.TextMetrics.Instance} instance 新实例 */ createInstance : function(el, fixedWidth){ return Ext.util.TextMetrics.Instance(el, fixedWidth); } }; }(); Ext.util.TextMetrics.Instance = function(bindTo, fixedWidth){ var ml = new Ext.Element(document.createElement('div')); document.body.appendChild(ml.dom); ml.position('absolute'); ml.setLeftTop(-1000, -1000); ml.hide(); if(fixedWidth){ ml.setWidth(fixedWidth); } var instance = { /** * 返回一个指定文字的尺寸。该文字内置元素的样式和宽度属性 * @param {String} text 要测量的文字 * @return {Object} 由文字尺寸组成的对象 {width: (width), height: (height)} */ getSize : function(text){ ml.update(text); var s = ml.getSize(); ml.update(''); return s; }, /** * 绑定某个样式的TextMetrics实例,使得被渲染之文字重新获得CSS样式。 * @param {String/HTMLElement} el 元素,DOM节点或ID */ bind : function(el){ ml.setStyle( Ext.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height') ); }, /** * 对内置的测量元素设置一个固定的宽度。 如果文字是多行的,您必须先设置好一个宽度。 * 以便正确地测出高度。 * @param {Number} width 设置元素的宽度。 */ setFixedWidth : function(width){ ml.setWidth(width); }, /** * 返回指定文字的宽度 * @param {String} text 要测量的文字 * @return {Number} width 宽度(象素) */ getWidth : function(text){ ml.dom.style.width = 'auto'; return this.getSize(text).width; }, /** * 返回指定文字的高度,对于多行文本,有可能需要调用 {@link #setFixedWidth} 。 * @param {String} text 要测量的文字 * @return {Number} height 高度(象素) */ getHeight : function(text){ return this.getSize(text).height; } }; instance.bind(bindTo); return instance; }; // 向后兼容 Ext.Element.measureText = Ext.util.TextMetrics.measure;
JavaScript
/** * @class Ext.XTemplate * <p>支持高级功能的模板类, * 如自动数组输出、条件判断、子模板、基本数学运行、特殊内建的模板变量, * 直接执行代码和更多的功能。XTemplate亦提供相应的机制整合到 {@link Ext.DataView}. * </p> * <p>XTemplate有些特殊的标签和内建的操作运算符,是模板创建时生成的,不属于API条目的一部分。 * 下面的例子就演示了这些特殊部分的用法。每一个例子使用的数据对象如下:</p> * <pre><code> var data = { name: 'Jack Slocum', title: 'Lead Developer', company: 'Ext JS, LLC', email: 'jack@extjs.com', address: '4 Red Bulls Drive', city: 'Cleveland', state: 'Ohio', zip: '44102', drinks: ['Red Bull', 'Coffee', 'Water'], kids: [{ name: 'Sara Grace', age:3 },{ name: 'Zachary', age:2 },{ name: 'John James', age:0 }] }; </cpde></pre> * <p> * 配合使用标签<code>tpl</code>和操作符<code>for</code>, * 你可自由切换<code>for<code>所指定的对象作用域,即可访问声明于模板之中对象。 * 如果这个对象是一个数组,它就会自动循环输出,不断重复<code>tpl</code>标签内的模板代码块,输出数组内的每一条内容: * <b>自动数组输出和作用域切换。</b> * </p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Title: {title}&lt;/p>', '&lt;p>Company: {company}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;p>{name}&lt;/p>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * <p><b>在子模板的范围内访问父元素对象。</b> * 当正在处理子模板时,例如在循环子数组的时候, * 可以通过<code>parent</code>对象访问父级的对象成员。 * </p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &gt; 1">', '&lt;p>{name}&lt;/p>', '&lt;p>Dad: {parent.name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * <p><b>数组元素索引和简单匹配支持。</b> 当正在处理数组的时候,特殊变量<code>#</code>表示当前数组索引+1(由1开始,不是0)。 * 如遇到数字型的元素,模板也支持简单的数学运算符+ - * /。 * </p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &gt; 1">', '&lt;p>{#}: {name}&lt;/p>', // <-- 每一项都加上序号 '&lt;p>In 5 Years: {age+5}&lt;/p>', // <-- 简单的运算 '&lt;p>Dad: {parent.name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * <p><b>自动渲染单根数组(flat arrays)。</b> * 单根数组(Flat arrays),指的是不包含分支对象只包含值的数组。 * 使用特殊变量<code>{.}</code>可循环输出这类型的数组: * </p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>{name}\'s favorite beverages:&lt;/p>', '&lt;tpl for="drinks">', '&lt;div> - {.}&lt;/div>', '&lt;/tpl>' ); tpl.overwrite(panel.body, data); </code></pre> * <p><b>基本的条件逻辑判断</b> * 配合标签<coed>tpl</code>和操作符<code>if</code>的使用,可为你执行条件判断,以决定模板的哪一部分需要被渲染出来。 * 注意这没有<code>else</code>的操作符--如需要,就要写两个逻辑相反的<code>if</code>的语句。 * 属性项要记得进行编码,好像下面的例子:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', // <-- 注意&gt;要被编码 '&lt;p>{name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * <p><b>即时执行任意的代码</b> <br/> * 在XTemplate中,{[ ... ]}范围内的内容会在模板作用域的范围下执行。这里有一些特殊的变量: * <ul> * <li><b><tt>values</tt></b>:当前作用域下的值。若想改变其中的<tt>值</tt>,你可以切换子模板的作用域。</li> * <li><b><tt>parent</tt></b>:父级模板的对象</li> * <li><b><tt>xindex</tt></b>:若是循环模板,这是当前循环的索引index(从1开始)。</li> * <li><b><tt>xcount</tt></b>:若是循环模板,这是循环的次数。</li> * <li><b><tt>fm</tt></b>:<tt>Ext.util.Format</tt>的简写方式。</li> * </ul> * 这是一个例子说明怎么利用这个知识点生成交错行: </p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Company: {[company.toUpperCase() + ', ' + title]}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">, '{name}', '&lt;/div>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * <p><b>模板成员函数。</b> 对于一些复制的处理, * 可以配置项对象的方式传入一个或一个以上的成员函数到XTemplate构造器中:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="this.isGirl(name)">', '&lt;p>Girl: {name} - {age}&lt;/p>', '&lt;/tpl>', '&lt;tpl if="this.isGirl(name) == false">', '&lt;p>Boy: {name} - {age}&lt;/p>', '&lt;/tpl>', '&lt;tpl if="this.isBaby(age)">', '&lt;p>{name} is a baby!&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>', { isGirl: function(name){ return name == 'Sara Grace'; }, isBaby: function(age){ return age < 1; } }); tpl.overwrite(panel.body, data); </code></pre> * @constructor * @param {String/Array/Object} parts HTML判断或片断组成的数组,或多个参数然后执行join("")。 */ Ext.XTemplate = function(){ Ext.XTemplate.superclass.constructor.apply(this, arguments); var s = this.html; s = ['<tpl>', s, '</tpl>'].join(''); var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/; var nameRe = /^<tpl\b[^>]*?for="(.*?)"/; var ifRe = /^<tpl\b[^>]*?if="(.*?)"/; var execRe = /^<tpl\b[^>]*?exec="(.*?)"/; var m, id = 0; var tpls = []; while(m = s.match(re)){ var m2 = m[0].match(nameRe); var m3 = m[0].match(ifRe); var m4 = m[0].match(execRe); var exp = null, fn = null, exec = null; var name = m2 && m2[1] ? m2[1] : ''; if(m3){ exp = m3 && m3[1] ? m3[1] : null; if(exp){ fn = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ return '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(m4){ exp = m4 && m4[1] ? m4[1] : null; if(exp){ exec = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(name){ switch(name){ case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break; case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break; default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }'); } } tpls.push({ id: id, target: name, exec: exec, test: fn, body: m[1]||'' }); s = s.replace(m[0], '{xtpl'+ id + '}'); ++id; } for(var i = tpls.length-1; i >= 0; --i){ this.compileTpl(tpls[i]); } this.master = tpls[tpls.length-1]; this.tpls = tpls; }; Ext.extend(Ext.XTemplate, Ext.Template, { // private re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g, // private codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g, // private applySubTemplate : function(id, values, parent, xindex, xcount){ var t = this.tpls[id]; if(t.test && !t.test.call(this, values, parent, xindex, xcount)){ return ''; } if(t.exec && t.exec.call(this, values, parent, xindex, xcount)){ return ''; } var vs = t.target ? t.target.call(this, values, parent) : values; parent = t.target ? values : parent; if(t.target && vs instanceof Array){ var buf = []; for(var i = 0, len = vs.length; i < len; i++){ buf[buf.length] = t.compiled.call(this, vs[i], parent, i+1, len); } return buf.join(''); } return t.compiled.call(this, vs, parent, xindex, xcount); }, // private compileTpl : function(tpl){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args, math){ if(name.substr(0, 4) == 'xtpl'){ return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'"; } var v; if(name === '.'){ v = 'values'; }else if(name === '#'){ v = 'xindex'; }else if(name.indexOf('.') != -1){ v = name; }else{ v = "values['" + name + "']"; } if(math){ v = '(' + v + math + ')'; } if(format && useF){ args = args ? ',' + args : ""; if(format.substr(0, 5) != "this."){ format = "fm." + format + '('; }else{ format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } }else{ args= ''; format = "("+v+" === undefined ? '' : "; } return "'"+ sep + format + v + args + ")"+sep+"'"; }; var codeFn = function(m, code){ return "'"+ sep +'('+code+')'+sep+"'"; }; var body; // branched to use + in gecko and [].join() in others if(Ext.isGecko){ body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" + tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) + "';};"; }else{ body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"]; body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, /** * {@link #applyTemplate}的简写方式。 */ apply : function(values){ return this.master.compiled.call(this, values, {}, 1, 1); }, /** * 返回HTML片断,这块片断是由数据填充模板之后而成的。 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @return {String} HTML片断 */ applyTemplate : function(values){ return this.master.compiled.call(this, values, {}, 1, 1); }, /** * 把这个模板编译为一个函数,推荐多次使用这个模板时用这个方法,以提供性能。 * @return {Function} 编译后的函数 */ compile : function(){return this;} /** * @property re * @hide */ /** * @property disableFormats * @hide */ /** * @method set * @hide */ }); /** * 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML. * @param {String/HTMLElement} DOM元素或某id * @param {Object} config 一个配置项对象 * @returns {Ext.Template} 创建好的模板 * @static */ Ext.XTemplate.from = function(el){ el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML); };
JavaScript
/** * @class Date * * 日期的处理和格式化是<a href="http://www.php.net/date">PHP's date() function</a>的一个子集, * 提供的格式和转换后的结果将和 PHP 版本的一模一样。下面列出的是目前所有支持的格式: *<pre> 样本数据: 'Wed Jan 10 2007 15:05:01 GMT-0600 (中区标准时间)' 格式符 输出 说明 ------ ---------- -------------------------------------------------------------- d 10 月份中的天数,两位数字,不足位补“0” D Wed 当前星期的缩写,三个字母 j 10 月份中的天数,不补“0” l Wednesday 当前星期的完整拼写 S th 英语中月份天数的序数词的后缀,2个字符(与格式符“j”连用) w 3 一周之中的天数(1~7) z 9 一年之中的天数(0~365) W 01 一年之中的周数,两位数字(00~52) F January 当前月份的完整拼写 m 01 当前的月份,两位数字,不足位补“0” M Jan 当前月份的完整拼写,三个字母 n 1 当前的月份,不补“0” t 31 当前月份的总天数 L 0 是否闰年(“1”为闰年,“0”为平年) Y 2007 4位数字表示的当前年数 y 07 2位数字表示的当前年数 a pm 小写的“am”和“pm” A PM 大写的“am”和“pm” g 3 12小时制表示的当前小时数,不补“0” G 15 24小时制表示的当前小时数,不补“0” h 03 12小时制表示的当前小时数,不足位补“0” H 15 24小时制表示的当前小时数,不足位补“0” i 05 不足位补“0”的分钟数 s 01 不足位补“0”的秒数 O -0600 用小时数表示的与 GMT 差异数 T CST 当前系统设定的时区 Z -21600 用秒数表示的时区偏移量(西方为负数,东方为正数) </pre> * * 用法举例:(注意你必须在字母前使用转意字符“\\”才能将其作为字母本身而不是格式符输出): * <pre><code> var dt = new Date('1/10/2007 03:05:01 PM GMT-0600'); document.write(dt.format('Y-m-d')); //2007-01-10 document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm document.write(dt.format('l, \\t\\he dS of F Y h:i:s A')); //Wednesday, the 10th of January 2007 03:05:01 PM </code></pre> * * 下面有一些标准的日期/时间模板可能会对你有用。它们不是 Date.js 的一部分,但是你可以将下列代码拷出,并放在 Date.js 之后所引用的任何脚本内,都将成为一个全局变量,并对所有的 Date 对象起作用。你可以按照你的需要随意增加、删除此段代码。 * <pre><code> Date.patterns = { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }; </code></pre> * * 用法举例: * <pre><code> var dt = new Date(); document.write(dt.format(Date.patterns.ShortDate)); </code></pre> */ /* * Most of the date-formatting functions below are the excellent work of Baron Schwartz. * They generate precompiled functions from date formats instead of parsing and * processing the pattern every time you format a date. These functions are available * on every Date object (any javascript function). * * 下列大部分的日期格式化函数都是 Baron Schwartz 的杰作。 * 它们会由日期格式生成预编译函数,而不是在你每次格式化一个日期的时候根据模板转换和处理日期对象。 * 这些函数可以应用于每一个日期对象(在任何 JS 函数中)。 * * The original article and download are here: * 原文及下载在这里: * http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/ * */ // private Date.parseFunctions = {count:0}; // private Date.parseRegexes = []; // private Date.formatFunctions = {count:0}; // private Date.prototype.dateFormat = function(format) { if (Date.formatFunctions[format] == null) { Date.createNewFormat(format); } var func = Date.formatFunctions[format]; return this[func](); }; /** * 根据指定的格式将对象格式化。 * @param {String} 格式符 * @return {String} 格式化后的日期对象 * @method */ Date.prototype.format = Date.prototype.dateFormat; // private Date.createNewFormat = function(format) { var funcName = "format" + Date.formatFunctions.count++; Date.formatFunctions[format] = funcName; var code = "Date.prototype." + funcName + " = function(){return "; var special = false; var ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; code += "'" + String.escape(ch) + "' + "; } else { code += Date.getFormatCode(ch); } } eval(code.substring(0, code.length - 3) + ";}"); }; // private Date.getFormatCode = function(character) { switch (character) { case "d": return "String.leftPad(this.getDate(), 2, '0') + "; case "D": return "Date.dayNames[this.getDay()].substring(0, 3) + "; case "j": return "this.getDate() + "; case "l": return "Date.dayNames[this.getDay()] + "; case "S": return "this.getSuffix() + "; case "w": return "this.getDay() + "; case "z": return "this.getDayOfYear() + "; case "W": return "this.getWeekOfYear() + "; case "F": return "Date.monthNames[this.getMonth()] + "; case "m": return "String.leftPad(this.getMonth() + 1, 2, '0') + "; case "M": return "Date.monthNames[this.getMonth()].substring(0, 3) + "; case "n": return "(this.getMonth() + 1) + "; case "t": return "this.getDaysInMonth() + "; case "L": return "(this.isLeapYear() ? 1 : 0) + "; case "Y": return "this.getFullYear() + "; case "y": return "('' + this.getFullYear()).substring(2, 4) + "; case "a": return "(this.getHours() < 12 ? 'am' : 'pm') + "; case "A": return "(this.getHours() < 12 ? 'AM' : 'PM') + "; case "g": return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + "; case "G": return "this.getHours() + "; case "h": return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + "; case "H": return "String.leftPad(this.getHours(), 2, '0') + "; case "i": return "String.leftPad(this.getMinutes(), 2, '0') + "; case "s": return "String.leftPad(this.getSeconds(), 2, '0') + "; case "O": return "this.getGMTOffset() + "; case "T": return "this.getTimezone() + "; case "Z": return "(this.getTimezoneOffset() * -60) + "; default: return "'" + String.escape(character) + "' + "; } }; /** * 将输入的字串按照指定的格式转换为日期对象。 * 请注意此函数接受的是普通的日历格式,这意味着月份由1开始(1 = 1月)而不是像 JS 的日期对象那样由0开始。 * 任何没有指定的日期部分将默认为当前日期中对应的部分。 * 时间部分也是可以指定的,默认值为 0. * 一定要注意输入的日期字串必须与指定的格式化字串相符,否则处理操作将会失败。 * * 用法举例: <pre><code> //dt = Fri May 25 2007(当前日期) var dt = new Date(); //dt = Thu May 25 2006 (today's month/day in 2006) dt = Date.parseDate("2006", "Y"); //dt = Sun Jan 15 2006 (指定日期的所有部分) dt = Date.parseDate("2006-1-15", "Y-m-d"); //dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST) dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" ); </code></pre> * @param {String} input 输入的日期字串 * @param {String} format 转换格式符 * @return {Date} 转换后的日期对象 * @static */ Date.parseDate = function(input, format) { if (Date.parseFunctions[format] == null) { Date.createParser(format); } var func = Date.parseFunctions[format]; return Date[func](input); }; // private Date.createParser = function(format) { var funcName = "parse" + Date.parseFunctions.count++; var regexNum = Date.parseRegexes.length; var currentGroup = 1; Date.parseFunctions[format] = funcName; var code = "Date." + funcName + " = function(input){\n" + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n" + "var d = new Date();\n" + "y = d.getFullYear();\n" + "m = d.getMonth();\n" + "d = d.getDate();\n" + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n" + "if (results && results.length > 0) {"; var regex = ""; var special = false; var ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; regex += String.escape(ch); } else { var obj = Date.formatCodeToRegex(ch, currentGroup); currentGroup += obj.g; regex += obj.s; if (obj.g && obj.c) { code += obj.c; } } } code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n" + "{v = new Date(y, m, d, h, i, s);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n" + "{v = new Date(y, m, d, h, i);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n" + "{v = new Date(y, m, d, h);}\n" + "else if (y >= 0 && m >= 0 && d > 0)\n" + "{v = new Date(y, m, d);}\n" + "else if (y >= 0 && m >= 0)\n" + "{v = new Date(y, m);}\n" + "else if (y >= 0)\n" + "{v = new Date(y);}\n" + "}return (v && (z || o))?\n" // favour UTC offset over GMT offset + " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset + ";}"; Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$"); eval(code); }; // private Date.formatCodeToRegex = function(character, currentGroup) { switch (character) { case "D": return {g:0, c:null, s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"}; case "j": return {g:1, c:"d = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{1,2})"}; // day of month without leading zeroes case "d": return {g:1, c:"d = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; // day of month with leading zeroes case "l": return {g:0, c:null, s:"(?:" + Date.dayNames.join("|") + ")"}; case "S": return {g:0, c:null, s:"(?:st|nd|rd|th)"}; case "w": return {g:0, c:null, s:"\\d"}; case "z": return {g:0, c:null, s:"(?:\\d{1,3})"}; case "W": return {g:0, c:null, s:"(?:\\d{2})"}; case "F": return {g:1, c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n", s:"(" + Date.monthNames.join("|") + ")"}; case "M": return {g:1, c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n", s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"}; case "n": return {g:1, c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros case "m": return {g:1, c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros case "t": return {g:0, c:null, s:"\\d{1,2}"}; case "L": return {g:0, c:null, s:"(?:1|0)"}; case "Y": return {g:1, c:"y = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{4})"}; case "y": return {g:1, c:"var ty = parseInt(results[" + currentGroup + "], 10);\n" + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", s:"(\\d{1,2})"}; case "a": return {g:1, c:"if (results[" + currentGroup + "] == 'am') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}", s:"(am|pm)"}; case "A": return {g:1, c:"if (results[" + currentGroup + "] == 'AM') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}", s:"(AM|PM)"}; case "g": case "G": return {g:1, c:"h = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes case "h": case "H": return {g:1, c:"h = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes case "i": return {g:1, c:"i = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "s": return {g:1, c:"s = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "O": return {g:1, c:[ "o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", // get + / - sign "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also) "var mn = o.substring(3,5) % 60;\n", // get minutes "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n" ].join(""), s:"([+\-]\\d{4})"}; case "T": return {g:0, c:null, s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars case "Z": return {g:1, c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400 + "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n", s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset default: return {g:0, c:null, s:String.escape(character)}; } }; /** * 返回当前所在时区的缩写(等同于指定输出格式“T”)。 * @return {String} 时区缩写(例如:“CST”) */ Date.prototype.getTimezone = function() { return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1"); }; /** * 返回 GMT 到当前日期的偏移量(等同于指定输出格式“O”)。 * @return {String} 以“+”或“-”加上4位字符表示的偏移量(例如:“-0600”) */ Date.prototype.getGMTOffset = function() { return (this.getTimezoneOffset() > 0 ? "-" : "+") + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0") + String.leftPad(this.getTimezoneOffset() % 60, 2, "0"); }; /** * 返回当前年份中天数的数值,已经根据闰年调整过。 * @return {Number} 0 到 365(闰年时为 366) */ Date.prototype.getDayOfYear = function() { var num = 0; Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; for (var i = 0; i < this.getMonth(); ++i) { num += Date.daysInMonth[i]; } return num + this.getDate() - 1; }; /** * 返回当前的星期数(等同于指定输出格式“W”)。 * @return {String} “00”~“52” */ Date.prototype.getWeekOfYear = function() { // Skip to Thursday of this week var now = this.getDayOfYear() + (4 - this.getDay()); // Find the first Thursday of the year var jan1 = new Date(this.getFullYear(), 0, 1); var then = (7 - jan1.getDay() + 4); return String.leftPad(((now - then) / 7) + 1, 2, "0"); }; /** * 返回当前日期是否闰年。 * @return {Boolean} 闰年为“true”,平年为“false” */ Date.prototype.isLeapYear = function() { var year = this.getFullYear(); return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); }; /** * 返回当前月份第一天的数值,已经根据闰年调整过。 * 返回值为以数字表示的一周中的第几天(0~6) * 可以与数组 dayNames (译者注:此处原文为“{@link #monthNames}”。)一起使用来表示当天的星期。 * 例子: *<pre><code> var dt = new Date('1/10/2007'); document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //输出: 'Monday' </code></pre> * @return {Number} 一周中的天数(0~6) */ Date.prototype.getFirstDayOfMonth = function() { var day = (this.getDay() - (this.getDate() - 1)) % 7; return (day < 0) ? (day + 7) : day; }; /** * 返回当前月份最后一天的数值,已经根据闰年调整过。 * 返回值为以数字表示的一周中的第几天(0~6) * 可以与数组 dayNames (译者注:此处原文为“{@link #monthNames}”。)一起使用来表示当天的星期。 * 例子: *<pre><code> var dt = new Date('1/10/2007'); document.write(Date.dayNames[dt.getLastDayOfMonth()]); //输出: 'Monday' </code></pre> * @return {Number} 一周中的天数(0~6) */ Date.prototype.getLastDayOfMonth = function() { var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7; return (day < 0) ? (day + 7) : day; }; /** * 返回当前月份第一天的日期对象。 * @return {Date} */ Date.prototype.getFirstDateOfMonth = function() { return new Date(this.getFullYear(), this.getMonth(), 1); }; /** * 返回当前月份中最后一天的日期对象。 * @return {Date} */ Date.prototype.getLastDateOfMonth = function() { return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth()); }; /** * 返回当前月份中天数的数值,已经根据闰年调整过。 * @return {Number} 月份中的天数 */ Date.prototype.getDaysInMonth = function() { Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; return Date.daysInMonth[this.getMonth()]; }; /** * 返回当天的英文单词的后缀(等同于指定输出格式“S”)。 * @return {String} 'st, 'nd', 'rd' or 'th' */ Date.prototype.getSuffix = function() { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }; // private Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; /** * 月份名称的数组。 * 覆盖此属性即可实现日期对象的本地化,例如: * Date.monthNames = ['一月', '二月', '三月' ...]; * @type Array * @static */ Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; /** * 天数名称的数组。 * 覆盖此属性即可实现日期对象的本地化,例如: * Date.dayNames = ['日', '一', '二' ...]; * @type Array * @static */ Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // private Date.y2kYear = 50; // private Date.monthNumbers = { Jan:0, Feb:1, Mar:2, Apr:3, May:4, Jun:5, Jul:6, Aug:7, Sep:8, Oct:9, Nov:10, Dec:11}; /** * 创建并返回一个新的与原来一模一样的日期实例。 * 新的实例通过地址复制,因此新的实例的变量发生改变后,原来的实例的变量也会随之改变。 * 当你想要创建一个新的变量而又不希望对原始实例产生影响时,你应该复制一个原始的实例。 * 正确复制一个日期实例的例子: * <pre><code> //错误的方式: var orig = new Date('10/1/2006'); var copy = orig; copy.setDate(5); document.write(orig); //返回 'Thu Oct 05 2006'! //正确的方式: var orig = new Date('10/1/2006'); var copy = orig.clone(); copy.setDate(5); document.write(orig); //返回 'Thu Oct 01 2006' </code></pre> * @return {Date} 新的日期实例 */ Date.prototype.clone = function() { return new Date(this.getTime()); }; /** * 清除日期对象中的所有时间信息。 @param {Boolean} 值为“true”时复制一个当前日期实例,清除时间信息后返回。 @return {Date} 实例本身或复制的实例 */ Date.prototype.clearTime = function(clone){ if(clone){ return this.clone().clearTime(); } this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); return this; }; // private // safari setMonth is broken if(Ext.isSafari){ Date.brokenSetMonth = Date.prototype.setMonth; Date.prototype.setMonth = function(num){ if(num <= -1){ var n = Math.ceil(-num); var back_year = Math.ceil(n/12); var month = (n % 12) ? 12 - n % 12 : 0 ; this.setFullYear(this.getFullYear() - back_year); return Date.brokenSetMonth.call(this, month); } else { return Date.brokenSetMonth.apply(this, arguments); } }; } /** Date interval constant @static @type String */ Date.MILLI = "ms"; /** Date interval constant @static @type String */ Date.SECOND = "s"; /** Date interval constant @static @type String */ Date.MINUTE = "mi"; /** Date interval constant @static @type String */ Date.HOUR = "h"; /** Date interval constant @static @type String */ Date.DAY = "d"; /** Date interval constant @static @type String */ Date.MONTH = "mo"; /** Date interval constant @static @type String */ Date.YEAR = "y"; /** * 一个便利的日期运算的方法。 * 这个方法不会改变日期实例本身,而是返回一个以运算结果创建的日期对象新实例。 * 例如: * <pre><code> //基本用法: var dt = new Date('10/29/2006').add(Date.DAY, 5); document.write(dt); //返回 'Fri Oct 06 2006 00:00:00' //负数的值将会减去数值: var dt2 = new Date('10/1/2006').add(Date.DAY, -5); document.write(dt2); //返回 'Tue Sep 26 2006 00:00:00' //你甚至可以连续多次调用此方法 var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30); document.write(dt3); //返回 'Fri Oct 06 2006 07:30:00' </code></pre> * * @param {String} interval 一个合法的日期间隔常数 * @param {Number} value 修改的数值 * @return {Date} 新的日期对象实例 */ Date.prototype.add = function(interval, value){ var d = this.clone(); if (!interval || value === 0) return d; switch(interval.toLowerCase()){ case Date.MILLI: d.setMilliseconds(this.getMilliseconds() + value); break; case Date.SECOND: d.setSeconds(this.getSeconds() + value); break; case Date.MINUTE: d.setMinutes(this.getMinutes() + value); break; case Date.HOUR: d.setHours(this.getHours() + value); break; case Date.DAY: d.setDate(this.getDate() + value); break; case Date.MONTH: var day = this.getDate(); if(day > 28){ day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate()); } d.setDate(day); d.setMonth(this.getMonth() + value); break; case Date.YEAR: d.setFullYear(this.getFullYear() + value); break; } return d; }; /** * 返回date对象创建时间与现在时间的时间差,单位为毫秒 * (译注:)例:var date = new Date(); * var x=0; * while(x<2){ * alert('x'); * x++; * } * * var theTime = date.getElapsed(); * alert(theTime); //将显示间隔的时间,单位是毫秒 * * @param {Date} date (该参数可选) 默认时间是now * @return {Number} 间隔毫秒数 * @member Date getElapsed */ Date.prototype.getElapsed = function(date) { return Math.abs((date || new Date()).getTime()-this.getTime()); };
JavaScript
/** * @class Ext.util.TaskRunner * 提供以多线程的方式执行一个或多个任务的能力。通常情况下,你可以使用 {@link Ext.TaskMgr} 来代替,但是如果需要你可以创建一个独立的 TaskRunner 实例。 * 任意个独立的任务都可以在任何时候开始,并彼此独立地运行。使用示例: * <pre><code> // 开始一个简单的每秒更新 DIV 的定时任务 var task = { run: function(){ Ext.fly('clock').update(new Date().format('g:i:s A')); }, interval: 1000 //1 second } var runner = new Ext.util.TaskRunner(); runner.start(task); </code></pre> * @constructor * @param {Number} interval (可选项) The minimum precision in milliseconds supported by this TaskRunner instance * @param {Number} interval (可选项) 以毫秒表示的该 TaskRunner 实例所支持的最低精度 * (默认为 10) */ Ext.util.TaskRunner = function(interval){ interval = interval || 10; var tasks = [], removeQueue = []; var id = 0; var running = false; // private var stopThread = function(){ running = false; clearInterval(id); id = 0; }; // private var startThread = function(){ if(!running){ running = true; id = setInterval(runTasks, interval); } }; // private var removeTask = function(t){ removeQueue.push(t); if(t.onStop){ t.onStop.apply(t.scope || t); } }; // private var runTasks = function(){ if(removeQueue.length > 0){ for(var i = 0, len = removeQueue.length; i < len; i++){ tasks.remove(removeQueue[i]); } removeQueue = []; if(tasks.length < 1){ stopThread(); return; } } var now = new Date().getTime(); for(var i = 0, len = tasks.length; i < len; ++i){ var t = tasks[i]; var itime = now - t.taskRunTime; if(t.interval <= itime){ var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]); t.taskRunTime = now; if(rt === false || t.taskRunCount === t.repeat){ removeTask(t); return; } } if(t.duration && t.duration <= (now - t.taskStartTime)){ removeTask(t); } } }; /** * @member Ext.util.TaskRunner * @method start * 开始一个新任务。 * @param {Object} task 一个任务配置项,支持的属性如下:<ul> * <li><code>run</code> : Function<div class="sub-desc">任务每次运行时执行的函数。 * 该函数将在每次间隔后被调用并传入 <code>args</code> 参数,如果该项被指定了的话。 * 如果需要特定的作用域,请保证设置了 <code>scope</scope> 参数。</div></li> * <li><code>interval</code> : Number<div class="sub-desc">以毫秒为单位表示的任务执行的间隔。</div></li> * <li><code>args</code> : Array<div class="sub-desc">(可选项) 一个由传递给 <code>run</code> 所指定的函数的参数组成的数组。</div></li> * <li><code>scope</code> : Object<div class="sub-desc">(可选项) <code>run</code> 指定的函数的作用域。</div></li> * <li><code>duration</code> : Number<div class="sub-desc">(可选项) 任务在自动停止前的执行时长(默认为无限制)。</div></li> * <li><code>repeat</code> : Number<div class="sub-desc">(可选项) 任务在自动停止前的执行次数(默认为无数次)。</div></li> * </ul> * @return {Object} 该任务 */ this.start = function(task){ tasks.push(task); task.taskStartTime = new Date().getTime(); task.taskRunTime = 0; task.taskRunCount = 0; startThread(); return task; }; /** * @member Ext.util.TaskRunner * @method stop * 停止一个运行中的任务。 * @param {Object} task 要停止的任务 * @return {Object} 该任务 */ this.stop = function(task){ removeTask(task); return task; }; /** * @member Ext.util.TaskRunner * @method stopAll * 停止所有当前运行的任务。 */ this.stopAll = function(){ stopThread(); for(var i = 0, len = tasks.length; i < len; i++){ if(tasks[i].onStop){ tasks[i].onStop(); } } tasks = []; removeQueue = []; }; }; /** * @class Ext.TaskMgr * 一个静态的 {@link Ext.util.TaskRunner} 实例,可以用来开始和停止任意任务。可查看 {@link Ext.util.TaskRunner} 中支持的方法和任务配置项属性。 * <pre><code> // 开始一个简单的每秒更新 DIV 的定时任务 var task = { run: function(){ Ext.fly('clock').update(new Date().format('g:i:s A')); }, interval: 1000 //1 秒 } Ext.TaskMgr.start(task); </code></pre> * @singleton */ Ext.TaskMgr = new Ext.util.TaskRunner();
JavaScript
/** @class Ext.util.ClickRepeater @extends Ext.util.Observable 适用于任何元素的包装类。当鼠标按下时触发一个“单击”的事件。 可在配置项中设置间隔时间,默认是20毫秒。 可选地,按下的过程中可能会加入一个CSS类。 @cfg {Mixed} el 该元素作为一个按钮。 @cfg {Number} delay 开始触发事件重复之前的初始延迟,类似自动重复键延时。 @cfg {Number} interval “fire”事件之间的间隔时间。默认20ms。 @cfg {String} pressClass 当元素被按下时所指定的CSS样式。 @cfg {Boolean} accelerate True:如果要自动重复开始时缓慢,然后加速的话,设置为TRUE。 "interval" 和 "delay"将会被忽略。 @cfg {Boolean} preventDefault True:预防默认的单击事件 @cfg {Boolean} stopDefault True:停止默认的单击事件 @constructor @param {String/HTMLElement/Element} el 侦听的函数 @param {Object} config */ Ext.util.ClickRepeater = function(el, config) { this.el = Ext.get(el); this.el.unselectable(); Ext.apply(this, config); this.addEvents( /** * @event mousedown * Fires when the mouse button is depressed. * @param {Ext.util.ClickRepeater} this */ "mousedown", /** * @event click * Fires on a specified interval during the time the element is pressed. * @param {Ext.util.ClickRepeater} this */ "click", /** * @event mouseup * Fires when the mouse key is released. * @param {Ext.util.ClickRepeater} this */ "mouseup" ); this.el.on("mousedown", this.handleMouseDown, this); if(this.preventDefault || this.stopDefault){ this.el.on("click", function(e){ if(this.preventDefault){ e.preventDefault(); } if(this.stopDefault){ e.stopEvent(); } }, this); } // allow inline handler if(this.handler){ this.on("click", this.handler, this.scope || this); } Ext.util.ClickRepeater.superclass.constructor.call(this); }; Ext.extend(Ext.util.ClickRepeater, Ext.util.Observable, { interval : 20, delay: 250, preventDefault : true, stopDefault : false, timer : 0, // private handleMouseDown : function(){ clearTimeout(this.timer); this.el.blur(); if(this.pressClass){ this.el.addClass(this.pressClass); } this.mousedownTime = new Date(); Ext.getDoc().on("mouseup", this.handleMouseUp, this); this.el.on("mouseout", this.handleMouseOut, this); this.fireEvent("mousedown", this); this.fireEvent("click", this); // Do not honor delay or interval if acceleration wanted. if (this.accelerate) { this.delay = 400; } this.timer = this.click.defer(this.delay || this.interval, this); }, // private click : function(){ this.fireEvent("click", this); this.timer = this.click.defer(this.accelerate ? this.easeOutExpo(this.mousedownTime.getElapsed(), 400, -390, 12000) : this.interval, this); }, easeOutExpo : function (t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, // private handleMouseOut : function(){ clearTimeout(this.timer); if(this.pressClass){ this.el.removeClass(this.pressClass); } this.el.on("mouseover", this.handleMouseReturn, this); }, // private handleMouseReturn : function(){ this.el.un("mouseover", this.handleMouseReturn); if(this.pressClass){ this.el.addClass(this.pressClass); } this.click(); }, // private handleMouseUp : function(){ clearTimeout(this.timer); this.el.un("mouseover", this.handleMouseReturn); this.el.un("mouseout", this.handleMouseOut); Ext.getDoc().un("mouseup", this.handleMouseUp); this.el.removeClass(this.pressClass); this.fireEvent("mouseup", this); } });
JavaScript
/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.3 (11-JUL-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.3'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { /*global console */ if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {}; opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {}; $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animInDelay = opts.animInDelay, animOutDelay = opts.animOutDelay; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.delay(animInDelay).animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.delay(animOutDelay).animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animInDelay: 0, // allows delay before next slide transitions in animOut: null, // properties that define how the slide animates out animOutDelay: 0, // allows delay before current slide transitions out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);
JavaScript
/* * Inline Form Validation Engine 2.6.1, jQuery plugin * * Copyright(c) 2010, Cedric Dugas * http://www.position-absolute.com * * 2.0 Rewrite by Olivier Refalo * http://www.crionics.com * * Form validation engine allowing custom regex rules to be added. * Licensed under the MIT License */ (function($) { "use strict"; var methods = { /** * Kind of the constructor, called before any action * @param {Map} user options */ init: function(options) { var form = this; if (!form.data('jqv') || form.data('jqv') == null ) { options = methods._saveOptions(form, options); // bind all formError elements to close on click $(".formError").live("click", function() { $(this).fadeOut(150, function() { // remove prompt once invisible $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); }); } return this; }, /** * Attachs jQuery.validationEngine to form.submit and field.blur events * Takes an optional params: a list of options * ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"}); */ attach: function(userOptions) { if(!$(this).is("form")) { alert("Sorry, jqv.attach() only applies to a form"); return this; } var form = this; var options; if(userOptions) options = methods._saveOptions(form, userOptions); else options = form.data('jqv'); options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class"; if (options.binded) { // bind fields form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox],["+options.validateAttribute+"*=validate][type=radio]").bind("click", methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][class*=datepicker]").bind(options.validationEventTrigger,{"delay": 300}, methods._onFieldEvent); } if (options.autoPositionUpdate) { $(window).bind("resize", { "noAnimation": true, "formElem": form }, methods.updatePromptsPosition); } // bind form.submit form.bind("submit", methods._onSubmitEvent); return this; }, /** * Unregisters any bindings that may point to jQuery.validaitonEngine */ detach: function() { if(!$(this).is("form")) { alert("Sorry, jqv.detach() only applies to a form"); return this; } var form = this; var options = form.data('jqv'); // unbind fields form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox],[class*=validate][type=radio]").unbind("click", methods._onFieldEvent); // unbind form.submit form.unbind("submit", methods.onAjaxFormComplete); // unbind live fields (kill) form.find("["+options.validateAttribute+"*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent); form.find("["+options.validateAttribute+"*=validate][type=checkbox]").die("click", methods._onFieldEvent); // unbind form.submit form.die("submit", methods.onAjaxFormComplete); form.removeData('jqv'); if (options.autoPositionUpdate) $(window).unbind("resize", methods.updatePromptsPosition); return this; }, /** * Validates either a form or a list of fields, shows prompts accordingly. * Note: There is no ajax form validation with this method, only field ajax validation are evaluated * * @return true if the form validates, false if it fails */ validate: function() { var element = $(this); var valid = null; if(element.is("form") && !element.hasClass('validating')) { element.addClass('validating'); var options = element.data('jqv'); valid = methods._validateFields(this); // If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again setTimeout(function(){ element.removeClass('validating'); }, 100); if (valid && options.onFormSuccess) { options.onFormSuccess(); } else if (!valid && options.onFormFailure) { options.onFormFailure(); } } else if (element.is('form')) { element.removeClass('validating'); } else { // field validation var form = element.closest('form'); var options = form.data('jqv'); valid = methods._validateField(element, options); if (valid && options.onFieldSuccess) options.onFieldSuccess(); else if (options.onFieldFailure && options.InvalidFields.length > 0) { options.onFieldFailure(); } } return valid; }, /** * Redraw prompts position, useful when you change the DOM state when validating */ updatePromptsPosition: function(event) { if (event && this == window) { var form = event.data.formElem; var noAnimation = event.data.noAnimation; } else var form = $(this.closest('form')); var options = form.data('jqv'); // No option, take default one form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each(function(){ var field = $(this); if (options.prettySelect && field.is(":hidden")) field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix); var prompt = methods._getPrompt(field); var promptText = $(prompt).find(".formErrorContent").html(); if(prompt) methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation); }); return this; }, /** * Displays a prompt on a element. * Note that the element needs an id! * * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight */ showPrompt: function(promptText, type, promptPosition, showArrow) { var form = this.closest('form'); var options = form.data('jqv'); // No option, take default one if(!options) options = methods._saveOptions(this, options); if(promptPosition) options.promptPosition=promptPosition; options.showArrow = showArrow==true; methods._showPrompt(this, promptText, type, false, options); return this; }, /** * Closes form error prompts, CAN be invidual */ hide: function() { var form = $(this).closest('form'); var options = form.data('jqv'); var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3; var closingtag; if($(this).is("form")) { closingtag = "parentForm"+methods._getClassName($(this).attr("id")); } else { closingtag = methods._getClassName($(this).attr("id")) +"formError"; } $('.'+closingtag).fadeTo(fadeDuration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Closes all error prompts on the page */ hideAll: function() { var form = this; var options = form.data('jqv'); var duration = options ? options.fadeDuration:0.3; $('.formError').fadeTo(duration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Typically called when user exists a field using tab or a mouse click, triggers a field * validation */ _onFieldEvent: function(event) { var field = $(this); var form = field.closest('form'); var options = form.data('jqv'); options.eventTrigger = "field"; // validate the current field window.setTimeout(function() { methods._validateField(field, options); if (options.InvalidFields.length == 0 && options.onFieldSuccess) { options.onFieldSuccess(); } else if (options.InvalidFields.length > 0 && options.onFieldFailure) { options.onFieldFailure(); } }, (event.data) ? event.data.delay : 0); }, /** * Called when the form is submited, shows prompts accordingly * * @param {jqObject} * form * @return false if form submission needs to be cancelled */ _onSubmitEvent: function() { var form = $(this); var options = form.data('jqv'); options.eventTrigger = "submit"; // validate each field // (- skip field ajax validation, not necessary IF we will perform an ajax form validation) var r=methods._validateFields(form); if (r && options.ajaxFormValidation) { methods._validateFormWithAjax(form, options); // cancel form auto-submission - process with async call onAjaxFormComplete return false; } if(options.onValidationComplete) { // !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing return !!options.onValidationComplete(form, r); } return r; }, /** * Return true if the ajax field validations passed so far * @param {Object} options * @return true, is all ajax validation passed so far (remember ajax is async) */ _checkAjaxStatus: function(options) { var status = true; $.each(options.ajaxValidCache, function(key, value) { if (!value) { status = false; // break the each return false; } }); return status; }, /** * Return true if the ajax field is validated * @param {String} fieldid * @param {Object} options * @return true, if validation passed, false if false or doesn't exist */ _checkAjaxFieldStatus: function(fieldid, options) { return options.ajaxValidCache[fieldid] == true; }, /** * Validates form fields, shows prompts accordingly * * @param {jqObject} * form * @param {skipAjaxFieldValidation} * boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked * * @return true if form is valid, false if not, undefined if ajax form validation is done */ _validateFields: function(form) { var options = form.data('jqv'); // this variable is set to true if an error is found var errorFound = false; // Trigger hook, start validation form.trigger("jqv.form.validating"); // first, evaluate status of non ajax fields var first_err=null; form.find('['+options.validateAttribute+'*=validate]').not(":disabled").each( function() { var field = $(this); var names = []; if ($.inArray(field.attr('name'), names) < 0) { errorFound |= methods._validateField(field, options); if (errorFound && first_err==null) if (field.is(":hidden") && options.prettySelect) first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); else first_err=field; if (options.doNotShowAllErrosOnSubmit) return false; names.push(field.attr('name')); //if option set, stop checking validation rules after one error is found if(options.showOneMessage == true && errorFound){ return false; } } }); // second, check to see if all ajax calls completed ok // errorFound |= !methods._checkAjaxStatus(options); // third, check status and scroll the container accordingly form.trigger("jqv.form.result", [errorFound]); if (errorFound) { if (options.scroll) { var destination=first_err.offset().top; var fixleft = first_err.offset().left; //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType=options.promptPosition; if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1) positionType=positionType.substring(0,positionType.indexOf(":")); if (positionType!="bottomRight" && positionType!="bottomLeft") { var prompt_err= methods._getPrompt(first_err); if (prompt_err) { destination=prompt_err.offset().top; } } // get the position of the first error, there should be at least one, no need to check this //var destination = form.find(".formError:not('.greenPopup'):first").offset().top; if (options.isOverflown) { var overflowDIV = $(options.overflownDIV); if(!overflowDIV.length) return false; var scrollContainerScroll = overflowDIV.scrollTop(); var scrollContainerPos = -parseInt(overflowDIV.offset().top); destination += scrollContainerScroll + scrollContainerPos - 5; var scrollContainer = $(options.overflownDIV + ":not(:animated)"); scrollContainer.animate({ scrollTop: destination }, 1100, function(){ if(options.focusFirstField) first_err.focus(); }); } else { $("html, body").animate({ scrollTop: destination }, 1100, function(){ if(options.focusFirstField) first_err.focus(); }); $("html, body").animate({scrollLeft: fixleft},1100) } } else if(options.focusFirstField) first_err.focus(); return false; } return true; }, /** * This method is called to perform an ajax form validation. * During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true * * @param {jqObject} form * @param {Map} options */ _validateFormWithAjax: function(form, options) { var data = form.serialize(); var type = (options.ajaxFormMethod) ? options.ajaxFormMethod : "GET"; var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action"); var dataType = (options.dataType) ? options.dataType : "json"; $.ajax({ type: type, url: url, cache: false, dataType: dataType, data: data, form: form, methods: methods, options: options, beforeSend: function() { return options.onBeforeAjaxFormValidation(form, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { if ((dataType == "json") && (json !== true)) { // getting to this case doesn't necessary means that the form is invalid // the server may return green or closing prompt actions // this flag helps figuring it out var errorInForm=false; for (var i = 0; i < json.length; i++) { var value = json[i]; var errorFieldId = value[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { // promptText or selector var msg = value[2]; // if the field is valid if (value[1] == true) { if (msg == "" || !msg){ // if for some reason, status==true and error="", just close the prompt methods._closePrompt(errorField); } else { // the field is valid, but we are displaying a green prompt if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "pass", false, options, true); } } else { // the field is invalid, show the red error prompt errorInForm|=true; if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "", false, options, true); } } } options.onAjaxFormComplete(!errorInForm, form, json, options); } else options.onAjaxFormComplete(true, form, json, options); } }); }, /** * Validates field, shows prompts accordingly * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @param {Map} * user options * @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.) */ _validateField: function(field, options, skipAjaxValidation) { if (!field.attr("id")) { field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter); ++$.validationEngine.fieldIdCounter; } if (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden")) return false; var rulesParsing = field.attr(options.validateAttribute); var getRules = /validate\[(.*)\]/.exec(rulesParsing); if (!getRules) return false; var str = getRules[1]; var rules = str.split(/\[|,|\]/); // true if we ran the ajax validation, tells the logic to stop messing with prompts var isAjaxValidator = false; var fieldName = field.attr("name"); var promptText = ""; var promptType = ""; var required = false; var limitErrors = false; options.isError = false; options.showArrow = true; // If the programmer wants to limit the amount of error messages per field, if (options.maxErrorsPerField > 0) { limitErrors = true; } var form = $(field.closest("form")); // Fix for adding spaces in the rules for (var i = 0; i < rules.length; i++) { rules[i] = rules[i].replace(" ", ""); // Remove any parsing errors if (rules[i] === '') { delete rules[i]; } } for (var i = 0, field_errors = 0; i < rules.length; i++) { // If we are limiting errors, and have hit the max, break if (limitErrors && field_errors >= options.maxErrorsPerField) { // If we haven't hit a required yet, check to see if there is one in the validation rules for this // field and that it's index is greater or equal to our current index if (!required) { var have_required = $.inArray('required', rules); required = (have_required != -1 && have_required >= i); } break; } var errorMsg = undefined; switch (rules[i]) { case "required": required = true; errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required); break; case "custom": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom); break; case "groupRequired": // Check is its the first of group, if not, reload validation with first field // AND continue normal validation on present field var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]"; var firstOfGroup = form.find(classGroup).eq(0); if(firstOfGroup[0] != field[0]){ methods._validateField(firstOfGroup, options, skipAjaxValidation); options.showArrow = true; continue; } errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired); if(errorMsg) required = true; options.showArrow = false; break; case "ajax": // AJAX defaults to returning it's loading message errorMsg = methods._ajax(field, rules, i, options); if (errorMsg) { promptType = "load"; } break; case "minSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize); break; case "maxSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize); break; case "min": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min); break; case "max": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max); break; case "past": errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._past); break; case "future": errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._future); break; case "dateRange": var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateRange); } if (errorMsg) required = true; options.showArrow = false; break; case "dateTimeRange": var classGroup = "["+options.validateAttribute+"*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field,rules[i], rules, i, options, methods._dateTimeRange); } if (errorMsg) required = true; options.showArrow = false; break; case "maxCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox); break; case "minCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox); break; case "equals": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals); break; case "funcCall": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall); break; case "creditCard": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard); break; case "condRequired": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired); if (errorMsg !== undefined) { required = true; } break; default: } var end_validation = false; // If we were passed back an message object, check what the status was to determine what to do if (typeof errorMsg == "object") { switch (errorMsg.status) { case "_break": end_validation = true; break; // If we have an error message, set errorMsg to the error message case "_error": errorMsg = errorMsg.message; break; // If we want to throw an error, but not show a prompt, return early with true case "_error_no_prompt": return true; break; // Anything else we continue on default: break; } } // If it has been specified that validation should end now, break if (end_validation) { break; } // If we have a string, that means that we have an error, so add it to the error message. if (typeof errorMsg == 'string') { promptText += errorMsg + "<br/>"; options.isError = true; field_errors++; } } // If the rules required is not added, an empty field is not validated if(!required && field.val().length < 1) options.isError = false; // Hack for radio/checkbox group button, the validation go into the // first radio/checkbox of the group var fieldType = field.prop("type"); if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) { field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first")); options.showArrow = false; } if(field.is(":hidden") && options.prettySelect) { field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); } if (options.isError){ methods._showPrompt(field, promptText, promptType, false, options); }else{ if (!isAjaxValidator) methods._closePrompt(field); } if (!isAjaxValidator) { field.trigger("jqv.field.result", [field, options.isError, promptText]); } /* Record error */ var errindex = $.inArray(field[0], options.InvalidFields); if (errindex == -1) { if (options.isError) options.InvalidFields.push(field[0]); } else if (!options.isError) { options.InvalidFields.splice(errindex, 1); } methods._handleStatusCssClasses(field, options); return options.isError; }, /** * Handling css classes of fields indicating result of validation * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @private */ _handleStatusCssClasses: function(field, options) { /* remove all classes */ if(options.addSuccessCssClassToField) field.removeClass(options.addSuccessCssClassToField); if(options.addFailureCssClassToField) field.removeClass(options.addFailureCssClassToField); /* Add classes */ if (options.addSuccessCssClassToField && !options.isError) field.addClass(options.addSuccessCssClassToField); if (options.addFailureCssClassToField && options.isError) field.addClass(options.addFailureCssClassToField); }, /******************** * _getErrorMessage * * @param form * @param field * @param rule * @param rules * @param i * @param options * @param originalValidationMethod * @return {*} * @private */ _getErrorMessage:function (form, field, rule, rules, i, options, originalValidationMethod) { // If we are using the custon validation type, build the index for the rule. // Otherwise if we are doing a function call, make the call and return the object // that is passed back. var beforeChangeRule = rule; if (rule == "custom") { var custom_validation_type_index = jQuery.inArray(rule, rules)+ 1; var custom_validation_type = rules[custom_validation_type_index]; rule = "custom[" + custom_validation_type + "]"; } var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class"); var element_classes_array = element_classes.split(" "); // Call the original validation method. If we are dealing with dates or checkboxes, also pass the form var errorMsg; if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") { errorMsg = originalValidationMethod(form, field, rules, i, options); } else { errorMsg = originalValidationMethod(field, rules, i, options); } // If the original validation method returned an error and we have a custom error message, // return the custom message instead. Otherwise return the original error message. if (errorMsg != undefined) { var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, beforeChangeRule, options); if (custom_message) errorMsg = custom_message; } return errorMsg; }, _getCustomErrorMessage:function (field, classes, rule, options) { var custom_message = false; var validityProp = methods._validityProp[rule]; // If there is a validityProp for this rule, check to see if the field has an attribute for it if (validityProp != undefined) { custom_message = field.attr("data-errormessage-"+validityProp); // If there was an error message for it, return the message if (custom_message != undefined) return custom_message; } custom_message = field.attr("data-errormessage"); // If there is an inline custom error message, return it if (custom_message != undefined) return custom_message; var id = '#' + field.attr("id"); // If we have custom messages for the element's id, get the message for the rule from the id. // Otherwise, if we have custom messages for the element's classes, use the first class message we find instead. if (typeof options.custom_error_messages[id] != "undefined" && typeof options.custom_error_messages[id][rule] != "undefined" ) { custom_message = options.custom_error_messages[id][rule]['message']; } else if (classes.length > 0) { for (var i = 0; i < classes.length && classes.length > 0; i++) { var element_class = "." + classes[i]; if (typeof options.custom_error_messages[element_class] != "undefined" && typeof options.custom_error_messages[element_class][rule] != "undefined") { custom_message = options.custom_error_messages[element_class][rule]['message']; break; } } } if (!custom_message && typeof options.custom_error_messages[rule] != "undefined" && typeof options.custom_error_messages[rule]['message'] != "undefined"){ custom_message = options.custom_error_messages[rule]['message']; } return custom_message; }, _validityProp: { "required": "value-missing", "custom": "custom-error", "groupRequired": "value-missing", "ajax": "custom-error", "minSize": "range-underflow", "maxSize": "range-overflow", "min": "range-underflow", "max": "range-overflow", "past": "type-mismatch", "future": "type-mismatch", "dateRange": "type-mismatch", "dateTimeRange": "type-mismatch", "maxCheckbox": "range-overflow", "minCheckbox": "range-underflow", "equals": "pattern-mismatch", "funcCall": "custom-error", "creditCard": "pattern-mismatch", "condRequired": "value-missing" }, /** * Required validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @param {bool} condRequired flag when method is used for internal purpose in condRequired check * @return an error string if validation failed */ _required: function(field, rules, i, options, condRequired) { switch (field.prop("type")) { case "text": case "password": case "textarea": case "file": case "select-one": case "select-multiple": default: if (! $.trim(field.val()) || field.val() == field.attr("data-validation-placeholder") || field.val() == field.attr("placeholder")) return options.allrules[rules[i]].alertText; break; case "radio": case "checkbox": // new validation style to only check dependent field if (condRequired) { if (!field.attr('checked')) { return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } // old validation style var form = field.closest("form"); var name = field.attr("name"); if (form.find("input[name='" + name + "']:checked").size() == 0) { if (form.find("input[name='" + name + "']:visible").size() == 1) return options.allrules[rules[i]].alertTextCheckboxe; else return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } }, /** * Validate that 1 from the group field is required * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _groupRequired: function(field, rules, i, options) { var classGroup = "["+options.validateAttribute+"*=" +rules[i + 1] +"]"; var isValid = false; // Check all fields from the group field.closest("form").find(classGroup).each(function(){ if(!methods._required($(this), rules, i, options)){ isValid = true; return false; } }); if(!isValid) { return options.allrules[rules[i]].alertText; } }, /** * Validate rules * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _custom: function(field, rules, i, options) { var customRule = rules[i + 1]; var rule = options.allrules[customRule]; var fn; if(!rule) { alert("jqv:custom rule not found - "+customRule); return; } if(rule["regex"]) { var ex=rule.regex; if(!ex) { alert("jqv:custom regex not found - "+customRule); return; } var pattern = new RegExp(ex); if (!pattern.test(field.val())) return options.allrules[customRule].alertText; } else if(rule["func"]) { fn = rule["func"]; if (typeof(fn) !== "function") { alert("jqv:custom parameter 'function' is no function - "+customRule); return; } if (!fn(field, rules, i, options)) return options.allrules[customRule].alertText; } else { alert("jqv:custom type not allowed "+customRule); return; } }, /** * Validate custom function outside of the engine scope * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _funcCall: function(field, rules, i, options) { var functionName = rules[i + 1]; var fn; if(functionName.indexOf('.') >-1) { var namespaces = functionName.split('.'); var scope = window; while(namespaces.length) { scope = scope[namespaces.shift()]; } fn = scope; } else fn = window[functionName] || options.customFunctions[functionName]; if (typeof(fn) == 'function') return fn(field, rules, i, options); }, /** * Field match * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _equals: function(field, rules, i, options) { var equalsField = rules[i + 1]; if (field.val() != $("#" + equalsField).val()) return options.allrules.equals.alertText; }, /** * Check the maximum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxSize: function(field, rules, i, options) { var max = rules[i + 1]; var len = field.val().length; if (len > max) { var rule = options.allrules.maxSize; return rule.alertText + max + rule.alertText2; } }, /** * Check the minimum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minSize: function(field, rules, i, options) { var min = rules[i + 1]; var len = field.val().length; if (len < min) { var rule = options.allrules.minSize; return rule.alertText + min + rule.alertText2; } }, /** * Check number minimum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _min: function(field, rules, i, options) { var min = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len < min) { var rule = options.allrules.min; if (rule.alertText2) return rule.alertText + min + rule.alertText2; return rule.alertText + min; } }, /** * Check number maximum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _max: function(field, rules, i, options) { var max = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len >max ) { var rule = options.allrules.max; if (rule.alertText2) return rule.alertText + max + rule.alertText2; //orefalo: to review, also do the translations return rule.alertText + max; } }, /** * Checks date is in the past * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _past: function(form, field, rules, i, options) { var p=rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate > pdate ) { var rule = options.allrules.past; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks date is in the future * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _future: function(form, field, rules, i, options) { var p=rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate < pdate ) { var rule = options.allrules.future; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks if valid date * * @param {string} date string * @return a bool based on determination of valid date */ _isDate: function (value) { var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/); return dateRegEx.test(value); }, /** * Checks if valid date time * * @param {string} date string * @return a bool based on determination of valid date time */ _isDateTime: function (value){ var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/); return dateTimeRegEx.test(value); }, //Checks if the start date is before the end date //returns true if end is later than start _dateCompare: function (start, end) { return (new Date(start.toString()) < new Date(end.toString())); }, /** * Checks date range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateRange: function (field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Checks date time range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateTimeRange: function (field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Max number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize > nbCheck) { options.showArrow = false; if (options.allrules.maxCheckbox.alertText2) return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2; return options.allrules.maxCheckbox.alertText; } }, /** * Min number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize < nbCheck) { options.showArrow = false; return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2; } }, /** * Checks that it is a valid credit card number according to the * Luhn checksum algorithm. * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _creditCard: function(field, rules, i, options) { //spaces and dashes may be valid characters, but must be stripped to calculate the checksum. var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, ''); var numDigits = cardNumber.length; if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) { var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String(); do { digit = parseInt(cardNumber.charAt(i)); luhn += (pos++ % 2 == 0) ? digit * 2 : digit; } while (--i >= 0) for (i = 0; i < luhn.length; i++) { sum += parseInt(luhn.charAt(i)); } valid = sum % 10 == 0; } if (!valid) return options.allrules.creditCard.alertText; }, /** * Ajax field validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return nothing! the ajax validator handles the prompts itself */ _ajax: function(field, rules, i, options) { var errorSelector = rules[i + 1]; var rule = options.allrules[errorSelector]; var extraData = rule.extraData; var extraDataDynamic = rule.extraDataDynamic; var data = { "fieldId" : field.attr("id"), "fieldValue" : field.val() }; if (typeof extraData === "object") { $.extend(data, extraData); } else if (typeof extraData === "string") { var tempData = extraData.split("&"); for(var i = 0; i < tempData.length; i++) { var values = tempData[i].split("="); if (values[0] && values[0]) { data[values[0]] = values[1]; } } } if (extraDataDynamic) { var tmpData = []; var domIds = String(extraDataDynamic).split(","); for (var i = 0; i < domIds.length; i++) { var id = domIds[i]; if ($(id).length) { var inputValue = field.closest("form").find(id).val(); var keyValue = id.replace('#', '') + '=' + escape(inputValue); data[id.replace('#', '')] = inputValue; } } } // If a field change event triggered this we want to clear the cache for this ID if (options.eventTrigger == "field") { delete(options.ajaxValidCache[field.attr("id")]); } // If there is an error or if the the field is already validated, do not re-execute AJAX if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) { $.ajax({ type: options.ajaxFormValidationMethod, url: rule.url, cache: false, dataType: "json", data: data, field: field, rule: rule, methods: methods, options: options, beforeSend: function() {}, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json[0]; //var errorField = $($("#" + errorFieldId)[0]); var errorField = $("#"+ errorFieldId).eq(0); // make sure we found the element if (errorField.length == 1) { var status = json[1]; // read the optional msg from the server var msg = json[2]; if (!status) { // Houston we got a problem - display an red prompt options.ajaxValidCache[errorFieldId] = false; options.isError = true; // resolve the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) { msg = txt; } } } else msg = rule.alertText; methods._showPrompt(errorField, msg, "", true, options); } else { options.ajaxValidCache[errorFieldId] = true; // resolves the msg prompt if(msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) { msg = txt; } } } else msg = rule.alertTextOk; // see if we should display a green prompt if (msg) methods._showPrompt(errorField, msg, "pass", true, options); else methods._closePrompt(errorField); // If a submit form triggered this, we want to re-submit the form if (options.eventTrigger == "submit") field.closest("form").submit(); } } errorField.trigger("jqv.field.result", [errorField, options.isError, msg]); } }); return rule.alertTextLoad; } }, /** * Common method to handle ajax errors * * @param {Object} data * @param {Object} transport */ _ajaxError: function(data, transport) { if(data.status == 0 && transport == null) alert("The page is not served from a server! ajax call failed"); else if(typeof console != "undefined") console.log("Ajax error: " + data.status + " " + transport); }, /** * date -> string * * @param {Object} date */ _dateToString: function(date) { return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); }, /** * Parses an ISO date * @param {String} d */ _parseDate: function(d) { var dateParts = d.split("-"); if(dateParts==d) dateParts = d.split("/"); return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]); }, /** * Builds or updates a prompt with the given information * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) { var prompt = methods._getPrompt(field); // The ajax submit errors are not see has an error in the form, // When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time // Because no error was found befor submitting if(ajaxform) prompt = false; if (prompt) methods._updatePrompt(field, prompt, promptText, type, ajaxed, options); else methods._buildPrompt(field, promptText, type, ajaxed, options); }, /** * Builds and shades a prompt for the given field. * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _buildPrompt: function(field, promptText, type, ajaxed, options) { // create the prompt var prompt = $('<div>'); prompt.addClass(methods._getClassName(field.attr("id")) + "formError"); // add a class name to identify the parent form of the prompt prompt.addClass("parentForm"+methods._getClassName(field.parents('form').attr("id"))); prompt.addClass("formError"); switch (type) { case "pass": prompt.addClass("greenPopup"); break; case "load": prompt.addClass("blackPopup"); break; default: /* it has error */ //alert("unknown popup type:"+type); } if (ajaxed) prompt.addClass("ajaxed"); // create the prompt content var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt); // create the css arrow pointing at the field // note that there is no triangle on max-checkbox and radio if (options.showArrow) { var arrow = $('<div>').addClass("formErrorArrow"); //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType=field.data("promptPosition") || options.promptPosition; if (typeof(positionType)=='string') { var pos=positionType.indexOf(":"); if(pos!=-1) positionType=positionType.substring(0,pos); } switch (positionType) { case "bottomLeft": case "bottomRight": prompt.find(".formErrorContent").before(arrow); arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); break; case "topLeft": case "topRight": arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); prompt.append(arrow); break; } } // Modify z-indexes for jquery ui if (field.closest('.ui-dialog').length) prompt.addClass('formErrorInsideDialog'); prompt.css({ "opacity": 0, 'position':'absolute' }); field.before(prompt); var pos = methods._calculatePosition(field, prompt, options); prompt.css({ "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize, "opacity": 0 }).data("callerField", field); if (options.autoHidePrompt) { setTimeout(function(){ prompt.animate({ "opacity": 0 },function(){ prompt.closest('.formErrorOuter').remove(); prompt.remove(); }); }, options.autoHideDelay); } return prompt.animate({ "opacity": 0.87 }); }, /** * Updates the prompt text field - the field for which the prompt * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) { if (prompt) { if (typeof type !== "undefined") { if (type == "pass") prompt.addClass("greenPopup"); else prompt.removeClass("greenPopup"); if (type == "load") prompt.addClass("blackPopup"); else prompt.removeClass("blackPopup"); } if (ajaxed) prompt.addClass("ajaxed"); else prompt.removeClass("ajaxed"); prompt.find(".formErrorContent").html(promptText); var pos = methods._calculatePosition(field, prompt, options); var css = {"top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize}; if (noAnimation) prompt.css(css); else prompt.animate(css); } }, /** * Closes the prompt associated with the given field * * @param {jqObject} * field */ _closePrompt: function(field) { var prompt = methods._getPrompt(field); if (prompt) prompt.fadeTo("fast", 0, function() { prompt.parent('.formErrorOuter').remove(); prompt.remove(); }); }, closePrompt: function(field) { return methods._closePrompt(field); }, /** * Returns the error prompt matching the field if any * * @param {jqObject} * field * @return undefined or the error prompt (jqObject) */ _getPrompt: function(field) { var formId = $(field).closest('form').attr('id'); var className = methods._getClassName(field.attr("id")) + "formError"; var match = $("." + methods._escapeExpression(className) + '.parentForm' + formId)[0]; if (match) return $(match); }, /** * Returns the escapade classname * * @param {selector} * className */ _escapeExpression: function (selector) { return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1"); }, /** * returns true if we are in a RTLed document * * @param {jqObject} field */ isRTL: function(field) { var $document = $(document); var $body = $('body'); var rtl = (field && field.hasClass('rtl')) || (field && (field.attr('dir') || '').toLowerCase()==='rtl') || $document.hasClass('rtl') || ($document.attr('dir') || '').toLowerCase()==='rtl' || $body.hasClass('rtl') || ($body.attr('dir') || '').toLowerCase()==='rtl'; return Boolean(rtl); }, /** * Calculates prompt position * * @param {jqObject} * field * @param {jqObject} * the prompt * @param {Map} * options * @return positions */ _calculatePosition: function (field, promptElmt, options) { var promptTopPosition, promptleftPosition, marginTopSize; var fieldWidth = field.width(); var fieldLeft = field.position().left; var fieldTop = field.position().top; var fieldHeight = field.height(); var promptHeight = promptElmt.height(); // is the form contained in an overflown container? promptTopPosition = promptleftPosition = 0; // compensation for the arrow marginTopSize = -promptHeight; //prompt positioning adjustment support //now you can adjust prompt position //usage: positionType:Xshift,Yshift //for example: // bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally // topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top //You can use +pixels, - pixels. If no sign is provided than + is default. var positionType=field.data("promptPosition") || options.promptPosition; var shift1=""; var shift2=""; var shiftX=0; var shiftY=0; if (typeof(positionType)=='string') { //do we have any position adjustments ? if (positionType.indexOf(":")!=-1) { shift1=positionType.substring(positionType.indexOf(":")+1); positionType=positionType.substring(0,positionType.indexOf(":")); //if any advanced positioning will be needed (percents or something else) - parser should be added here //for now we use simple parseInt() //do we have second parameter? if (shift1.indexOf(",") !=-1) { shift2=shift1.substring(shift1.indexOf(",") +1); shift1=shift1.substring(0,shift1.indexOf(",")); shiftY=parseInt(shift2); if (isNaN(shiftY)) shiftY=0; }; shiftX=parseInt(shift1); if (isNaN(shift1)) shift1=0; }; }; switch (positionType) { default: case "topRight": promptleftPosition += fieldLeft + fieldWidth - 30; promptTopPosition += fieldTop; break; case "topLeft": promptTopPosition += fieldTop; promptleftPosition += fieldLeft + (field.outerWidth(true)/2); break; case "centerRight": promptTopPosition = fieldTop+4; marginTopSize = 0; promptleftPosition= fieldLeft + field.outerWidth(true)+5; break; case "centerLeft": promptleftPosition = fieldLeft - (promptElmt.width() + 2); promptTopPosition = fieldTop+4; marginTopSize = 0; break; case "bottomLeft": promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; promptleftPosition = fieldLeft; break; case "bottomRight": promptleftPosition = fieldLeft + fieldWidth - 30; promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; }; //apply adjusments if any promptleftPosition += shiftX; promptTopPosition += shiftY; return { "callerTopPosition": promptTopPosition + "px", "callerleftPosition": promptleftPosition + "px", "marginTopSize": marginTopSize + "px" }; }, /** * Saves the user options and variables in the form.data * * @param {jqObject} * form - the form where the user option should be saved * @param {Map} * options - the user options * @return the user options (extended from the defaults) */ _saveOptions: function(form, options) { // is there a language localisation ? if ($.validationEngineLanguage) var allRules = $.validationEngineLanguage.allRules; else $.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page"); // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 $.validationEngine.defaults.allrules = allRules; var userOptions = $.extend(true,{},$.validationEngine.defaults,options); form.data('jqv', userOptions); return userOptions; }, /** * Removes forbidden characters from class name * @param {String} className */ _getClassName: function(className) { if(className) return className.replace(/:/g, "_").replace(/\./g, "_"); }, /** * Escape special character for jQuery selector * http://totaldev.com/content/escaping-characters-get-valid-jquery-id * @param {String} selector */ _jqSelector: function(str){ return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); }, /** * Conditionally required field * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _condRequired: function(field, rules, i, options) { var idx, dependingField; for(idx = (i + 1); idx < rules.length; idx++) { dependingField = jQuery("#" + rules[idx]).first(); /* Use _required for determining wether dependingField has a value. * There is logic there for handling all field types, and default value; so we won't replicate that here * Indicate this special use by setting the last parameter to true so we only validate the dependingField on chackboxes and radio buttons (#462) */ if (dependingField.length && methods._required(dependingField, ["required"], 0, options, true) == undefined) { /* We now know any of the depending fields has a value, * so we can validate this field as per normal required code */ return methods._required(field, ["required"], 0, options); } } } }; /** * Plugin entry point. * You may pass an action as a parameter or a list of options. * if none, the init and attach methods are being called. * Remember: if you pass options, the attached method is NOT called automatically * * @param {String} * method (optional) action */ $.fn.validationEngine = function(method) { var form = $(this); if(!form[0]) return form; // stop here if the form does not exist if (typeof(method) == 'string' && method.charAt(0) != '_' && methods[method]) { // make sure init is called once if(method != "showPrompt" && method != "hide" && method != "hideAll") methods.init.apply(form); return methods[method].apply(form, Array.prototype.slice.call(arguments, 1)); } else if (typeof method == 'object' || !method) { // default constructor with or without arguments methods.init.apply(form, arguments); return methods.attach.apply(form); } else { $.error('Method ' + method + ' does not exist in jQuery.validationEngine'); } }; // LEAK GLOBAL OPTIONS $.validationEngine= {fieldIdCounter: 0,defaults:{ // Name of the event triggering field validation validationEventTrigger: "blur", // Automatically scroll viewport to the first error scroll: true, // Focus on the first input focusFirstField:true, // Opening box position, possible locations are: topLeft, // topRight, bottomLeft, centerRight, bottomRight promptPosition: "topRight", bindMethod:"bind", // internal, automatically set to true when it parse a _ajax rule inlineAjax: false, // if set to true, the form data is sent asynchronously via ajax to the form.action url (get) ajaxFormValidation: false, // The url to send the submit ajax validation (default to action) ajaxFormValidationURL: false, // HTTP method used for ajax validation ajaxFormValidationMethod: 'get', // Ajax form validation callback method: boolean onComplete(form, status, errors, options) // retuns false if the form.submit event needs to be canceled. onAjaxFormComplete: $.noop, // called right before the ajax call, may return false to cancel onBeforeAjaxFormValidation: $.noop, // Stops form from submitting and execute function assiciated with it onValidationComplete: false, // Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages doNotShowAllErrosOnSubmit: false, // Object where you store custom messages to override the default error messages custom_error_messages:{}, // true if you want to vind the input fields binded: true, // set to true, when the prompt arrow needs to be displayed showArrow: true, // did one of the validation fail ? kept global to stop further ajax validations isError: false, // Limit how many displayed errors a field can have maxErrorsPerField: false, // Caches field validation status, typically only bad status are created. // the array is used during ajax form validation to detect issues early and prevent an expensive submit ajaxValidCache: {}, // Auto update prompt position after window resize autoPositionUpdate: false, InvalidFields: [], onFieldSuccess: false, onFieldFailure: false, onFormSuccess: false, onFormFailure: false, addSuccessCssClassToField: false, addFailureCssClassToField: false, // Auto-hide prompt autoHidePrompt: false, // Delay before auto-hide autoHideDelay: 10000, // Fade out duration while hiding the validations fadeDuration: 0.3, // Use Prettify select library prettySelect: false, // Custom ID uses prefix usePrefix: "", // Custom ID uses suffix useSuffix: "", // Only show one message per error prompt showOneMessage: false }}; $(function(){$.validationEngine.defaults.promptPosition = methods.isRTL()?'topLeft':"topRight"}); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "geen", "alertText": "* Dit veld is verplicht", "alertTextCheckboxMultiple": "* Selecteer a.u.b. een optie", "alertTextCheckboxe": "* Dit selectievakje is verplicht" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Field must equal test" }, "minSize": { "regex": "none", "alertText": "* Minimaal ", "alertText2": " karakters toegestaan" }, "maxSize": { "regex": "none", "alertText": "* Maximaal ", "alertText2": " karakters toegestaan" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields" }, "min": { "regex": "none", "alertText": "* Minimale waarde is " }, "max": { "regex": "none", "alertText": "* Maximale waarde is " }, "past": { "regex": "none", "alertText": "* Datum voorafgaand aan " }, "future": { "regex": "none", "alertText": "* Datum na " }, "maxCheckbox": { "regex": "none", "alertText": "* Toegestane aantal vinkjes overschreden" }, "minCheckbox": { "regex": "none", "alertText": "* Selecteer a.u.b. ", "alertText2": " opties" }, "equals": { "regex": "none", "alertText": "* Velden komen niet overeen" }, "creditCard": { "regex": "none", "alertText": "* Ongeldige credit card nummer" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* Ongeldig telefoonnummer" }, "email": { // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "alertText": "* Ongeldig e-mailadres" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Ongeldig geheel getal" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Ongeldig drijvende comma getal" }, "date": { "regex": /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/, "alertText": "* Ongeldige datum, formaat moet JJJJ-MM-DD zijn" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Ongeldig IP-adres" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* Ongeldige URL" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Alleen cijfers" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Alleen leestekens" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* Geen vreemde tekens toegestaan" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* Deze gebruiker bestaat al", "alertTextLoad": "* Bezig met valideren, even geduld aub" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* Deze naam bestaat al", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* Deze naam is beschikbaar", // speaks by itself "alertTextLoad": "* Bezig met valideren, even geduld aub" }, "validate2fields": { "alertText": "* Voer aub HELLO in" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* This field is required", "alertTextCheckboxMultiple": "* Please select an option", "alertTextCheckboxe": "* This checkbox is required", "alertTextDateRange": "* Both date range fields are required" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Field must equal test" }, "dateRange": { "regex": "none", "alertText": "* Invalid ", "alertText2": "Date Range" }, "dateTimeRange": { "regex": "none", "alertText": "* Invalid ", "alertText2": "Date Time Range" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " characters allowed" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " characters allowed" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields" }, "min": { "regex": "none", "alertText": "* Minimum value is " }, "max": { "regex": "none", "alertText": "* Maximum value is " }, "past": { "regex": "none", "alertText": "* Date prior to " }, "future": { "regex": "none", "alertText": "* Date past " }, "maxCheckbox": { "regex": "none", "alertText": "* Maximum ", "alertText2": " options allowed" }, "minCheckbox": { "regex": "none", "alertText": "* Please select ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Fields do not match" }, "creditCard": { "regex": "none", "alertText": "* Invalid credit card number" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/, "alertText": "* Invalid phone number" }, "email": { // HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 ) "regex": /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/, "alertText": "* Invalid email address" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Not a valid integer" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Invalid floating decimal number" }, "date": { // Check if date is valid by leap year "func": function (field) { var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/); var match = pattern.exec(field.val()); if (match == null) return false; var year = match[1]; var month = match[2]*1; var day = match[3]*1; var date = new Date(year, month - 1, day); // because months starts from 0. return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day); }, "alertText": "* Invalid date, must be in YYYY-MM-DD format" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Invalid IP address" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* Invalid URL" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Numbers only" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Letters only" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* No special characters allowed" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxUserCallPhp": { "url": "phpajax/ajaxValidateFieldUser.php", // you may want to pass extra data on the ajax call "extraData": "name=eric", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This username is available", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "ajaxNameCallPhp": { // remote json service location "url": "phpajax/ajaxValidateFieldName.php", // error "alertText": "* This name is already taken", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* Please input HELLO" }, //tls warning:homegrown not fielded "dateFormat":{ "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/, "alertText": "* Invalid Date" }, //tls warning:homegrown not fielded "dateTimeFormat": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/, "alertText": "* Invalid Date or Date Format", "alertText2": "Expected Format: ", "alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ", "alertText4": "yyyy-mm-dd hh:mm:ss AM|PM" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { "regex": "none", "alertText": "* Ce champ est requis", "alertTextCheckboxMultiple": "* Choisir une option", "alertTextCheckboxe": "* Cette option est requise" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Field must equal test" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " caractères requis" }, "groupRequired": { "regex": "none", "alertText": "* Vous devez remplir un des champs suivant" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " caractères requis" }, "min": { "regex": "none", "alertText": "* Valeur minimum requise " }, "max": { "regex": "none", "alertText": "* Valeur maximum requise " }, "past": { "regex": "none", "alertText": "* Date antérieure au " }, "future": { "regex": "none", "alertText": "* Date postérieure au " }, "maxCheckbox": { "regex": "none", "alertText": "* Nombre max de choix excédé" }, "minCheckbox": { "regex": "none", "alertText": "* Veuillez choisir ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Votre champ n'est pas identique" }, "creditCard": { "regex": "none", "alertText": "* Numéro de carte bancaire valide" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, "alertText": "* Numéro de téléphone invalide" }, "email": { // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/ "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "alertText": "* Adresse email invalide" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Nombre entier invalide" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Nombre flottant invalide" }, "date": { "regex": /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/, "alertText": "* Date invalide, format JJ/MM/AAAA requis" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Adresse IP invalide" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* URL invalide" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Seuls les chiffres sont acceptés" }, "onlyLetterSp": { "regex": /^[a-zA-Z\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FD\ \']+$/, "alertText": "* Seules les lettres sont acceptées" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z\u00C0-\u00D6\u00D9-\u00F6\u00F9-\u00FD]+$/, "alertText": "* Aucun caractère spécial n'est accepté" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", "extraData": "name=eric", "alertTextLoad": "* Chargement, veuillez attendre", "alertText": "* Ce nom est déjà pris" }, "ajaxNameCall": { "url": "ajaxValidateFieldName", "alertText": "* Ce nom est déjà pris", "alertTextOk": "*Ce nom est disponible", "alertTextLoad": "* Chargement, veuillez attendre" }, "validate2fields": { "alertText": "Veuillez taper le mot HELLO" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
// JavaScript Document // modif 2013-01-28 ; ( function ($) { $.fn.myTab = function (settings) { settings = jQuery.extend( { isLocal : true, /* true is default, false if you want to use ajax to load content */ ajaxContainer : '', /* id or class */ tabDefaultIndex : 0, tabClassActive : 'active', tabClassContainer : 'tab_container', tabClassPanel : 'tab_content', beforeLoaded : null, /* fonction to call before loading content */ afterLoaded : null /* callback fonction after loaded content */ }, settings ); return this.each ( function () { var $this = $(this); //var $tabcontainer = $this.next('.tab_container'); var $tabcontainer = $this.next('.' + settings.tabClassContainer); var $tabcontent = $tabcontainer.find('.' + settings.tabClassPanel); var $tabItem = $(">li", this); //console.log( $tabItem ); $tabItem.each ( function (index) { $(this).find('a').click ( function () { setActiveTab (index); return false; }); }); var setActiveTab = function (elIndex) { var el = $tabItem.eq(elIndex); $tabItem.removeClass(settings.tabClassActive); $(el).addClass(settings.tabClassActive); var _url = $(el).find('a').attr('href'); if (settings.beforeLoaded) { settings.beforeLoaded.call ($this); } if ( settings.isLocal ) { $tabcontent.hide(); //console.log( $tabcontainer ); $tabcontainer.find(_url).show(); if (settings.afterLoaded) { settings.afterLoaded.call ($this); } } else { $.ajax ({ url : _url, dataType : 'html', success : function (html) { if (settings.afterLoaded) { settings.afterLoaded.call (); } $(settings.ajaxContainer).html(html); }, error : function () { $(settings.ajaxContainer).html('<p>Erreur de chargement ....</p>'); } }); } return false; }; setActiveTab (settings.tabDefaultIndex); }); }; })(jQuery);
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript