code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.Toolbar * Basic Toolbar class. * @constructor * 创建一个新的工具条对象 * @param {String/HTMLElement/Element} container 工具条的容器元素或元素id * @param {Array} buttons (optional) 要加入的按钮配置数组或是元素 * @param {Object} config 配置项对象 */ Ext.Toolbar = function(container, buttons, config){ if(container instanceof Array){ // omit the container for later rendering buttons = container; config = buttons; container = null; } Ext.apply(this, config); this.buttons = buttons; if(container){ this.render(container); } }; Ext.Toolbar.prototype = { // private render : function(ct){ this.el = Ext.get(ct); if(this.cls){ this.el.addClass(this.cls); } // using a table allows for vertical alignment this.el.update('<div class="x-toolbar x-small-editor"><table cellspacing="0"><tr></tr></table></div>'); this.tr = this.el.child("tr", true); var autoId = 0; this.items = new Ext.util.MixedCollection(false, function(o){ return o.id || ("item" + (++autoId)); }); if(this.buttons){ this.add.apply(this, this.buttons); delete this.buttons; } }, /** * 加入工具条一个或多个的元素 -- 该函数需要几个不同类型的参数传入到工具条。 * @param {Mixed} arg1 可传入下列不同类型的参数:<br /> * <ul> * <li>{@link Ext.Toolbar.Button} config: 有效的按钮配置对象(相当于{@link #addButton})</li> * <li>HtmlElement:任意标准的HTML元素(相当于{@link #addElement})</li> * <li>Field: 任意表单对象(相当于{@link #addField})</li> * <li>Item:任意{@link Ext.Toolbar.Item}的子类(相当于{@link #addItem})</li> * <li>String: 一般意义的字符(经{@link Ext.Toolbar.TextItem}包装,相当于 {@link #addText})。 * 须注意有些特殊的字符用于不同的场合,如下面说明的。</li> * <li>'separator' 或 '-':创建一个分隔符元素(相当于{@link #addSeparator})</li> * <li>' ': 创建一个空白符(equivalent to {@link #addSpacer})</li> * <li>'->': 创建一个填充元素(相当于{@link #addFill})</li> * </ul> * @param {Mixed} 参数2 * @param {Mixed} 参数3 */ add : function(){ var a = arguments, l = a.length; for(var i = 0; i < l; i++){ var el = a[i]; if(el.applyTo){ // some kind of form field this.addField(el); }else if(el.render){ // some kind of Toolbar.Item this.addItem(el); }else if(typeof el == "string"){ // string if(el == "separator" || el == "-"){ this.addSeparator(); }else if(el == " "){ this.addSpacer(); }else if(el == "->"){ this.addFill(); }else{ this.addText(el); } }else if(el.tagName){ // element this.addElement(el); }else if(typeof el == "object"){ // must be button config? this.addButton(el); } } }, /** * 返回工具条的元素 * @return {Ext.Element} */ getEl : function(){ return this.el; }, /** * 加入一个分隔符 * @return {Ext.Toolbar.Item} 分隔符 */ addSeparator : function(){ return this.addItem(new Ext.Toolbar.Separator()); }, /** * 加入一个空白元素 * @return {Ext.Toolbar.Spacer} 空白项 */ addSpacer : function(){ return this.addItem(new Ext.Toolbar.Spacer()); }, /** * 加入一个填充元素。规定是从工具条后插入(右方开始) * @return {Ext.Toolbar.Fill} 填充项 */ addFill : function(){ return this.addItem(new Ext.Toolbar.Fill()); }, /** * 加入任意的HTML元素到工具条中去 * @param {String/HTMLElement/Element} el 要加入的元素或元素id * @return {Ext.Toolbar.Item} 元素项 */ addElement : function(el){ return this.addItem(new Ext.Toolbar.Item(el)); }, /** * 加入任意的Toolbar.Item或子类 * @param {Ext.Toolbar.Item} item * @return {Ext.Toolbar.Item} Item项 */ addItem : function(item){ var td = this.nextBlock(); item.render(td); this.items.add(item); return item; }, /** * 加入一个或多个按钮。更多配置的资讯可参阅{@link Ext.Toolbar.Button} * @param {Object/Array} config 按钮配置或配置项数组 * @return {Ext.Toolbar.Button/Array} */ addButton : function(config){ if(config instanceof Array){ var buttons = []; for(var i = 0, len = config.length; i < len; i++) { buttons.push(this.addButton(config[i])); } return buttons; } var b = config; if(!(config instanceof Ext.Toolbar.Button)){ b = config.split ? new Ext.Toolbar.SplitButton(config) : new Ext.Toolbar.Button(config); } var td = this.nextBlock(); b.render(td); this.items.add(b); return b; }, /** * 在工具条中加入文本 * @param {String} text 要加入的文本 * @return {Ext.Toolbar.Item} 元素项 */ addText : function(text){ return this.addItem(new Ext.Toolbar.TextItem(text)); }, /** * 位于索引的某一项插入任意的{@link Ext.Toolbar.Item}/{@link Ext.Toolbar.Button} * @param {Number} index 插入项所在的索引位置 * @param {Object/Ext.Toolbar.Item/Ext.Toolbar.Button (可能是数组类型)} item 要插入的按钮,或按钮的配置项对象 * @return {Ext.Toolbar.Button/Item} */ insertButton : function(index, item){ if(item instanceof Array){ var buttons = []; for(var i = 0, len = item.length; i < len; i++) { buttons.push(this.insertButton(index + i, item[i])); } return buttons; } if (!(item instanceof Ext.Toolbar.Button)){ item = new Ext.Toolbar.Button(item); } var td = document.createElement("td"); this.tr.insertBefore(td, this.tr.childNodes[index]); item.render(td); this.items.insert(index, item); return item; }, /** * 传入一个{@link Ext.DomHelper}配置参数,然后作为新元素加入到工具条。 * @param {Object} config * @return {Ext.Toolbar.Item} 元素项 */ addDom : function(config, returnEl){ var td = this.nextBlock(); Ext.DomHelper.overwrite(td, config); var ti = new Ext.Toolbar.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, /** * 动态加入一个可渲染的Ext.form字段(TextField,Combobox,等等)。 * 注意:字段应该是还未被渲染的。如已渲染,使用{@link #addElement}插入。 * @param {Ext.form.Field} field * @return {Ext.ToolbarItem} */ addField : function(field){ var td = this.nextBlock(); field.render(td); var ti = new Ext.Toolbar.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, // private nextBlock : function(){ var td = document.createElement("td"); this.tr.appendChild(td); return td; }, // private destroy : function(){ if(this.items){ // rendered? Ext.destroy.apply(Ext, this.items.items); } Ext.Element.uncache(this.el, this.tr); } }; /** * @class Ext.Toolbar.Item * 一个简单的用来将文本呈现到 toolbar 上的类。 * @constructor * 创建一个 TextItem 对象。 * @param {HTMLElement} el */ Ext.Toolbar.Item = function(el){ this.el = Ext.getDom(el); this.id = Ext.id(this.el); this.hidden = false; }; Ext.Toolbar.Item.prototype = { /** * 取得此项的 HTML 元素。 * @return {HTMLElement} */ getEl : function(){ return this.el; }, // private render : function(td){ this.td = td; td.appendChild(this.el); }, /** * 移除此项。 */ destroy : function(){ this.td.parentNode.removeChild(this.td); }, /** * 显示此项。 */ show: function(){ this.hidden = false; this.td.style.display = ""; }, /** * 隐藏此项。 */ hide: function(){ this.hidden = true; this.td.style.display = "none"; }, /** * 方便的布尔函数用来控制显示/隐藏。 * @param {Boolean} visible true时显示/false 时隐藏 */ setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } }, /** * 试着聚焦到此项。 */ focus : function(){ Ext.fly(this.el).focus(); }, /** * 禁止此项。 */ disable : function(){ Ext.fly(this.td).addClass("x-item-disabled"); this.disabled = true; this.el.disabled = true; }, /** * 启用此项。 */ enable : function(){ Ext.fly(this.td).removeClass("x-item-disabled"); this.disabled = false; this.el.disabled = false; } }; /** * @class Ext.Toolbar.Separator * @extends Ext.Toolbar.Item * 一个在工具条内的分隔符类 * @constructor * 创建一个新分隔符(Separator)对象 */ Ext.Toolbar.Separator = function(){ var s = document.createElement("span"); s.className = "ytb-sep"; Ext.Toolbar.Separator.superclass.constructor.call(this, s); }; Ext.extend(Ext.Toolbar.Separator, Ext.Toolbar.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); /** * @class Ext.Toolbar.Spacer * @extends Ext.Toolbar.Item * 在工具条中插入一条水平占位符元素。 * @constructor * 创建一个新Spacer对象 */ Ext.Toolbar.Spacer = function(){ var s = document.createElement("div"); s.className = "ytb-spacer"; Ext.Toolbar.Spacer.superclass.constructor.call(this, s); }; Ext.extend(Ext.Toolbar.Spacer, Ext.Toolbar.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); /** * @class Ext.Toolbar.Fill * @extends Ext.Toolbar.Spacer * 在工具条中插入一条100%宽度的空白水平占位符元素。 * @constructor * Creates a new Spacer */ Ext.Toolbar.Fill = Ext.extend(Ext.Toolbar.Spacer, { // private render : function(td){ td.style.width = '100%'; Ext.Toolbar.Fill.superclass.render.call(this, td); } }); /** * @class Ext.Toolbar.TextItem * @extends Ext.Toolbar.Item * 一个将文本直接渲染到工具条的简易类。 * @constructor * 创建一个新TextItem的对象 * @param {String} text */ Ext.Toolbar.TextItem = function(text){ var s = document.createElement("span"); s.className = "ytb-text"; s.innerHTML = text; Ext.Toolbar.TextItem.superclass.constructor.call(this, s); }; Ext.extend(Ext.Toolbar.TextItem, Ext.Toolbar.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); /** * @class Ext.Toolbar.Button * @extends Ext.Button * 用于渲染工具条的按钮。 * @constructor * 创建一个新的按钮对象 * @param {Object} config 标准{@link Ext.Button}配置项对象 */ Ext.Toolbar.Button = function(config){ Ext.Toolbar.Button.superclass.constructor.call(this, null, config); }; Ext.extend(Ext.Toolbar.Button, Ext.Button, { render : function(td){ this.td = td; Ext.Toolbar.Button.superclass.render.call(this, td); }, /** * 移除并消耗该按钮 */ destroy : function(){ Ext.Toolbar.Button.superclass.destroy.call(this); this.td.parentNode.removeChild(this.td); }, /** * 显示按钮 */ show: function(){ this.hidden = false; this.td.style.display = ""; }, /** * 隐藏按钮 */ hide: function(){ this.hidden = true; this.td.style.display = "none"; }, /** * 禁止此项 */ disable : function(){ Ext.fly(this.td).addClass("x-item-disabled"); this.disabled = true; }, /** * 启用此项 */ enable : function(){ Ext.fly(this.td).removeClass("x-item-disabled"); this.disabled = false; } }); // backwards compat Ext.ToolbarButton = Ext.Toolbar.Button; /** * @class Ext.Toolbar.SplitButton * @extends Ext.SplitButton * 用于渲染工具条的菜单。 * @constructor * 创建一个新的SplitButton对象 * @param {Object} config 标准{@link Ext.SplitButton}配置项对象 */ Ext.Toolbar.SplitButton = function(config){ Ext.Toolbar.SplitButton.superclass.constructor.call(this, null, config); }; Ext.extend(Ext.Toolbar.SplitButton, Ext.SplitButton, { render : function(td){ this.td = td; Ext.Toolbar.SplitButton.superclass.render.call(this, td); }, /** * 移除并销毁该按钮 */ destroy : function(){ Ext.Toolbar.SplitButton.superclass.destroy.call(this); this.td.parentNode.removeChild(this.td); }, /** * 显示按钮 */ show: function(){ this.hidden = false; this.td.style.display = ""; }, /** * 隐藏按钮 */ hide: function(){ this.hidden = true; this.td.style.display = "none"; } }); // 向后兼容 Ext.Toolbar.MenuButton = Ext.Toolbar.SplitButton;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.View * @extends Ext.util.Observable * 创建某个元素的“视图(View)”,这个“视图”可基于Data Model(数据模型)或 UpdateManager, 并由 DomHelper提供模板的支持。 * 选区模式支持单选或多选. <br> * 将Data Model绑定到 View。 <pre><code> var store = new Ext.data.Store(...); var view = new Ext.View("my-element", '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // 自动创建模板 { singleSelect: true, selectedClass: "ydataview-selected", store: store }); //是否侦听节点的单击事件? view.on("click", function(vw, index, node, e){ alert('Node "' + node.id + '" at index: ' + index + " was clicked."); }); //加载XML数据 dataModel.load("foobar.xml"); </code></pre> * 关于创建 JSON/UpdateManager view 的例子,可见 {@link Ext.JsonView}. * <br><br> * <b>注意:模板的根节点必须是单一节点。由于IE插入的限制和Opera事件上报的失效,表格/行(table/row)的实现可能渲染失真。</b> * @constructor * Create a new View * @param {String/HTMLElement/Element} container View渲染所在的容器元素 * @param {String/DomHelper.Template} tpl 渲染模板对象或是创建模板的字符串 * @param {Object} config 配置项对象 */ Ext.View = function(container, tpl, config){ this.el = Ext.get(container); if(typeof tpl == "string"){ tpl = new Ext.Template(tpl); } tpl.compile(); /** * View所使用的模板 * @type {Ext.DomHelper.Template} */ this.tpl = tpl; Ext.apply(this, config); /** @private */ this.addEvents({ /** * @event beforeclick * 单击执行之前触发,如返回 false 则取消默认的动作。 * @param {Ext.View} this * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "beforeclick" : true, /** * @event click * 当模板节点单击时触发事件 * @param {Ext.View} this * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "click" : true, /** * @event dblclick * 当模板节点双击时触发事件 * @param {Ext.View} this * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "dblclick" : true, /** * @event contextmenu * 当模板节右击时触发事件 * @param {Ext.View} this * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "contextmenu" : true, /** * @event selectionchange * 当选取改变时触发. * @param {Ext.View} this * @param {Array} selections 已选取节点所组成的数组 */ "selectionchange" : true, /** * @event beforeselect * 选取生成之前触发,如返回false,则选区不会生成. * @param {Ext.View} this * @param {HTMLElement} node 要选取的节点 * @param {Array} selections 当前已选取节点所组成的数组 */ "beforeselect" : true }); this.el.on({ "click": this.onClick, "dblclick": this.onDblClick, "contextmenu": this.onContextMenu, scope:this }); this.selections = []; this.nodes = []; this.cmp = new Ext.CompositeElementLite([]); if(this.store){ this.setStore(this.store, true); } Ext.View.superclass.constructor.call(this); }; Ext.extend(Ext.View, Ext.util.Observable, { /** * 显示节点已选取的CSS样式类. * @type {Ext.DomHelper.Template} */ selectedClass : "x-view-selected", emptyText : "", /** * 返回view所绑定的元素. * @return {Ext.Element} */ getEl : function(){ return this.el; }, /** * 刷新视图. */ refresh : function(){ var t = this.tpl; this.clearSelections(); this.el.update(""); var html = []; var records = this.store.getRange(); if(records.length < 1){ this.el.update(this.emptyText); return; } for(var i = 0, len = records.length; i < len; i++){ var data = this.prepareData(records[i].data, i, records[i]); html[html.length] = t.apply(data); } this.el.update(html.join("")); this.nodes = this.el.dom.childNodes; this.updateIndexes(0); }, /** * 重写该函数,可对每个节点的数据进行格式化,再交给模板进一步处理. * @param {Array/Object} data 原始数据,是Data Model 绑定视图对象或UpdateManager数据对象绑定的JSON对象 */ prepareData : function(data){ return data; }, onUpdate : function(ds, record){ this.clearSelections(); var index = this.store.indexOf(record); var n = this.nodes[index]; this.tpl.insertBefore(n, this.prepareData(record.data)); n.parentNode.removeChild(n); this.updateIndexes(index, index); }, onAdd : function(ds, records, index){ this.clearSelections(); if(this.nodes.length == 0){ this.refresh(); return; } var n = this.nodes[index]; for(var i = 0, len = records.length; i < len; i++){ var d = this.prepareData(records[i].data); if(n){ this.tpl.insertBefore(n, d); }else{ this.tpl.append(this.el, d); } } this.updateIndexes(index); }, onRemove : function(ds, record, index){ this.clearSelections(); this.el.dom.removeChild(this.nodes[index]); this.updateIndexes(index); }, /** * 刷新不同的节点. * @param {Number} index */ refreshNode : function(index){ this.onUpdate(this.store, this.store.getAt(index)); }, updateIndexes : function(startIndex, endIndex){ var ns = this.nodes; startIndex = startIndex || 0; endIndex = endIndex || ns.length - 1; for(var i = startIndex; i <= endIndex; i++){ ns[i].nodeIndex = i; } }, /** * 改变在使用的Data Store并刷新 view。 * @param {Store} store */ setStore : function(store, initial){ if(!initial && this.store){ this.store.un("datachanged", this.refresh); this.store.un("add", this.onAdd); this.store.un("remove", this.onRemove); this.store.un("update", this.onUpdate); this.store.un("clear", this.refresh); } if(store){ store.on("datachanged", this.refresh, this); store.on("add", this.onAdd, this); store.on("remove", this.onRemove, this); store.on("update", this.onUpdate, this); store.on("clear", this.refresh, this); } this.store = store; if(store){ this.refresh(); } }, /** * 传入一个节点(node)的参数,返回该属于模板的节点,返回null则代表它不属于模板的任何一个节点。 * @param {HTMLElement} node * @return {HTMLElement} 模板节点 */ findItemFromChild : function(node){ var el = this.el.dom; if(!node || node.parentNode == el){ return node; } var p = node.parentNode; while(p && p != el){ if(p.parentNode == el){ return p; } p = p.parentNode; } return null; }, /** @ignore */ onClick : function(e){ var item = this.findItemFromChild(e.getTarget()); if(item){ var index = this.indexOf(item); if(this.onItemClick(item, index, e) !== false){ this.fireEvent("click", this, index, item, e); } }else{ this.clearSelections(); } }, /** @ignore */ onContextMenu : function(e){ var item = this.findItemFromChild(e.getTarget()); if(item){ this.fireEvent("contextmenu", this, this.indexOf(item), item, e); } }, /** @ignore */ onDblClick : function(e){ var item = this.findItemFromChild(e.getTarget()); if(item){ this.fireEvent("dblclick", this, this.indexOf(item), item, e); } }, onItemClick : function(item, index, e){ if(this.fireEvent("beforeclick", this, index, item, e) === false){ return false; } if(this.multiSelect || this.singleSelect){ if(this.multiSelect && e.shiftKey && this.lastSelection){ this.select(this.getNodes(this.indexOf(this.lastSelection), index), false); }else{ this.select(item, this.multiSelect && e.ctrlKey); this.lastSelection = item; } e.preventDefault(); } return true; }, /** * 获取节点选中数 * @return {Number} */ getSelectionCount : function(){ return this.selections.length; }, /** * 获取当前选中的节点 * @return {Array} HTMLElements数组 */ getSelectedNodes : function(){ return this.selections; }, /** * 获取选中节点的索引 * @return {Array} */ getSelectedIndexes : function(){ var indexes = [], s = this.selections; for(var i = 0, len = s.length; i < len; i++){ indexes.push(s[i].nodeIndex); } return indexes; }, /** * 清除选区 * @param {Boolean} suppressEvent (可选项) true表示为跳过所有selectionchange事件 */ clearSelections : function(suppressEvent){ if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){ this.cmp.elements = this.selections; this.cmp.removeClass(this.selectedClass); this.selections = []; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selections); } } }, /** * 传入一个节点的参数,如果是属于已选取的话便返回true. * @param {HTMLElement/Number} node 节点或节点索引 * @return {Boolean} */ isSelected : function(node){ var s = this.selections; if(s.length < 1){ return false; } node = this.getNode(node); return s.indexOf(node) !== -1; }, /** * 选取节点 * @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID * @param {Boolean} keepExisting (可选项) true 代表保留当前选区 * @param {Boolean} suppressEvent (可选项) true表示为跳过所有selectionchange事件 */ select : function(nodeInfo, keepExisting, suppressEvent){ if(nodeInfo instanceof Array){ if(!keepExisting){ this.clearSelections(true); } for(var i = 0, len = nodeInfo.length; i < len; i++){ this.select(nodeInfo[i], true, true); } } else{ var node = this.getNode(nodeInfo); if(node && !this.isSelected(node)){ if(!keepExisting){ this.clearSelections(true); } if(this.fireEvent("beforeselect", this, node, this.selections) !== false){ Ext.fly(node).addClass(this.selectedClass); this.selections.push(node); if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selections); } } } } }, /** * 获取多个模板节点 * @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID * @return {HTMLElement} 若找不到返回null */ getNode : function(nodeInfo){ if(typeof nodeInfo == "string"){ return document.getElementById(nodeInfo); }else if(typeof nodeInfo == "number"){ return this.nodes[nodeInfo]; } return nodeInfo; }, /** * 获取某个范围的模板节点。 * @param {Number} 索引头 * @param {Number} 索引尾 * @return {Array} 节点数组 */ getNodes : function(start, end){ var ns = this.nodes; start = start || 0; end = typeof end == "undefined" ? ns.length - 1 : end; var nodes = []; if(start <= end){ for(var i = start; i <= end; i++){ nodes.push(ns[i]); } } else{ for(var i = start; i >= end; i--){ nodes.push(ns[i]); } } return nodes; }, /** * 传入一个node作为参数,找到它的索引 * @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID * @return {Number} 节点索引或-1 * */ indexOf : function(node){ node = this.getNode(node); if(typeof node.nodeIndex == "number"){ return node.nodeIndex; } var ns = this.nodes; for(var i = 0, len = ns.length; i < len; i++){ if(ns[i] == node){ return i; } } return -1; } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.tree.TreeFilter * Note this class is experimental and doesn't update the indent (lines) or expand collapse icons of the nodes * 注意这个类是试验性的所以不会更新节点的缩进(连线)或者展开收回图标 * @param {TreePanel} tree * @param {Object} config (optional) */ 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, /** * Filter the data by a specific attribute.通过指定的属性过滤数据 * @param {String/RegExp} value Either string that the attribute value * should start with or a RegExp to test against the attribute * value既可以是属性值开头的字符串也可以是针对这个属性的正则表达式 * @param {String} attr (optional) The attribute passed in your node's attributes collection. Defaults to "text". * (可选)这个被传递的属性是你的属性的集合中的。默认是"text" * @param {TreeNode} startNode (optional) The node to start the filter at.(可选)从这个节点开始是过滤的 */ 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); }, /** * Filter by a function. The passed function will be called with each * node in the tree (or from the startNode). If the function returns true, the node is kept * otherwise it is filtered. If a node is filtered, its children are also filtered. * 通过一个函数过滤,这个被传递的函数将被这棵树中的每个节点调用(或从startNode开始)。如果函数返回true,那么该节点将保留否则它将被过滤掉. * 如果一个节点被过滤掉,那么它的子节点也都被过滤掉了 * @param {Function} fn The filter function * @param {Object} scope (optional) The scope of the function (defaults to the current node)函数的作用域(默认是现在这个节点) */ 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); } } } } }, /** * Clears the current filter. Note: with the "remove" option * set a filter cannot be cleared. * 清理现在的过滤。注意:设置的过滤带有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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.tree.DefaultSelectionModel * @extends Ext.util.Observable * The default single selection for a TreePanel.一个TreePanel默认是单选择区 */ Ext.tree.DefaultSelectionModel = function(){ this.selNode = null; this.addEvents({ /** * @event selectionchange * Fires when the selected node changes 当选择区的节点被改变时触发 * @param {DefaultSelectionModel} this * @param {TreeNode} node the new selection */ "selectionchange" : true, /** * @event beforeselect * Fires before the selected node changes, return false to cancel the change 当选择区的节点被改变之前触发,返回false时放弃改变 * @param {DefaultSelectionModel} this * @param {TreeNode} node the new selection 节点新的选择区 * @param {TreeNode} node the old selection 节点旧的选择区 */ "beforeselect" : true }); }; 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 The node to select 选择的节点 * @return {TreeNode} The selected node 选择的节点 */ 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; }, /** * Deselect a node. 如果该节点在选择区中,则将该节点移除选择区 * @param {TreeNode} node The node to unselect 被移除的节点 */ unselect : function(node){ if(this.selNode == node){ this.clearSelections(); } }, /** * Clear all selections 清空选择区,并返回选择区中的节点 */ clearSelections : function(){ var n = this.selNode; if(n){ n.ui.onSelectedChange(false); this.selNode = null; this.fireEvent("selectionchange", this, null); } return n; }, /** * Get the selected node 得到选择区中的节点 * @return {TreeNode} The selected node */ getSelectedNode : function(){ return this.selNode; }, /** * Returns true if the node is selected 如果节点在选择区中则返回true * @param {TreeNode} node The node to check 待检查的节点 * @return {Boolean} */ isSelected : function(node){ return this.selNode == node; }, /** * Selects the node above the selected node in the tree, intelligently walking the nodes 将选择区中的节点在这棵树中上一个节点放入选择区,而且是智能的检索 * @return TreeNode The new selection */ 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; }, /** * Selects the node above the selected node in the tree, intelligently walking the nodes 将选择区中的节点在这棵树中下一个节点放入选择区,而且是智能的检索 * @return TreeNode The new selection */ 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; }; } }); /** * @class Ext.tree.MultiSelectionModel * @extends Ext.util.Observable * Multi selection for a TreePanel. 一个多选择区的TreePanel */ Ext.tree.MultiSelectionModel = function(){ this.selNodes = []; this.selMap = {}; this.addEvents({ /** * @event selectionchange * Fires when the selected nodes change当选择区中的节点改变时触发 * @param {MultiSelectionModel} this * @param {Array} nodes Array of the selected nodes */ "selectionchange" : true }); }; 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); }, /** * Select a node. 将节点放入选择区 * @param {TreeNode} node The node to select 要放入的节点 * @param {EventObject} e (optional) An event associated with the selection 为选择区分配的event对象 * @param {Boolean} keepExisting True to retain existing selections 如果为true,则保存选择区中已存在的节点 * @return {TreeNode} The selected node */ 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; }, /** * Deselect a node. 如果传入的节点在选择区则从中删除 * @param {TreeNode} node The node to unselect */ unselect : function(node){ if(this.selMap[node.id]){ node.ui.onSelectedChange(false); var sn = this.selNodes; var index = -1; if(sn.indexOf){ index = sn.indexOf(node); }else{ for(var i = 0, len = sn.length; i < len; i++){ if(sn[i] == node){ index = i; break; } } } if(index != -1){ this.selNodes.splice(index, 1); } delete this.selMap[node.id]; this.fireEvent("selectionchange", this, this.selNodes); } }, /** * Clear all selections 清理选择区中的节点 */ 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); } } }, /** * Returns true if the node is selected 如果节点已经在选择区中则返回true * @param {TreeNode} node The node to check 检查的节点 * @return {Boolean} */ isSelected : function(node){ return this.selMap[node.id] ? true : false; }, /** * Returns an array of the selected nodes 返回选择区中所有的节点 * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.tree.AsyncTreeNode * @extends Ext.tree.TreeNode * @cfg {TreeLoader} loader A TreeLoader to be used by this node (defaults to the loader defined on the tree) * 加载这个节点使用的TreeLoader(默认是加载该节点所在树的TreeLoader) * @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 * Fires before this node is loaded, return false to cancel当该节点加载时触发,返回false将取消事件 * @param {Node} this This node */ this.addEvents({'beforeload':true, 'load': true}); /** * @event load * Fires when this node is loaded当该节点被加载后触发 * @param {Node} this This node */ /** * The loader used by this node (defaults to using the tree's defined loader)该节点所使用的loader(默认为tree本身的loader)。 * @type TreeLoader * @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); }, /** * Returns true if this node is currently loading如果该节点正在被加载则返回true * @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); }, /** * Returns true if this node has been loaded如果该节点被加载过则返回true * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.tree.TreeLoader * @extends Ext.util.Observable * 树加载器(TreeLoader)的目的是从URL延迟加载树节点{@link Ext.tree.TreeNode}的子节点。 * 返回值必须是以树格式的javascript数组。 * 例如: * <pre><code> [{ 'id': 1, 'text': 'A folder Node', 'leaf': false }, { 'id': 2, 'text': 'A leaf 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 = {}; this.requestMethod = "POST"; Ext.apply(this, config); this.addEvents({ /** * @event beforeload * 在请求网络连接之前触发,对应每一个子节点都会触发该事件。 * @param {Object} This TreeLoader object. * @param {Object} node The {@link Ext.tree.TreeNode} object being loaded. * @param {Object} callback 针对 {@link #load} 调用的回调函数。 */ "beforeload" : true, /** * @event load * 在成功读取数据后触发该事件。 * @param {Object} This TreeLoader object. * @param {Object} node The {@link Ext.tree.TreeNode} object being loaded. * @param {Object} response 从服务端返回的数据。 */ "load" : true, /** * @event loadexception * 在读取数据失败时触发该事件。 * @param {Object} This TreeLoader object. * @param {Object} node The {@link Ext.tree.TreeNode} object being loaded. * @param {Object} response 从服务端返回的数据。 */ "loadexception" : true }); Ext.tree.TreeLoader.superclass.constructor.call(this); }; Ext.extend(Ext.tree.TreeLoader, Ext.util.Observable, { /** * @cfg {String} dataUrl 进行请求的URL。 */ /** * @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(node.attributes.children){ // preloaded json children var cs = node.attributes.children; for(var i = 0, len = cs.length; i < len; i++){ node.appendChild(this.createNode(cs[i])); } if(typeof callback == "function"){ callback(); } }else if(this.dataUrl){ this.requestData(node, callback); } }, 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+")"); for(var i = 0, len = o.length; i < len; i++){ var n = this.createNode(o[i]); if(n){ node.appendChild(n); } } 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.tree.TreeNode * @extends Ext.data.Node * @cfg {String} text The text for this node该节点所显示的文本 * @cfg {Boolean} expanded true to start the node expanded如果为"true",该节点被展开 * @cfg {Boolean} allowDrag false to make this node undraggable if DD is on (defaults to true)如果dd为on时,设置为fals将使得该节点不能拖拽 * @cfg {Boolean} allowDrop false if this node cannot be drop on为false时该节点不能将拖拽的对象放在该节点下 * @cfg {Boolean} disabled true to start the node disabled为true该节点被禁止 * @cfg {String} icon 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. * 设置该节点上图标的路径.这种方式是首选的,比使用cls或iconCls属性和为这个图标加一个CSS的background-image都好. * @cfg {String} cls A css class to be added to the node为该节点设置css样式类 * @cfg {String} iconCls A css class to be added to the nodes icon element for applying css background images * 为该节点上的图标元素应用背景 * @cfg {String} href URL of the link used for the node (defaults to #)设置该节点url连接(默认是#) * @cfg {String} hrefTarget target frame for the link设置该连接应用到那个frame * @cfg {String} qtip An Ext QuickTip for the node为该节点设置用于提示的文本 * @cfg {String} qtipCfg An Ext QuickTip config for the node (used instead of qtip)为该节点设置QuickTip类(用于替换qtip属性) * @cfg {Boolean} singleClickExpand True for single click expand on this node为true时当节点被单击时展开 * @cfg {Function} uiProvider A UI <b>class</b> to use for this node (defaults to Ext.tree.TreeNodeUI)该节点所使用的UI类(默认时Ext.tree.TreeNodeUI) * @cfg {Boolean} checked True to render a checked checkbox for this node, false to render an unchecked checkbox * (defaults to undefined with no checkbox rendered) * 为true将为该节点添加checkbox选择框,为false将不添加(默认为undefined是不添加checkbox的) * @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; /** * Read-only. The text for this node. To change it use setText().只读属性,该节点所显示的文本.可以用setText方法改变 * @type String */ this.text = attributes.text; /** * True if this node is disabled.如果该节点为disabled那为true * @type Boolean */ this.disabled = attributes.disabled === 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" : true, /** * @event beforeexpand * Fires before this node is expanded, return false to cancel当该节点被展开之前触发,返回false将取消事件 * @param {Node} this This node该节点 * @param {Boolean} deep 该节点当前是否也展开所有子节点的状态 * @param {Boolean} anim 该节点当前是否启用动画效果的状态 */ "beforeexpand" : true, /** * @event beforecollapse * Fires before this node is collapsed, return false to cancel.当该节点被收回之前触发,返回false将取消事件 * @param {Node} this This node该节点 * @param {Boolean} deep 该节点当前是否也展开所有子节点的状态 * @param {Boolean} anim 该节点当前是否启用动画效果的状态 */ "beforecollapse" : true, /** * @event expand * Fires when this node is expanded当该节点被展开时触发。 * @param {Node} this This node该节点 */ "expand" : true, /** * @event disabledchange * Fires when the disabled status of this node changes当该节点的disabled状态被改变时触发 * @param {Node} this This node该节点 * @param {Boolean} disabled该节点的disabled属性的状态 */ "disabledchange" : true, /** * @event collapse * Fires when this node is collapsed当该节点被收回时触发。 * @param {Node} this This node该节点 */ "collapse" : true, /** * @event beforeclick * Fires before click processing. Return false to cancel the default action.单击处理之前触发,返回false将停止默认的动作 * @param {Node} this This node该节点 * @param {Ext.EventObject} e The event object 事件对象 */ "beforeclick":true, /** * @event checkchange * Fires when a node with a checkbox's checked property changes当节点的checkbox的状态被改变时触发 * @param {Node} this This node该节点 * @param {Boolean} checked当前节点checkbox的状态 */ "checkchange":true, /** * @event click * Fires when this node is clicked当节点被点击时触发 * @param {Node} this This node该节点 * @param {Ext.EventObject} e The event object 事件对象 */ "click":true, /** * @event dblclick * Fires when this node is double clicked 当节点被双点击时触发 * @param {Node} this This node该节点 * @param {Ext.EventObject} e The event object 事件对象 */ "dblclick":true, /** * @event contextmenu * Fires when this node is right clicked 当节点被右键点击时触发 * @param {Node} this This node该节点 * @param {Ext.EventObject} e The event object 事件对象 */ "contextmenu":true, /** * @event beforechildrenrendered * Fires right before the child nodes for this node are rendered 当节点的子节点被渲染之前触发 * @param {Node} this This node该节点 */ "beforechildrenrendered":true }); var uiClass = this.attributes.uiProvider || Ext.tree.TreeNodeUI; /** * Read-only. The UI for this node这个节点的UI * @type TreeNodeUI */ this.ui = new uiClass(this); }; Ext.extend(Ext.tree.TreeNode, Ext.data.Node, { preventHScroll: true, /** * Returns true if this node is expanded如果该节点被展开则返回true * @return {Boolean} */ isExpanded : function(){ return this.expanded; }, /** * Returns the UI object for this node返回该节点的UI对象 * @return {TreeNodeUI} */ getUI : function(){ return this.ui; }, // 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(){ var node = Ext.tree.TreeNode.superclass.appendChild.apply(this, arguments); 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.childrenRendered = false; } return node; }, // private override insertBefore : function(node, refNode){ var newNode = Ext.tree.TreeNode.superclass.insertBefore.apply(this, arguments); 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); }, /** * Returns true if this node is selected如果该节点被选中则返回true * @return {Boolean} */ isSelected : function(){ return this.getOwnerTree().getSelectionModel().isSelected(this); }, /** * Expand this node.展开这个节点 * @param {Boolean} deep (optional) True to expand all children as well如果为true展开所有的子节点 * @param {Boolean} anim (optional) false to cancel the default animation如果为false不启用动画效果 * @param {Function} callback (optional) A callback to be called when * expanding this node completes (does not wait for deep expand to complete).当展开完成时调用这个callback(不等待所有子节点都展开完成后才执行) * 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 (optional) True to collapse all children as well 为true则也展开所有的子结点 * @param {Boolean} anim (optional) false to cancel the default animation 如果为false不启用动画效果 */ 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 确保所有的父节点都被展开了(没理解这个函数的作用) */ ensureVisible : function(callback){ var tree = this.getOwnerTree(); tree.expandPath(this.parentNode.getPath(), false, function(){ tree.getTreeEl().scrollChildIntoView(this.ui.anchor); Ext.callback(callback); }.createDelegate(this)); }, /** * Expand all child nodes展开所有的子节点 * @param {Boolean} deep (optional) true if the child nodes should also expand their child nodes如果为true,子节点如果还有子节点也将被展开 */ 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 (optional) true if the child nodes should also collapse their child nodes如果为true,子节点如果还有子节点也将被收回 */ 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){ 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); } } } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.tree.TreeSorter * Provides sorting of nodes in a TreePanel * 提供一个可排序节点的Tree面板 * * @cfg {Boolean} folderSort True to sort leaf nodes under non leaf nodes设置为真时则同级的叶节点排在 * @cfg {String} property The named attribute on the node to sort by (defaults to text)用节点上的那个属性排序(默认是text属性) * @cfg {String} dir The direction to sort (asc or desc) (defaults to asc)排序的方式(升序或降序)(默认时升序) * @cfg {String} leafAttr The attribute used to determine leaf nodes in folder sort (defaults to "leaf") * @cfg {Boolean} caseSensitive true for case sensitive sort (defaults to false)排序时大小写敏感(默认时false) * @cfg {Function} sortType A custom "casting" function used to convert node values before sorting * 在排序之前可以写一个强转函数用来转换节点的值 * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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: true }); 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.MasterTemplate( '<tpl><a href="#" class="color-{0}" hidefocus="on"><em><span style="background:#{0}" unselectable="on">&#160;</span></em></a></tpl>' ); var c = this.colors; for(var i = 0, len = c.length; i < len; i++){ t.add([c[i]]); } var el = document.createElement("div"); el.className = this.itemCls; t.overwrite(el); 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); } } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.TextArea * @extends Ext.form.TextField * 多行文本域。可以直接用于替代textarea,支持自动调整大小。 * @constructor * 创建一个新的TextArea对象 * @param {Object} config 配置选项 */ Ext.form.TextArea = function(config){ Ext.form.TextArea.superclass.constructor.call(this, config); // 提供向后兼容 // growMin/growMax替代minHeight/maxHeight // 兼容TextField递增的配置值 if(this.minHeight !== undefined){ this.growMin = this.minHeight; } if(this.maxHeight !== undefined){ this.growMax = this.maxHeight; } }; Ext.extend(Ext.form.TextArea, Ext.form.TextField, { /** * @cfg {Number} growMin 当grow = true时允许的高度下限(默认为60) */ growMin : 60, /** * @cfg {Number} growMax 当grow = true时允许的高度上限(默认为1000) */ growMax: 1000, /** * @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:300px;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){ this.textSizeEl.parentNode.removeChild(this.textSizeEl); } Ext.form.TextArea.superclass.onDestroy.call(this); }, // 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 += "&#160;\n&#160;"; } ts.innerHTML = v; var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin)); if(h != this.lastHeight){ this.lastHeight = h; this.el.setHeight(h); this.fireEvent("autosize", this, h); } } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.Radio * @extends Ext.form.Checkbox * 单个的radio按钮。与Checkbox类似,提供一种简便,自动的输入方式。 * 如果你给radio按钮组中的每个按钮相同的名字(属性name值相同),按钮组会自动被浏览器获得。 * @constructor * 创建一个新的radio按钮对象 * @param {Object} config 配置选项 */ Ext.form.Radio = function(){ Ext.form.Radio.superclass.constructor.apply(this, arguments); }; Ext.extend(Ext.form.Radio, Ext.form.Checkbox, { inputType: 'radio', /** * 如果该radio是组的一部分,将返回已选中的值。 * @return {String} */ getGroupValue : function(){ return this.el.up('form').child('input[name='+this.el.dom.name+']:checked', true).value; } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.Field * @extends Ext.BoxComponent * Base class for form fields that provides default event handling, sizing, value handling and other functionality. * 表单元素的基类,提供事件操作、尺寸调整、值操作与其它功能。 * @constructor * Creates a new Field * 创建一个新的字段 * @param {Object} config Configuration options * 配制选项 */ Ext.form.Field = function(config){ Ext.form.Field.superclass.constructor.call(this, config); }; Ext.extend(Ext.form.Field, Ext.BoxComponent, { /** * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to "x-form-invalid") * 表单元素无效时标在上面的CSS样式(默认为"x-form-invalid") */ invalidClass : "x-form-invalid", /** * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid") * 表单元素无效时标在上面的文本信息(默认为"The value in this field is invalid") */ invalidText : "The value in this field is invalid", /** * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to "x-form-focus") * 当表单元素获取焦点时的CSS样式(默认为"x-form-focus") */ focusClass : "x-form-focus", /** * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable automatic validation (defaults to "keyup"). * 初始化元素验证的事件名,如果设假,则不进行验证(默认"keyup") */ validationEvent : "keyup", /** * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true). * 是否当失去焦点时验证此表单元素(默认真)。 */ validateOnBlur : true, /** * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation is initiated (defaults to 250) * 用户输入开始到验证开始的间隔毫秒数(默认250毫秒) */ validationDelay : 250, /** * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to * {tag: "input", type: "text", size: "20", autocomplete: "off"}) * 一个指定的DomHelper对象,如果为真则为一个默认对象(默认 {tag: "input", type: "text", size: "20", autocomplete: "off"}) */ defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"}, /** * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field") * 表单元素一般状态CSS样式(默认为"x-form-field") */ fieldClass : "x-form-field", /** * @cfg {String} msgTarget The location where error text should display. Should be one of the following values (defaults to 'qtip'): * 错误提示的显示位置。 可以是以下列表中的任意一项(默认为"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> The effect used when displaying a validation message under the field (defaults to 'normal'). * 表单元素无效提示显示的动画效果(默认为"normal") */ msgFx : 'normal', /** * @cfg {Boolean} readOnly True to mark the field as readOnly in HTML (defaults to false) -- Note: this only sets the element's readOnly DOM attribute. * 如果为真,则在HTML时标明此表单元素为只读 -- 注意:只是设置表单对象的只读属性。 */ readOnly : false, /** * @cfg {Boolean} disabled True to disable the field (defaults to false). * 为真则标明此表单元素为不可用(默认为假) */ disabled : false, /** * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password (defaults to "text"). * "input"类表单元素的类型属性 -- 例如:radio,text,password (默认为"text") */ inputType : undefined, /** * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined). * 这个表单元素的"tabIndex"(Tab键索引数)。只适用于被渲染的表单元素,并不是通过用"applyTo"方法建立的对象(默认为未定义) */ tabIndex : undefined, // private isFormField : true, // private hasFocus : false, /** * @cfg {Mixed} value A value to initialize this field with. * 表单元素初始化值。 */ value : undefined, /** * @cfg {String} name The field's HTML name attribute. * 在表单元素的HTML名称属性。 */ /** * @cfg {String} cls A CSS class to apply to the field's underlying element. * 一个应用于表单元素上的CSS样式。 */ // private ?? initComponent : function(){ Ext.form.Field.superclass.initComponent.call(this); this.addEvents({ /** * @event focus * Fires when this field receives input focus. * 当此元素获取焦点时激发此事件。 * @param {Ext.form.Field} this */ focus : true, /** * @event blur * Fires when this field loses input focus. * 当此元素推动焦点时激发此事件。 * @param {Ext.form.Field} this */ blur : true, /** * @event specialkey * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check * {@link Ext.EventObject#getKey} to determine which key was pressed. * 任何一个关于导航类键(arrows,tab,enter,esc等)被敲击则触发此事件。你可以查看{@link Ext.EventObject#getKey}去断定哪个键被敲击。 * @param {Ext.form.Field} this * @param {Ext.EventObject} e The event object */ specialkey : true, /** * @event change * Fires just before the field blurs if the field value has changed. * 当元素失去焦点时,如果值被修改则触发此事件。 * @param {Ext.form.Field} this * @param {Mixed} newValue The new value 新值 * @param {Mixed} oldValue The original value 原始值 */ change : true, /** * @event invalid * Fires after the field has been marked as invalid. * 当此元素被标为无效后触发此事件。 * @param {Ext.form.Field} this * @param {String} msg The validation message */ invalid : true, /** * @event valid * Fires after the field has been validated with no errors. * 在此元素被验证有效后触发此事件。 * @param {Ext.form.Field} this */ valid : true }); }, /** * Returns the name attribute of the field if available * 试图获取元素的名称。 * @return {String} name The field name */ getName: function(){ return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || ''); }, // private 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(); }, /** * Apply the behaviors of this component to an existing element. <b>This is used instead of render().</b> * 把组件应用到一个现有的对象上。这个被用来代替render()方法。 * @param {String/HTMLElement/Element} el The id of the node, a DOM node or an existing Element * 节点对象的ID、DOM节点或一个现有对象。 * @return {Ext.form.Field} this */ applyTo : function(target){ this.allowDomMove = false; this.el = Ext.get(target); this.render(this.el.dom.parentNode); return this; }, // private initValue : function(){ if(this.value !== undefined){ this.setValue(this.value); }else if(this.el.dom.value.length > 0){ this.setValue(this.el.dom.value); } }, /** * Returns true if this field has been changed since it was originally loaded and is not disabled. * 它的原始值没有变更,并且它是可用的则返回真。 */ 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.isNavKeyPress()){ this.fireEvent("specialkey", this, e); } }, /** * Resets the current field value to the originally loaded value and clears any validation messages * 重置此元素的值到原始值,并且清除所有无效提示信息。 */ reset : function(){ this.setValue(this.originalValue); this.clearInvalid(); }, // private initEvents : function(){ this.el.on(Ext.isIE ? "keydown" : "keypress", this.fireKey, this); this.el.on("focus", this.onFocus, this); this.el.on("blur", this.onBlur, this); // reference to original value for reset this.originalValue = this.getValue(); }, // private onFocus : function(){ if(!Ext.isOpera && this.focusClass){ // don't touch in Opera this.el.addClass(this.focusClass); } if(!this.hasFocus){ this.hasFocus = true; this.startValue = this.getValue(); this.fireEvent("focus", this); } }, beforeBlur : Ext.emptyFn, // private onBlur : function(){ this.beforeBlur(); if(!Ext.isOpera && this.focusClass){ // don't touch in Opera 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); }, /** * Returns whether or not the field value is currently valid * 此元素是否有效。 * @param {Boolean} preventMark True to disable marking the field invalid * 为真则不去标志此对象任何无效信息。 * @return {Boolean} True if the value is valid, else false * 有效过则返回真,否则返回假。 */ 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; }, // private // Subclasses should provide the validation implementation by overriding this // 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.el.findParent('.x-form-element', 5, true); 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.el.findParent('.x-form-element', 5, true); 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); }, // private alignErrorIcon : function(){ this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]); }, /** * Clear any invalid styles/messages for this field * 清除元素任何无效标志样式与信息。 */ 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); }, /** * Returns the raw data value which may or may not be a valid, defined value. To return a normalized value see {@link #getValue}. * 返回可能无效的原始值。 * @return {Mixed} value The field value */ getRawValue : function(){ var v = this.el.getValue(); if(v === this.emptyText){ v = ''; } return v; }, /** * Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}. * 返回格式化后的数据(未定义或空值则会返回'')。返回原始值可以查看{@link #getRawValue}。 * @return {Mixed} value The field value */ getValue : function(){ var v = this.el.getValue(); if(v === this.emptyText || v === undefined){ v = ''; } return v; }, /** * Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}. * 跃过验证直接设置DOM元素值。需要验证的设值方法可以查看{@link #setValue}。 * @param {Mixed} value The value to set */ setRawValue : function(v){ return this.el.dom.value = (v === null || v === undefined ? '' : v); }, /** * Sets a data value into the field and validates it. To set the value directly without validation see {@link #setRawValue}. * 设置元素值并加以验证。如果想跃过验证直接设值则请看{@link #setRawValue}。 * @param {Mixed} value The value to set */ 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.isStrict && !Ext.isSafari){ if(Ext.isIE && (tag == 'input' || tag == 'textarea')){ if(tag == 'input'){ return w + 2; } if(tag = 'textarea'){ return w-2; } }else if(Ext.isOpera){ if(tag == 'input'){ return w + 2; } if(tag = 'textarea'){ return w-2; } } } return w; } }); // anything other than normal should be considered experimental 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}); } } };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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); }, /** * The error text to display when the email validation function returns false * @type String */ 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"', /** * The keystroke filter mask to be applied on email input * @type RegExp */ 'emailMask' : /[a-z0-9_\.\-@]/i, /** * The function used to validate URLs * @param {String} value The URL */ 'url' : function(v){ return url.test(v); }, /** * The error text to display when the url validation function returns false * @type String */ 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"', /** * The function used to validate alpha values * @param {String} value The value */ 'alpha' : function(v){ return alpha.test(v); }, /** * The error text to display when the alpha validation function returns 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, /** * The function used to validate alphanumeric values * @param {String} value The value */ 'alphanum' : function(v){ return alphanum.test(v); }, /** * The error text to display when the alphanumeric validation function returns false * @type String */ 'alphanumText' : 'This field should only contain letters, numbers and _', /** * The keystroke filter mask to be applied on alphanumeric input * @type RegExp */ 'alphanumMask' : /[a-z0-9_]/i }; }();
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ // 定义动作的接口(action interface) Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; Ext.form.Action.CLIENT_INVALID = 'client'; Ext.form.Action.SERVER_INVALID = 'server'; Ext.form.Action.CONNECT_FAILURE = 'connect'; Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { type : 'default', failureType : undefined, response : undefined, result : undefined, // 接口方法 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(){ return { success: this.success, failure: this.failure, scope: this, timeout: (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } }; 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, { type : 'submit', 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(), { 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); } }, 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 = 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, { type : 'load', run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(), { method:this.getMethod(), url:this.getUrl(false), params:this.getParams() })); }, 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); }, 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 = function(config){ this.mimicing = false; Ext.form.TriggerField.superclass.constructor.call(this, config); }; Ext.extend(Ext.form.TriggerField, 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, /** @cfg {Boolean} grow @hide */ /** @cfg {Number} growMin @hide */ /** @cfg {Number} growMax @hide */ /** * @hide * @method */ autoSize: Ext.emptyFn, // private monitorTab : true, // private deferHeight : true, // private onResize : function(w, h){ Ext.form.TriggerField.superclass.onResize.apply(this, arguments); if(typeof w == 'number'){ this.el.setWidth(this.adjustWidth('input', w - 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); 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, t){ if(!this.wrap.contains(t) && this.validateBlur()){ 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.wrap.removeClass('x-trigger-wrap-focus'); Ext.form.TriggerField.superclass.onBlur.call(this); }, // private // This should be overriden by any subclass that needs to check whether or not the field can be blurred. // 这个方法须有子类重写(覆盖),需要确认该域是否可以被雾化。 validateBlur : function(e, t){ 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 }); // 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 });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.BasicForm * @extends Ext.util.Observable * Supplies the functionality to do "actions" on forms and initialize Ext.form.Field types on existing markup. * 提供表单的多种动作("actions")功能,并且初始化 Ext.form.Field 类型在现有的标签上 * @constructor * @param {String/HTMLElement/Ext.Element} el The form element or its id 表单对象或它的ID * @param {Object} config Configuration options 配置表单对象的配置项选项 */ Ext.form.BasicForm = function(el, config){ Ext.apply(this, config); /* * The Ext.form.Field items in this form. * 所有表单内元素的集合。 * @type MixedCollection */ this.items = new Ext.util.MixedCollection(false, function(o){ return o.id || (o.id = Ext.id()); }); this.addEvents({ /** * @event beforeaction * Fires before any action is performed. Return false to cancel the action. * 在任何动作被执行前被触发。如果返回假则取消这个动作 * @param {Form} this * @param {Action} action action The action to be performed 要被执行的动作对象 */ beforeaction: true, /** * @event actionfailed * Fires when an action fails. * 当动作失败时被触发。 * @param {Form} this * @param {Action} action The action that failed 失败的动作对象 */ actionfailed : true, /** * @event actioncomplete * Fires when an action is completed. * 当动作完成时被触发。 * @param {Form} this * @param {Action} action action The action that completed 完成的动作对象 */ actioncomplete : true }); if(el){ this.initEl(el); } Ext.form.BasicForm.superclass.constructor.call(this); }; Ext.extend(Ext.form.BasicForm, Ext.util.Observable, { /** * @cfg {String} method * The request method to use (GET or POST) for form actions if one isn't supplied in the action options. * 所有动作的默认表单请求方法(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 * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read data when reading validation errors on "submit" actions. * This is completely optional as there is built-in support for processing JSON. * 一个Ext.data.DataReader对象(e.g. {@link Ext.data.XmlReader}),当执行"submit"动作出错时被用来读取数据 */ /** * @cfg {String} url * The URL to use for form actions if one isn't supplied in the action options. * 当动作选项未指定url时使用 */ /** * @cfg {Boolean} fileUpload * Set to true if this form is a file upload. * 当为true时,表单为文件上传类型。 */ /** * @cfg {Object} baseParams * Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}. * 表单请求时传递的参数。例,baseParams: {id: '123', foo: 'bar'} */ /** * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds). * 表单动作的超时秒数(默认30秒) */ timeout: 30, // private activeAction : null, /** * @cfg {Boolean} trackResetOnLoad If set to true, form.reset() resets to the last loaded * or setValues() data instead of when the form was first created. * 如果为true,表单对象的form.reset()方法重置到最后一次加载或setValues()数据, * */ trackResetOnLoad : 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 */ waitMsgTarget : undefined, // private initEl : function(el){ this.el = Ext.get(el); this.id = this.el.id || Ext.id(); this.el.on('submit', this.onSubmit, this); this.el.addClass('x-form'); }, // private onSubmit : function(e){ e.stopEvent(); }, /** * Returns true if client-side validation on the form is successful. * 如果客户端的验证通过则返回真 * @return Boolean */ isValid : function(){ var valid = true; this.items.each(function(f){ if(!f.validate()){ valid = false; } }); return valid; }, /** * Returns true if any fields in this form have changed since their original load. * 如果自从被加载后任何一个表单元素被修了,则返回真 * @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 (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; }, /** * Shortcut to do a submit action. * 做提交动作的简便方法。 * @param {Object} options The options to pass to the action (see {@link #doAction} for details) * 传递给动作对象的选项配制 (请见 {@link #doAction} ) * @return {BasicForm} this */ submit : function(options){ this.doAction('submit', options); return this; }, /** * Shortcut to do a load action. * 做加载动作的简便方法。 * @param {Object} options The options to pass to the action (see {@link #doAction} for details) * 传递给动作对象的选项配制 (请见 {@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); } }, /** * Find a Ext.form.Field in this form by id, dataIndex, name or hiddenName * 按传递的ID、索引或名称查询表单中的元素。 * @param {String} id The value to search for * 所要查询的值 * @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; }, /** * Mark fields in this form invalid in bulk. * 可以批量的标记表单元素为失效的。 * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2} * 即可以是像这样的 [{id:'fieldId', msg:'The message'},...] 数组,也可以是像这样 {id: msg, id2: msg2} 的一个HASH结构对象。 * @return {BasicForm} this */ markInvalid : function(errors){ if(errors instanceof Array){ 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; }, /** * Set values for fields in this form in bulk. * 表单元素批量赋值。 * @param {Array/Object} values Either an array in the form [{id:'fieldId', value:'foo'},...] or an object hash of {id: value, id2: value2} * 即可以是像这样的 [{id:'fieldId', value:'foo'},...] 数组,也可以是像这样 {id: value, id2: value2} 的一个HASH结构对象。 * @return {BasicForm} this */ setValues : function(values){ if(values instanceof Array){ // 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; }, /** * Returns the fields in this form as an object with key/value pairs. If multiple fields exist with the same name * 返回以键/值形式包函表单所有元素的信息对象。 * they are returned as an array. * 如果表单元素中有相同名称的对象,则返回一个同名数组。 * @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); }, /** * Clears all invalid messages in this form. * 清除表单中所有校验错误的显示信息。 * @return {BasicForm} this */ clearInvalid : function(){ this.items.each(function(f){ f.clearInvalid(); }); return this; }, /** * Resets this form. * 重置表单。 * @return {BasicForm} this */ reset : function(){ this.items.each(function(f){ f.reset(); }); return this; }, /** * Add Ext.form components to this form. * 向表单中清加组件。 * @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; }, /** * Removes a field from the items collection (does NOT remove its markup). * 从表单对象集中清除一个元素(不清除它的页面标签)。 * @param {Field} field * @return {BasicForm} this */ remove : function(field){ this.items.remove(field); return this; }, /** * Looks at the fields in this form, checks them for an id attribute, * 遍历表单所有元素,以ID属性检查它们是否在页面上存在, * and calls applyTo on the existing dom element with that 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.applyTo(f.id); } }); return this; }, /** * Calls {@link Ext#apply} for all fields in this form with the passed object. * 遍历表单元素并以传递的对象为参调用 {@link Ext#apply} 方法。 * @param {Object} values * @return {BasicForm} this */ applyToFields : function(o){ this.items.each(function(f){ Ext.apply(f, o); }); return this; }, /** * Calls {@link Ext#applyIf} for all field in this form with the passed object. * 遍历表单元素并以传递的对象为参调用 {@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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.TextField * @extends Ext.form.Field * Basic text field. Can be used as a direct replacement for traditional text inputs, or as the base * class for more sophisticated input controls (like {@link Ext.form.TextArea} and {@link Ext.form.ComboBox}). * 基本的文本字段。可以被当作传统文本转入框的直接代替, 或者当作其他更复杂输入控件的基础类(比如 {@link Ext.form.TextArea} 和 {@link Ext.form.ComboBox})。 * @constructor * 创建一个 TextField 对象 * @param {Object} config 配置项 */ Ext.form.TextField = function(config){ Ext.form.TextField.superclass.constructor.call(this, config); 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 文本字段本身 * @param {Number} width 新的字段宽度 */ autosize : true }); }; Ext.extend(Ext.form.TextField, 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', // 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.onKeyUp, this, {buffer:50}); this.el.on("click", this.autoSize, 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 onKeyUp : function(e){ if(!e.isNavKeyPress()){ this.autoSize(); } }, /** * Resets the current field value to the originally-loaded value and clears any validation messages. * Also adds emptyText and emptyClass if the original value was blank. * 将字段值重置为原始值, 并清除所有效验信息。如果原始值为空时还将使 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(); }, /** * Validates a value according to the field's validation rules and marks the field as invalid * if the validation fails * 根据字段的效验规则效验字段值, 并在效验失败时将字段标记为无效 * @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", v.length-end); range.select(); } } }, /** * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed. * This only takes effect if grow = true, and fires the autosize event. * 自动增长字段宽度以便容纳字段所允许的最大文本。仅在 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); } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.NumberField * @extends Ext.form.TextField * 数字型文本域,提供自动键击过滤和数字校验。 * @constructor * 创建一个新的NumberField对象 * @param {Object} config 配置选项 */ Ext.form.NumberField = function(config){ Ext.form.NumberField.superclass.constructor.call(this, config); }; Ext.extend(Ext.form.NumberField, 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", // private initEvents : function(){ Ext.form.NumberField.superclass.initEvents.call(this); var allowed = "0123456789"; 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; } var num = this.parseValue(value); if(isNaN(num)){ this.markInvalid(String.format(this.nanText, value)); return false; } 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))); }, // 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(value).toFixed(this.decimalPrecision); }, setValue : function(v){ Ext.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator)); }, // private decimalPrecisionFcn : function(v){ return Math.floor(v); }, beforeBlur : function(){ var v = this.parseValue(this.getRawValue()); if(v){ this.setValue(this.fixPrecision(v)); } } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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: true, /** * @event activate * 当编辑器首次获取焦点时触发。所有的插入操作都必须等待此事件完成。 * @param {HtmlEditor} this */ activate: true, /** * @event beforesync * 在把编辑器的 iframe 中的内容同步更新到文本域之前触发。返回 false 可取消更新。 * @param {HtmlEditor} this * @param {String} html */ beforesync: true, /** * @event beforepush * 在把文本域中的内容同步更新到编辑器的 iframe 之前触发。返回 false 可取消更新。 * @param {HtmlEditor} this * @param {String} html */ beforepush: true, /** * @event sync * 当把编辑器的 iframe 中的内容同步更新到文本域后触发。 * @param {HtmlEditor} this * @param {String} html */ sync: true, /** * @event push * 当把文本域中的内容同步更新到编辑器的 iframe 后触发。 * @param {HtmlEditor} this * @param {String} html */ push: true, /** * @event editmodechange * 当切换了编辑器的编辑模式后触发 * @param {HtmlEditor} this * @param {Boolean} sourceEdit 值为 true 时表示源码编辑模式, false 表示常规编辑模式。 */ editmodechange: true }) }, 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(''); }, /** * 受保护的方法, 一般不会被直接调用。当编辑器创建工具栏时调用此方法。如果你需要添加定制的工具栏按钮, 你可以覆写此方法。 * @param {HtmlEditor} editor */ createToolbar : function(editor){ function btn(id, toggle, handler){ return { id : 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(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', tabIndex: -1, 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( '-', { id:'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' }) }, { id:'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>'; }, // 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.id != '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){ 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'){ this.doc.designMode="on"; Ext.TaskMgr.stop(task); 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.doc.body || this.doc.documentElement).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.id != '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(); } this.setSize(this.wrap.getSize()); 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.doc.body || this.doc.documentElement); 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(v.length < 1){ v = '&nbsp;'; } if(this.fireEvent('beforepush', this, v) !== false){ (this.doc.body || this.doc.documentElement).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.doc.body || this.doc.documentElement); 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.doc.body || this.doc.documentElement)); 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.id == '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.id); }, /** * 对编辑的文本执行一条 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 */ });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.Form * @extends Ext.form.BasicForm * 使用js为类{@link Ext.form.BasicForm}添加动态加载效果的能力 * @constructor * @param {Object} config 配置选项 */ Ext.form.Form = function(config){ Ext.form.Form.superclass.constructor.call(this, null, config); this.url = this.url || this.action; if(!this.root){ this.root = new Ext.form.Layout(Ext.applyIf({ id: Ext.id() }, config)); } this.active = this.root; /** * 通过addButton方法向该表单添加的全部button(数组类型) * @type Array */ this.buttons = []; this.addEvents({ /** * @event clientvalidation * If the 如果配置项monitorValid为true,, 该事件会反复执行以通知valid state * @param {Form} this * @param {Boolean} valid true表示通过客户端的验证 */ clientvalidation: true }); }; Ext.extend(Ext.form.Form, Ext.form.BasicForm, { /** * @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容器对象 */ column : function(c){ var col = new Ext.form.Column(c); this.start(col); if(arguments.length > 1){ //兼容Opera的代码(duplicated) this.add.apply(this, Array.prototype.slice.call(arguments, 1)); this.end(); } return col; }, /** * 在布局堆栈中打开一个新的{@link Ext.form.FieldSet}类容器。 * 如果所有域在配置之后被通过,域将被添加同时该fieldset(域集合)被关闭,如果没有域被通过该fieldset仍然打开,直至end()方法被调用 * @param {Object} config 传入fieldset的配置 * @param {Field} field1 (可选的) 参数变量field1(Field类型) * @param {Field} field2 (可选的) 参数变量field2(Field类型) * @param {Field} etc (可选的) 可以自行添加多个域参数 * @return Column 该fieldset容器对象 */ fieldset : function(c){ var fs = new Ext.form.FieldSet(c); this.start(fs); if(arguments.length > 1){ //兼容Opera的代码(duplicated) this.add.apply(this, Array.prototype.slice.call(arguments, 1)); this.end(); } return fs; }, /** * 在布局堆栈中打开一个新的{@link Ext.form.Layout}类容器。如果所有域在配置之后被通过,域将被添加同时该容器被关闭, * 如果没有域被通过该容器仍然打开,直至end()方法被调用。 * @param {Object} config 传入Layout的配置 * @param {Field} field1 (可选的)参数变量field1(Field类型)(可选) * @param {Field} field2 (可选的)参数变量field2(Field类型)(可选) * @param {Field} etc (可选的) 可自行添加多个域参数 * @return Layout The container object 返回Layout,该容器对象 */ container : function(c){ var l = new Ext.form.Layout(c); this.start(l); if(arguments.length > 1){ //兼容Opera的代码(duplicated) this.add.apply(this, Array.prototype.slice.call(arguments, 1)); this.end(); } return l; }, /** * 在布局堆栈中打开被通过的容器。该容器可以是任意{@link Ext.form.Layout}或其子类的类型。 * @param {Object} container 一个类型为{@link Ext.form.Layout}或其子类的布局 * @return {Form} this */ start : function(c){ // 级联标签信息 Ext.applyIf(c, {'labelAlign': this.active.labelAlign, 'labelWidth': this.active.labelWidth, 'itemCls': this.active.itemCls}); this.active.stack.push(c); c.ownerCt = this.active; this.active = c; return this; }, /** * 关闭当前打开的容器 * @return {Form} this */ end : function(){ if(this.active == this.root){ return this; } this.active = this.active.ownerCt; return this; }, /** * 将Ext.form组件添加至当前打开的容器(例如 column、fieldset..等等)通过该方法加入的域, * 可允许带有fieldLabel的属性,这样的话,会有域标签(label of the field)文字的显示。 * @param {Field} field1 * @param {Field} field2 (可选的) * @param {Field} etc. (可选的) * @return {Form} this */ add : function(){ this.active.stack.push.apply(this.active.stack, arguments); var r = []; for(var i = 0, a = arguments, len = a.length; i < len; i++) { if(a[i].isFormField){ r.push(a[i]); } } if(r.length > 0){ Ext.form.Form.superclass.add.apply(this, r); } return this; }, /** * 在被通过的容器中实施该form, * 传入一个容器的参数,在该容器上渲染form,该方法只能被调用一次。 * @param {String/HTMLElement/Element} container 要渲染组件所在的元素 * @return {Form} this */ render : function(ct){ ct = Ext.get(ct); var o = this.autoCreate || { tag: 'form', method : this.method || 'POST', id : this.id || Ext.id() }; this.initEl(ct.createChild(o)); this.root.render(this.el); this.items.each(function(f){ f.render('x-form-el-'+f.id); }); if(this.buttons.length > 0){ // 要在IE上实现正确的布局,离不开表格 var tb = this.el.createChild({cls:'x-form-btns-ct', cn: { cls:"x-form-btns x-form-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-form-btn-td'; b.render(tr.appendChild(td)); } } if(this.monitorValid){ // 渲染后的初始化 this.startMonitoring(); } return this; }, /** * 在该form末尾添加按钮,<b>必须</b>在该form被渲染之前被调用。 * @param {String/Object} config 字符串会成为按钮的文字,一个对象可以是一个Button的config或者一个有效的Ext.DomHelper生成元素的配置对象 * @param {Function} handler 单击按钮时调用的函数 * @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(null, bc); this.buttons.push(btn); return btn; }, /** * 开始监视该form的有效状态。通常传入配置项“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; }, // private bindHandler : function(){ if(!this.bound){ return false; // 停止绑定 } var valid = true; this.items.each(function(f){ if(!f.isValid(true)){ valid = false; return false; } }); 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.Form = Ext.form.Form;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.Layout * @extends Ext.Component * 为布局(layout)创建一个容器,域以{@link Ext.form.Form}类型显示 * @constructor * @param {Object} config 配置选项 */ Ext.form.Layout = function(config){ Ext.form.Layout.superclass.constructor.call(this, config); this.stack = []; }; Ext.extend(Ext.form.Layout, Ext.Component, { /** * @cfg {String/Object} autoCreate * 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为{tag: 'div', cls: 'x-form-ct'}) */ /** * @cfg {String/Object/Function} style * 字符串特定的一种风格,例如"width:100px",或者form中的对象{width:"100px"},或者返回这样风格的函数。 */ /** * @cfg {String} labelAlign * 属性labelAlign(字符串),有效值为 "left," "top" 和 "right"(默认为 "left") */ /** * @cfg {Number} labelWidth * 属性labelWidth(数字型),用像素固定域中全部标签的宽度(默认为 undefined) */ /** * @cfg {Boolean} clear * 属性clear(布朗型),值为true时在布局的结尾添加一个清除元素,等价于CSS的属性clear: both (默认为true) */ clear : true, /** * @cfg {String} labelSeparator * 此分隔符用于域标签之后(默认为':') */ labelSeparator : ':', /** * @cfg {Boolean} hideLabels * 值为true时隐藏域中的全部标签(默认为false) */ hideLabels : false, // private defaultAutoCreate : {tag: 'div', cls: 'x-form-ct'}, // private onRender : function(ct, position){ if(this.el){ // from markup this.el = Ext.get(this.el); }else { // generate var cfg = this.getAutoCreate(); this.el = ct.createChild(cfg, position); } if(this.style){ this.el.applyStyles(this.style); } if(this.labelAlign){ this.el.addClass('x-form-label-'+this.labelAlign); } if(this.hideLabels){ this.labelStyle = "display:none"; this.elementStyle = "padding-left:0;"; }else{ if(typeof this.labelWidth == 'number'){ this.labelStyle = "width:"+this.labelWidth+"px;"; this.elementStyle = "padding-left:"+((this.labelWidth+(typeof this.labelPad == 'number' ? this.labelPad : 5))+'px')+";"; } if(this.labelAlign == 'top'){ this.labelStyle = "width:auto;"; this.elementStyle = "padding-left:0;"; } } var stack = this.stack; var slen = stack.length; if(slen > 0){ if(!this.fieldTpl){ var t = new Ext.Template( '<div class="x-form-item {5}">', '<label for="{0}" style="{2}">{1}{4}</label>', '<div class="x-form-element" id="x-form-el-{0}" style="{3}">', '</div>', '</div><div class="x-form-clear-left"></div>' ); t.disableFormats = true; t.compile(); Ext.form.Layout.prototype.fieldTpl = t; } for(var i = 0; i < slen; i++) { if(stack[i].isFormField){ this.renderField(stack[i]); }else{ this.renderComponent(stack[i]); } } } if(this.clear){ this.el.createChild({cls:'x-form-clear'}); } }, // private renderField : function(f){ this.fieldTpl.append(this.el, [ f.id, f.fieldLabel, f.labelStyle||this.labelStyle||'', this.elementStyle||'', typeof f.labelSeparator == 'undefined' ? this.labelSeparator : f.labelSeparator, f.itemCls||this.itemCls||'' ]); }, // private renderComponent : function(c){ c.render(this.el); } }); /** * @class Ext.form.Column * @extends Ext.form.Layout * 为布局创建一个列向容器,以{@link Ext.form.Form}类型呈现。 * @constructor * @param {Object} config 配置选项 */ Ext.form.Column = function(config){ Ext.form.Column.superclass.constructor.call(this, config); }; Ext.extend(Ext.form.Column, Ext.form.Layout, { /** * @cfg {Number/String} width * 该列的固定宽度,单位像素或是CSS允许的值( 默认为auto) */ /** * @cfg {String/Object} autoCreate * @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为{tag: 'div', cls: 'x-form-ct x-form-column'}) */ // private defaultAutoCreate : {tag: 'div', cls: 'x-form-ct x-form-column'}, // private onRender : function(ct, position){ Ext.form.Column.superclass.onRender.call(this, ct, position); if(this.width){ this.el.setWidth(this.width); } } }); /** * @class Ext.form.FieldSet * @extends Ext.form.Layout * 为布局创建一个域集合容器,以一个{@link Ext.form.Form}类型呈现 * @constructor * @param {Object} config 配置选项 */ Ext.form.FieldSet = function(config){ Ext.form.FieldSet.superclass.constructor.call(this, config); }; Ext.extend(Ext.form.FieldSet, Ext.form.Layout, { /** * @cfg {String} legend * 域集合说明的显示文字(默认'') */ /** * @cfg {String/Object} autoCreate * 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为(defaults to {tag: 'fieldset', cn: {tag:'legend'}}) */ // private defaultAutoCreate : {tag: 'fieldset', cn: {tag:'legend'}}, // private onRender : function(ct, position){ Ext.form.FieldSet.superclass.onRender.call(this, ct, position); if(this.legend){ this.setLegend(this.legend); } }, // private setLegend : function(text){ if(this.rendered){ this.el.child('legend').update(text); } } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 配置选项 */ Ext.form.ComboBox = function(config){ Ext.form.ComboBox.superclass.constructor.call(this, config); this.addEvents({ /** * @event expand * Fires when the dropdown list is expanded * 当下拉列表展开的时候触发 * @param {Ext.form.ComboBox} combo 组合框本身 */ 'expand' : true, /** * @event collapse * Fires when the dropdown list is collapsed * 当下拉列表收起的时候触发 * @param {Ext.form.ComboBox} combo 组合框本身 */ 'collapse' : true, /** * @event beforeselect * Fires before a list item is selected. Return false to cancel the selection. * 列表项被选中前触发。返回 false 可以取消选择。 * @param {Ext.form.ComboBox} combo 组合框本身 * @param {Ext.data.Record} record 从数据仓库中返回的数据记录(The data record returned from the underlying store) * @param {Number} index 选中项在下拉列表中的索引位置 */ 'beforeselect' : true, /** * @event select * Fires when a list item is selected * 当列表项被选中时触发 * @param {Ext.form.ComboBox} combo 组合框本身 * @param {Ext.data.Record} record 从数据仓库中返回的数据记录(The data record returned from the underlying store) * @param {Number} index 选中项在下拉列表中的索引位置 */ 'select' : true, /** * @event beforequery * Fires before all queries are processed. Return false to cancel the query or set cancel to true. * 所有的查询被处理前触发。返回 false 或者设置 cancel 参数为 true 可以取消查询。 * The event object passed has these properties: * 传递的事件对象包含这些属性: * @param {Ext.form.ComboBox} combo 组合框本身 * @param {String} query 查询语句 * @param {Boolean} forceAll 值为 true 时强制为 "all" 查询 * @param {Boolean} cancel 值为 true 时取消查询 * @param {Object} e 查询事件对象 */ 'beforequery': true }); 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); s.parentNode.removeChild(s); // remove it this.render(this.el.parentNode); }else{ s.parentNode.removeChild(s); // remove it } } this.selectedIndex = -1; if(this.mode == 'local'){ if(config.queryDelay === undefined){ this.queryDelay = 10; } if(config.minChars === undefined){ this.minChars = 0; } } }; Ext.extend(Ext.form.ComboBox, Ext.form.TriggerField, { /** * @cfg {String/HTMLElement/Element} transform 要转换为组合框的 id, DOM 节点 或者已有的 select 元素 */ /** * @cfg {Boolean} lazyRender 值为 true 时阻止 ComboBox 渲染直到该对象被请求(被渲染到 Ext.Editor 组件的时候应该使用这个参数,默认为 false) */ /** * @cfg {Boolean/Object} autoCreate 指定一个 DomHelper 对象, 或者设置值为 true 使用默认元素(默认为:{tag: "input", type: "text", size: "24", autocomplete: "off"}) */ /** * @cfg {Ext.data.Store} store 该组合框绑定的数据仓库(默认为 undefined) */ /** * @cfg {String} title 如果提供了, 则会创建一个包含此文本的元素并被添加到下拉列表的顶部(默认为 undefined, 表示没有头部元素) */ // private defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"}, /** * @cfg {Number} listWidth 以象素表示的下拉列表的宽度(默认的宽度与 ComboBox 的 width 属性一致) */ listWidth: undefined, /** * @cfg {String} displayField The underlying data field name to bind to this CombBox (defaults to undefined if mode = 'remote' or 'text' if mode = 'local') * 组合框用以展示的数据的字段名(如果 mode = 'remote' 则默认为 undefined, 如果 mode = 'local' 则默认为 'text') */ displayField: undefined, /** * @cfg {String} valueField The underlying data value name to bind to this CombBox (defaults to undefined if * mode = 'remote' or 'value' if mode = 'local'). Note: use of a valueField requires the user make a selection * in order for a value to be mapped. * 组合框用以取值的数据的字段名(如果 mode = 'remote' 则默认为 undefined, 如果 mode = 'local' 则默认为 'value')。 */ valueField: undefined, /** * @cfg {String} hiddenName 如果指定了, 则会动态生成一个以指定名称命名的隐藏域用来存放值数据(默认为) */ hiddenName: undefined, /** * @cfg {String} listClass 下拉列表元素应用的 CSS 类(默认为 '') */ listClass: '', /** * @cfg {String} selectedClass 下拉列表中选中项应用的 CSS 类(默认为 '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). * 触发器按钮使用的 CSS 类。触发器的类固定为 'x-form-trigger', 而如果指定了 triggerClass 属性的值则会被 <b>附加</b> 在其后。(默认为 'x-form-arrow-trigger' 用来显示一个向下的箭头图标) */ triggerClass : 'x-form-arrow-trigger', /** * @cfg {Boolean/String} shadow 值为 true 或者 "sides" 为默认效果, "frame" 为四方向阴影, "drop" 为右下角方向阴影 */ shadow:'sides', /** * @cfg {String} listAlign 一个有效的方位锚点值。 点击 {@link Ext.Element#alignTo} 查看支持的方向锚点(默认为 'tl-bl') */ listAlign: 'tl-bl?', /** * @cfg {Number} maxHeight 以象素表示的下拉列表最大高度(默认为 300) */ maxHeight: 300, /** * @cfg {String} triggerAction 触发器被激活时执行的动作。使用 'all' 来运行由 allQuery 属性指定的查询(默认为 'query') */ triggerAction: 'query', /** * @cfg {Number} minChars 在 autocomplete 和 typeahead 被激活之前用户必须输入的字符数(默认为 4, 如果 editable = false 则此属性无效) */ minChars : 4, /** * @cfg {Boolean} typeAhead 值为 true 时在经过指定延迟(typeAheadDelay)后弹出并自动选择输入的文本, 如果该文本与已知的值相匹配(默认为 false) */ typeAhead: false, /** * @cfg {Number} queryDelay 以毫秒表示的从开始输入到发出查询语句过滤下拉列表的时长(如果 mode = 'remote' 则默认为 500, 如果 mode = 'local' 则默认为 10) */ queryDelay: 500, /** * @cfg {Number} pageSize 如果值大于 0 ,则在下拉列表的底部显示一个分页工具条, 并且在执行过滤查询时将传递起始页和限制参数。只在 mode = 'remote' 时生效(默认为 0) */ pageSize: 0, /** * @cfg {Boolean} selectOnFocus 值为 true 时选择任何字段内已有文本时立即取得焦点。只在 editable = true 时生效(默认为 false) */ selectOnFocus:false, /** * @cfg {String} queryParam 供 querystring 查询时传递的名字(默认为 'query') */ queryParam: 'query', /** * @cfg {String} loadingText 当读取数据时在下拉列表显示的文本。仅当 mode = 'remote' 时可用(默认为 'Loading...') */ loadingText: 'Loading...', /** * @cfg {Boolean} resizable 值为 true 时则在下拉列表的底部添加缩放柄(默认为 false) */ resizable: false, /** * @cfg {Number} handleHeight 以像素表示的下拉列表的缩放柄的高度, 仅当 resizable = true 时可用(默认为 8) */ handleHeight : 8, /** * @cfg {Boolean} editable 值为 false 时防止用户直接在输入框内输入文本, 就像传统的选择框一样(默认为 true) */ editable: true, /** * @cfg {String} allQuery 发送到服务器用以返回不经过滤的所有记录的文本(默认为 '' */ allQuery: '', /** * @cfg {String} mode 如果 ComboBox 读取本地数据则将值设为 'local' (默认为 'remote' 表示从服务器读取数据) */ mode: 'remote', /** * @cfg {Number} minListWidth 以像素表示的下拉列表的最小宽度(默认为 70, 如果 listWidth 的指定值更高则自动忽略该参数) */ minListWidth : 70, /** * @cfg {Boolean} forceSelection 值为 true 时将限定选中的值为列表中的值, 值为 false 则允许用户将任意文本设置到字段(默认为 false) */ forceSelection:false, /** * @cfg {Number} typeAheadDelay 以毫秒表示的 typeahead 文本延迟显示量, 仅当 typeAhead = true 时生效(默认为 250) */ typeAheadDelay : 250, /** * @cfg {String} valueNotFoundText 当使用 name/value 组合框时, 如果调用 setValue 方法时传递的值没有在仓库中找到, 且定义了 valueNotFoundText 则在字段中显示该值(默认为 undefined) */ valueNotFoundText : undefined, // 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'); } 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(this.footer, this.store, {pageSize: this.pageSize}); this.assetHeight += this.footer.getHeight(); } if(!this.tpl){ this.tpl = '<div class="'+cls+'-item">{' + this.displayField + '}</div>'; } this.view = new Ext.View(this.innerList, this.tpl, { singleSelect:true, store: this.store, selectedClass: this.selectedClass }); this.view.on('click', this.onViewClick, this); this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.collapse, this); 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'); } if(!this.editable){ this.editable = true; this.setEditable(false); } }, // 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.setStore(null); this.view.el.removeAllListeners(); this.view.el.remove(); this.view.purgeListeners(); } if(this.list){ this.list.destroy(); } if(this.store){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.collapse, this); } 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')); } }, /** * 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. * 允许或防止用户直接编辑字段文本。如果传递值为 false, 用户将只能选择下拉列表中已经定义的选项。此方法相当于在配置时设置 'editable' 属性。 * @param {Boolean} value 值为 true 时允许用户直接编辑字段文本 */ 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 选中的值 */ 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 * 清除所有当前字段中设定的 text/value */ 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). * 将指定的值设定到字段。如果找到匹配的值, 字段中将显示相应的记录。如果在已有的选项中没有找到匹配的值, 则显示 valueNotFoundText 属性指定的文本。其他情况下显示为空(但仍然将字段的值设置为指定值)。 * @param {String} value 匹配的值 */ 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 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()+this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight); this.list.alignTo(this.el, this.listAlign); this.list.endUpdate(); }, // private onEmptyResults : function(){ this.collapse(); }, /** * 如果下拉列表已经展开则返回 true, 否则返回 false。 */ isExpanded : function(){ return this.list.isVisible(); }, /** * 根据数据的值选择下拉列表中的选项。本函数不会触发 'select' 事件。使用此函数必须在数据已经被读取且列表已经展开, 否则请使用 setValue 方法。 * @param {String} value 要选择的项的值 * @param {Boolean} scrollIntoView 值为 false 时阻止下拉列表自动滚动到选中项位置(默认为 true) * @return {Boolean} 如果给定值在列表中则返回 true, 否则返回 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' 事件。使用此函数必须在数据已经被读取且列表已经展开, 否则请使用 setValue 方法。 * @param {Number} index 选中项在列表中以 0 开始的索引数 * @param {Boolean} scrollIntoView 值为 false 时阻止下拉列表自动滚动到选中项位置(默认为 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(); } }, /** * 执行一个查询语句用以过滤下拉列表。在查询之前触发 'beforequery' 事件, 以便可以在需要的时候取消查询动作。 * @param {String} query 要执行的查询语句 * @param {Boolean} forceAll 值为 true 时强制执行查询即使当前输入的字符少于 minChars 设置项指定的值。同时还会清除当前数据仓库中保存的前一次结果(默认为 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; }, /** * 如果下拉列表当前是展开状态则隐藏它。并触发 'collapse' 事件。 */ collapse : function(){ if(!this.isExpanded()){ return; } this.list.hide(); Ext.get(document).un('mousedown', this.collapseIf, this); Ext.get(document).un('mousewheel', this.collapseIf, this); this.fireEvent('collapse', this); }, // private collapseIf : function(e){ if(!e.within(this.wrap) && !e.within(this.list)){ this.collapse(); } }, /** * 如果下拉列表当前是隐藏状态则展开它。并触发 'expand' 事件。 */ expand : function(){ if(this.isExpanded() || !this.hasFocus){ return; } this.list.alignTo(this.el, this.listAlign); this.list.show(); Ext.get(document).on('mousedown', this.collapseIf, this); Ext.get(document).on('mousewheel', 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.hasFocus = true; if(this.triggerAction == 'all') { this.doQuery(this.allQuery, true); } else { this.doQuery(this.getRawValue()); } this.el.focus(); } } /** @cfg {Boolean} grow @hide */ /** @cfg {Number} growMin @hide */ /** @cfg {Number} growMax @hide */ /** * @hide * @method autoSize */ });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 = function(config){ Ext.form.DateField.superclass.constructor.call(this, config); 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 + ")"); } }; Ext.extend(Ext.form.DateField, Ext.form.TriggerField, { /** * @cfg {String} format * The default date format string which can be overriden for localization support. The format must be * valid according to {@link Date#parseDate} (defaults to 'm/d/y'). * 用以覆盖本地化的默认日期格式化字串。字串必须为符合 {@link Date#parseDate} 指定的形式(默认为 'm/d/y')。 */ format : "m/d/y", /** * @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'). * 用 "|" 符号分隔的多个日期格式化字串, 当输入的日期与默认的格式不符时用来尝试格式化输入值(默认为 '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 * An array of days to disable, 0 based. For example, [0, 6] disables Sunday and Saturday (defaults to null). * 一个禁用的星期数组, 以 0 开始。例如, [0,6] 表示禁用周六和周日(默认为 null)。 */ disabledDays : null, /** * @cfg {String} disabledDaysText * The tooltip to display when the date falls on a disabled day (defaults to 'Disabled') * 禁用星期上显示的工具提示(默认为 '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> * In order to support regular expressions, if you are using a date format that has "." in it, you will have to * escape the dot when restricting dates. For example: ["03\\.08\\.03"]. * 为了提供正则表达式的支持, 如果你使用一个包含 "." 的日期格式, 你就得将小数点转义使用。例如: ["03\\.08\\.03"]。 */ disabledDates : null, /** * @cfg {String} disabledDatesText * The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled') * 禁用日期上显示的工具提示(默认为 'Disabled') */ disabledDatesText : "Disabled", /** * @cfg {Date/String} minValue * The minimum allowed date. Can be either a Javascript date object or a string date in a * valid format (defaults to null). * 允许的最小日期。可以是一个 Javascript 日期对象或一个有效格式的字串(默认为 null) */ minValue : null, /** * @cfg {Date/String} maxValue * The maximum allowed date. Can be either a Javascript date object or a string date in a * valid format (defaults to null). * 允许的最大日期。可以是一个 Javascript 日期对象或一个有效格式的字串(默认为 null) */ maxValue : null, /** * @cfg {String} minText * The error text to display when the date in the cell is before minValue (defaults to * 'The date in this field must be after {minValue}'). * 当字段的日期早于 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 * The error text to display when the date in the cell is after maxValue (defaults to * 'The date in this field must be before {maxValue}'). * 当字段的日期晚于 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 * The error text to display when the date in the field is invalid (defaults to * '{value} is not a valid date - it must be in the format {format}'). * 当字段的日期无效时显示的错误文本(默认为 '{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 * 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-date-trigger' * which displays a calendar icon). * 用以指定触发按钮的附加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"}, // 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(); }, /** * Returns the current date value of the date field. * @return {Date} The date value */ 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 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 */ });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.form.Checkbox * @extends Ext.form.Field * 单独的checkbox域,可以直接代替传统checkbox域 * @constructor * 创建一个新的CheckBox对象 * @param {Object} config 配置项选项 */ Ext.form.Checkbox = function(config){ Ext.form.Checkbox.superclass.constructor.call(this, config); this.addEvents({ /** * @event check * 当checkbox被单击时触发事件,无论有选中还是没有选中。 * @param {Ext.form.Checkbox} this 表示当前checkbox * @param {Boolean} checked 选中的值 */ check : true }); }; Ext.extend(Ext.form.Checkbox, 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旁边显示的文字 * */ boxLabel : undefined, /** * @cfg {String} inputValue 导出input元素属性值 */ // onResize : function(){ Ext.form.Checkbox.superclass.onResize.apply(this, arguments); if(!this.boxLabel){ this.el.alignTo(this.wrap, 'c-c'); } }, initEvents : function(){ Ext.form.Checkbox.superclass.initEvents.call(this); this.el.on("click", this.onClick, this); this.el.on("change", this.onClick, this); }, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, // 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 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); } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /** * @class Ext.SplitButton * @extends Ext.Button * Split按钮可为按钮提供内建的箭头,能触发与按钮本身的单击事件不同事件。 * 典型的应用是一个“总的”按钮按下后出现的下拉菜单,以提供更大的选择,但是也可以在箭头被单击时提供一个自定义的事件处理器实现。 * @cfg {Function} arrowHandler 当箭头按钮被单击时所执行的函数(可代替单击的事件) * @cfg {String} arrowTooltip 箭头的title属性 * @constructor * 创建菜单按钮 * @param {String/HTMLElement/Element} renderTo 按钮加入到的元素 * @param {Object} config 配置项对象 */ Ext.SplitButton = function(renderTo, config){ Ext.SplitButton.superclass.constructor.call(this, renderTo, config); /** * @event arrowclick * 当按钮箭头单击时触发 * @param {SplitButton} this * @param {EventObject} e 单击事件 */ this.addEvents({"arrowclick":true}); }; Ext.extend(Ext.SplitButton, Ext.Button, { render : function(renderTo){ // this is one sweet looking template! var tpl = new Ext.Template( '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>', '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>', '<tr><td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>', "</tbody></table></td><td>", '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>', '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button">&#160;</button></td><td class="x-btn-right"><i>&#160;</i></td></tr>', "</tbody></table></td></tr></table>" ); var btn = tpl.append(renderTo, [this.text, this.type], true); var btnEl = btn.child("button"); if(this.cls){ btn.addClass(this.cls); } if(this.icon){ btnEl.setStyle('background-image', 'url(' +this.icon +')'); } if(this.iconCls){ btnEl.addClass(this.iconCls); if(!this.cls){ btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon'); } } this.el = btn; if(this.handleMouseEvents){ btn.on("mouseover", this.onMouseOver, this); btn.on("mouseout", this.onMouseOut, this); btn.on("mousedown", this.onMouseDown, this); btn.on("mouseup", this.onMouseUp, this); } btn.on(this.clickEvent, this.onClick, this); if(this.tooltip){ if(typeof this.tooltip == 'object'){ Ext.QuickTips.tips(Ext.apply({ target: btnEl.id }, this.tooltip)); } else { btnEl.dom[this.tooltipType] = this.tooltip; } } if(this.arrowTooltip){ btn.child("button:nth(2)").dom[this.tooltipType] = this.arrowTooltip; } if(this.hidden){ this.hide(); } if(this.disabled){ this.disable(); } if(this.pressed){ this.el.addClass("x-btn-pressed"); } if(Ext.isIE && !Ext.isIE7){ this.autoWidth.defer(1, this); }else{ this.autoWidth(); } if(this.menu){ this.menu.on("show", this.onMenuShow, this); this.menu.on("hide", this.onMenuHide, this); } }, // private autoWidth : function(){ if(this.el){ var tbl = this.el.child("table:first"); var tbl2 = this.el.child("table:last"); this.el.setWidth("auto"); tbl.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child('button:first'); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if(this.hidden){ this.el.beginMeasure(); } if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){ tbl.setWidth(this.minWidth-tbl2.getWidth()); } if(this.hidden){ this.el.endMeasure(); } } this.el.setWidth(tbl.getWidth()+tbl2.getWidth()); } }, /** * 设置按钮单击时的事件处理器 * @param {Function} handler 按钮单击时调用的函数 * @param {Object} scope (可选的)刚才传入函数的作用域 */ setHandler : function(handler, scope){ this.handler = handler; this.scope = scope; }, /** * 设置按钮箭头被单击时的动作(事件处理器) * @param {Function} handler 箭头单击时调用的函数 * @param {Object} scope (可选的)刚才传入函数的作用域 */ setArrowHandler : function(handler, scope){ this.arrowHandler = handler; this.scope = scope; }, /** * 按钮得到焦点 */ focus : function(){ if(this.el){ this.el.child("button:first").focus(); } }, // private onClick : function(e){ e.preventDefault(); if(!this.disabled){ if(e.getTarget(".x-btn-menu-arrow-wrap")){ if(this.menu && !this.menu.isVisible()){ this.menu.show(this.el, this.menuAlign); } this.fireEvent("arrowclick", this, e); if(this.arrowHandler){ this.arrowHandler.call(this.scope || this, this, e); } }else{ this.fireEvent("click", this, e); if(this.handler){ this.handler.call(this.scope || this, this, e); } } } }, // private onMouseDown : function(e){ if(!this.disabled){ Ext.fly(e.getTarget("table")).addClass("x-btn-click"); } }, // private onMouseUp : function(e){ Ext.fly(e.getTarget("table")).removeClass("x-btn-click"); } }); // backwards compat Ext.MenuButton = Ext.SplitButton;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.grid.CellSelectionModel * @extends Ext.grid.AbstractSelectionModel * 本类提供了grid单元格选区的基本实现。 * @constructor * @param {Object} config 针对该模型的配置对象。 */ Ext.grid.CellSelectionModel = function(config){ Ext.apply(this, config); this.selection = null; this.addEvents({ /** * @event beforerowselect * 单元格(cell)被选中之前触发 * @param {SelectionModel} this * @param {Number} rowIndex 选中的行索引 * @param {Number} colIndex 选中的单元格索引 */ "beforecellselect" : true, /** * @event cellselect * 当单元格(cell)被选中时触发 * @param {SelectionModel} this * @param {Number} rowIndex 选中的行索引 * @param {Number} colIndex 选中的单元格索引 */ "cellselect" : true, /** * @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" : true }); }; Ext.extend(Ext.grid.CellSelectionModel, Ext.grid.AbstractSelectionModel, { /** @ignore */ initEvents : function(){ this.grid.on("mousedown", 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(e, t){ var v = this.grid.getView(); if(this.isLocked()){ return; }; var row = v.findRowIndex(t); var cell = v.findCellIndex(t); if(row !== false && cell !== false){ this.select(row, cell); } }, /** * 选中一个单元格(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.dataSource.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 && !e.ctrlKey){ ed.completeEdit(); e.stopEvent(); }else if(k == e.ESC){ ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ // 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:"frame" });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.grid.EditorGrid * @extends Ext.grid.Grid * 创建和编辑GRID的类。 * @param {String/HTMLElement/Ext.Element} container 承载GRID的那个元素 * 容器必须先定义一些类型和长度,以便Grid填充。容器会自动设置其为相对定位( position relative)。 * @param {Object} dataSource 绑定的数据模型(DataModel) * @param {Object} colModel Grid的列模型(Column Model),负责保存grid每一列的有关信息 */ Ext.grid.EditorGrid = function(container, config){ Ext.grid.EditorGrid.superclass.constructor.call(this, container, config); this.getGridEl().addClass("xedit-grid"); 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" : true, /** * @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" : true, /** * @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" : true }); this.on("bodyscroll", this.stopEditing, this); this.on(this.clicksToEdit == 1 ? "cellclick" : "celldblclick", this.onCellDblClick, this); }; Ext.extend(Ext.grid.EditorGrid, Ext.grid.Grid, { isEditor : true, /** * @cfg {Number} clicksToEdit * 要转换单元格为编辑状态所需的鼠标点击数(默认为两下,即双击) */ clicksToEdit: 2, trackMouseOver: false, // 引起奇怪的FF错误 onCellDblClick : function(g, row, col){ this.startEditing(row, col); }, 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} row 行索引 * @param {Number} col 类索引 */ startEditing : function(row, col){ this.stopEditing(); if(this.colModel.isCellEditable(col, row)){ this.view.ensureVisible(row, col, true); var r = this.dataSource.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(ed.parentEl || document.body); } (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; } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.grid.GridView * @extends Ext.util.Observable * * @constructor * @param {Object} config */ Ext.grid.GridView = function(config){ Ext.grid.GridView.superclass.constructor.call(this); this.el = null; Ext.apply(this, config); }; Ext.extend(Ext.grid.GridView, Ext.grid.AbstractGridView, { /** * 重写该函数可应用自定义CSS Class进行渲染 * @param {Record} record The record * @param {Number} index * @method getRowClass */ rowClass : "x-grid-row", cellClass : "x-grid-col", tdClass : "x-grid-td", hdClass : "x-grid-hd", splitClass : "x-grid-split", sortClasses : ["sort-asc", "sort-desc"], enableMoveAnim : false, hlColor: "C3DAF9", dh : Ext.DomHelper, fly : Ext.Element.fly, css : Ext.util.CSS, borderWidth: 1, splitOffset: 3, scrollIncrement : 22, cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/, findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/, bind : 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("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){ this.generateRules(cm); 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; }, init: function(grid){ Ext.grid.GridView.superclass.init.call(this, grid); this.bind(grid.dataSource, grid.colModel); grid.on("headerclick", this.handleHeaderClick, this); if(grid.trackMouseOver){ grid.on("mouseover", this.onRowOver, this); grid.on("mouseout", this.onRowOut, this); } grid.cancelTextSelection = function(){}; this.gridId = grid.id; var tpls = this.templates || {}; if(!tpls.master){ tpls.master = new Ext.Template( '<div class="x-grid" hidefocus="true">', '<div class="x-grid-topbar"></div>', '<div class="x-grid-scroller"><div></div></div>', '<div class="x-grid-locked">', '<div class="x-grid-header">{lockedHeader}</div>', '<div class="x-grid-body">{lockedBody}</div>', "</div>", '<div class="x-grid-viewport">', '<div class="x-grid-header">{header}</div>', '<div class="x-grid-body">{body}</div>', "</div>", '<div class="x-grid-bottombar"></div>', '<a href="#" class="x-grid-focus" tabIndex="-1"></a>', '<div class="x-grid-resize-proxy">&#160;</div>', "</div>" ); tpls.master.disableformats = true; } if(!tpls.header){ tpls.header = new Ext.Template( '<table border="0" cellspacing="0" cellpadding="0">', '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>', "</table>{splits}" ); tpls.header.disableformats = true; } tpls.header.compile(); if(!tpls.hcell){ tpls.hcell = new Ext.Template( '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">', '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" /></div>', "</div></td>" ); tpls.hcell.disableFormats = true; } tpls.hcell.compile(); if(!tpls.hsplit){ tpls.hsplit = new Ext.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on">&#160;</div>'); tpls.hsplit.disableFormats = true; } tpls.hsplit.compile(); if(!tpls.body){ tpls.body = new Ext.Template( '<table border="0" cellspacing="0" cellpadding="0">', "<tbody>{rows}</tbody>", "</table>" ); tpls.body.disableFormats = true; } tpls.body.compile(); if(!tpls.row){ tpls.row = new Ext.Template('<tr class="x-grid-row {alt}">{cells}</tr>'); tpls.row.disableFormats = true; } tpls.row.compile(); if(!tpls.cell){ tpls.cell = new Ext.Template( '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">', '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text" unselectable="on" {attr}>{value}</div></div>', "</td>" ); tpls.cell.disableFormats = true; } tpls.cell.compile(); this.templates = tpls; }, // 为向后兼容 onColWidthChange : function(){ this.updateColumns.apply(this, arguments); }, onHeaderChange : function(){ this.updateHeaders.apply(this, arguments); }, onHiddenChange : function(){ this.handleHiddenChange.apply(this, arguments); }, onColumnMove : function(){ this.handleColumnMove.apply(this, arguments); }, onColumnLock : function(){ this.handleLockChange.apply(this, arguments); }, onDataChange : function(){ this.refresh(); this.updateHeaderSortState(); }, onClear : function(){ this.refresh(); }, onUpdate : function(ds, record){ this.refreshRow(record); }, refreshRow : function(record){ var ds = this.ds, index; if(typeof record == 'number'){ index = record; record = ds.getAt(index); }else{ index = ds.indexOf(record); } this.insertRows(ds, index, index, true); this.onRemove(ds, record, index+1, true); this.syncRowHeights(index, index); this.layout(); this.fireEvent("rowupdated", this, index, record); }, onAdd : function(ds, records, index){ this.insertRows(ds, index, index + (records.length-1)); }, onRemove : function(ds, record, index, isUpdate){ if(isUpdate !== true){ this.fireEvent("beforerowremoved", this, index, record); } var bt = this.getBodyTable(), lt = this.getLockedTable(); if(bt.rows[index]){ bt.firstChild.removeChild(bt.rows[index]); } if(lt.rows[index]){ lt.firstChild.removeChild(lt.rows[index]); } if(isUpdate !== true){ this.stripeRows(index); this.syncRowHeights(index, index); this.layout(); this.fireEvent("rowremoved", this, index, record); } }, onLoad : function(){ this.scrollToTop(); }, /** * 滚动grid到顶部 */ scrollToTop : function(){ if(this.scroller){ this.scroller.dom.scrollTop = 0; this.syncScroll(); } }, /** * 获取grid的头部面板,用于放置工具条(toolbars)等的面板。 * 每当面板的内容有所变动的话,应调用grid.autoSize()刷新尺寸。 * @param {Boolean} doShow 默认情况下header是隐藏的,传入true的参数可展示 * @return Ext.Element */ getHeaderPanel : function(doShow){ if(doShow){ this.headerPanel.show(); } return this.headerPanel; }, /** * 获取grid的底部部面板,用于放置工具条(toolbars)等的面板。 * 每当面板的内容有所变动的话,应调用grid.autoSize()刷新尺寸。 * @param {Boolean} doShow 默认情况下header是隐藏的,传入true的参数可展示 * @return Ext.Element */ getFooterPanel : function(doShow){ if(doShow){ this.footerPanel.show(); } return this.footerPanel; }, initElements : function(){ var E = Ext.Element; var el = this.grid.getGridEl().dom.firstChild; var cs = el.childNodes; this.el = new E(el); this.headerPanel = new E(el.firstChild); this.headerPanel.enableDisplayMode("block"); this.scroller = new E(cs[1]); this.scrollSizer = new E(this.scroller.dom.firstChild); this.lockedWrap = new E(cs[2]); this.lockedHd = new E(this.lockedWrap.dom.firstChild); this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]); this.mainWrap = new E(cs[3]); this.mainHd = new E(this.mainWrap.dom.firstChild); this.mainBody = new E(this.mainWrap.dom.childNodes[1]); this.footerPanel = new E(cs[4]); this.footerPanel.enableDisplayMode("block"); this.focusEl = new E(cs[5]); this.focusEl.swallowEvent("click", true); this.resizeProxy = new E(cs[6]); this.headerSelector = String.format( '#{0} td.x-grid-hd, #{1} td.x-grid-hd', this.lockedHd.id, this.mainHd.id ); this.splitterSelector = String.format( '#{0} div.x-grid-split, #{1} div.x-grid-split', this.lockedHd.id, this.mainHd.id ); }, getHeaderCell : function(index){ return Ext.DomQuery.select(this.headerSelector)[index]; }, getHeaderCellMeasure : function(index){ return this.getHeaderCell(index).firstChild; }, getHeaderCellText : function(index){ return this.getHeaderCell(index).firstChild.firstChild; }, getLockedTable : function(){ return this.lockedBody.dom.firstChild; }, getBodyTable : function(){ return this.mainBody.dom.firstChild; }, getLockedRow : function(index){ return this.getLockedTable().rows[index]; }, getRow : function(index){ return this.getBodyTable().rows[index]; }, getRowComposite : function(index){ if(!this.rowEl){ this.rowEl = new Ext.CompositeElementLite(); } var els = [], lrow, mrow; if(lrow = this.getLockedRow(index)){ els.push(lrow); } if(mrow = this.getRow(index)){ els.push(mrow); } this.rowEl.elements = els; return this.rowEl; }, getCell : function(rowIndex, colIndex){ var locked = this.cm.getLockedCount(); var source; if(colIndex < locked){ source = this.lockedBody.dom.firstChild; }else{ source = this.mainBody.dom.firstChild; colIndex -= locked; } return source.rows[rowIndex].childNodes[colIndex]; }, getCellText : function(rowIndex, colIndex){ return this.getCell(rowIndex, colIndex).firstChild.firstChild; }, getCellBox : function(cell){ var b = this.fly(cell).getBox(); if(Ext.isOpera){ // opera fails to report the Y b.y = cell.offsetTop + this.mainBody.getY(); } return b; }, getCellIndex : function(cell){ var id = String(cell.className).match(this.cellRE); if(id){ return parseInt(id[1], 10); } return 0; }, findHeaderIndex : function(n){ var r = Ext.fly(n).findParent("td." + this.hdClass, 6); return r ? this.getCellIndex(r) : false; }, findHeaderCell : function(n){ var r = Ext.fly(n).findParent("td." + this.hdClass, 6); return r ? r : false; }, findRowIndex : function(n){ if(!n){ return false; } var r = Ext.fly(n).findParent("tr." + this.rowClass, 6); return r ? r.rowIndex : false; }, findCellIndex : function(node){ var stop = this.el.dom; while(node && node != stop){ if(this.findRE.test(node.className)){ return this.getCellIndex(node); } node = node.parentNode; } return false; }, getColumnId : function(index){ return this.cm.getColumnId(index); }, getSplitters : function(){ if(this.splitterSelector){ return Ext.DomQuery.select(this.splitterSelector); }else{ return null; } }, getSplitter : function(index){ return this.getSplitters()[index]; }, onRowOver : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false){ this.getRowComposite(row).addClass("x-grid-row-over"); } }, onRowOut : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){ this.getRowComposite(row).removeClass("x-grid-row-over"); } }, renderHeaders : function(){ var cm = this.cm; var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit; var cb = [], lb = [], sb = [], lsb = [], p = {}; for(var i = 0, len = cm.getColumnCount(); i < len; i++){ p.cellId = "x-grid-hd-0-" + i; p.splitId = "x-grid-csplit-0-" + i; p.id = cm.getColumnId(i); p.title = cm.getColumnTooltip(i) || ""; p.value = cm.getColumnHeader(i) || ""; p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : ''; if(!cm.isLocked(i)){ cb[cb.length] = ct.apply(p); sb[sb.length] = st.apply(p); }else{ lb[lb.length] = ct.apply(p); lsb[lsb.length] = st.apply(p); } } return [ht.apply({cells: lb.join(""), splits:lsb.join("")}), ht.apply({cells: cb.join(""), splits:sb.join("")})]; }, updateHeaders : function(){ var html = this.renderHeaders(); this.lockedHd.update(html[0]); this.mainHd.update(html[1]); }, /** * 使指定的行得到焦点 * @param {Number} row 行索引 */ focusRow : function(row){ var x = this.scroller.dom.scrollLeft; this.focusCell(row, 0, false); this.scroller.dom.scrollLeft = x; }, /** * 使指定的单元格得到焦点 * @param {Number} row 行索引 * @param {Number} col 列索引 * @param {Boolean} hscroll false含义为禁止水平滚动 */ focusCell : function(row, col, hscroll){ var el = this.ensureVisible(row, col, hscroll); this.focusEl.alignTo(el, "tl-tl"); if(Ext.isGecko){ this.focusEl.focus(); }else{ this.focusEl.focus.defer(1, this.focusEl); } }, /** * 将指定的单元格滚动到视图(view) * @param {Number} row 行索引 * @param {Number} col 列索引 * @param {Boolean} hscroll false含义为禁止水平滚动 */ 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 cm = this.grid.colModel; while(cm.isHidden(col)){ col++; } var el = this.getCell(row, col); if(!el){ return; } var c = this.scroller.dom; var ctop = parseInt(el.offsetTop, 10); var cleft = parseInt(el.offsetLeft, 10); var cbot = ctop + el.offsetHeight; var cright = cleft + el.offsetWidth; var ch = c.clientHeight - this.mainHd.dom.offsetHeight; var stop = parseInt(c.scrollTop, 10); var sleft = parseInt(c.scrollLeft, 10); var sbot = stop + ch; var sright = sleft + c.clientWidth; if(ctop < stop){ c.scrollTop = ctop; }else if(cbot > sbot){ c.scrollTop = cbot-ch; } if(hscroll !== false){ if(cleft < sleft){ c.scrollLeft = cleft; }else if(cright > sright){ c.scrollLeft = cright-c.clientWidth; } } return el; }, updateColumns : function(){ this.grid.stopEditing(); var cm = this.grid.colModel, colIds = this.getColumnIds(); //var totalWidth = cm.getTotalWidth(); var pos = 0; for(var i = 0, len = cm.getColumnCount(); i < len; i++){ //if(cm.isHidden(i)) continue; var w = cm.getColumnWidth(i); this.css.updateRule(this.colSelector+colIds[i], "width", (w - this.borderWidth) + "px"); this.css.updateRule(this.hdSelector+colIds[i], "width", (w - this.borderWidth) + "px"); } this.updateSplitters(); }, generateRules : function(cm){ var ruleBuf = [], rulesId = this.grid.id + '-cssrules'; Ext.util.CSS.removeStyleSheet(rulesId); for(var i = 0, len = cm.getColumnCount(); i < len; i++){ var cid = cm.getColumnId(i); var align = ''; if(cm.config[i].align){ align = 'text-align:'+cm.config[i].align+';'; } var hidden = ''; if(cm.isHidden(i)){ hidden = 'display:none;'; } var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;"; ruleBuf.push( this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n", this.hdSelector, cid, " {\n", align, width, "}\n", this.tdSelector, cid, " {\n",hidden,"\n}\n", this.splitSelector, cid, " {\n", hidden , "\n}\n"); } return Ext.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId); }, updateSplitters : function(){ var cm = this.cm, s = this.getSplitters(); if(s){ // splitters not created yet var pos = 0, locked = true; for(var i = 0, len = cm.getColumnCount(); i < len; i++){ if(cm.isHidden(i)) continue; var w = cm.getColumnWidth(i); if(!cm.isLocked(i) && locked){ pos = 0; locked = false; } pos += w; s[i].style.left = (pos-this.splitOffset) + "px"; } } }, handleHiddenChange : function(colModel, colIndex, hidden){ if(hidden){ this.hideColumn(colIndex); }else{ this.unhideColumn(colIndex); } }, hideColumn : function(colIndex){ var cid = this.getColumnId(colIndex); this.css.updateRule(this.tdSelector+cid, "display", "none"); this.css.updateRule(this.splitSelector+cid, "display", "none"); if(Ext.isSafari){ this.updateHeaders(); } this.updateSplitters(); this.layout(); }, unhideColumn : function(colIndex){ var cid = this.getColumnId(colIndex); this.css.updateRule(this.tdSelector+cid, "display", ""); this.css.updateRule(this.splitSelector+cid, "display", ""); if(Ext.isSafari){ this.updateHeaders(); } this.updateSplitters(); this.layout(); }, 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 s = this.getScrollState(); var markup = this.renderRows(firstRow, lastRow); this.bufferRows(markup[0], this.getLockedTable(), firstRow); this.bufferRows(markup[1], this.getBodyTable(), firstRow); this.restoreScroll(s); if(!isUpdate){ this.fireEvent("rowsinserted", this, firstRow, lastRow); this.syncRowHeights(firstRow, lastRow); this.stripeRows(firstRow); this.layout(); } } }, bufferRows : function(markup, target, index){ var before = null, trows = target.rows, tbody = target.tBodies[0]; if(index < trows.length){ before = trows[index]; } var b = document.createElement("div"); b.innerHTML = "<table><tbody>"+markup+"</tbody></table>"; var rows = b.firstChild.rows; for(var i = 0, len = rows.length; i < len; i++){ if(before){ tbody.insertBefore(rows[0], before); }else{ tbody.appendChild(rows[0]); } } b.innerHTML = ""; b = null; }, deleteRows : function(dm, firstRow, lastRow){ if(dm.getRowCount()<1){ this.fireEvent("beforerefresh", this); this.mainBody.update(""); this.lockedBody.update(""); this.fireEvent("refresh", this); }else{ this.fireEvent("beforerowsdeleted", this, firstRow, lastRow); var bt = this.getBodyTable(); var tbody = bt.firstChild; var rows = bt.rows; for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){ tbody.removeChild(rows[firstRow]); } this.stripeRows(firstRow); this.fireEvent("rowsdeleted", this, firstRow, lastRow); } }, updateRows : function(dataSource, firstRow, lastRow){ var s = this.getScrollState(); this.refresh(); this.restoreScroll(s); }, handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){ if(!noRefresh){ this.refresh(); } this.updateHeaderSortState(); }, getScrollState : function(){ var sb = this.scroller.dom; return {left: sb.scrollLeft, top: sb.scrollTop}; }, stripeRows : function(startRow){ if(!this.grid.stripeRows || this.ds.getCount() < 1){ return; } startRow = startRow || 0; var rows = this.getBodyTable().rows; var lrows = this.getLockedTable().rows; var cls = ' x-grid-row-alt '; for(var i = startRow, len = rows.length; i < len; i++){ var row = rows[i], lrow = lrows[i]; var isAlt = ((i+1) % 2 == 0); var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1; if(isAlt == hasAlt){ continue; } if(isAlt){ row.className += " x-grid-row-alt"; }else{ row.className = row.className.replace("x-grid-row-alt", ""); } if(lrow){ lrow.className = row.className; } } }, restoreScroll : function(state){ var sb = this.scroller.dom; sb.scrollLeft = state.left; sb.scrollTop = state.top; this.syncScroll(); }, syncScroll : function(){ var sb = this.scroller.dom; var sh = this.mainHd.dom; var bs = this.mainBody.dom; var lv = this.lockedBody.dom; sh.scrollLeft = bs.scrollLeft = sb.scrollLeft; lv.scrollTop = bs.scrollTop = sb.scrollTop; }, handleScroll : function(e){ this.syncScroll(); var sb = this.scroller.dom; this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop); e.stopEvent(); }, handleWheel : function(e){ var d = e.getWheelDelta(); this.scroller.dom.scrollTop -= d*22; // set this here to prevent jumpy scrolling on large tables this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop; e.stopEvent(); }, renderRows : function(startRow, endRow){ // pull in all the crap needed to render rows var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows; var colCount = cm.getColumnCount(); if(ds.getCount() < 1){ return ["", ""]; } // build a map for all the columns var cs = []; for(var i = 0; i < colCount; i++){ var name = cm.getDataIndex(i); cs[i] = { name : typeof name == 'undefined' ? ds.fields.get(i).name : name, renderer : cm.getRenderer(i), id : cm.getColumnId(i), locked : cm.isLocked(i) }; } 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); }, // As much as I hate to duplicate code, this was branched because FireFox really hates // [].join("") on strings. The performance difference was substantial enough to // branch this function doRender : Ext.isGecko ? function(cs, rs, ds, startRow, colCount, stripe){ var ts = this.templates, ct = ts.cell, rt = ts.row; // buffers var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex; for(var j = 0, len = rs.length; j < len; j++){ r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow); for(var i = 0; i < colCount; i++){ c = cs[i]; p.cellId = "x-grid-cell-" + rowIndex + "-" + i; p.id = c.id; p.css = p.attr = ""; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); if(p.value == undefined || p.value === "") p.value = "&#160;"; if(r.dirty && typeof r.modified[c.name] !== 'undefined'){ p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell'; } var markup = ct.apply(p); if(!c.locked){ cb+= markup; }else{ lcb+= markup; } } var alt = []; if(stripe && ((rowIndex+1) % 2 == 0)){ alt[0] = "x-grid-row-alt"; } if(r.dirty){ alt[1] = " x-grid-dirty-row"; } rp.cells = lcb; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex); } rp.alt = alt.join(" "); lbuf+= rt.apply(rp); rp.cells = cb; buf+= rt.apply(rp); } return [lbuf, buf]; } : function(cs, rs, ds, startRow, colCount, stripe){ var ts = this.templates, ct = ts.cell, rt = ts.row; // buffers var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex; for(var j = 0, len = rs.length; j < len; j++){ r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow); for(var i = 0; i < colCount; i++){ c = cs[i]; p.cellId = "x-grid-cell-" + rowIndex + "-" + i; p.id = c.id; p.css = p.attr = ""; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); if(p.value == undefined || p.value === "") p.value = "&#160;"; if(r.dirty && typeof r.modified[c.name] !== 'undefined'){ p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell'; } var markup = ct.apply(p); if(!c.locked){ cb[cb.length] = markup; }else{ lcb[lcb.length] = markup; } } var alt = []; if(stripe && ((rowIndex+1) % 2 == 0)){ alt[0] = "x-grid-row-alt"; } if(r.dirty){ alt[1] = " x-grid-dirty-row"; } rp.cells = lcb; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex); } rp.alt = alt.join(" "); rp.cells = lcb.join(""); lbuf[lbuf.length] = rt.apply(rp); rp.cells = cb.join(""); buf[buf.length] = rt.apply(rp); } return [lbuf.join(""), buf.join("")]; }, renderBody : function(){ var markup = this.renderRows(); var bt = this.templates.body; return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})]; }, /** * 刷新grid * @param {Boolean} headersToo */ refresh : function(headersToo){ this.fireEvent("beforerefresh", this); this.grid.stopEditing(); var result = this.renderBody(); this.lockedBody.update(result[0]); this.mainBody.update(result[1]); if(headersToo === true){ this.updateHeaders(); this.updateColumns(); this.updateSplitters(); this.updateHeaderSortState(); } this.syncRowHeights(); this.layout(); this.fireEvent("refresh", this); }, handleColumnMove : function(cm, oldIndex, newIndex){ this.indexMap = null; var s = this.getScrollState(); this.refresh(true); this.restoreScroll(s); this.afterMove(newIndex); }, afterMove : function(colIndex){ if(this.enableMoveAnim && Ext.enableFx){ this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor); } }, updateCell : function(dm, rowIndex, dataIndex){ var colIndex = this.getColumnIndexByDataIndex(dataIndex); if(typeof colIndex == "undefined"){ // not present in grid return; } var cm = this.grid.colModel; var cell = this.getCell(rowIndex, colIndex); var cellText = this.getCellText(rowIndex, colIndex); var p = { cellId : "x-grid-cell-" + rowIndex + "-" + colIndex, id : cm.getColumnId(colIndex), css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : "" }; var renderer = cm.getRenderer(colIndex); var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm); if(typeof val == "undefined" || val === "") val = "&#160;"; cellText.innerHTML = val; cell.className = this.cellClass + " " + p.cellId + " " + p.css; this.syncRowHeights(rowIndex, rowIndex); }, calcColumnWidth : function(colIndex, maxRowsToMeasure){ var maxWidth = 0; if(this.grid.autoSizeHeaders){ var h = this.getHeaderCellMeasure(colIndex); maxWidth = Math.max(maxWidth, h.scrollWidth); } var tb, index; if(this.cm.isLocked(colIndex)){ tb = this.getLockedTable(); index = colIndex; }else{ tb = this.getBodyTable(); index = colIndex - this.cm.getLockedCount(); } if(tb && tb.rows){ var rows = tb.rows; var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length); for(var i = 0; i < stopIndex; i++){ var cell = rows[i].childNodes[index].firstChild; maxWidth = Math.max(maxWidth, cell.scrollWidth); } } return maxWidth + /*margin for error in IE*/ 5; }, /** * 自动适配列和列内容 * @param {Number} colIndex * @param {Boolean} forceMinSize true表示为强制列(column)尽可能缩小 */ autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){ if(this.cm.isHidden(colIndex)){ return; // can't calc a hidden column } if(forceMinSize){ var cid = this.cm.getColumnId(colIndex); this.css.updateRule(this.colSelector + cid, "width", this.grid.minColumnWidth + "px"); if(this.grid.autoSizeHeaders){ this.css.updateRule(this.hdSelector + cid, "width", this.grid.minColumnWidth + "px"); } } var newWidth = this.calcColumnWidth(colIndex); this.cm.setColumnWidth(colIndex, Math.max(this.grid.minColumnWidth, newWidth), suppressEvent); if(!suppressEvent){ this.grid.fireEvent("columnresize", colIndex, newWidth); } }, /** * 自动适配列和列内容,然后扩展以适配grid的空间 */ autoSizeColumns : function(){ var cm = this.grid.colModel; var colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ this.autoSizeColumn(i, true, true); } if(cm.getTotalWidth() < this.scroller.dom.clientWidth){ this.fitColumns(); }else{ this.updateColumns(); this.layout(); } }, /** * 根据当前尺寸按比例地自动适配列和列内容 * @param {Boolean} reserveScrollSpace 滚动条保留空间 */ fitColumns : function(reserveScrollSpace){ var cm = this.grid.colModel; var colCount = cm.getColumnCount(); var cols = []; var width = 0; var i, w; for (i = 0; i < colCount; i++){ if(!cm.isHidden(i) && !cm.isFixed(i)){ w = cm.getColumnWidth(i); cols.push(i); cols.push(w); width += w; } } var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth()); if(reserveScrollSpace){ avail -= 17; } var frac = (avail - cm.getTotalWidth())/width; while (cols.length){ w = cols.pop(); i = cols.pop(); cm.setColumnWidth(i, Math.floor(w + w*frac), true); } this.updateColumns(); this.layout(); }, onRowSelect : function(rowIndex){ var row = this.getRowComposite(rowIndex); row.addClass("x-grid-row-selected"); }, onRowDeselect : function(rowIndex){ var row = this.getRowComposite(rowIndex); row.removeClass("x-grid-row-selected"); }, onCellSelect : function(row, col){ var cell = this.getCell(row, col); if(cell){ Ext.fly(cell).addClass("x-grid-cell-selected"); } }, onCellDeselect : function(row, col){ var cell = this.getCell(row, col); if(cell){ Ext.fly(cell).removeClass("x-grid-cell-selected"); } }, updateHeaderSortState : function(){ var state = this.ds.getSortState(); if(!state){ return; } this.sortState = state; var sortColumn = this.cm.findColumnIndex(state.field); if(sortColumn != -1){ var sortDir = state.direction; var sc = this.sortClasses; var hds = this.el.select(this.headerSelector).removeClass(sc); hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]); } }, handleHeaderClick : function(g, index){ if(this.headersDisabled){ return; } var dm = g.dataSource, cm = g.colModel; if(!cm.isSortable(index)){ return; } g.stopEditing(); dm.sort(cm.getDataIndex(index)); }, 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.util.CSS.removeStyleSheet(this.grid.id + '-cssrules'); this.bind(null, null); Ext.EventManager.removeResizeListener(this.onWindowResize, this); }, handleLockChange : function(){ this.refresh(true); }, onDenyColumnLock : function(){ }, onDenyColumnHide : function(){ }, 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; case "lock": var lc = cm.getLockedCount(); if(cm.getColumnCount(true) <= lc+1){ this.onDenyColumnLock(); return; } if(lc != index){ cm.setLocked(index, true, true); cm.moveColumn(index, lc); this.grid.fireEvent("columnmove", index, lc); }else{ cm.setLocked(index, true); } break; case "unlock": var lc = cm.getLockedCount(); if((lc-1) != index){ cm.setLocked(index, false, true); cm.moveColumn(index, lc-1); this.grid.fireEvent("columnmove", index, lc-1); }else{ cm.setLocked(index, false); } break; default: index = cm.getIndexById(item.id.substr(4)); if(index != -1){ if(item.checked && cm.getColumnCount(true) <= 1){ this.onDenyColumnHide(); return false; } cm.setHidden(index, item.checked); } } return true; }, beforeColMenuShow : function(){ var cm = this.cm, colCount = cm.getColumnCount(); this.colMenu.removeAll(); for(var i = 0; i < colCount; i++){ this.colMenu.add(new Ext.menu.CheckItem({ id: "col-"+cm.getColumnId(i), text: cm.getColumnHeader(i), checked: !cm.isHidden(i), hideOnClick:false })); } }, handleHdCtx : function(g, index, e){ e.stopEvent(); var hd = this.getHeaderCell(index); 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)); if(this.grid.enableColLock !== false){ ms.get("lock").setDisabled(cm.isLocked(index)); ms.get("unlock").setDisabled(!cm.isLocked(index)); } this.hmenu.show(hd, "tl-bl"); }, handleHdOver : function(e){ var hd = this.findHeaderCell(e.getTarget()); if(hd && !this.headersDisabled){ if(this.grid.colModel.isSortable(this.getCellIndex(hd))){ this.fly(hd).addClass("x-grid-hd-over"); } } }, handleHdOut : function(e){ var hd = this.findHeaderCell(e.getTarget()); if(hd){ this.fly(hd).removeClass("x-grid-hd-over"); } }, handleSplitDblClick : function(e, t){ var i = this.getCellIndex(t); if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){ this.autoSizeColumn(i, true); this.layout(); } }, render : function(){ var cm = this.cm; var colCount = cm.getColumnCount(); if(this.grid.monitorWindowResize === true){ Ext.EventManager.onWindowResize(this.onWindowResize, this, true); } var header = this.renderHeaders(); var body = this.templates.body.apply({rows:""}); var html = this.templates.master.apply({ lockedBody: body, body: body, lockedHeader: header[0], header: header[1] }); //this.updateColumns(); this.grid.getGridEl().dom.innerHTML = html; this.initElements(); this.scroller.on("scroll", this.handleScroll, this); this.lockedBody.on("mousewheel", this.handleWheel, this); this.mainBody.on("mousewheel", this.handleWheel, this); this.mainHd.on("mouseover", this.handleHdOver, this); this.mainHd.on("mouseout", this.handleHdOut, this); this.mainHd.on("dblclick", this.handleSplitDblClick, this, {delegate: "."+this.splitClass}); this.lockedHd.on("mouseover", this.handleHdOver, this); this.lockedHd.on("mouseout", this.handleHdOut, this); this.lockedHd.on("dblclick", this.handleSplitDblClick, this, {delegate: "."+this.splitClass}); if(this.grid.enableColumnResize !== false && Ext.grid.SplitDragZone){ new Ext.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom); } this.updateSplitters(); if(this.grid.enableColumnMove && Ext.grid.HeaderDragZone){ new Ext.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom); new Ext.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom); } if(this.grid.enableCtxMenu !== false && Ext.menu.Menu){ this.hmenu = new Ext.menu.Menu({id: this.grid.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(this.grid.enableColLock !== false){ this.hmenu.add('-', {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"}, {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"} ); } if(this.grid.enableColumnHide !== false){ this.colMenu = new Ext.menu.Menu({id:this.grid.id + "-hcols-menu"}); this.colMenu.on("beforeshow", this.beforeColMenuShow, this); this.colMenu.on("itemclick", this.handleHdMenuClick, this); this.hmenu.add('-', {id:"columns", text: this.columnsText, menu: this.colMenu} ); } this.hmenu.on("itemclick", this.handleHdMenuClick, this); this.grid.on("headercontextmenu", this.handleHdCtx, this); } if((this.grid.enableDragDrop || this.grid.enableDrag) && Ext.grid.GridDragZone){ this.dd = new Ext.grid.GridDragZone(this.grid, { ddGroup : this.grid.ddGroup || 'GridDD' }); } /* for(var i = 0; i < colCount; i++){ if(cm.isHidden(i)){ this.hideColumn(i); } if(cm.config[i].align){ this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align); this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align); } }*/ this.updateHeaderSortState(); this.beforeInitialResize(); this.layout(true); // two part rendering gives faster view to the user this.renderPhase2.defer(1, this); }, renderPhase2 : function(){ // render the rows now this.refresh(); if(this.grid.autoSizeColumns){ this.autoSizeColumns(); } }, beforeInitialResize : function(){ }, onColumnSplitterMoved : function(i, w){ this.userResized = true; var cm = this.grid.colModel; cm.setColumnWidth(i, w, true); var cid = cm.getColumnId(i); this.css.updateRule(this.colSelector + cid, "width", (w-this.borderWidth) + "px"); this.css.updateRule(this.hdSelector + cid, "width", (w-this.borderWidth) + "px"); this.updateSplitters(); this.layout(); this.grid.fireEvent("columnresize", i, w); }, syncRowHeights : function(startIndex, endIndex){ if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){ startIndex = startIndex || 0; var mrows = this.getBodyTable().rows; var lrows = this.getLockedTable().rows; var len = mrows.length-1; endIndex = Math.min(endIndex || len, len); for(var i = startIndex; i <= endIndex; i++){ var m = mrows[i], l = lrows[i]; var h = Math.max(m.offsetHeight, l.offsetHeight); m.style.height = l.style.height = h + "px"; } } }, layout : function(initialRender, is2ndPass){ var g = this.grid; var auto = g.autoHeight; var scrollOffset = 16; var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this; //c.beginMeasure(); if(!c.dom.offsetWidth){ // display:none? if(initialRender){ this.lockedWrap.show(); this.mainWrap.show(); } return; } var hasLock = this.cm.isLocked(0); var tbh = this.headerPanel.getHeight(); var bbh = this.footerPanel.getHeight(); if(auto){ var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight(); var newHeight = ch + c.getBorderWidth("tb"); if(g.maxHeight){ newHeight = Math.min(g.maxHeight, newHeight); } c.setHeight(newHeight); } if(g.autoWidth){ c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr')); } var s = this.scroller; var csize = c.getSize(true); this.el.setSize(csize.width, csize.height); this.headerPanel.setWidth(csize.width); this.footerPanel.setWidth(csize.width); var hdHeight = this.mainHd.getHeight(); var vw = csize.width; var vh = csize.height - (tbh + bbh); s.setSize(vw, vh); var bt = this.getBodyTable(); var ltWidth = hasLock ? Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0; var scrollHeight = bt.offsetHeight; var scrollWidth = ltWidth + bt.offsetWidth; var vscroll = false, hscroll = false; this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight); var lw = this.lockedWrap, mw = this.mainWrap; var lb = this.lockedBody, mb = this.mainBody; setTimeout(function(){ var t = s.dom.offsetTop; var w = s.dom.clientWidth, h = s.dom.clientHeight; lw.setTop(t); lw.setSize(ltWidth, h); mw.setLeftTop(ltWidth, t); mw.setSize(w-ltWidth, h); lb.setHeight(h-hdHeight); mb.setHeight(h-hdHeight); if(is2ndPass !== true && !gv.userResized && expandCol){ // high speed resize without full column calculation var ci = cm.getIndexById(expandCol); var tw = cm.getTotalWidth(false); var currentWidth = cm.getColumnWidth(ci); var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax); if(currentWidth != cw){ cm.setColumnWidth(ci, cw, true); gv.css.updateRule(gv.colSelector+expandCol, "width", (cw - gv.borderWidth) + "px"); gv.css.updateRule(gv.hdSelector+expandCol, "width", (cw - gv.borderWidth) + "px"); gv.updateSplitters(); gv.layout(false, true); } } if(initialRender){ lw.show(); mw.show(); } //c.endMeasure(); }, 10); }, onWindowResize : function(){ if(!this.grid.monitorWindowResize || this.grid.autoHeight){ return; } this.layout(); }, appendFooter : function(parentEl){ return null; }, sortAscText : "Sort Ascending", sortDescText : "Sort Descending", lockText : "Lock Column", unlockText : "Unlock Column", columnsText : "Columns" });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** @class Ext.grid.RowSelectionModel * @extends Ext.grid.AbstractSelectionModel * {@link Ext.grid.Grid}默认使用的SelectionModel。支持多个选区和键盘选区/导航 <br><br> @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 * 当选区改变时触发 * @param {SelectionModel} this */ "selectionchange" : true, /** * @event beforerowselect * 当行(row)是选中又被选择触发,返回false取消。 * @param {SelectionModel} this * @param {Number} rowIndex 选中的索引 */ "beforerowselect" : true, /** * @event rowselect * 当行(row)被选中时触发。 * @param {SelectionModel} this * @param {Number} rowIndex 选中的索引 */ "rowselect" : true, /** * @event rowdeselect * 当行(row)反选时触发。 * @param {SelectionModel} this * @param {Number} rowIndex 选中的索引 */ "rowdeselect" : true }); this.locked = false; }; Ext.extend(Ext.grid.RowSelectionModel, Ext.grid.AbstractSelectionModel, { /** * @cfg {Boolean} singleSelect * True:同时只能选单行(默认false) */ singleSelect : false, // private initEvents : function(){ if(!this.grid.enableDragDrop && !this.grid.enableDrag){ this.grid.on("mousedown", 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.selectPrevious(e.shiftKey); }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.selectNext(e.shiftKey); }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.dataSource, i, v = this.grid.view; var s = this.selections; s.each(function(r){ if((i = ds.indexOfId(r.id)) != -1){ v.onRowSelect(i); }else{ s.remove(r); } }); }, // private onRemove : function(v, index, r){ this.selections.remove(r); }, // private onRowUpdated : function(v, index, r){ if(this.isSelected(r)){ v.onRowSelect(index); } }, /** * 选择多个记录 * @param {Array} records 要选择的record * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区 */ selectRecords : function(records, keepExisting){ if(!keepExisting){ this.clearSelections(); } var ds = this.grid.dataSource; for(var i = 0, len = records.length; i < len; i++){ this.selectRow(ds.indexOf(records[i]), true); } }, /** * 获取已选择的行数 * @return {Number} */ getCount : function(){ return this.selections.length; }, /** * 选择GRID的第一行 */ selectFirstRow : function(){ this.selectRow(0); }, /** * 选择最后一行 * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区 */ selectLastRow : function(keepExisting){ this.selectRow(this.grid.dataSource.getCount() - 1, keepExisting); }, /** * 选取上次选取的最后一行 * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区 */ selectNext : function(keepExisting){ if(this.last !== false && (this.last+1) < this.grid.dataSource.getCount()){ this.selectRow(this.last+1, keepExisting); this.grid.getView().focusRow(this.last); } }, /** * 选取上次选取的最前一行 * @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区 */ selectPrevious : function(keepExisting){ if(this.last){ this.selectRow(this.last-1, keepExisting); this.grid.getView().focusRow(this.last); } }, /** * 返回选中的记录 * @return {Array} 选中记录的数组 */ getSelections : function(){ return [].concat(this.selections.items); }, /** * 返回第一个选中的记录 * @return {Record} */ getSelected : function(){ return this.selections.itemAt(0); }, /** * 清楚所有选区 */rSelections : function(fast){ if(this.locked) return; if(fast !== true){ var ds = this.grid.dataSource; var s = this.selections; s.each(function(r){ this.deselectRow(ds.indexOfId(r.id)); }, this); s.clear(); }else{ this.selections.clear(); } this.last = false; }, /** * 选择所有行。 */ selectAll : function(){ if(this.locked) return; this.selections.clear(); for(var i = 0, len = this.grid.dataSource.getCount(); i < len; i++){ this.selectRow(i, true); } }, /** * 返回true说明这里有选区 * @return {Boolean} */ hasSelection : function(){ return this.selections.length > 0; }, /** * 返回true说明指定的行被选中 * @param {Number/Record} record Record record或者是要检查record的索引 * @return {Boolean} */ isSelected : function(index){ var r = typeof index == "number" ? this.grid.dataSource.getAt(index) : index; return (r && this.selections.key(r.id) ? true : false); }, /** * 返回true说明指定的record之id被选中。 * @param {String} id 检查record的id * @return {Boolean} */ isIdSelected : function(id){ return (this.selections.key(id) ? true : false); }, // private handleMouseDown : function(e, t){ var view = this.grid.getView(), rowIndex; if(this.isLocked() || (rowIndex = view.findRowIndex(t)) === false){ return; }; if(e.shiftKey && 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.button != 0 && isSelected){ view.focusRow(rowIndex); }else if(e.ctrlKey && isSelected){ this.deselectRow(rowIndex); }else{ this.selectRow(rowIndex, e.button == 0 && (e.ctrlKey || e.shiftKey)); view.focusRow(rowIndex); } } }, /** * 选取多行。 * @param {Array} rows 要选取行的Id集合 * @param {Boolean} keepExisting (可选的)表示为保持现有的选区 */ 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之间的行都会被选中。 * @param {Number} startRow 范围内的第一行之索引 * @param {Number} endRow 范围内的最后一行之索引 * @param {Boolean} keepExisting(可选的)表示为保持现有的选区 */ selectRange : function(startRow, endRow, keepExisting){ if(this.locked) 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之间的行都会被选反。 * @param {Number} startRow 范围内的第一行之索引 * @param {Number} endRow 范围内的最后一行之索引 * @param {Boolean} keepExisting (可选的)true表示为保持现有的选区 */ deselectRange : function(startRow, endRow, preventViewNotify){ if(this.locked) return; for(var i = startRow; i <= endRow; i++){ this.deselectRow(i, preventViewNotify); } }, /** * 选择一行 * @param {Number} row 要选择行的index * @param {Boolean} keepExisting(可选的)表示为保持现有的选区 */ selectRow : function(index, keepExisting, preventViewNotify){ if(this.locked || (index < 0 || index >= this.grid.dataSource.getCount())) return; if(this.fireEvent("beforerowselect", this, index, keepExisting) !== false){ if(!keepExisting || this.singleSelect){ this.clearSelections(); } var r = this.grid.dataSource.getAt(index); 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); } }, /** * 反选一个行 * @param {Number} row 反选行的索引 */ deselectRow : function(index, preventViewNotify){ if(this.locked) return; if(this.last == index){ this.last = false; } if(this.lastActive == index){ this.lastActive = false; } var r = this.grid.dataSource.getAt(index); this.selections.remove(r); if(!preventViewNotify){ this.grid.getView().onRowDeselect(index); } this.fireEvent("rowdeselect", this, index); 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; if(k == e.TAB){ e.stopEvent(); ed.completeEdit(); 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); } }else if(k == e.ENTER && !e.ctrlKey){ e.stopEvent(); ed.completeEdit(); if(e.shiftKey){ 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ // 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ Ext.grid.AbstractGridView = function(){ this.grid = null; this.events = { "beforerowremoved" : true, "beforerowsinserted" : true, "beforerefresh" : true, "rowremoved" : true, "rowsinserted" : true, "rowupdated" : true, "refresh" : true }; Ext.grid.AbstractGridView.superclass.constructor.call(this); }; Ext.extend(Ext.grid.AbstractGridView, Ext.util.Observable, { rowClass : "x-grid-row", cellClass : "x-grid-cell", tdClass : "x-grid-td", hdClass : "x-grid-hd", splitClass : "x-grid-hd-split", init: function(grid){ this.grid = grid; var cid = this.grid.getGridEl().id; this.colSelector = "#" + cid + " ." + this.cellClass + "-"; this.tdSelector = "#" + cid + " ." + this.tdClass + "-"; this.hdSelector = "#" + cid + " ." + this.hdClass + "-"; this.splitSelector = "#" + cid + " ." + this.splitClass + "-"; }, getColumnRenderers : function(){ var renderers = []; var cm = this.grid.colModel; var colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ renderers[i] = cm.getRenderer(i); } return renderers; }, getColumnIds : function(){ var ids = []; var cm = this.grid.colModel; var colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ ids[i] = cm.getColumnId(i); } return ids; }, getDataIndexes : function(){ if(!this.indexMap){ this.indexMap = this.buildIndexMap(); } return this.indexMap.colToData; }, getColumnIndexByDataIndex : function(dataIndex){ if(!this.indexMap){ this.indexMap = this.buildIndexMap(); } return this.indexMap.dataToCol[dataIndex]; }, /** * 为某个列动态设置CSS样式 * @param {Number} colIndex column索引 * @param {String} name CSS属性名称 * @param {String} value CSS值 */ setCSSStyle : function(colIndex, name, value){ var selector = "#" + this.grid.id + " .x-grid-col-" + colIndex; Ext.util.CSS.updateRule(selector, name, value); }, generateRules : function(cm){ var ruleBuf = [], rulesId = this.grid.id + '-cssrules'; Ext.util.CSS.removeStyleSheet(rulesId); for(var i = 0, len = cm.getColumnCount(); i < len; i++){ var cid = cm.getColumnId(i); ruleBuf.push(this.colSelector, cid, " {\n", cm.config[i].css, "}\n", this.tdSelector, cid, " {\n}\n", this.hdSelector, cid, " {\n}\n", this.splitSelector, cid, " {\n}\n"); } return Ext.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId); } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.grid.Grid * @extends Ext.util.Observable * 将主要的控制Grid组件的接口呈现为该类。 * * <br><br>Usage:<pre><code> var grid = new Ext.grid.Grid("my-container-id", { ds: myDataStore, cm: myColModel, selModel: mySelectionModel, autoSizeColumns: true, monitorWindowResize: false, trackMouseOver: true }); // 设置任意的选项 grid.render(); * </code></pre> * <b>常见问题:</b><br/> * - Grid变小的时候并不会自己调整大小,不过可以通用在容器元素上设置overflow:hidden来修正这个问题。<br/> * - 如果得到的el.style[camel]= NaNpx 或 -2px 或是相关的内容,须确认你已经指定了容器元素的尺寸。 * Grid会自适应容器的尺寸大小,如不设置容器的大小会导致难以预料的问题。 <br/> * -不要在一个display:none的元素上渲染grid。尝试一下visibility:hidden。不然的话grid不能够计算出尺寸、偏移值。<br/> * @constructor * @param {String/HTMLElement/Ext.Element} container Grid进行渲染的那个元素 - * 为了能够装下grid,容器须指定相应的宽度、高度。 * 容器会自动设置为相对布局。 * @param {Object} config 设置GRID属性的配置项对象 */ Ext.grid.Grid = function(container, config){ // 初始化容器 this.container = Ext.get(container); this.container.update(""); this.container.setStyle("overflow", "hidden"); this.container.addClass('x-grid-container'); this.id = this.container.id; Ext.apply(this, config); // check and correct shorthanded configs if(this.ds){ this.dataSource = 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; } if(this.width){ this.container.setWidth(this.width); } if(this.height){ this.container.setHeight(this.height); } /** @private */ this.addEvents({ // 原始未加工的事件 /** * @event click * 单击整个grid的原始事件 * @param {Ext.EventObject} e */ "click" : true, /** * @event dblclick * 双击整个grid的原始事件 * @param {Ext.EventObject} e */ "dblclick" : true, /** * @event contextmenu * 右击整个grid的原始事件 * @param {Ext.EventObject} e */ "contextmenu" : true, /** * @event mousedown * 整个grid mousedown 的原始事件 * @param {Ext.EventObject} e */ "mousedown" : true, /** * @event mouseup * 整个grid mouseup 的原始事件 * @param {Ext.EventObject} e */ "mouseup" : true, /** * @event mouseover * 整个grid mouseover 的原始事件 * @param {Ext.EventObject} e */ "mouseover" : true, /** * @event mouseout * 整个grid mouseout 的原始事件 * @param {Ext.EventObject} e */ "mouseout" : true, /** * @event keypress * 整个grid keypress 的原始事件 * @param {Ext.EventObject} e */ "keypress" : true, /** * @event keydown * 整个grid keydown 的原始事件 * @param {Ext.EventObject} e */ "keydown" : true, // custom events /** * @event cellclick * 单元格(cell)被单击时触发 * @param {Grid} this * @param {Number} rowIndex行索引 * @param {Number} columnIndex列索引 * @param {Ext.EventObject} e */ "cellclick" : true, /** * @event celldblclick * 单元格(cell)被双击时触发 * @param {Grid} this * @param {Number} rowIndex行索引 * @param {Number} columnIndex列索引 * @param {Ext.EventObject} e */ "celldblclick" : true, /** * @event rowclick * 行(row)被单击时触发 * @param {Grid} this * @param {Number} rowIndex行索引 * @param {Ext.EventObject} e */ "rowclick" : true, /** * @event rowdblclick * 行(row)被双击时触发 * @param {Grid} this * @param {Number} rowIndex行索引 * @param {Ext.EventObject} e */ "rowdblclick" : true, /** * @event headerclick * 头部(header)被单击时触发 * @param {Grid} this * @param {Number} columnIndex列索引 * @param {Ext.EventObject} e */ "headerclick" : true, /** * @event headerdblclick * 头部(header)被双击时触发 * @param {Grid} this * @param {Number} columnIndex列索引 * @param {Ext.EventObject} e */ "headerdblclick" : true, /** * @event rowcontextmenu * 行(row)被右击时触发 * @param {Grid} this * @param {Number} rowIndex行索引 * @param {Ext.EventObject} e */ "rowcontextmenu" : true, /** * @event cellcontextmenu * 单元格(cell)被右击时触发 * @param {Grid} this * @param {Number} rowIndex行索引 * @param {Number} cellIndex单元格索引 * @param {Ext.EventObject} e */ "cellcontextmenu" : true, /** * @event headercontextmenu * 头部(header)被右击时触发 * @param {Grid} this * @param {Number} columnIndex列索引 * @param {Ext.EventObject} e */ "headercontextmenu" : true, /** * @event bodyscroll * 当body元素被滚动后触发 * @param {Number} scrollLeft * @param {Number} scrollTop */ "bodyscroll" : true, /** * @event columnresize * 当用户调整某个列(column)大小时触发 * @param {Number} columnIndex列索引 * @param {Number} newSize */ "columnresize" : true, /** * @event columnmove * 当用户移动某个列(column)时触发 * @param {Number} oldIndex * @param {Number} newIndex */ "columnmove" : true, /** * @event startdrag * 当行(row)开始被拖动时触发 * @param {Grid} this * @param {Ext.GridDD} dd 拖放对象 * @param {event} e 浏览器原始的事件对象 */ "startdrag" : true, /** * @event enddrag * 当拖动完成后触发 * @param {Grid} this * @param {Ext.GridDD} dd 拖放对象 * @param {event} e 浏览器原始的事件对象 */ "enddrag" : true, /** * @event dragdrop * 拖动行(row)放到一个有效的DD target 身上,触发该事件 * @param {Grid} this * @param {Ext.GridDD} dd 拖放对象 * @param {String} targetId 拖放对象之目标 * @param {event} e 浏览器原始的事件对象 */ "dragdrop" : true, /** * @event dragover * 当行(row)拖动着的时候触发。 * “targetId”是行拖动中Yahoo.util.DD对象所选取的ID。 * @param {Grid} this * @param {Ext.GridDD} dd 拖放对象 * @param {String} targetId 拖放对象之目标 * @param {event} e 浏览器原始的事件对象 */ "dragover" : true, /** * @event dragenter * 当拖动的行开始进入其它DD目标时触发。 * @param {Grid} this * @param {Ext.GridDD} dd 拖放对象 * @param {String} targetId 拖放对象之目标 * @param {event} e 浏览器原始的事件对象 */ "dragenter" : true, /** * @event dragout * 当拖动的行开始离开其它DD目标时触发。 * @param {Grid} this * @param {Ext.GridDD} dd 拖放对象 * @param {String} targetId 拖放对象之目标 * @param {event} e 浏览器原始的事件对象 */ "dragout" : true, /** * @event render * 当grid渲染完成后触发 * @param {Grid} grid */ render : true }); Ext.grid.Grid.superclass.constructor.call(this); }; Ext.extend(Ext.grid.Grid, Ext.util.Observable, { /** * @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, /** * @cfg {Boolean} autoWidth True表示为grid的总宽度为各个列宽度之和,而不是一个固定值。默认为false。 */ /** * @cfg {Number} maxHeight 设置grid的高度上限。若关闭autoHeight则忽略。 */ /** * 完成Grid所有设置后,进入可用状态后,即可调用该方法渲染Grid。 * @return {Ext.grid.Grid} this */ render : function(){ var c = this.container; // try to detect autoHeight/width mode if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){ this.autoHeight = true; } var view = this.getView(); view.init(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); view.render(); if(this.loadMask){ this.loadMask = new Ext.LoadMask(this.container, Ext.apply({store:this.dataSource}, this.loadMask)); } this.rendered = true; this.fireEvent('render', this); return this; }, /** * 重新配置Grid的Store和Column Model(列模型)。 * 视图会重新绑定对象并刷新。 * @param {Ext.data.Store} dataSource 另外一个{@link Ext.data.Store}对象 * @param {Ext.grid.ColumnModel} 另外一个{@link Ext.grid.ColumnModel}对象 */ reconfigure : function(dataSource, colModel){ if(this.loadMask){ this.loadMask.destroy(); this.loadMask = new Ext.LoadMask(this.container, Ext.apply({store:dataSource}, this.loadMask)); } this.view.bind(dataSource, colModel); this.dataSource = dataSource; this.colModel = colModel; this.view.refresh(true); }, // private onKeyDown : function(e){ this.fireEvent("keydown", e); }, /** * 销毁该Grid * @param {Boolean} removeEl True :移除元素 */ destroy : function(removeEl, keepListeners){ if(this.loadMask){ this.loadMask.destroy(); } var c = this.container; c.removeAllListeners(); this.view.destroy(); this.colModel.purgeListeners(); if(!keepListeners){ this.purgeListeners(); } c.update(""); if(removeEl === true){ c.remove(); } }, // 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 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.dataSource, 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(); }, /**让Grid重新计算尺寸。一般情况下无须手工执行, * 除非手动更新后需要调整一下。 */ autoSize : function(){ if(this.rendered){ this.view.layout(); if(this.view.adjustForScroll){ this.view.adjustForScroll(); } } }, /** * 返回Grid的元素 * @return {Element} 元素 */ getGridEl : function(){ return this.container; }, // private for compatibility, overridden by editor grid stopEditing : function(){}, /** * 返回grid的SelectionModel. * @return {SelectionModel} */ getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.grid.RowSelectionModel(); } return this.selModel; }, /** * 返回Grid的DataSource. * @return {DataSource} */ getDataSource : function(){ return this.dataSource; }, /** * 返回Grid的ColumnModel. * @return {ColumnModel} */ getColumnModel : function(){ return this.colModel; }, /** * 返回Grid的GridView object. * @return {GridView} */ getView : function(){ if(!this.view){ this.view = new Ext.grid.GridView(this.viewConfig); } return this.view; }, /** *获取GRID拖动的代理文本,默认返回 this.ddText。 * @return {String} */ getDragDropText : function(){ var count = this.selModel.getCount(); return String.format(this.ddText, count, count == 1 ? '' : 's'); } }); /** * 配置一段文本,将(默认的“%0 selected row(s)”)中的"%0"替换为选取的行数。 * @type String */ Ext.grid.Grid.prototype.ddText = "{0} selected row{1}";
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ Ext.grid.PropertyRecord = Ext.data.Record.create([ {name:'name',type:'string'}, 'value' ]); 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, { 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); }, 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(); } } }, getProperty : function(row){ return this.store.getAt(row); }, isEditableValue: function(val){ if(val && val instanceof Date){ return true; }else if(typeof val == 'object' || typeof val == 'function'){ return false; } return true; }, setValue : function(prop, value){ this.source[prop] = value; this.store.getById(prop).set('value', value); }, getSource : function(){ return this.source; } }); Ext.grid.PropertyColumnModel = function(grid, store){ this.grid = grid; var g = Ext.grid; g.PropertyColumnModel.superclass.constructor.call(this, [ {header: this.nameText, sortable: true, dataIndex:'name', id: 'name'}, {header: this.valueText, resizable:false, dataIndex: 'value', id: 'value'} ]); this.store = store; this.bselect = Ext.DomHelper.append(document.body, { tag: 'select', style:'display:none', cls: 'x-grid-editor', children: [ {tag: 'option', value: 'true', html: 'true'}, {tag: 'option', value: 'false', html: 'false'} ] }); Ext.id(this.bselect); var f = Ext.form; 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(new f.Field({el:this.bselect,selectOnFocus:true})) }; this.renderCellDelegate = this.renderCell.createDelegate(this); this.renderPropDelegate = this.renderProp.createDelegate(this); }; Ext.extend(Ext.grid.PropertyColumnModel, Ext.grid.ColumnModel, { nameText : 'Name', valueText : 'Value', dateFormat : 'm/j/Y', renderDate : function(dateVal){ return dateVal.dateFormat(this.dateFormat); }, renderBool : function(bVal){ return bVal ? 'true' : 'false'; }, isCellEditable : function(colIndex, rowIndex){ return colIndex == 1; }, getRenderer : function(col){ return col == 1 ? this.renderCellDelegate : this.renderPropDelegate; }, renderProp : function(v){ return this.getPropertyName(v); }, 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); }, getPropertyName : function(name){ var pn = this.grid.propertyNames; return pn && pn[name] ? pn[name] : name; }, 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']; } } }); Ext.grid.PropertyGrid = function(container, config){ config = config || {}; var store = new Ext.grid.PropertyStore(this); this.store = store; var cm = new Ext.grid.PropertyColumnModel(this, store); store.store.sort('name', 'ASC'); Ext.grid.PropertyGrid.superclass.constructor.call(this, container, Ext.apply({ ds: store.store, cm: cm, enableColLock:false, enableColumnMove:false, stripeRows:false, trackMouseOver: false, clicksToEdit:1 }, config)); this.getGridEl().addClass('x-props-grid'); this.lastEditRow = null; this.on('columnresize', this.onColumnResize, this); this.addEvents({ beforepropertychange: true, propertychange: true }); this.customEditors = this.customEditors || {}; }; Ext.extend(Ext.grid.PropertyGrid, Ext.grid.EditorGrid, { render : function(){ Ext.grid.PropertyGrid.superclass.render.call(this); this.autoSize.defer(100, this); }, autoSize : function(){ Ext.grid.PropertyGrid.superclass.autoSize.call(this); if(this.view){ this.view.fitColumns(); } }, onColumnResize : function(){ this.colModel.setColumnWidth(1, this.container.getWidth(true)-this.colModel.getColumnWidth(0)); this.autoSize(); }, setSource : function(source){ this.store.setSource(source); //this.autoSize(); }, getSource : function(){ return this.store.getSource(); } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.grid.ColumnModel * @extends Ext.util.Observable * 该实现(implementation)用于Grid的列模型(ColumnModel)。用于定义Grid里面的每一列的状态。 * <br>用法:<br> <pre><code> var colModel = new Ext.grid.ColumnModel([ {header: "Ticker", width: 60, sortable: true, locked: 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 An Array of column config objects列配置组成的数组,参阅关于本类的配置对象的更多资料。 */ Ext.grid.ColumnModel = function(config){ /** * 传入配置到构建函数 */ this.config = config; this.lookup = {}; // if no id, create one // if the column does not have a dataIndex mapping, // map it to the order it is in the config for(var i = 0, len = config.length; i < len; i++){ var c = config[i]; if(typeof c.dataIndex == "undefined"){ c.dataIndex = 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; } /** * 列宽度的默认值(默认为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": true, /** * @event headerchange * 当头部文字改变时触发 * @param {ColumnModel} this * @param {Number} columnIndex 列索引 * @param {Number} newText 新头部文字 */ "headerchange": true, /** * @event hiddenchange * 当列隐藏或“反隐藏”时触发 * @param {ColumnModel} this * @param {Number} columnIndex 列索引 * @param {Number} hidden true:隐藏,false:“反隐藏” */ "hiddenchange": true, /** * @event columnmoved * 当列被移动时触发 * @param {ColumnModel} this * @param {Number} oldIndex * @param {Number} newIndex */ "columnmoved" : true, /** * @event columlockchange * 当列锁定状态被改变时触发 * @param {ColumnModel} this * @param {Number} colIndex * @param {Boolean} locked true:已锁定的 */ "columnlockchange" : true }); Ext.grid.ColumnModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.ColumnModel, Ext.util.Observable, { /** * @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} fixed (可选的) True表示宽度不能改变。默认为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。 */ /** * 返回指定index的列Id * @param {Number} index * @return {String} the id */ getColumnId : function(index){ return this.config[index].id; }, /** * 返回指定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; }, 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); }, isLocked : function(colIndex){ return this.config[colIndex].locked === true; }, setLocked : function(colIndex, value, suppressEvent){ if(this.isLocked(colIndex) == value){ return; } this.config[colIndex].locked = value; if(!suppressEvent){ this.fireEvent("columnlockchange", this, colIndex, value); } }, 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; }, 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; }, /** * 返回对某个列的渲染(格式化formatting)函数 * @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; }, /** * 设置对某个列的渲染(格式化formatting)函数 * @param {Number} col 列索引 * @param {Function} fn 该函数用于加工单元格的原始数据,转换成为HTML并返回给GridView进一步处理。这个渲染函数调用时会有下列的参数:<ul> * <li>数据值。</li> * <li>单元格元数据(Cell metadata)。 你也可以设置这么一个对象,有下列的属性:<ul> * <li>css 单元格适用的CSS样式,类型字符串。</li> * <li>attr 一段HTML属性的字符串,应用于表格单元格的数据容器元素An HTML attribute definition string to apply to * the data container element <i>within</i> the table cell.</li></ul> * <li>从数据中提取的{@link Ext.data.Record}。</li> * <li>行索引</li> * <li>列索引</li> * <li>The {@link Ext.data.Store}从Record中提取的对象。</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; }, /** * 返回某个列的工具的dataindex * @param {Number} col 列索引 * @return {Number} */ getDataIndex : function(col){ return this.config[col].dataIndex; }, /** * 设置某个列的工具的dataindex * @param {Number} col 列索引 * @param {Number} dataIndex 新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 列索引 */ setHidden : function(colIndex, hidden){ this.config[colIndex].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; } }); 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ // 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ // 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(e, t); } 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.QuickTips * 为所有元素提供吸引人的、可定制的工具提示。 * @singleton */ Ext.QuickTips = function(){ var el, tipBody, tipBodyText, tipTitle, tm, cfg, close, tagEls = {}, esc, removeCls = null, bdLeft, bdRight; var ce, bd, xy, dd; var visible = false, disabled = true, inited = false; var showProc = 1, hideProc = 1, dismissProc = 1, locks = []; var onOver = function(e){ if(disabled){ return; } var t = e.getTarget(); if(!t || t.nodeType !== 1 || t == document || t == document.body){ return; } if(ce && t == ce.el){ clearTimeout(hideProc); return; } if(t && tagEls[t.id]){ tagEls[t.id].el = t; showProc = show.defer(tm.showDelay, tm, [tagEls[t.id]]); return; } var ttp, et = Ext.fly(t); var ns = cfg.namespace; if(tm.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){ showProc = show.defer(tm.showDelay, tm, [{ el: t, text: ttp, width: et.getAttributeNS(ns, cfg.width), autoHide: et.getAttributeNS(ns, cfg.hide) != "user", title: et.getAttributeNS(ns, cfg.title), cls: et.getAttributeNS(ns, cfg.cls) }]); } }; var onOut = function(e){ clearTimeout(showProc); var t = e.getTarget(); if(t && ce && ce.el == t && (tm.autoHide && ce.autoHide !== false)){ hideProc = setTimeout(hide, tm.hideDelay); } }; var onMove = function(e){ if(disabled){ return; } xy = e.getXY(); xy[1] += 18; if(tm.trackMouse && ce){ el.setXY(xy); } }; var onDown = function(e){ clearTimeout(showProc); clearTimeout(hideProc); if(!e.within(el)){ if(tm.hideOnClick){ hide(); tm.disable(); } } }; var onUp = function(e){ tm.enable(); }; var getPad = function(){ return bdLeft.getPadding('l')+bdRight.getPadding('r'); }; var show = function(o){ if(disabled){ return; } clearTimeout(dismissProc); ce = o; if(removeCls){ // in case manually hidden el.removeClass(removeCls); removeCls = null; } if(ce.cls){ el.addClass(ce.cls); removeCls = ce.cls; } if(ce.title){ tipTitle.update(ce.title); tipTitle.show(); }else{ tipTitle.update(''); tipTitle.hide(); } el.dom.style.width = tm.maxWidth+'px'; //tipBody.dom.style.width = ''; tipBodyText.update(o.text); var p = getPad(), w = ce.width; if(!w){ var td = tipBodyText.dom; var aw = Math.max(td.offsetWidth, td.clientWidth, td.scrollWidth); if(aw > tm.maxWidth){ w = tm.maxWidth; }else if(aw < tm.minWidth){ w = tm.minWidth; }else{ w = aw; } } //tipBody.setWidth(w); el.setWidth(parseInt(w, 10) + p); if(ce.autoHide === false){ close.setDisplayed(true); if(dd){ dd.unlock(); } }else{ close.setDisplayed(false); if(dd){ dd.lock(); } } if(xy){ el.avoidY = xy[1]-18; el.setXY(xy); } if(tm.animate){ el.setOpacity(.1); el.setStyle("visibility", "visible"); el.fadeIn({callback: afterShow}); }else{ afterShow(); } }; var afterShow = function(){ if(ce){ el.show(); esc.enable(); if(tm.autoDismiss && ce.autoHide !== false){ dismissProc = setTimeout(hide, tm.autoDismissDelay); } } }; var hide = function(noanim){ clearTimeout(dismissProc); clearTimeout(hideProc); ce = null; if(el.isVisible()){ esc.disable(); if(noanim !== true && tm.animate){ el.fadeOut({callback: afterHide}); }else{ afterHide(); } } }; var afterHide = function(){ el.hide(); if(removeCls){ el.removeClass(removeCls); removeCls = null; } }; return { /** * @cfg {Number} minWidth * 快捷提示的最小宽度(默认为 40) */ minWidth : 40, /** * @cfg {Number} maxWidth * 快捷提示的最大宽度(默认为 300) */ maxWidth : 300, /** * @cfg {Boolean} interceptTitles * 值为 true 时自动使用元素的 DOM 标题, 如果有的话(默认为 false) */ interceptTitles : false, /** * @cfg {Boolean} trackMouse * 值为 true 时当鼠标经过目标对象时快捷提示将跟随鼠标移动(默认为 false) */ trackMouse : false, /** * @cfg {Boolean} hideOnClick * 值为 true 时用户点击页面内任何位置都将隐藏快捷提示(默认为 true) */ hideOnClick : true, /** * @cfg {Number} showDelay * 以毫秒表示的当鼠标进入目标元素后显示快捷提示的延迟时间(默认为 500) */ showDelay : 500, /** * @cfg {Number} hideDelay * 以毫秒表示的隐藏快捷提示的延迟时间, 仅在 autoHide = true 时生效(默认为 200) */ hideDelay : 200, /** * @cfg {Boolean} autoHide * 值为 true 时在鼠标移出目标元素自动隐藏快捷提示(默认为 true)。与 hideDelay 协同生效。 */ autoHide : true, /** * @cfg {Boolean} * 值为 true 时自动在规定时间后隐藏快捷提示, 无论用户执行何种操作(默认为 true)。与 autoDismissDelay 协同生效。 */ autoDismiss : true, /** * @cfg {Number} * 以毫秒表示的隐藏快捷提示的延迟时间, 仅在 autoDismiss = true 时生效(默认为 5000) */ autoDismissDelay : 5000, /** * @cfg {Boolean} animate * 值为 true 时打开渐变动画。默认为 false (ClearType/scrollbar 在 IE7 中将导致闪烁)。 */ animate : false, /** * @cfg {String} title * 显示的标题文本(默认为 '')。此处可谓任意有效的 HTML 标识。 */ /** * @cfg {String} text * 显示的主体文本(默认为 '')。此处可谓任意有效的 HTML 标识。 */ /** * @cfg {String} cls * 快捷提示元素使用的 CSS 样式类(默认为 '')。 */ /** * @cfg {Number} width * 以像素为单位表示的快捷提示宽度(默认为 auto)。如果该值小于 minWidth 或大于 maxWidth 都将被忽略。 */ /** * 为首次使用初始化并启用 QuickTips 对象。在页面中试图使用或显示 QuickTips 对象之前必须调用一次该方法。 */ init : function(){ tm = Ext.QuickTips; cfg = tm.tagConfig; if(!inited){ if(!Ext.isReady){ // allow calling of init() before onReady Ext.onReady(Ext.QuickTips.init, Ext.QuickTips); return; } el = new Ext.Layer({cls:"x-tip", shadow:"drop", shim: true, constrain:true, shadowOffset:4}); el.fxDefaults = {stopFx: true}; // maximum custom styling el.update('<div class="x-tip-top-left"><div class="x-tip-top-right"><div class="x-tip-top"></div></div></div><div class="x-tip-bd-left"><div class="x-tip-bd-right"><div class="x-tip-bd"><div class="x-tip-close"></div><h3></h3><div class="x-tip-bd-inner"></div><div class="x-clear"></div></div></div></div><div class="x-tip-ft-left"><div class="x-tip-ft-right"><div class="x-tip-ft"></div></div></div>'); tipTitle = el.child('h3'); tipTitle.enableDisplayMode("block"); tipBody = el.child('div.x-tip-bd'); tipBodyText = el.child('div.x-tip-bd-inner'); bdLeft = el.child('div.x-tip-bd-left'); bdRight = el.child('div.x-tip-bd-right'); close = el.child('div.x-tip-close'); close.enableDisplayMode("block"); close.on("click", hide); var d = Ext.get(document); d.on("mousedown", onDown); d.on("mouseup", onUp); d.on("mouseover", onOver); d.on("mouseout", onOut); d.on("mousemove", onMove); esc = d.addKeyListener(27, hide); esc.disable(); if(Ext.dd.DD){ dd = el.initDD("default", null, { onDrag : function(){ el.sync(); } }); dd.setHandleElId(tipTitle.id); dd.lock(); } inited = true; } this.enable(); }, /** * 配置一个新的快捷提示实例, 并指定到目标元素(目标元素应在 config.target 属性上指定)。 * @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++){ tagEls[target[j]] = c; } }else{ tagEls[typeof target == 'string' ? target : Ext.id(target)] = c; } } } }, /** * 从元素中删除此快捷提示并销毁它。 * @param {String/HTMLElement/Element} el 要删除快捷提示的元素。 */ unregister : function(el){ delete tagEls[Ext.id(el)]; }, /** * 启用此快捷提示。 */ enable : function(){ if(inited && disabled){ locks.pop(); if(locks.length < 1){ disabled = false; } } }, /** * 禁用此快捷提示。 */ disable : function(){ disabled = true; clearTimeout(showProc); clearTimeout(hideProc); clearTimeout(dismissProc); if(ce){ hide(true); } locks.push(1); }, /** * 如果快捷提示被启用则返回 true , 否则返回 false。 */ isEnabled : function(){ return !disabled; }, // private tagConfig : { namespace : "ext", attribute : "qtip", width : "width", target : "target", title : "qtitle", hide : "hide", cls : "qclass" } }; }(); // backwards compat Ext.QuickTips.tips = Ext.QuickTips.register;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.SplitBar * @extends Ext.util.Observable * Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized). * <br><br> * Usage: * <pre><code> var split = new Ext.SplitBar("elementToDrag", "elementToSize", Ext.SplitBar.HORIZONTAL, Ext.SplitBar.LEFT); split.setAdapter(new Ext.SplitBar.AbsoluteLayoutAdapter("container")); split.minSize = 100; split.maxSize = 600; split.animate = true; split.on('moved', splitterMoved); </code></pre> * @constructor * Create a new SplitBar * @param {String/HTMLElement/Ext.Element} dragElement The element to be dragged and act as the SplitBar. * @param {String/HTMLElement/Ext.Element} resizingElement The element to be resized based on where the SplitBar element is dragged * @param {Number} orientation (optional) Either Ext.SplitBar.HORIZONTAL or Ext.SplitBar.VERTICAL. (Defaults to HORIZONTAL) * @param {Number} placement (optional) Either Ext.SplitBar.LEFT or Ext.SplitBar.RIGHT for horizontal or Ext.SplitBar.TOP or Ext.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial position of the SplitBar). */ Ext.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){ /** @private */ this.el = Ext.get(dragElement, true); this.el.dom.unselectable = "on"; /** @private */ this.resizingEl = Ext.get(resizingElement, true); /** * @private * The orientation of the split. Either Ext.SplitBar.HORIZONTAL or Ext.SplitBar.VERTICAL. (Defaults to HORIZONTAL) * Note: If this is changed after creating the SplitBar, the placement property must be manually updated * @type Number */ this.orientation = orientation || Ext.SplitBar.HORIZONTAL; /** * The minimum size of the resizing element. (Defaults to 0) * @type Number */ this.minSize = 0; /** * The maximum size of the resizing element. (Defaults to 2000) * @type Number */ this.maxSize = 2000; /** * Whether to animate the transition to the new size * @type Boolean */ this.animate = false; /** * Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes. * @type Boolean */ this.useShim = false; /** @private */ this.shim = null; if(!existingProxy){ /** @private */ this.proxy = Ext.SplitBar.createProxy(this.orientation); }else{ this.proxy = Ext.get(existingProxy).dom; } /** @private */ this.dd = new Ext.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id}); /** @private */ this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this); /** @private */ this.dd.endDrag = this.onEndProxyDrag.createDelegate(this); /** @private */ this.dragSpecs = {}; /** * @private The adapter to use to positon and resize elements */ this.adapter = new Ext.SplitBar.BasicLayoutAdapter(); this.adapter.init(this); if(this.orientation == Ext.SplitBar.HORIZONTAL){ /** @private */ this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Ext.SplitBar.LEFT : Ext.SplitBar.RIGHT); this.el.addClass("x-splitbar-h"); }else{ /** @private */ this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Ext.SplitBar.TOP : Ext.SplitBar.BOTTOM); this.el.addClass("x-splitbar-v"); } this.addEvents({ /** * @event resize * Fires when the splitter is moved (alias for {@link #event-moved}) * @param {Ext.SplitBar} this * @param {Number} newSize the new width or height */ "resize" : true, /** * @event moved * Fires when the splitter is moved * @param {Ext.SplitBar} this * @param {Number} newSize the new width or height */ "moved" : true, /** * @event beforeresize * Fires before the splitter is dragged * @param {Ext.SplitBar} this */ "beforeresize" : true, "beforeapply" : true }); Ext.SplitBar.superclass.constructor.call(this); }; Ext.extend(Ext.SplitBar, Ext.util.Observable, { onStartProxyDrag : function(x, y){ this.fireEvent("beforeresize", this); if(!this.overlay){ var o = Ext.DomHelper.insertFirst(document.body, {cls: "x-drag-overlay", html: "&#160;"}, true); o.unselectable(); o.enableDisplayMode("block"); // all splitbars share the same overlay Ext.SplitBar.prototype.overlay = o; } this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.overlay.show(); Ext.get(this.proxy).setDisplayed("block"); var size = this.adapter.getElementSize(this); this.activeMinSize = this.getMinimumSize();; this.activeMaxSize = this.getMaximumSize();; var c1 = size - this.activeMinSize; var c2 = Math.max(this.activeMaxSize - size, 0); if(this.orientation == Ext.SplitBar.HORIZONTAL){ this.dd.resetConstraints(); this.dd.setXConstraint( this.placement == Ext.SplitBar.LEFT ? c1 : c2, this.placement == Ext.SplitBar.LEFT ? c2 : c1 ); this.dd.setYConstraint(0, 0); }else{ this.dd.resetConstraints(); this.dd.setXConstraint(0, 0); this.dd.setYConstraint( this.placement == Ext.SplitBar.TOP ? c1 : c2, this.placement == Ext.SplitBar.TOP ? c2 : c1 ); } this.dragSpecs.startSize = size; this.dragSpecs.startPoint = [x, y]; Ext.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y); }, /** * @private Called after the drag operation by the DDProxy */ onEndProxyDrag : function(e){ Ext.get(this.proxy).setDisplayed(false); var endPoint = Ext.lib.Event.getXY(e); if(this.overlay){ this.overlay.hide(); } var newSize; if(this.orientation == Ext.SplitBar.HORIZONTAL){ newSize = this.dragSpecs.startSize + (this.placement == Ext.SplitBar.LEFT ? endPoint[0] - this.dragSpecs.startPoint[0] : this.dragSpecs.startPoint[0] - endPoint[0] ); }else{ newSize = this.dragSpecs.startSize + (this.placement == Ext.SplitBar.TOP ? endPoint[1] - this.dragSpecs.startPoint[1] : this.dragSpecs.startPoint[1] - endPoint[1] ); } newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize); if(newSize != this.dragSpecs.startSize){ if(this.fireEvent('beforeapply', this, newSize) !== false){ this.adapter.setElementSize(this, newSize); this.fireEvent("moved", this, newSize); this.fireEvent("resize", this, newSize); } } }, /** * Get the adapter this SplitBar uses * @return The adapter object */ getAdapter : function(){ return this.adapter; }, /** * Set the adapter this SplitBar uses * @param {Object} adapter A SplitBar adapter object */ setAdapter : function(adapter){ this.adapter = adapter; this.adapter.init(this); }, /** * Gets the minimum size for the resizing element * @return {Number} The minimum size */ getMinimumSize : function(){ return this.minSize; }, /** * Sets the minimum size for the resizing element * @param {Number} minSize The minimum size */ setMinimumSize : function(minSize){ this.minSize = minSize; }, /** * Gets the maximum size for the resizing element * @return {Number} The maximum size */ getMaximumSize : function(){ return this.maxSize; }, /** * Sets the maximum size for the resizing element * @param {Number} maxSize The maximum size */ setMaximumSize : function(maxSize){ this.maxSize = maxSize; }, /** * Sets the initialize size for the resizing element * @param {Number} size The initial size */ setCurrentSize : function(size){ var oldAnimate = this.animate; this.animate = false; this.adapter.setElementSize(this, size); this.animate = oldAnimate; }, /** * Destroy this splitbar. * @param {Boolean} removeEl True to remove the element */ destroy : function(removeEl){ if(this.shim){ this.shim.remove(); } this.dd.unreg(); this.proxy.parentNode.removeChild(this.proxy); if(removeEl){ this.el.remove(); } } }); /** * @private static Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color. */ Ext.SplitBar.createProxy = function(dir){ var proxy = new Ext.Element(document.createElement("div")); proxy.unselectable(); var cls = 'x-splitbar-proxy'; proxy.addClass(cls + ' ' + (dir == Ext.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v')); document.body.appendChild(proxy.dom); return proxy.dom; }; /** * @class Ext.SplitBar.BasicLayoutAdapter * Default Adapter. It assumes the splitter and resizing element are not positioned * elements and only gets/sets the width of the element. Generally used for table based layouts. */ Ext.SplitBar.BasicLayoutAdapter = function(){ }; Ext.SplitBar.BasicLayoutAdapter.prototype = { // do nothing for now init : function(s){ }, /** * Called before drag operations to get the current size of the resizing element. * @param {Ext.SplitBar} s The SplitBar using this adapter */ getElementSize : function(s){ if(s.orientation == Ext.SplitBar.HORIZONTAL){ return s.resizingEl.getWidth(); }else{ return s.resizingEl.getHeight(); } }, /** * Called after drag operations to set the size of the resizing element. * @param {Ext.SplitBar} s The SplitBar using this adapter * @param {Number} newSize The new size to set * @param {Function} onComplete A function to be invoked when resizing is complete */ setElementSize : function(s, newSize, onComplete){ if(s.orientation == Ext.SplitBar.HORIZONTAL){ if(!s.animate){ s.resizingEl.setWidth(newSize); if(onComplete){ onComplete(s, newSize); } }else{ s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut'); } }else{ if(!s.animate){ s.resizingEl.setHeight(newSize); if(onComplete){ onComplete(s, newSize); } }else{ s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut'); } } } }; /** *@class Ext.SplitBar.AbsoluteLayoutAdapter * @extends Ext.SplitBar.BasicLayoutAdapter * Adapter that moves the splitter element to align with the resized sizing element. * Used with an absolute positioned SplitBar. * @param {String/HTMLElement/Ext.Element} container The container that wraps around the absolute positioned content. If it's * document.body, make sure you assign an id to the body element. */ Ext.SplitBar.AbsoluteLayoutAdapter = function(container){ this.basic = new Ext.SplitBar.BasicLayoutAdapter(); this.container = Ext.get(container); }; Ext.SplitBar.AbsoluteLayoutAdapter.prototype = { init : function(s){ this.basic.init(s); }, getElementSize : function(s){ return this.basic.getElementSize(s); }, setElementSize : function(s, newSize, onComplete){ this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s])); }, moveSplitter : function(s){ var yes = Ext.SplitBar; switch(s.placement){ case yes.LEFT: s.el.setX(s.resizingEl.getRight()); break; case yes.RIGHT: s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px"); break; case yes.TOP: s.el.setY(s.resizingEl.getBottom()); break; case yes.BOTTOM: s.el.setY(s.resizingEl.getTop() - s.el.getHeight()); break; } } }; /** * Orientation constant - Create a vertical SplitBar * @static * @type Number */ Ext.SplitBar.VERTICAL = 1; /** * Orientation constant - Create a horizontal SplitBar * @static * @type Number */ Ext.SplitBar.HORIZONTAL = 2; /** * Placement constant - The resizing element is to the left of the splitter element * @static * @type Number */ Ext.SplitBar.LEFT = 1; /** * Placement constant - The resizing element is to the right of the splitter element * @static * @type Number */ Ext.SplitBar.RIGHT = 2; /** * Placement constant - The resizing element is positioned above the splitter element * @static * @type Number */ Ext.SplitBar.TOP = 3; /** * Placement constant - The resizing element is positioned under splitter element * @static * @type Number */ Ext.SplitBar.BOTTOM = 4;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /** * @class Ext.LoadMask * 一个简单的工具类,用于在加载数据时为元素做出类似于遮罩的效果。 * 对于有可用的{@link Ext.data.Store},可将效果与Store的加载达到同步,而mask本身会被缓存以备复用。 * 而对于其他元素,这个遮照类会替换元素本身的UpdateManager加载指示器,并在初始化完毕后销毁。 * @constructor * Create a new LoadMask * @param {String/HTMLElement/Ext.Element} 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 = false; }else{ var um = this.el.getUpdateManager(); 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 = 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); } }, // 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.getUpdateManager(); um.un('beforeupdate', this.onBeforeLoad, this); um.un('update', this.onLoad, this); um.un('failure', this.onLoad, this); } } };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.ComponentMgr * 公开提供一个包含所有组件的注册页,以便可以轻松地通过ID访问组件(参阅{@link Ext.getCmp})。 * @singleton */ Ext.ComponentMgr = function(){ var all = new Ext.util.MixedCollection(); return { /** * 登记组件。 * @param {Ext.Component} c 组件 */ register : function(c){ all.add(c); }, /** * 注销组件 * @param {Ext.Component} c 组件 */ unregister : function(c){ all.remove(c); }, /** * 根据ID返回组件。 * @param {String} id 组件的ID */ get : function(id){ return all.get(id); }, /** * 注册一个函数,当指定的组件加入到 ComponentMgr 对象时调用。 * @param {String} id 组件的ID * @param {Funtction} fn 回调函数 * @param {Object} scope 回调的作用域 */ onAvailable : function(id, fn, scope){ all.on("add", function(index, o){ if(o.id == id){ fn.call(scope || o, o); all.un("add", fn, scope); } }); } }; }(); /** * @class Ext.Component * @extends Ext.util.Observable * EXT大部分组件的基类。组件所有的子类都按照标准的Ext组件创建、渲染、销毁这样的周期生存,并具有隐藏/显示,启用/禁用的基本行为。 * 组件的任意子类允许延时渲染(lazy-rendered)到任何的{@link Ext.Container},并且在{@link Ext.ComponentMgr}自动登记, * 以便随时可让{@link Ext.getCmp}获取其引用。所有可视的组件(widgets/器件)渲染时都离不开某个布局,因此均应为组件的子类。 * @constructor * @param {Ext.Element/String/Object} config 若传入一个元素类型的参数,会被设置为内置使用的元素,其id会作为组件id使用。 * 若传入一个字符串类型的参数,会被认为是利用现有元素的id,当作组件的id用。若不是,则被认为是标准的配置项对象, * 应用到组件上。 */ Ext.Component = function(config){ config = config || {}; if(config.tagName || config.dom || typeof config == "string"){ // 元素对象 config = {el: config, id: config.id || config}; } this.initialConfig = config; Ext.apply(this, config); this.addEvents({ /** * @event disable * 组件被禁止之后触发。 * @param {Ext.Component} this */ disable : true, /** * @event enable * 组件被启用之后触发。 * @param {Ext.Component} this */ enable : true, /** * @event beforeshow * 组件显示之前触发。如返回false则取消显示 * @param {Ext.Component} this */ beforeshow : true, /** * @event show * 组件显示之后触发。 * @param {Ext.Component} this */ show : true, /** * @event beforehide * 组件隐藏之前触发。如返回false则取消隐藏。 * @param {Ext.Component} this */ beforehide : true, /** * @event hide * 组件隐藏之后触发。 * @param {Ext.Component} this */ hide : true, /** * @event beforerender * 组件渲染之前触发。如返回false则取消渲染。 * @param {Ext.Component} this */ beforerender : true, /** * @event render * 组件渲染之后触发。 * @param {Ext.Component} this */ render : true, /** * @event beforedestroy * 组件销毁之前触发。如返回false则取消消耗。 * @param {Ext.Component} this */ beforedestroy : true, /** * @event destroy * 组件销毁之后触发。 * @param {Ext.Component} this */ destroy : true }); if(!this.id){ this.id = "ext-comp-" + (++Ext.Component.AUTO_ID); } Ext.ComponentMgr.register(this); Ext.Component.superclass.constructor.call(this); this.initComponent(); if(this.renderTo){ // not supported by all components yet. use at your own risk! this.render(this.renderTo); delete this.renderTo; } }; // private Ext.Component.AUTO_ID = 1000; Ext.extend(Ext.Component, Ext.util.Observable, { /** * 只读。组件隐藏时为true */ hidden : false, /** * 只读。组件禁用时为true */ disabled : false, /** * 只读。组件未被渲染时为true */ rendered : false, /** @cfg {String} disableClass * 组件禁用时所调用的CSS样式类(默认为x-item-disabled) */ disabledClass : "x-item-disabled", /** @cfg {Boolean} allowDomMove * 当渲染时,组件能否在DOM树中间移动(默认为true)。 */ allowDomMove : true, /** @cfg {String} hideMode * 怎么样去隐藏组件。可支持"visibility"(CSS的visibility), * "offsets"(负值偏移位置)和"display"(CSS display)。-默认为"display"。 */ hideMode: 'display', // private ctype : "Ext.Component", // private actionMode : "el", // private getActionEl : function(){ return this[this.actionMode]; }, initComponent : Ext.emptyFn, /** * 如果这是一个延时渲染的组件,那么渲染其容器所在的元素。 * @param {String/HTMLElement/Element} container (可选的)这个组件发生渲染所在的元素。 * If it is being applied to existing markup, this should be left off. */ 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); 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.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(); } } return this; }, // private // default function is not really useful onRender : function(ct, position){ 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.purgeListeners(); 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); } }, // private beforeDestroy : function(){ }, // private onDestroy : function(){ }, /** * 返回所属的 {@link Ext.Element}. * @return {Ext.Element} 元素 */ getEl : function(){ return this.el; }, /** * 返回该组件的id。 * @return {String} */ getId : function(){ return this.id; }, /** * 试着聚焦到此项。 * @param {Boolean} selectText true的话同时亦选中组件中的文本(尽可能) * @return {Ext.Component} this */ focus : function(selectText){ 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.rendered){ this.onShow(); } this.fireEvent("show", this); } return this; }, // private onShow : function(){ var ae = this.getActionEl(); if(this.hideMode == 'visibility'){ ae.dom.style.visibility = "visible"; }else if(this.hideMode == 'offsets'){ ae.removeClass('x-hidden'); }else{ ae.dom.style.display = ""; } }, /** * 隐藏该组件。 * @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(){ var ae = this.getActionEl(); if(this.hideMode == 'visibility'){ ae.dom.style.visibility = "hidden"; }else if(this.hideMode == 'offsets'){ ae.addClass('x-hidden'); }else{ ae.dom.style.display = "none"; } }, /** * 方便的布尔函数用来控制组件显示/隐藏。 * @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.getActionEl().isVisible(); }, 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); } });
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 {String/HTMLElement/Ext.Element} 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({ /** * @event beforeresize * 在缩放被实施之前触发。设置 enabled 为 false 可以取消缩放。 * @param {Ext.Resizable} this * @param {Ext.EventObject} e mousedown 事件 */ "beforeresize" : true, /** * @event resize * 缩放之后触发。 * @param {Ext.Resizable} this * @param {Number} width 新的宽度 * @param {Number} height 新的高度 * @param {Ext.EventObject} e mouseup 事件 */ "resize" : true }); 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 {String/HTMLElement/Element} constrainTo 强制缩放到一个指定的元素 */ constrainTo: undefined, /** * @cfg {Ext.lib.Region} resizeRegion 强制缩放到一个指定区域 */ resizeRegion: undefined, /** * 执行手动缩放 * @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;"}); 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(); } } }); // 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.DomHelper * 处理DOM或模板(Templates)的实用类。 * 能较清晰地编写HTML片段(HTML fragments)或DOM。 * 更多资讯,请参阅 <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为修正IE破表格 */ 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"); }, // private doInsert : function(el, o, returnElement, pos, sibling){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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){ if(removeDom){ var d = this.elements[index]; if(d.dom){ d.remove(); }else{ d.parentNode.removeChild(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); } }; })(); /** * @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); d.parentNode.removeChild(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选择符的参数,然后基于该选择符的子节点(Child nodes) * 创建一个 {@link Ext.CompositeElement}组合元素。(选择符不应有id) * @param {String} selector CSS选择符 * @param {Boolean} unique true:为每个子元素创建唯一的 Ext.Element * (默认为false享元的普通对象flyweight object) * @return {CompositeElement/CompositeElementLite} 复合元素 */ Ext.select = Ext.Element.select;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ //通知 Element 对象 FX 的方法可用 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> <<<<<<< .mine * <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"; attr = o.attr || "backgroundColor"; this.clearOpacity(); this.show(); var origColor = this.getColor(attr); var restoreColor = this.dom.style[attr]; 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; duration = o.duration || 1; this.show(); var b = this.getBox(); var animFn = function(){ var proxy = this.createProxy({ 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.defer((duration/2)*1000, this); }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(){ //以支持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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /* * This is code is also distributed under MIT license for use * with jQuery and prototype JavaScript libraries. * * 本代码与 jQuery、prototype JavaScript 类库同样遵循 MIT 授权协议发布与使用。 */ /** * @class Ext.DomQuery Provides high performance selector/xpath processing by compiling queries into reusable functions. New pseudo classes and matchers can be plugged. It works on HTML and XML documents (if a content node is passed in). 根据编译请求提供高效的将选择符 / xpath 处理为可复用的函数的方法。可以添加新的伪类和匹配器。该类可以运行于 HTML 和 XML 文档之上(如果给出了一个内容节点)。 <p> DomQuery supports most of the <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 selectors spec</a>, along with some custom selectors and basic XPath. DomQuery 提供大多数的<a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 选择符</a>,同时也支持某些自定义选择符和基本的 XPath。</p> <p> All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. Node filters are processed in the order in which they appear, which allows you to optimize your queries for your document structure. 下列所有的选择符、属性过滤器和伪类可以在任何命令中无限地组合使用。例如:“div.foo:nth-child(odd)[@foo=bar].bar:first”将是一个完全有效的选择符。命令中出现的节点过滤器将可以使你根据自己的文档结构对查询做出优化。 </p> <h4>Element Selectors:</h4> <h4>元素选择符:</h4> <ul class="list"> <li> <b>*</b> any element</li> <li> <b>*</b> 任意元素</li> <li> <b>E</b> an element with the tag E</li> <li> <b>E</b> 一个标签为 E 的元素</li> <li> <b>E F</b> All descendent elements of E that have the tag F</li> <li> <b>E F</b> 所有 E 元素的分支元素中含有标签为 F 的元素</li> <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li> <li> <b>E > F</b> 或 <b>E/F</b> 所有 E 元素的直系子元素中含有标签为 F 的元素</li> <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li> <li> <b>E + F</b> 所有标签为 F 并紧随着标签为 E 的元素之后的元素</li> <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li> <li> <b>E ~ F</b> 所有标签为 F 并与标签为 E 的元素是兄弟的元素</li> </ul> <h4>Attribute Selectors:</h4> <h4>属性选择符:</h4> <p>The use of @ and quotes are optional. For example, div[@foo='bar'] is also a valid attribute selector.</p> <p>@ 与引号的使用是可选的。例如:div[@foo='bar'] 也是一个有效的属性选择符。</p> <ul class="list"> <li> <b>E[foo]</b> has an attribute "foo"</li> <li> <b>E[foo]</b> 拥有一个名为 “foo” 的属性</li> <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li> <li> <b>E[foo=bar]</b> 拥有一个名为 “foo” 且值为 “bar” 的属性</li> <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li> <li> <b>E[foo^=bar]</b> 拥有一个名为 “foo” 且值以 “bar” 开头的属性</li> <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li> <li> <b>E[foo$=bar]</b> 拥有一个名为 “foo” 且值以 “bar” 结尾的属性</li> <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li> <li> <b>E[foo*=bar]</b> 拥有一个名为 “foo” 且值包含字串 “bar” 的属性</li> <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li> <li> <b>E[foo%=2]</b> 拥有一个名为 “foo” 且值能够被2整除的属性</li> <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</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 is the first child of its parent</li> <li> <b>E:first-child</b> E 元素为其父元素的第一个子元素</li> <li> <b>E:last-child</b> E is the last child of its parent</li> <li> <b>E:last-child</b> E 元素为其父元素的最后一个子元素</li> <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li> <li> <b>E:nth-child(<i>n</i>)</b> E 元素为其父元素的第 <i>n</i> 个子元素(由1开始的个数)</li> <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li> <li> <b>E:nth-child(odd)</b> E 元素为其父元素的奇数个数的子元素</li> <li> <b>E:nth-child(even)</b> E is an even child of its parent</li> <li> <b>E:nth-child(even)</b> E 元素为其父元素的偶数个数的子元素</li> <li> <b>E:only-child</b> E is the only child of its parent</li> <li> <b>E:only-child</b> E 元素为其父元素的唯一子元素</li> <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li> <li> <b>E:checked</b> E 元素为拥有一个名为“checked”且值为“true”的元素(例如:单选框或复选框)</li> <li> <b>E:first</b> the first E in the resultset</li> <li> <b>E:first</b> 结果集中第一个 E 元素</li> <li> <b>E:last</b> the last E in the resultset</li> <li> <b>E:last</b> 结果集中最后一个 E 元素</li> <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li> <li> <b>E:nth(<i>n</i>)</b> 结果集中第 <i>n</i> 个 E 元素(由1开始的个数)</li> <li> <b>E:odd</b> shortcut for :nth-child(odd)</li> <li> <b>E:odd</b> :nth-child(odd) 的简写</li> <li> <b>E:even</b> shortcut for :nth-child(even)</li> <li> <b>E:even</b> :nth-child(even) 的简写</li> <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li> <li> <b>E:contains(foo)</b> E 元素的 innerHTML 属性中包含“foo”字串</li> <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li> <li> <b>E:nodeValue(foo)</b> E 元素包含一个 textNode 节点且 nodeValue 等于“foo”</li> <li> <b>E:not(S)</b> an E element that does not match simple selector S</li> <li> <b>E:not(S)</b> 一个与简单选择符 S 不匹配的 E 元素</li> <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li> <li> <b>E:has(S)</b> 一个包含与简单选择符 S 相匹配的分支元素的 E 元素</li> <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li> <li> <b>E:next(S)</b> 下一个兄弟元素为与简单选择符 S 相匹配的 E 元素</li> <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li> <li> <b>E:prev(S)</b> 上一个兄弟元素为与简单选择符 S 相匹配的 E 元素</li> </ul> <h4>CSS Value Selectors:</h4> <h4>CSS 值选择符:</h4> <ul class="list"> <li> <b>E{display=none}</b> css value "display" that equals "none"</li> <li> <b>E{display=none}</b> css 的“display”属性等于“none”</li> <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li> <li> <b>E{display^=none}</b> css 的“display”属性以“none”开始</li> <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li> <li> <b>E{display$=none}</b> css 的“display”属性以“none”结尾</li> <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li> <li> <b>E{display*=none}</b> css 的“display”属性包含字串“none”</li> <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li> <li> <b>E{display%=2}</b> css 的“display”属性能够被2整除</li> <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</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); }, /** * Compiles a selector/xpath query into a reusable function. The returned function * takes one parameter "root" (optional), which is the context node from where the query should start. * * 将一个 选择符 / xpath 查询编译为一个可利用的函数。返回的函数获得一个“root”参数(可选)作为查询的起点。 * @param {String} selector The selector/xpath query 选择符 / xpath 查询 * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match * (可选)可以是“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; }, /** * Selects a group of elements. * 选择一组元素。 * @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; }, /** * Selects a single element. * 选择单个元素。 * @param {String} selector 选择符 / xpath 查询 * @param {Node} root (可选)查询的起点(默认为:document)。 * @return {Element} */ selectNode : function(path, root){ return Ext.DomQuery.select(path, root)[0]; }, /** * Selects the value of a node, optionally replacing null with the defaultValue. * 选择一个节点的值,可选择使用 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); }, "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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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> * 在这个博客的日志中可找到相关的例子: <a href="http://www.jackslocum.com/yui/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">DomHelper - Create Elements using DOM, HTML fragments and Templates</a>. * @constructor * @param {String/Array} html HTML片段或是片断的数组(用于join(''))或多个参数(用于join(''))。 */ Ext.Template = function(html){ if(html instanceof Array){ html = html.join(""); }else if(arguments.length > 1){ html = Array.prototype.join.call(arguments, ""); } /**@private*/ this.html = html; }; Ext.Template.prototype = { /** * 返回HTML片段,这块片段是由数据填充模板之后得到的。 * @param {Object} 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 {String/HTMLElement/Ext.Element} el 正文元素. * @param {Object} 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 {String/HTMLElement/Ext.Element} el 正文元素. * @param {Object} 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 {String/HTMLElement/Ext.Element} el 正文元素. * @param {Object} 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 {String/HTMLElement/Ext.Element} el 正文元素. * @param {Object} 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 {String/HTMLElement/Ext.Element} el 正文元素 * @param {Object} 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; } }; /** * Alias for {@link #applyTemplate} * @method */ Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; // backwards compat Ext.DomHelper.Template = Ext.Template; /** * 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML. * @param {String/HTMLElement} DOM元素或某id * @returns {Ext.Template} 创建好的模板 * @static */ Ext.Template.from = function(el){ el = Ext.getDom(el); return new Ext.Template(el.value || el.innerHTML); };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.UpdateManager * @extends Ext.util.Observable *为元素对象提供Ajax式更新。<br><br> * 用法:<br> * <pre><code> * // 从Ext.Element对象上获取 * var el = Ext.get("foo"); * var mgr = el.getUpdateManager(); * mgr.update("http://myserver.com/index.php", "param1=1&amp;param2=2"); * ... * mgr.formUpdate("myFormId", "http://myserver.com/index.php"); * <br> * // 或直接声明(返回相同的UpdateManager实例) * var mgr = new Ext.UpdateManager("myElementId"); * mgr.startAutoRefresh(60, "http://myserver.com/index.php"); * mgr.on("update", myFcnNeedsToKnow); * <br> //用快捷的方法在元素上直接访问 Ext.get("foo").load({ url: "bar.php", scripts:true, params: "for=bar", text: "Loading Foo..." }); * </code></pre> * @constructor * 直接创建新UpdateManager。 * @param {String/HTMLElement/Ext.Element} el 被更新的元素 * @param {Boolean} forceNew (可选地) 默认下 构造器会检查传入之元素是否有UpdateManager,如果有的话它返回该实例。这个也跳过检查(继承类时有用)。 */ Ext.UpdateManager = 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.UpdateManager.defaults; /** * 用于SSL文件上传的空白页面地址。(默认为Ext.UpdateManager.defaults.sslBlankUrl 或 "about:blank") * @type String */ this.sslBlankUrl = d.sslBlankUrl; /** * 是否在请求中添加上随机的参数,以禁止返回缓冲的数据(默认为Ext.UpdateManager.defaults.disableCaching或false) * @type Boolean */ this.disableCaching = d.disableCaching; /** * “加载中...”显示的文字(默认为 Ext.UpdateManager.defaults.indicatorText或'&lt;div class="loading-indicator"&gt;加载中...&lt;/div&gt;')。 * @type String */ this.indicatorText = d.indicatorText; /** * 加载时是否显示像“加载中...”的文字(默认为 Ext.UpdateManager.defaults.showLoadIndicator或true)。 * @type String */ this.showLoadIndicator = d.showLoadIndicator; /** * 请求或表单post的超时时限,单位:秒(默认为Ext.UpdateManager.defaults.timeout或30秒)。 * @type Number */ this.timeout = d.timeout; /** * 是否执行输出的脚本(默认为 Ext.UpdateManager.defaults.loadScripts (false)) * @type Boolean */ this.loadScripts = d.loadScripts; /** * 执行当前事务的事务对象。 */ this.transaction = null; /** * @private */ this.autoRefreshProcId = null; /** * refresh()的委托,预绑定到"this",使用myUpdater.refreshDelegate.createCallback(arg1, arg2)绑定参数。 * @type Function */ this.refreshDelegate = this.refresh.createDelegate(this); /** * update()的委托,预绑定到"this",使用myUpdater.updateDelegate.createCallback(arg1, arg2)绑定参数。 * @type Function */ this.updateDelegate = this.update.createDelegate(this); /** * formUpdate()的委托,预绑定到"this",使用myUpdater.formUpdateDelegate.createCallback(arg1, arg2)绑定参数。 * @type Function */ this.formUpdateDelegate = this.formUpdate.createDelegate(this); /** * @private */ this.successDelegate = this.processSuccess.createDelegate(this); /** * @private */ this.failureDelegate = this.processFailure.createDelegate(this); if(!this.renderer){ /** * UpdateManager所用的渲染器。默认为{@link Ext.UpdateManager.BasicRenderer}。 */ this.renderer = new Ext.UpdateManager.BasicRenderer(); } Ext.UpdateManager.superclass.constructor.call(this); }; Ext.extend(Ext.UpdateManager, Ext.util.Observable, { /** * 获取当前UpdateManager所绑定的元素 * @return {Ext.Element} 元素 */ getEl : function(){ return this.el; }, /** * 发起一个的异步请求,然后根据响应的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的话,就不会保存。 */ update : function(url, params, callback, discardUrl){ if(this.fireEvent("beforeupdate", this.el, url, params) !== false){ var method = this.method, cfg; if(typeof url == "object"){ //必需系对象 cfg = url; url = cfg.url; params = params || cfg.params; callback = callback || cfg.callback; discardUrl = discardUrl || cfg.discardUrl; if(callback && cfg.scope){ callback = callback.createDelegate(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: params, success: this.successDelegate, failure: this.failureDelegate, callback: undefined, timeout: (this.timeout*1000), argument: {"url": url, "form": null, "callback": callback, "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 事务完成后 ,执行的回调(带参数oElement, bSuccess) */ 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.successDelegate, failure: this.failureDelegate, 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{ //由于旧版的FF这段代码会有点问题所以加上try/catch 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(this.el, true, response); } }, /** * @private */ processFailure : function(response){ this.transaction = null; this.fireEvent("failure", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback(this.el, false, response); } }, /** * 为这次更新设置内容渲染器。参阅{@link Ext.UpdateManager.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.UpdateManager.defaults * UpdateManager组件中可定制的属性,这里是默认值集合。 */ Ext.UpdateManager.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.UpdateManager.updateElement("my-div", "stuff.php");</code></pre> * @param {String/HTMLElement/Ext.Element} el The element to update * @param {String} url The url * @param {String/Object} params (可选的) Url encoded param string or an object of name/value pairs * @param {Object} options (可选的) A config object with any of the UpdateManager properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."} * @static * @deprecated * @member Ext.UpdateManager */ Ext.UpdateManager.updateElement = function(el, url, params, options){ var um = Ext.get(el, true).getUpdateManager(); Ext.apply(um, options); um.update(url, params, options ? options.callback : null); }; // 向后兼容 Ext.UpdateManager.update = Ext.UpdateManager.updateElement; /** * @class Ext.UpdateManager.BasicRenderer * 默认的内容渲染器。使用responseText更新元素的innerHTML属性。 */ Ext.UpdateManager.BasicRenderer = function(){}; Ext.UpdateManager.BasicRenderer.prototype = { /** * 当事务完成并准备更新元素的时候调用此方法。 * BasicRenderer 使用 responseText 更新元素的 innerHTML 属性。 * 如想要指定一个定制的渲染器(如:XML 或 JSON),使用“render(el, response)”方法创建一个对象, * 并通过setRenderer方法传递给UpdateManager。 * @param {Ext.Element} el 呈现的元素。 * @param {Object} response YUI 响应的对象。 * @param {UpdateManager} updateManager 调用的 UpdateManager 对象。 * @param {Function} callback 如果 loadScripts 属性为 true 时,UpdateManager 对象需要指定一个回调函数。 */ render : function(el, response, updateManager, callback){ el.update(response.responseText, updateManager.loadScripts, callback); } };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.EventManager * 对于登记的事件句柄(Event handlers),能够接受一个常规化的(已作跨浏览器处理的)EventObject的参数 * ,而非浏览器的标准事件,并直接提供一些有用的事件。 * 更多“已常规化的事件对象(normalized event objects)”的信息,请参阅{@link Ext.EventObject} * @singleton */ Ext.EventManager = function(){ var docReadyEvent, docReadyProcId, docReadyState = false; var resizeEvent, resizeTask, textEvent, textSize; var E = Ext.lib.Event; var D = Ext.lib.Dom; var fireDocReady = function(){ if(!docReadyState){ docReadyState = true; Ext.isReady = true; if(docReadyProcId){ clearInterval(docReadyProcId); } if(Ext.isGecko || Ext.isOpera) { document.removeEventListener("DOMContentLoaded", fireDocReady, false); } if(docReadyEvent){ docReadyEvent.fire(); docReadyEvent.clearListeners(); } } }; var initDocReady = function(){ docReadyEvent = new Ext.util.Event(); if(Ext.isGecko || Ext.isOpera) { document.addEventListener("DOMContentLoaded", fireDocReady, false); }else if(Ext.isIE){ // inspired by http://www.thefutureoftheweb.com/blog/2006/6/adddomloadevent document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>"); var defer = document.getElementById("ie-deferred-loader"); defer.onreadystatechange = function(){ if(this.readyState == "complete"){ fireDocReady(); defer.onreadystatechange = null; defer.parentNode.removeChild(defer); } }; }else if(Ext.isSafari){ docReadyProcId = setInterval(function(){ var rs = document.readyState; if(rs == "complete") { fireDocReady(); } }, 10); } // no matter what, make sure it fires on load // 无论怎么样,保证on load时触发 E.on(window, "load", fireDocReady); }; var createBuffered = function(h, o){ var task = new Ext.util.DelayedTask(h); return function(e){ // create new event object impl so new events don't wipe out properties // 创建新的impl事件对象,这样新的事件就不会消灭掉(wipe out)属性(译注,js都是by refenerce) e = new Ext.EventObjectImpl(e); task.delay(o.buffer, h, null, [e]); }; }; var createSingle = function(h, el, ename, fn){ return function(e){ Ext.EventManager.removeListener(el, ename, fn); h(e); }; }; var createDelayed = function(h, o){ return function(e){ // create new event object impl so new events don't wipe out properties e = new Ext.EventObjectImpl(e); setTimeout(function(){ h(e); }, o.delay || 10); }; }; var listen = function(element, ename, opt, fn, scope){ var o = (!opt || typeof opt == "boolean") ? {} : opt; fn = fn || o.fn; scope = scope || o.scope; var el = Ext.getDom(element); if(!el){ throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.'; } var h = function(e){ e = Ext.EventObject.setEvent(e); var t; if(o.delegate){ t = e.getTarget(o.delegate, el); if(!t){ return; } }else{ t = e.target; } if(o.stopEvent === true){ e.stopEvent(); } if(o.preventDefault === true){ e.preventDefault(); } if(o.stopPropagation === true){ e.stopPropagation(); } if(o.normalized === false){ e = e.browserEvent; } fn.call(scope || el, e, t, o); }; if(o.delay){ h = createDelayed(h, o); } if(o.single){ h = createSingle(h, el, ename, fn); } if(o.buffer){ h = createBuffered(h, o); } fn._handlers = fn._handlers || []; fn._handlers.push([Ext.id(el), ename, h]); E.on(el, ename, h); if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery el.addEventListener("DOMMouseScroll", h, false); E.on(window, 'unload', function(){ el.removeEventListener("DOMMouseScroll", h, false); }); } if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document Ext.EventManager.stoppedMouseDownEvent.addListener(h); } return h; }; var stopListening = function(el, ename, fn){ var id = Ext.id(el), hds = fn._handlers, hd = fn; if(hds){ for(var i = 0, len = hds.length; i < len; i++){ var h = hds[i]; if(h[0] == id && h[1] == ename){ hd = h[2]; hds.splice(i, 1); break; } } } E.un(el, ename, hd); el = Ext.getDom(el); if(ename == "mousewheel" && el.addEventListener){ el.removeEventListener("DOMMouseScroll", hd, false); } if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document Ext.EventManager.stoppedMouseDownEvent.removeListener(hd); } }; var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/; var pub = { /** * 这个已经不在使用而且不推荐使用 * Places a simple wrapper around an event handler to override the browser event * object with a Ext.EventObject * @param {Function} fn The method the event invokes * @param {Object} scope An object that becomes the scope of the handler * @param {boolean} override If true, the obj passed in becomes * the execution scope of the listener * @return {Function} The wrapped function * @deprecated */ wrap : function(fn, scope, override){ return function(e){ Ext.EventObject.setEvent(e); fn.call(override ? scope || window : window, Ext.EventObject, scope); }; }, /** * 为该组件加入事件句柄(event handler)。跟简写方式{@link #on}是一样的。 * 通常你会更多的使用元素本身{@link Ext.Element#removeListener}的方法。 * @param {String} 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> * <b>组合选项</b><br> * 利用参数选项,可以组合成不同类型的侦听器:<br> * <br> * 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId) * 的一次性侦听器 <pre><code> el.on('click', this.onClick, this, { single: true, delay: 100, forumId: 4 }); </code></pre> * <p> * <b>在同一个调用附加上多个句柄(handlers)</b><br> * 这个方法可允许单个参数传入,包含多个句柄的配置对象。 * <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> * 或者是以简写方式将相同的作用域对象传入到所有的句柄中: <pre><code> el.on({ 'click': this.onClick, 'mouseover': this.onMouseOver, 'mouseout': this.onMouseOut, scope: this }); </code></pre> */ addListener : function(element, eventName, fn, scope, options){ if(typeof eventName == "object"){ var o = eventName; for(var e in o){ if(propRe.test(e)){ continue; } if(typeof o[e] == "function"){ // shared options listen(element, e, o, o[e], o.scope); }else{ // individual options listen(element, e, o[e]); } } return; } return listen(element, eventName, options, fn, scope); }, /** * 移除事件句柄(event handler),跟简写方式{@link #un}是一样的。 * 通常你会更多的使用元素本身{@link Ext.Element#removeListener}的方法。 * @param {String/HTMLElement} element 欲移除事件的html元素或id * @param {String} eventName 事件的类型 * @param {Function} fn 事件的执行那个函数 * @return {Boolean} true表示为侦听器移除成功 */ removeListener : function(element, eventName, fn){ return stopListening(element, eventName, fn); }, /** * 当Document准备好的时候触发(在onload之前和在图片加载之前)。可以简写为Ext.onReady()。 * @param {Function} fn 方法所涉及的事件 * @param {Object} scope 句柄的作用域 * @param {boolean} override (可选的)标准{@link #addListener}的选型对象 * @member Ext * @method onReady */ onDocumentReady : function(fn, scope, options){ if(docReadyState){ // if it already fired fn.call(scope || window, scope); return; } if(!docReadyEvent){ initDocReady(); } docReadyEvent.addListener(fn, scope, options); }, /** * 当window改变大小后触发,并有随改变大小的缓冲(50毫秒), * 对句柄传入新视图的高度、宽度的参数。 * @param {Function} fn 事件执行的方法 * @param {Object} scope 句柄的作用域 * @param {boolean} options */ onWindowResize : function(fn, scope, options){ if(!resizeEvent){ resizeEvent = new Ext.util.Event(); resizeTask = new Ext.util.DelayedTask(function(){ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); }); E.on(window, "resize", function(){ if(Ext.isIE){ resizeTask.delay(50); }else{ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); } }); } resizeEvent.addListener(fn, scope, options); }, /** * 当激活的文本尺寸被用户改变时触发该事件。 * 对句柄传入旧尺寸、新尺寸的参数。 * @param {Function} fn 事件涉及的方法 * @param {Object} scope 句柄的作用域 * @param {boolean} options */ onTextResize : function(fn, scope, options){ if(!textEvent){ textEvent = new Ext.util.Event(); var textEl = new Ext.Element(document.createElement('div')); textEl.dom.className = 'x-text-resize'; textEl.dom.innerHTML = 'X'; textEl.appendTo(document.body); textSize = textEl.dom.offsetHeight; setInterval(function(){ if(textEl.dom.offsetHeight != textSize){ textEvent.fire(textSize, textSize = textEl.dom.offsetHeight); } }, this.textResizeInterval); } textEvent.addListener(fn, scope, options); }, /** * 移除传入的window resize侦听器。 * @param {Function} fn 事件涉及的方法 * @param {Object} scope 句柄的作用域 */ removeResizeListener : function(fn, scope){ if(resizeEvent){ resizeEvent.removeListener(fn, scope); } }, fireResize : function(){ if(resizeEvent){ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); } }, /** * 配合SSL为onDocumentReady使用的Url(默认为Ext.SSL_SECURE_URL) */ ieDeferSrc : false, textResizeInterval : 50 }; /** * 为该组件加入事件处理器(event handler) * @param {String} 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> * <b>组合选项</b><br> * 利用参数选项,可以组合成不同类型的侦听器:<br> * <br> * 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId) * 的一次性侦听器 <pre><code> el.on('click', this.onClick, this, { single: true, delay: 100, forumId: 4 }); </code></pre> * <p> * <b>在同一个调用附加上多个句柄(handlers)</b><br> * 这个方法可允许单个参数传入,包含多个句柄的配置对象。 * <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> * 或者是以简写方式将相同的作用域对象传入到所有的句柄中: <pre><code> el.on({ 'click': this.onClick, 'mouseover': this.onMouseOver, 'mouseout': this.onMouseOut, scope: this }); </code></pre> */ pub.on = pub.addListener; pub.un = pub.removeListener; pub.stoppedMouseDownEvent = new Ext.util.Event(); return pub; }(); /** * 当文档准备好的时候触发(在onload之前和在图片加载之前)。可以简写为Ext.onReady()。 * @param {Function} fn 方法所涉及的事件 * @param {Object} scope handler的作用域 * @param {boolean} override 传入的对象将会是这个监听器(listener)所执行的作用域 * @member Ext * @method onReady */ Ext.onReady = Ext.EventManager.onDocumentReady; Ext.onReady(function(){ var bd = Ext.get(document.body); if(!bd){ return; } var cls = [ Ext.isIE ? "ext-ie" : Ext.isGecko ? "ext-gecko" : Ext.isOpera ? "ext-opera" : Ext.isSafari ? "ext-safari" : ""]; if(Ext.isMac){ cls.push("ext-mac"); } if(Ext.isLinux){ cls.push("ext-linux"); } if(Ext.isBorderBox){ cls.push('ext-border-box'); } if(Ext.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie" var p = bd.dom.parentNode; if(p){ p.className = p.className ? ' ext-strict' : 'ext-strict'; } } bd.addClass(cls.join(' ')); }); /** * @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 if the shift key was down during the event */ shiftKey : false, /** True if the control key was down during the event */ ctrlKey : false, /** 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.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){ return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : 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; /* In Opera 9, delta differs in sign as compared to IE. */ if(window.opera) delta = -delta; }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表示如果该事件的目标对象等于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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ Ext = {}; //为老版本浏览器提供 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 = ua.indexOf("msie") > -1, isIE7 = 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", 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; }; }(), /** * 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]; } } }, /** * 创建命名空间 * @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]; var type = typeof ov; if(type == 'undefined'){ buf.push(encodeURIComponent(key), "=&"); }else if(type != "function" && type != "object"){ buf.push(encodeURIComponent(key), "=", encodeURIComponent(ov), "&"); }else if(ov instanceof Array){ for(var i = 0, len = ov.length; i < len; i++) { buf.push(encodeURIComponent(key), "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&"); } } } 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; }; } }, // 不推荐使用 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"); }, // 内部函数 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){ return null; } return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el); }, /** * {@link Ext.ComponentMgr#get}的简写方式 * @param {String} id * @return Ext.Component */ getCmp : function(id){ return Ext.ComponentMgr.get(id); }, num : function(v, defaultValue){ if(typeof v != 'number'){ return defaultValue; } return v; }, 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.purgeListeners == 'function'){ as.purgeListeners(); } if(typeof as.destroy == 'function'){ as.destroy(); } } } }, // 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); }, /** @type Boolean */ isOpera : isOpera, /** @type Boolean */ isSafari : isSafari, /** @type Boolean */ isIE : isIE, /** @type Boolean */ isIE7 : isIE7, /** @type Boolean */ isGecko : isGecko, /** @type Boolean */ isBorderBox : isBorderBox, /** @type Boolean */ isWindows : isWindows, /** @type Boolean */ isLinux : isLinux, /** @type Boolean */ isMac : isMac, /** Ext 自动决定浮动元素是否应该被填充。 @type Boolean */ useShims : ((isIE && !isIE7) || (isGecko && isMac)) }); })(); Ext.namespace("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"); /** * @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被调用时会被传入原函数的参数。 * @addon * @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); }; } }); /** * @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 now contains the string: '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; }; Ext.applyIf(Number.prototype, { /** * 检验数字大小。 * 传入两个数字,一小一大,如果当前数字小于传入的小数字,则返回小的;如果该数字大于大的,则返回大的;如果在中间,则返回该数字本身 * 注意:这个方法返回新数字,但并不改变现有数字 * @param {Number} 小数 * @param {Number} 大数 * @return {Number} 大小数字,或其本身 */ constrain : function(min, max){ return Math.min(Math.max(this, min), max); } }); 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); } } }); /** * 返回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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.Element * 呈现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 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; // 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){ //无效的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 * @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; }, /** * 传入一个选择符的参数,找到整个节点并按照选择符查找父节点。选择符应是简易的选择符,如 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的话表示没有匹配结果) */ 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); }, /** * 返回true,如果这个元素就是传入的简易选择符参数(如 div.some-class或span:first-child) * @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; }, // 私有的 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; }, // private calcOffsetsTo : function(el){ el = Ext.get(el); var d = el.dom; var restorePos = false; if(el.getStyle('position') == 'static'){ el.position('relative'); restorePos = true; } var x = 0, y =0; var op = this.dom; while(op && op != d && op.tagName != 'HTML'){ x+= op.offsetLeft; y+= op.offsetTop; op = op.offsetParent; } if(restorePos){ el.position('static'); } return [x, y]; }, /** * 传入一个容器(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) || document.body; var el = this.dom; var o = this.calcOffsetsTo(c), l = o[0], t = o[1], 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(t < ct){ c.scrollTop = t; }else if(b > cb){ c.scrollTop = b-ch; } if(hscroll !== false){ if(l < cl){ c.scrollLeft = l; }else if(r > cr){ c.scrollLeft = r-c.clientWidth; } } return this; }, // private scrollChildIntoView : function(child, hscroll){ Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll); }, /** * 测量元素其内容的实际高度,使元素之高度适合。 * 注:改函数使用setTimeout而且新高度或者不会立即有效。 * @param {Boolean} animate (可选的) 变换 (默认 false) * @param {Float} duration (可选的) 动画持续时间 (默认为 .35 seconds) * @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); // Safari特有的parseInt 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; }, /** * 返回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); }, /** * 检查当前该元素是否都使用属性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选择符的参数,然后基于该选择符的子节点(Child nodes) * 创建一个 {@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节点代替Ext.Element(optional)(默认为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节点代替Ext.Element(optional)(默认为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{ // 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; }, /** * 如果属性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; }, // private 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类。如果oldClassName不存在,新name就会加入 * @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; }, /** * 常规化当前样式和计算样式。这并不是YUI的getStyle,是一个已优化的版本。 * @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); }, /** * 设置元素基于页面坐标的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; return contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb"); }, /** * 返回元素的偏移(offset)宽度 * @param {Boolean} contentWidth (可选的) true表示为获取减去边框和内补丁(borders & padding)的宽度 * @return {Number} 元素宽度 */ getWidth : function(contentWidth){ var w = this.dom.offsetWidth || 0; return contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr"); }, /** * 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} */ 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} */ 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)}; }, /** * 返回视图的高度和宽度。 * @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; }, // 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; }, /** * 设置元素的宽度 * @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) * @param {String} eventName 加入事件的类型 * @param {Function} fn 事件涉及的方法 * @param {Object} scope (可选的)函数之作用域 (这个对象) * @param {Object} options (可选的)标准EventManager配置项之对象 */ addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); }, /** * 从这个元素上移除一个事件处理器(event handler) * @param {String} eventName 要移除事件的类型 * @param {Function} fn 事件涉及的方法 * @return {Ext.Element} this * @method */ 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; }, 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位置代替页面坐标 * @return {Number} */ 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; }, // 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"); } } }, /** * 快速设置left和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]; } //加入元素的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); var d = this.dom; if(!el.dom){ throw "Element.alignTo with an element that doesn't exist"; } var c = false; //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; }, /** * 对齐元素到另外一个元素的指定的标记。如果这个元素是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. * 下列可支持的锚点位置: <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> 使用范例: <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 {String/HTMLElement/Ext.Element} element 要对齐的元素 * @param {String} position 要对齐的位置 * @param {Array} offsets (可选的) 偏移位置 [x, y] * @param {Boolean/Object} animate (可选的) true表示为为默认动画,或有一个标准元素动画配置的对象 * @return {Ext.Element} this */ /** * 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> * 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 {String/HTMLElement/Ext.Element} 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 */ 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); // 立即对齐 return this; }, /** * 清除这个元素的透明度设置。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); }, /** * 先对元素进行display:none, 然后临时激活偏移(width、height、x、y)。最后使用endMeasure()。 * @return {Ext.Element} this */ beginMeasure : function(){ var el = this.dom; if(el.offsetWidth || el.offsetHeight){ return this; // 偏移正常 } var changed = []; var p = this.dom, b = document.body; //由这个元素开始 while((!el.offsetWidth && !el.offsetHeight) && p && p.tagName && p != b){ var pe = Ext.get(p); if(pe.getStyle('display') == 'none'){ changed.push({el: p, visibility: pe.getStyle("visibility")}); p.style.visibility = "hidden"; p.style.display = "block"; } p = p.parentNode; } this._measureChanged = changed; return this; }, /** * 在调用beginMeasure()之后恢复显示 * @return {Ext.Element} this */ endMeasure : function(){ var changed = this._measureChanged; if(changed){ for(var i = 0, len = changed.length; i < len; i++) { var r = changed[i]; r.el.style.visibility = r.visibility; r.el.style.display = "none"; } this._measureChanged = null; } return 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){ eval(match[2]); } } var el = document.getElementById(id); if(el){el.parentNode.removeChild(el);} if(typeof callback == "function"){ callback(); } }); dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, ""); return this; }, /** * 直接访问UpdateManager 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.getUpdateManager(); um.update.apply(um, arguments); return this; }, /** * 获取这个元素的UpdateManager * @return {Ext.UpdateManager} The UpdateManager */ getUpdateManager : function(){ if(!this.updateManager){ this.updateManager = new Ext.UpdateManager(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} x, y值为 [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 (可选的) If 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); } }, // 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; } } } 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){ if(renderTo){ renderTo = Ext.getDom(renderTo); }else{ renderTo = document.body; } config = typeof config == "object" ? config : {tag : "div", cls: config}; var proxy = Ext.DomHelper.append(renderTo, 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._mask){ this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true); } this.addClass("x-masked"); this._mask.setDisplayed(true); if(typeof msg == 'string'){ if(!this._maskMsg){ 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.setHeight(this.getHeight()); } return this._mask; }, /** * 移除之前的蒙板。 * 如果removeEl是true,则蒙板会被摧毁,否则放在缓存cache中。 */ unmask : function(removeEl){ if(this._mask){ if(removeEl === true){ this._mask.remove(); delete this._mask; if(this._maskMsg){ this._maskMsg.remove(); delete this._maskMsg; } }else{ this._mask.setDisplayed(false); if(this._maskMsg){ this._maskMsg.setDisplayed(false); } } } 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(){ if(this.dom.parentNode){ this.dom.parentNode.removeChild(this.dom); } delete El.cache[this.dom.id]; }, /** * 设置event handlers来添加和移除css类,当鼠标在该元素之上。 * @param {String} className * @param {Boolean} preventFlicker (可选的) 如果设置为true,则表示不会因mouseout事件引起在子元素上的轻移(Flicker) * @return {Ext.Element} this */ addClassOnOver : function(className, preventFlicker){ this.on("mouseover", function(){ Ext.fly(this, '_internal').addClass(className); }, this.dom); var removeFn = function(e){ if(preventFlicker !== true || !e.within(this, true)){ Ext.fly(this, '_internal').removeClass(className); } }; this.on("mouseout", removeFn, this.dom); return this; }, /** * 设置event handlers来添加和移除css类,当该元素得到焦点(focus)。 * @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.get(document); 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; }, /** * @private */ fitToParentDelegate : Ext.emptyFn, // 保留一个fitToParent委托的引用 /** * 调整该元素的大小,以适合父元素尺寸。需执行 box adjustments * @param {Boolean} monitorResize (可选的) :随着window改变大小而调整 * @param {String/HTMLElment/Element} targetParent (可选的) 目标元素,默认是父节点。 * @return {Ext.Element} this */ fitToParent : function(monitorResize, targetParent) { Ext.EventManager.removeResizeListener(this.fitToParentDelegate); // 总是移除之前的fitToParent 来自onWindowResize的委托 this.fitToParentDelegate = Ext.emptyFn; // 移除委托的引用 if (monitorResize === true && !this.dom.parentNode) { // 检查该元素是否存在 return; } var p = Ext.get(targetParent || this.dom.parentNode); this.setSize(p.getComputedWidth() - p.getFrameWidth('lr'), p.getComputedHeight() - p.getFrameWidth('tb')); if (monitorResize === true) { this.fitToParentDelegate = this.fitToParent.createDelegate(this, [true, targetParent]); Ext.EventManager.onWindowResize(this.fitToParentDelegate); } return this; }, /** * 获取下一个兄弟节点,跳过文本节点。 * @return {HTMLElement} 下一个兄弟节点或是null */ getNextSibling : function(){ var n = this.dom.nextSibling; while(n && n.nodeType != 1){ n = n.nextSibling; } return n; }, /** * 获取前一个兄弟节点,跳过文本节点。 * @return {HTMLElement} 前一个兄弟节点或是null */ getPrevSibling : function(){ var n = this.dom.previousSibling; while(n && n.nodeType != 1){ n = n.previousSibling; } return n; }, /** * 传入一个或多个元素,加入到该元素 * @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节点代替创建一个元素 * @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){ where = where ? where.toLowerCase() : 'before'; el = el || {}; var rt, 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), where == 'before' ? this.dom : this.dom.nextSibling); 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 {String/HTMLElement/Element} el 要替换的元素 * @return {Ext.Element} this */ replace: function(el){ el = Ext.get(el); this.insertBefore(el); el.remove(); 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(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 = window.pageXOffset || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0; var t = window.pageYOffset || doc.documentElement.scrollTop || 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]).toString(16); if(h < 16){ h = "0" + h; } color += h; } } 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块,渲染成为斜纹背景、圆角和四边投影的灰色容器。 * @param {String} class (optional) 一个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]; } }; var ep = El.prototype; /** *加入一个event handler(addListener的简写方式) * @param {String} eventName 加入事件的类型 * @param {Function} fn 事件涉及的方法 * @param {Object} scope (可选的)函数之作用域 (这个对象) * @param {Object} options (可选的)标准EventManager配置项之对象 * @method */ ep.on = ep.addListener; // 向后兼容 ep.mon = ep.addListener; /** * 从这个元素上移除一个event handler(removeListener的简写方式) * @param {String} eventName 要移除事件的类型 * @param {Function} fn 事件涉及的方法 * @return {Ext.Element} this * @method */ 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; }; // 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)的常量 - 使用Visibility来隐藏元素 * @static * @type Number */ El.VISIBILITY = 1; /** * 显示模式(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; /** * 获取元素对象的静态方法。 * 如果是相同的对象的话,只是从缓存中提取。 * Automatically fixes if an object was recreated with the same id via AJAX or DOM. * @param {String/HTMLElement/Element} 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; }; 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]]; } } }; // 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); // dom是可选的 El.Flyweight = function(dom){ this.dom = dom; }; El.Flyweight.prototype = El.prototype; El._flyweights = {}; /** * 获取共享元的元素,传入的节点会成为活动元素。 * 不保存该元素的引用(reference)-可由其它代码重写dom节点。 * @param {String/HTMLElement} el Dom节点或id * @param {String} named (可选的) 为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。 * @static * @return {Element} The shared Element object */ 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} 元素对象 * @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} 共享用的元素对象 * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.state.Provider * 为State Provider的实现提供一个抽象基类。 * 该类对某些类型的变量提供了编码、解码方法,包括日期和定义Provider的接口。 */ Ext.state.Provider = function(){ /** * @event statechange * 当state发生改变时触发 * @param {Provider} this 该state提供者 * @param {String} key 已改名的那个键 * @param {String} value 已编码的state值 */ this.addEvents({ "statechange": true }); 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; 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"){ flat += key + "=" + this.encodeValue(v[key]) + "^"; } } enc = "o:" + flat.substring(0, flat.length-1); }else{ enc = "s:" + v; } return escape(enc); } }); /** * @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; } }; }(); /** * @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> * @cfg {String} path 激活cookie之路径(默认是根目录”/“,对该网站下所有的页面激活) * @cfg {Date} expires 过期的日子(默认七人之后) * @cfg {String} domain cookie保存的域名。 注意你在某个页面一旦设置好,将不能够再指定其它的域名,但可以是子域名, * 或者就是它本身如”extjs.com“,这样可以在不同子域名下访问cookies。 * 默认为null使用相同的域名(包括www如www.extjs.com) * @cfg {Boolean} secure True表示为网站使用SSL加密(默认false) * @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天 this.domain = null; this.secure = false; Ext.apply(this, config); this.state = this.readCookies(); }; 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.0 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 typeof value != "undefined" ? value : ""; }, /** * 转义(&, <, >, 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 ')字符还原 * @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'); } return "$" + whole + sub ; }, /** * 将某个值解析成为一个特定格式的日期。 * @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, ""); } }; }();
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 传入句柄(handlers)的参数 * @return {Boolean} 如果有句柄返回false而返回false,否则返回true */ fireEvent : function(){ var ce = this.events[arguments[0].toLowerCase()]; if(typeof ce == "object"){ return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1)); }else{ return true; } }, // private filterOptRe : /^(?:scope|delay|buffer|single)$/, /** * 为该组件加入事件句柄(event handler) * @param {String} eventName 侦听事件的类型 * @param {Function} handler 句柄,事件执行的方法 * @param {Object} scope (可选的) 句柄函数执行时所在的作用域。句柄函数“this”的上下文。 * @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会有下列的属性:<ul> * <li>scope {Object} 句柄函数执行时所在的作用域。句柄函数“this”的上下文。</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> * <b>不同配搭方式的选项</b><br> * 利用参数选项,可以组合成不同类型的侦听器:<br> * <br> * 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId) * 的一次性侦听器 <pre><code> el.on('click', this.onClick, this, { single: true, delay: 100, forumId: 4 }); </code></pre> * <p> * <b>一次调用加入上多个句柄(handlers)</b><br> * 这个方法可接收一个参数,该参数是包含了多个句柄的配置的对象。 * <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> * 或者是以简写的方式书写,前提是只允许同一个的作用域对象传入到所有的句柄中: <pre><code> el.on({ 'click': this.onClick, 'mouseover': this.onMouseOver, 'mouseout': this.onMouseOut, scope: this }); </code></pre> */ 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 (optional) 句柄之作用域 */ 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 = {}; } 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; } }; /** * 为该元素添加事件句柄(event handler),addListener的简写方式 * @param {String} eventName 侦听事件的类型 * @param {Object} scope (可选的) 执行句柄的作用域 * @param {Function} handler 事件涉及的方法 * @param {Object} options (可选的) * @method */ Ext.util.Observable.prototype.on = Ext.util.Observable.prototype.addListener; /** * 移除侦听器 * @param {String} eventName 侦听事件的类型 * @param {Function} handler 事件涉及的方法 * @param {Object} scope (可选的)句柄的作用域 * @method */ Ext.util.Observable.prototype.un = Ext.util.Observable.prototype.removeListener; /**. * 开始捕捉特定的观察者。 * 在事件触发<b>之前</b>,所有的事件会以"事件名称+标准签名"的形式传入到函数(传入的参数是function类型)。 * 如果传入的函数执行后返回false,则接下的事件将不会触发。 * @param {Observable} o 要捕捉的观察者 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的)函数作用域 * @static */ 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){ var o = options || {}; scope = scope || this.obj; if(!this.isListening(fn, scope)){ 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; if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop this.listeners.push(l); }else{ this.listeners = this.listeners.slice(0); this.listeners.push(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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 {String/HTMLElement/Ext.Element} 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) 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, 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 {String/HTMLElement/Ext.Element} 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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.util.MixedCollection * 一个负责维护数字下标(numeric indexes)和键值(key)的集合类,并暴露了一些事件。 * @constructor * @param {Boolean} allowFunctions True表示为允许加入函数指向到集合(默认为false) * @param {Function} keyFn 对于一个在该Mixed集合中已保存类型的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" : true, /** * @event add * 当item被加入到集合之后触发。 * @param {Number} index 加入item的索引 * @param {Object} o 加入的item * @param {String} key 加入item的键名称 */ "add" : true, /** * @event replace * 集合中的item被替换后触发。 * @param {String} key 新加入item的键名称 * @param {Object} old 被替换之item * @param {Object} new 新item. */ "replace" : true, /** * @event remove * 当item被移除集合时触发。 * @param {Object} o 被移除的item * @param {String} key (可选的)被移除的item的键名称 */ "remove" : true, "sort" : true }); 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。 <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); // 等等... </code> * @param o {Object} 根据item找到key * @return {Object} 传入item的key */ getKey : function(o){ return o.id; }, /** * 替换集合中的item。 * @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); } }, /** * 根据function产生匹配规则,在集合中找到第一个匹配的item * 返回在集合中第一个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 * @param {Number} index 移除item的索引 */ 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); } }, /** * 根据传入参数key,从集合中移除相关的item * @param {String} key 要移除item的key */ 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的索引 */ indexOf : function(o){ if(!this.items.indexOf){ for(var i = 0, len = this.items.length; i < len; i++){ if(this.items[i] == o) return i; } return -1; }else{ return this.items.indexOf(o); } }, /** * 传入一个Key,返回它的索引。 * @param {String} key 寻找索引的key * @return {Number} key的索引 */ indexOfKey : function(key){ if(!this.keys.indexOf){ for(var i = 0, len = this.keys.length; i < len; i++){ if(this.keys[i] == key) return i; } return -1; }else{ return this.keys.indexOf(key); } }, /** * 根据key或索引(index)返回item。key的优先权高于索引。 * @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} */ 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 查找的item * @return {Boolean} True:在集合中找到该item */ contains : function(o){ return this.indexOf(o) != -1; }, /** * 若在集合中找到传入的key,则返回true。 * @param {Object} o 查找的key * @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]; }, _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); }, /** * 按传入的function排列集合 * @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){ return String(a).toUpperCase()-String(b).toUpperCase(); }); }, /** * 返回这个集合中的某个范围内的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 也可以是属性开始的值或对于这个属性的正则表达式 * @return {MixedCollection} 过滤后的新对象 */ filter : function(property, value){ if(!value.exec){ // not a regex value = String(value); if(value.length == 0){ return this.clone(); } value = new RegExp("^" + Ext.escapeRe(value), "i"); } return this.filterBy(function(o){ return o && value.test(o[property]); }); }, /** * 由function过滤集合中的<i>对象</i>。 * 返回以过滤后的新集合 * 传入的函数会被集合中每个对象执行。如果函数返回true,则value会被包含否则会被过滤、 * @param {Function} fn 被调用的function,会接收o(object)和k (the key)参数 * @param {Object} scope (optional) function的作用域 (默认为 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; }, /** * 创建集合副本 * @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的优先权高于索引。 * @param {String/Number} key 或者是item的索引 * @return {Object} 传入key所关联的item */ Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ 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', 'with(values){ return '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(m4){ exp = m4 && m4[1] ? m4[1] : null; if(exp){ exec = new Function('values', 'parent', '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, { re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, applySubTemplate : function(id, values, parent){ var t = this.tpls[id]; if(t.test && !t.test.call(this, values, parent)){ return ''; } if(t.exec && t.exec.call(this, values, parent)){ 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); } return buf.join(''); } return t.compiled.call(this, vs, parent); }, compileTpl : function(tpl){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args){ if(name.substr(0, 4) == 'xtpl'){ return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'"; } var v; if(name.indexOf('.') != -1){ v = name; }else{ v = "values['" + name + "']"; } 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 body; // branched to use + in gecko and [].join() in others if(Ext.isGecko){ body = "tpl.compiled = function(values, parent){ return '" + tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) + "';};"; }else{ body = ["tpl.compiled = function(values, parent){ return ['"]; body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, applyTemplate : function(values){ return this.master.compiled.call(this, values, {}); var s = this.subs; }, apply : function(){ return this.applyTemplate.apply(this, arguments); }, compile : function(){return this;} }); Ext.XTemplate.from = function(el){ el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML); };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.MasterTemplate * @extends Ext.Template * 用于包含多个子模板的父级模板.其语法是: <pre><code> var t = new Ext.MasterTemplate( '&lt;select name="{name}"&gt;', '&lt;tpl name="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;', '&lt;/select&gt;' ); t.add('options', {value: 'foo', text: 'bar'}); // 或者是一次过加入多个元素 t.addAll('options', [ {value: 'foo', text: 'bar'}, {value: 'foo2', text: 'bar2'}, {value: 'foo3', text: 'bar3'} ]); // 然后根据相应的标签名称(name)应用模板 t.append('my-form', {name: 'my-select'}); </code></pre> * 如果只有一个子模板的情况,可不指子模板的name属性,又或你是想用索引指向它。 */ Ext.MasterTemplate = function(){ Ext.MasterTemplate.superclass.constructor.apply(this, arguments); this.originalHtml = this.html; var st = {}; var m, re = this.subTemplateRe; re.lastIndex = 0; var subIndex = 0; while(m = re.exec(this.html)){ var name = m[1], content = m[2]; st[subIndex] = { name: name, index: subIndex, buffer: [], tpl : new Ext.Template(content) }; if(name){ st[name] = st[subIndex]; } st[subIndex].tpl.compile(); st[subIndex].tpl.call = this.call.createDelegate(this); subIndex++; } this.subCount = subIndex; this.subs = st; }; Ext.extend(Ext.MasterTemplate, Ext.Template, { /** * 匹配子模板的正则表达式 * @type RegExp * @property */ subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi, /** * 对子模板填充数据 * @param {String/Number} name (可选的)子模板的名称或索引 * @param {Array/Object} values 要被填充的值 * @return {MasterTemplate} this */ add : function(name, values){ if(arguments.length == 1){ values = arguments[0]; name = 0; } var s = this.subs[name]; s.buffer[s.buffer.length] = s.tpl.apply(values); return this; }, /** * 填充所有的数据到子模板 * @param {String/Number} name (可选的)子模板的名称或索引 * @param {Array} values 要被填充的值,这应该是由多个对象组成的数组 * @param {Boolean} reset (可选的)Ture表示为先对模板复位. * @return {MasterTemplate} this */ fill : function(name, values, reset){ var a = arguments; if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){ values = a[0]; name = 0; reset = a[1]; } if(reset){ this.reset(); } for(var i = 0, len = values.length; i < len; i++){ this.add(name, values[i]); } return this; }, /** * 重置模板以备复用 * @return {MasterTemplate} this */ reset : function(){ var s = this.subs; for(var i = 0; i < this.subCount; i++){ s[i].buffer = []; } return this; }, applyTemplate : function(values){ var s = this.subs; var replaceIndex = -1; this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){ return s[++replaceIndex].buffer.join(""); }); return Ext.MasterTemplate.superclass.applyTemplate.call(this, values); }, apply : function(){ return this.applyTemplate.apply(this, arguments); }, compile : function(){return this;} }); /** * Alias for fill(). * @method */ Ext.MasterTemplate.prototype.addAll = Ext.MasterTemplate.prototype.fill; /** * 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML. * var tpl = Ext.MasterTemplate.from('element-id'); * @param {String/HTMLElement} el * @param {Object} config * @static */ Ext.MasterTemplate.from = function(el, config){ el = Ext.getDom(el); return new Ext.MasterTemplate(el.value || el.innerHTML, config || ''); };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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) + "' + "; } }; /** * 将输入的字串按照指定的格式转换为日期对象。 * Note that this function expects dates in normal calendar * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. * Any part of the date format that is not specified will default to the current date value for that part. * Time parts can also be specified, but default to 0. * Keep in mind that the input date string must precisely match the specified format * string or the parse operation will fail. * * 请注意此函数接受的是普通的日历格式,这意味着月份由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; };
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ Ext.util.TaskRunner = function(interval){ interval = interval || 10; var tasks = [], removeQueue = []; var id = 0; var running = false; var stopThread = function(){ running = false; clearInterval(id); id = 0; }; var startThread = function(){ if(!running){ running = true; id = setInterval(runTasks, interval); } }; var removeTask = function(task){ removeQueue.push(task); if(task.onStop){ task.onStop(); } }; 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); } } }; /** * 对一个新任务排列。 * @param {Object} task */ this.start = function(task){ tasks.push(task); task.taskStartTime = new Date().getTime(); task.taskRunTime = 0; task.taskRunCount = 0; startThread(); return task; }; this.stop = function(task){ removeTask(task); return task; }; this.stopAll = function(){ stopThread(); for(var i = 0, len = tasks.length; i < len; i++){ if(tasks[i].onStop){ tasks[i].onStop(); } } tasks = []; removeQueue = []; }; }; Ext.TaskMgr = new Ext.util.TaskRunner();
JavaScript
/* * 更新地址:http://jstang.5d6d.com/thread-715-1-1.html * 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》: * http://jstang.5d6d.com/thread-90-1-2.html * * 本翻译采用“创作共同约定、Creative Commons”。您可以自由: * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品 * 创作演绎作品 * 请遵守: * 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。 * # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。 * # 如果得到著作权人的许可,您可以不受任何这些条件的限制 * http://creativecommons.org/licenses/by/2.5/cn/ */ /* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** @class Ext.util.ClickRepeater @extends Ext.util.Observable 适用于任何元素的包装类。当鼠标按下时触发一个“单击”的事件。 可在配置项中设置间隔时间但默认是10毫秒。 可选地,按下的过程中可能会加入一个CSS类。 @cfg {String/HTMLElement/Element} el 该元素作为一个按钮。 @cfg {Number} delay 开始触发事件重复之前的初始延迟,类似自动重复键延时。 @cfg {Number} interval “fire”事件之间的间隔时间。默认10ms。 @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 * 当鼠标键按下的时候触发。 * @param {Ext.util.ClickRepeater} this */ "mousedown" : true, /** * @event click * 元素被按下的过程中,指定间隔的时间触发。 * @param {Ext.util.ClickRepeater} this */ "click" : true, /** * @event mouseup * 当鼠标键释放的时候触发。 * @param {Ext.util.ClickRepeater} this */ "mouseup" : true }); 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.get(document).on("mouseup", this.handleMouseUp, this); this.el.on("mouseout", this.handleMouseOut, this); this.fireEvent("mousedown", this); this.fireEvent("click", this); this.timer = this.click.defer(this.delay || this.interval, this); }, // private click : function(){ this.fireEvent("click", this); this.timer = this.click.defer(this.getInterval(), this); }, // private getInterval: function(){ if(!this.accelerate){ return this.interval; } var pressTime = this.mousedownTime.getElapsed(); if(pressTime < 500){ return 400; }else if(pressTime < 1700){ return 320; }else if(pressTime < 2600){ return 250; }else if(pressTime < 3500){ return 180; }else if(pressTime < 4400){ return 140; }else if(pressTime < 5300){ return 80; }else if(pressTime < 6200){ return 50; }else{ return 10; } }, // 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.get(document).un("mouseup", this.handleMouseUp); this.el.removeClass(this.pressClass); this.fireEvent("mouseup", this); } });
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.state.Provider * 为State Provider的实现提供一个抽象基类。 * 该类对某些类型的变量提供了编码、解码方法,包括日期和定义Provider的接口。 */ Ext.state.Provider = function(){ /** * @event statechange * 当state发生改变时触发 * @param {Provider} this 该state提供者 * @param {String} key 已改名的那个键 * @param {String} value 已编码的state值 */ this.addEvents({ "statechange": true }); 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; 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"){ flat += key + "=" + this.encodeValue(v[key]) + "^"; } } enc = "o:" + flat.substring(0, flat.length-1); }else{ enc = "s:" + v; } return escape(enc); } }); /** * @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; } }; }(); /** * @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> * @cfg {String} path 激活cookie之路径(默认是根目录”/“,对该网站下所有的页面激活) * @cfg {Date} expires 过期的日子(默认七人之后) * @cfg {String} domain cookie保存的域名。 注意你在某个页面一旦设置好,将不能够再指定其它的域名,但可以是子域名, * 或者就是它本身如”extjs.com“,这样可以在不同子域名下访问cookies。 * 默认为null使用相同的域名(包括www如www.extjs.com) * @cfg {Boolean} secure True表示为网站使用SSL加密(默认false) * @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天 this.domain = null; this.secure = false; Ext.apply(this, config); this.state = this.readCookies(); }; 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
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * Ext JS Library 1.0 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 typeof value != "undefined" ? value : ""; }, /** * 转义(&, <, >, 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 ')字符还原 * @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'); } return "$" + whole + sub ; }, /** * 将某个值解析成为一个特定格式的日期。 * @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, ""); } }; }();
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 传入句柄(handlers)的参数 * @return {Boolean} 如果有句柄返回false而返回false,否则返回true */ fireEvent : function(){ var ce = this.events[arguments[0].toLowerCase()]; if(typeof ce == "object"){ return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1)); }else{ return true; } }, // private filterOptRe : /^(?:scope|delay|buffer|single)$/, /** * 为该组件加入事件句柄(event handler) * @param {String} eventName 侦听事件的类型 * @param {Function} handler 句柄,事件执行的方法 * @param {Object} scope (可选的) 句柄函数执行时所在的作用域。句柄函数“this”的上下文。 * @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会有下列的属性:<ul> * <li>scope {Object} 句柄函数执行时所在的作用域。句柄函数“this”的上下文。</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> * <b>不同配搭方式的选项</b><br> * 利用参数选项,可以组合成不同类型的侦听器:<br> * <br> * 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId) * 的一次性侦听器 <pre><code> el.on('click', this.onClick, this, { single: true, delay: 100, forumId: 4 }); </code></pre> * <p> * <b>一次调用加入上多个句柄(handlers)</b><br> * 这个方法可接收一个参数,该参数是包含了多个句柄的配置的对象。 * <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> * 或者是以简写的方式书写,前提是只允许同一个的作用域对象传入到所有的句柄中: <pre><code> el.on({ 'click': this.onClick, 'mouseover': this.onMouseOver, 'mouseout': this.onMouseOut, scope: this }); </code></pre> */ 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 (optional) 句柄之作用域 */ 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 = {}; } 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; } }; /** * 为该元素添加事件句柄(event handler),addListener的简写方式 * @param {String} eventName 侦听事件的类型 * @param {Object} scope (可选的) 执行句柄的作用域 * @param {Function} handler 事件涉及的方法 * @param {Object} options (可选的) * @method */ Ext.util.Observable.prototype.on = Ext.util.Observable.prototype.addListener; /** * 移除侦听器 * @param {String} eventName 侦听事件的类型 * @param {Function} handler 事件涉及的方法 * @param {Object} scope (可选的)句柄的作用域 * @method */ Ext.util.Observable.prototype.un = Ext.util.Observable.prototype.removeListener; /**. * 开始捕捉特定的观察者。 * 在事件触发<b>之前</b>,所有的事件会以"事件名称+标准签名"的形式传入到函数(传入的参数是function类型)。 * 如果传入的函数执行后返回false,则接下的事件将不会触发。 * @param {Observable} o 要捕捉的观察者 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的)函数作用域 * @static */ 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){ var o = options || {}; scope = scope || this.obj; if(!this.isListening(fn, scope)){ 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; if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop this.listeners.push(l); }else{ this.listeners = this.listeners.slice(0); this.listeners.push(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
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 {String/HTMLElement/Ext.Element} 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) 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, 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
/* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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 {String/HTMLElement/Ext.Element} 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
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.util.MixedCollection * 一个负责维护数字下标(numeric indexes)和键值(key)的集合类,并暴露了一些事件。 * @constructor * @param {Boolean} allowFunctions True表示为允许加入函数指向到集合(默认为false) * @param {Function} keyFn 对于一个在该Mixed集合中已保存类型的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" : true, /** * @event add * 当item被加入到集合之后触发。 * @param {Number} index 加入item的索引 * @param {Object} o 加入的item * @param {String} key 加入item的键名称 */ "add" : true, /** * @event replace * 集合中的item被替换后触发。 * @param {String} key 新加入item的键名称 * @param {Object} old 被替换之item * @param {Object} new 新item. */ "replace" : true, /** * @event remove * 当item被移除集合时触发。 * @param {Object} o 被移除的item * @param {String} key (可选的)被移除的item的键名称 */ "remove" : true, "sort" : true }); 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。 <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); // 等等... </code> * @param o {Object} 根据item找到key * @return {Object} 传入item的key */ getKey : function(o){ return o.id; }, /** * 替换集合中的item。 * @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); } }, /** * 根据function产生匹配规则,在集合中找到第一个匹配的item * 返回在集合中第一个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 * @param {Number} index 移除item的索引 */ 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); } }, /** * 根据传入参数key,从集合中移除相关的item * @param {String} key 要移除item的key */ 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的索引 */ indexOf : function(o){ if(!this.items.indexOf){ for(var i = 0, len = this.items.length; i < len; i++){ if(this.items[i] == o) return i; } return -1; }else{ return this.items.indexOf(o); } }, /** * 传入一个Key,返回它的索引。 * @param {String} key 寻找索引的key * @return {Number} key的索引 */ indexOfKey : function(key){ if(!this.keys.indexOf){ for(var i = 0, len = this.keys.length; i < len; i++){ if(this.keys[i] == key) return i; } return -1; }else{ return this.keys.indexOf(key); } }, /** * 根据key或索引(index)返回item。key的优先权高于索引。 * @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} */ 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 查找的item * @return {Boolean} True:在集合中找到该item */ contains : function(o){ return this.indexOf(o) != -1; }, /** * 若在集合中找到传入的key,则返回true。 * @param {Object} o 查找的key * @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]; }, _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); }, /** * 按传入的function排列集合 * @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){ return String(a).toUpperCase()-String(b).toUpperCase(); }); }, /** * 返回这个集合中的某个范围内的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 也可以是属性开始的值或对于这个属性的正则表达式 * @return {MixedCollection} 过滤后的新对象 */ filter : function(property, value){ if(!value.exec){ // not a regex value = String(value); if(value.length == 0){ return this.clone(); } value = new RegExp("^" + Ext.escapeRe(value), "i"); } return this.filterBy(function(o){ return o && value.test(o[property]); }); }, /** * 由function过滤集合中的<i>对象</i>。 * 返回以过滤后的新集合 * 传入的函数会被集合中每个对象执行。如果函数返回true,则value会被包含否则会被过滤、 * @param {Function} fn 被调用的function,会接收o(object)和k (the key)参数 * @param {Object} scope (optional) function的作用域 (默认为 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; }, /** * 创建集合副本 * @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的优先权高于索引。 * @param {String/Number} key 或者是item的索引 * @return {Object} 传入key所关联的item */ Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ 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', 'with(values){ return '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(m4){ exp = m4 && m4[1] ? m4[1] : null; if(exp){ exec = new Function('values', 'parent', '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, { re : /\{([\w-\.]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, applySubTemplate : function(id, values, parent){ var t = this.tpls[id]; if(t.test && !t.test.call(this, values, parent)){ return ''; } if(t.exec && t.exec.call(this, values, parent)){ 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); } return buf.join(''); } return t.compiled.call(this, vs, parent); }, compileTpl : function(tpl){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args){ if(name.substr(0, 4) == 'xtpl'){ return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent)'+sep+"'"; } var v; if(name.indexOf('.') != -1){ v = name; }else{ v = "values['" + name + "']"; } 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 body; // branched to use + in gecko and [].join() in others if(Ext.isGecko){ body = "tpl.compiled = function(values, parent){ return '" + tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) + "';};"; }else{ body = ["tpl.compiled = function(values, parent){ return ['"]; body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, applyTemplate : function(values){ return this.master.compiled.call(this, values, {}); var s = this.subs; }, apply : function(){ return this.applyTemplate.apply(this, arguments); }, compile : function(){return this;} }); Ext.XTemplate.from = function(el){ el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML); };
JavaScript
/* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.MasterTemplate * @extends Ext.Template * 用于包含多个子模板的父级模板.其语法是: <pre><code> var t = new Ext.MasterTemplate( '&lt;select name="{name}"&gt;', '&lt;tpl name="options"&gt;&lt;option value="{value:trim}"&gt;{text:ellipsis(10)}&lt;/option&gt;&lt;/tpl&gt;', '&lt;/select&gt;' ); t.add('options', {value: 'foo', text: 'bar'}); // 或者是一次过加入多个元素 t.addAll('options', [ {value: 'foo', text: 'bar'}, {value: 'foo2', text: 'bar2'}, {value: 'foo3', text: 'bar3'} ]); // 然后根据相应的标签名称(name)应用模板 t.append('my-form', {name: 'my-select'}); </code></pre> * 如果只有一个子模板的情况,可不指子模板的name属性,又或你是想用索引指向它。 */ Ext.MasterTemplate = function(){ Ext.MasterTemplate.superclass.constructor.apply(this, arguments); this.originalHtml = this.html; var st = {}; var m, re = this.subTemplateRe; re.lastIndex = 0; var subIndex = 0; while(m = re.exec(this.html)){ var name = m[1], content = m[2]; st[subIndex] = { name: name, index: subIndex, buffer: [], tpl : new Ext.Template(content) }; if(name){ st[name] = st[subIndex]; } st[subIndex].tpl.compile(); st[subIndex].tpl.call = this.call.createDelegate(this); subIndex++; } this.subCount = subIndex; this.subs = st; }; Ext.extend(Ext.MasterTemplate, Ext.Template, { /** * 匹配子模板的正则表达式 * @type RegExp * @property */ subTemplateRe : /<tpl(?:\sname="([\w-]+)")?>((?:.|\n)*?)<\/tpl>/gi, /** * 对子模板填充数据 * @param {String/Number} name (可选的)子模板的名称或索引 * @param {Array/Object} values 要被填充的值 * @return {MasterTemplate} this */ add : function(name, values){ if(arguments.length == 1){ values = arguments[0]; name = 0; } var s = this.subs[name]; s.buffer[s.buffer.length] = s.tpl.apply(values); return this; }, /** * 填充所有的数据到子模板 * @param {String/Number} name (可选的)子模板的名称或索引 * @param {Array} values 要被填充的值,这应该是由多个对象组成的数组 * @param {Boolean} reset (可选的)Ture表示为先对模板复位. * @return {MasterTemplate} this */ fill : function(name, values, reset){ var a = arguments; if(a.length == 1 || (a.length == 2 && typeof a[1] == "boolean")){ values = a[0]; name = 0; reset = a[1]; } if(reset){ this.reset(); } for(var i = 0, len = values.length; i < len; i++){ this.add(name, values[i]); } return this; }, /** * 重置模板以备复用 * @return {MasterTemplate} this */ reset : function(){ var s = this.subs; for(var i = 0; i < this.subCount; i++){ s[i].buffer = []; } return this; }, applyTemplate : function(values){ var s = this.subs; var replaceIndex = -1; this.html = this.originalHtml.replace(this.subTemplateRe, function(m, name){ return s[++replaceIndex].buffer.join(""); }); return Ext.MasterTemplate.superclass.applyTemplate.call(this, values); }, apply : function(){ return this.applyTemplate.apply(this, arguments); }, compile : function(){return this;} }); /** * Alias for fill(). * @method */ Ext.MasterTemplate.prototype.addAll = Ext.MasterTemplate.prototype.fill; /** * 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML. * var tpl = Ext.MasterTemplate.from('element-id'); * @param {String/HTMLElement} el * @param {Object} config * @static */ Ext.MasterTemplate.from = function(el, config){ el = Ext.getDom(el); return new Ext.MasterTemplate(el.value || el.innerHTML, config || ''); };
JavaScript
/* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @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) + "' + "; } }; /** * 将输入的字串按照指定的格式转换为日期对象。 * Note that this function expects dates in normal calendar * format, meaning that months are 1-based (1 = January) and not zero-based like in JavaScript dates. * Any part of the date format that is not specified will default to the current date value for that part. * Time parts can also be specified, but default to 0. * Keep in mind that the input date string must precisely match the specified format * string or the parse operation will fail. * * 请注意此函数接受的是普通的日历格式,这意味着月份由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; };
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ Ext.util.TaskRunner = function(interval){ interval = interval || 10; var tasks = [], removeQueue = []; var id = 0; var running = false; var stopThread = function(){ running = false; clearInterval(id); id = 0; }; var startThread = function(){ if(!running){ running = true; id = setInterval(runTasks, interval); } }; var removeTask = function(task){ removeQueue.push(task); if(task.onStop){ task.onStop(); } }; 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); } } }; /** * 对一个新任务排列。 * @param {Object} task */ this.start = function(task){ tasks.push(task); task.taskStartTime = new Date().getTime(); task.taskRunTime = 0; task.taskRunCount = 0; startThread(); return task; }; this.stop = function(task){ removeTask(task); return task; }; this.stopAll = function(){ stopThread(); for(var i = 0, len = tasks.length; i < len; i++){ if(tasks[i].onStop){ tasks[i].onStop(); } } tasks = []; removeQueue = []; }; }; Ext.TaskMgr = new Ext.util.TaskRunner();
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** @class Ext.util.ClickRepeater @extends Ext.util.Observable 适用于任何元素的包装类。当鼠标按下时触发一个“单击”的事件。 可在配置项中设置间隔时间但默认是10毫秒。 可选地,按下的过程中可能会加入一个CSS类。 @cfg {String/HTMLElement/Element} el 该元素作为一个按钮。 @cfg {Number} delay 开始触发事件重复之前的初始延迟,类似自动重复键延时。 @cfg {Number} interval “fire”事件之间的间隔时间。默认10ms。 @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 * 当鼠标键按下的时候触发。 * @param {Ext.util.ClickRepeater} this */ "mousedown" : true, /** * @event click * 元素被按下的过程中,指定间隔的时间触发。 * @param {Ext.util.ClickRepeater} this */ "click" : true, /** * @event mouseup * 当鼠标键释放的时候触发。 * @param {Ext.util.ClickRepeater} this */ "mouseup" : true }); 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.get(document).on("mouseup", this.handleMouseUp, this); this.el.on("mouseout", this.handleMouseOut, this); this.fireEvent("mousedown", this); this.fireEvent("click", this); this.timer = this.click.defer(this.delay || this.interval, this); }, // private click : function(){ this.fireEvent("click", this); this.timer = this.click.defer(this.getInterval(), this); }, // private getInterval: function(){ if(!this.accelerate){ return this.interval; } var pressTime = this.mousedownTime.getElapsed(); if(pressTime < 500){ return 400; }else if(pressTime < 1700){ return 320; }else if(pressTime < 2600){ return 250; }else if(pressTime < 3500){ return 180; }else if(pressTime < 4400){ return 140; }else if(pressTime < 5300){ return 80; }else if(pressTime < 6200){ return 50; }else{ return 10; } }, // 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.get(document).un("mouseup", this.handleMouseUp); this.el.removeClass(this.pressClass); this.fireEvent("mouseup", this); } });
JavaScript
/** * @class Ext.data.Connection * @extends Ext.util.Observable */ Ext.data.Connection = Ext.extend(Ext.util.Observable, { method: 'post', url: null, /** * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true) * @type Boolean */ disableCaching: true, /** * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching * through a cache buster. Defaults to '_dc' * @type String */ disableCachingParam: '_dc', /** * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000) */ timeout : 30000, useDefaultHeader : true, defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8', useDefaultXhrHeader : true, defaultXhrHeader : 'XMLHttpRequest', constructor : function(config) { config = config || {}; Ext.apply(this, config); this.addEvents( /** * @event beforerequest * Fires before a network request is made to retrieve a data object. * @param {Connection} conn This Connection object. * @param {Object} options The options config object passed to the {@link #request} method. */ 'beforerequest', /** * @event requestcomplete * Fires if the request was successfully completed. * @param {Connection} conn This Connection object. * @param {Object} response The XHR object containing the response data. * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a> * for details. * @param {Object} options The options config object passed to the {@link #request} method. */ 'requestcomplete', /** * @event requestexception * Fires if an error HTTP status was returned from the server. * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a> * for details of HTTP status codes. * @param {Connection} conn This Connection object. * @param {Object} response The XHR object containing the response data. * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a> * for details. * @param {Object} options The options config object passed to the {@link #request} method. */ 'requestexception' ); this.requests = {}; Ext.data.Connection.superclass.constructor.call(this); }, /** * <p>Sends an HTTP request to a remote server.</p> * <p><b>Important:</b> Ajax server requests are asynchronous, and this call will * return before the response has been received. Process any returned data * in a callback function.</p> * <pre><code> Ext.Ajax.request({ url: 'ajax_demo/sample.json', success: function(response, opts) { var obj = Ext.decode(response.responseText); console.dir(obj); }, failure: function(response, opts) { console.log('server-side failure with status code ' + response.status); } }); * </code></pre> * <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p> * @param {Object} options An object which may contain the following properties:<ul> * <li><b>url</b> : String/Function (Optional)<div class="sub-desc">The URL to * which to send the request, or a function to call which returns a URL string. The scope of the * function is specified by the <tt>scope</tt> option. Defaults to the configured * <tt>{@link #url}</tt>.</div></li> * <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc"> * An object containing properties which are used as parameters to the * request, a url encoded string or a function to call to get either. The scope of the function * is specified by the <tt>scope</tt> option.</div></li> * <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use * for the request. Defaults to the configured method, or if no method was configured, * "GET" if no parameters are being sent, and "POST" if parameters are being sent. Note that * the method name is case-sensitive and should be all caps.</div></li> * <li><b>callback</b> : Function (Optional)<div class="sub-desc">The * function to be called upon receipt of the HTTP response. The callback is * called regardless of success or failure and is passed the following * parameters:<ul> * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li> * <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li> * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data. * See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about * accessing elements of the response.</div></li> * </ul></div></li> * <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function * to be called upon success of the request. The callback is passed the following * parameters:<ul> * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li> * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li> * </ul></div></li> * <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function * to be called upon failure of the request. The callback is passed the * following parameters:<ul> * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li> * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li> * </ul></div></li> * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in * which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were * specified as functions from which to draw values, then this also serves as the scope for those function calls. * Defaults to the browser window.</div></li> * <li><b>timeout</b> : Number (Optional)<div class="sub-desc">The timeout in milliseconds to be used for this request. Defaults to 30 seconds.</div></li> * <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt> * Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li> * <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used * with the <tt>form</tt> option</b>. * <p>True if the form object is a file upload (will be set automatically if the form was * configured with <b><tt>enctype</tt></b> "multipart/form-data").</p> * <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 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> 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 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> 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 <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a> * 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> * </div></li> * <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request * headers to set for the request.</div></li> * <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">XML document * to use for the post. Note: This will be used instead of params for the post * data. Any params will be appended to the URL.</div></li> * <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">JSON * data to use as the post. Note: This will be used instead of params for the post * data. Any params will be appended to the URL.</div></li> * <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True * to add a unique cache-buster param to GET requests.</div></li> * </ul></p> * <p>The options object may also contain any other property which might be needed to perform * postprocessing in a callback because it is passed to callback functions.</p> * @return {Object} request The request object. This may be used * to cancel the request. */ request : function(o) { var me = this; if (me.fireEvent('beforerequest', me, o) !== false) { var params = o.params, url = o.url || me.url, urlParams = o.urlParams, extraParams = me.extraParams, request, data, headers, method, key, xhr; // allow params to be a method that returns the params object if (Ext.isFunction(params)) { params = params.call(o.scope || window, o); } // allow url to be a method that returns the actual url if (Ext.isFunction(url)) { url = url.call(o.scope || window, o); } // check for xml or json data, and make sure json data is encoded data = o.rawData || o.xmlData || o.jsonData || null; if (o.jsonData && !Ext.isPrimitive(o.jsonData)) { data = Ext.encode(data); } // make sure params are a url encoded string and include any extraParams if specified params = Ext.urlEncode(extraParams, Ext.isObject(params) ? Ext.urlEncode(params) : params); urlParams = Ext.isObject(urlParams) ? Ext.urlEncode(urlParams) : urlParams; // decide the proper method for this request method = (o.method || ((params || data) ? 'POST' : 'GET')).toUpperCase(); // if the method is get append date to prevent caching if (method === 'GET' && o.disableCaching !== false && me.disableCaching) { url = Ext.urlAppend(url, o.disableCachingParam || me.disableCachingParam + '=' + (new Date().getTime())); } // if the method is get or there is json/xml data append the params to the url if ((method == 'GET' || data) && params){ url = Ext.urlAppend(url, params); params = null; } // allow params to be forced into the url if (urlParams) { url = Ext.urlAppend(url, urlParams); } // if autoabort is set, cancel the current transactions if (o.autoAbort === true || me.autoAbort) { me.abort(); } // create a connection object xhr = this.getXhrInstance(); // open the request xhr.open(method.toUpperCase(), url, true); // create all the headers headers = Ext.apply({}, o.headers || {}, me.defaultHeaders || {}); if (!headers['Content-Type'] && (data || params)) { var contentType = me.defaultPostHeader, jsonData = o.jsonData, xmlData = o.xmlData; if (data) { if (o.rawData) { contentType = 'text/plain'; } else { if (xmlData && Ext.isDefined(xmlData)) { contentType = 'text/xml'; } else if (jsonData && Ext.isDefined(jsonData)) { contentType = 'application/json'; } } } headers['Content-Type'] = contentType; } if (me.useDefaultXhrHeader && !headers['X-Requested-With']) { headers['X-Requested-With'] = me.defaultXhrHeader; } // set up all the request headers on the xhr object for (key in headers) { if (headers.hasOwnProperty(key)) { try { xhr.setRequestHeader(key, headers[key]); } catch(e) { me.fireEvent('exception', key, headers[key]); } } } // create the transaction object request = { id: ++Ext.data.Connection.requestId, xhr: xhr, headers: headers, options: o, timeout: setTimeout(function() { request.timedout = true; me.abort(request); }, o.timeout || me.timeout) }; me.requests[request.id] = request; // bind our statechange listener xhr.onreadystatechange = Ext.createDelegate(me.onStateChange, me, [request]); // start the request! xhr.send(data || params || null); return request; } else { return o.callback ? o.callback.apply(o.scope, [o, undefined, undefined]) : null; } }, getXhrInstance : function() { return new XMLHttpRequest(); }, /** * Determine whether this object has a request outstanding. * @param {Object} request (Optional) defaults to the last transaction * @return {Boolean} True if there is an outstanding request. */ isLoading : function(r) { // if there is a connection and readyState is not 0 or 4 return r && !{0:true, 4:true}[r.xhr.readyState]; }, /** * Aborts any outstanding request. * @param {Object} request (Optional) defaults to the last request */ abort : function(r) { if (r && this.isLoading(r)) { r.xhr.abort(); clearTimeout(r.timeout); delete(r.timeout); r.aborted = true; this.onComplete(r); } else if (!r) { var id; for(id in this.requests) { if (!this.requests.hasOwnProperty(id)) { continue; } this.abort(this.requests[id]); } } }, // private onStateChange : function(r) { if (r.xhr.readyState == 4) { clearTimeout(r.timeout); delete r.timeout; this.onComplete(r); } }, // private onComplete : function(r) { var status = r.xhr.status, options = r.options, success = true, response; if ((status >= 200 && status < 300) || status == 304) { response = this.createResponse(r); this.fireEvent('requestcomplete', this, response, options); if (options.success) { if (!options.scope) { options.success(response, options); } else { options.success.call(options.scope, response, options); } } } else { success = false; switch (status) { case 12002: case 12029: case 12030: case 12031: case 12152: case 13030: response = this.createException(r); break; default: response = this.createResponse(r); } this.fireEvent('requestexception', this, response, options); if (options.failure) { if (!options.scope) { options.failure(response, options); } else { options.failure.call(options.scope, response, options); } } } if (options.callback) { if (!options.scope) { options.callback(options, success, response); } else { options.callback.call(options.scope, options, success, response); } } delete this.requests[r.id]; }, // private createResponse : function(r) { var xhr = r.xhr, headers = {}, lines = xhr.getAllResponseHeaders().replace(/\r\n/g, '\n').split('\n'), count = lines.length, line, index, key, value; while (count--) { line = lines[count]; index = line.indexOf(':'); if(index >= 0) { key = line.substr(0, index).toLowerCase(); if (line.charAt(index + 1) == ' ') { ++index; } headers[key] = line.substr(index + 1); } } delete r.xhr; return { request: r, requestId : r.id, status : xhr.status, statusText : xhr.statusText, getResponseHeader : function(header){ return headers[header.toLowerCase()]; }, getAllResponseHeaders : function(){ return headers; }, responseText : xhr.responseText, responseXML : xhr.responseXML }; }, // private createException : function(r) { return { request : r, requestId : r.id, status : r.aborted ? -1 : 0, statusText : r.aborted ? 'transaction aborted' : 'communication failure', aborted: r.aborted, timedout: r.timedout }; } }); Ext.data.Connection.requestId = 0; /** * @class Ext.Ajax * @extends Ext.data.Connection * A singleton instance of an {@link Ext.data.Connection}. * @singleton */ Ext.Ajax = new Ext.data.Connection({ /** * @cfg {String} url @hide */ /** * @cfg {Object} extraParams @hide */ /** * @cfg {Object} defaultHeaders @hide */ /** * @cfg {String} method (Optional) @hide */ /** * @cfg {Number} timeout (Optional) @hide */ /** * @cfg {Boolean} autoAbort (Optional) @hide */ /** * @cfg {Boolean} disableCaching (Optional) @hide */ /** * @property disableCaching * True to add a unique cache-buster param to GET requests. (defaults to true) * @type Boolean */ /** * @property url * The default URL to be used for requests to the server. (defaults to undefined) * If the server receives all requests through one URL, setting this once is easier than * entering it on every request. * @type String */ /** * @property extraParams * An object containing properties which are used as extra parameters to each request made * by this object (defaults to undefined). Session information and other data that you need * to pass with each request are commonly put here. * @type Object */ /** * @property defaultHeaders * An object containing request headers which are added to each request made by this object * (defaults to undefined). * @type Object */ /** * @property method * The default HTTP method to be used for requests. Note that this is case-sensitive and * should be all caps (defaults to undefined; if not set but params are present will use * <tt>"POST"</tt>, otherwise will use <tt>"GET"</tt>.) * @type String */ /** * @property timeout * The timeout in milliseconds to be used for requests. (defaults to 30000) * @type Number */ /** * @property autoAbort * Whether a new request should abort any pending requests. (defaults to false) * @type Boolean */ autoAbort : false });
JavaScript
/** * @class Ext.IndexBar * @extends Ext.DataPanel * <p>IndexBar is a component used to display a list of data (primarily an {@link #alphabet}) which can then be used to quickly * navigate through a list (see {@link Ext.List}) of data. When a user taps on an item in the {@link Ext.IndexBar}, it will fire * the <tt>{@link #index}</tt> event.</p> * * <p>Here is an example of the usage in a {@link Ext.List}:</p> * <pre><code> Ext.regModel('Contact', { fields: ['firstName', 'lastName'] }); var store = new Ext.data.JsonStore({ model : 'Contact', sorters: 'lastName', getGroupString : function(record) { return record.get('lastName')[0]; }, data: [ {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Rob', lastName: 'Dougan'}, {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Jamie', lastName: 'Avins'}, {firstName: 'Aaron', lastName: 'Conran'}, {firstName: 'Dave', lastName: 'Kaneda'}, {firstName: 'Michael', lastName: 'Mullany'}, {firstName: 'Abraham', lastName: 'Elias'}, {firstName: 'Jay', lastName: 'Robinson'}, {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Rob', lastName: 'Dougan'}, {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Jamie', lastName: 'Avins'}, {firstName: 'Aaron', lastName: 'Conran'}, {firstName: 'Dave', lastName: 'Kaneda'}, {firstName: 'Michael', lastName: 'Mullany'}, {firstName: 'Abraham', lastName: 'Elias'}, {firstName: 'Jay', lastName: 'Robinson'} ] }); var list = new Ext.List({ tpl: '&lt;tpl for="."&gt;&lt;div class="contact"&gt;{firstName} &lt;strong&gt;{lastName}&lt;/strong&gt;&lt;/div&gt;&lt;/tpl&gt;', itemSelector: 'div.contact', singleSelect: true, grouped : true, indexBar : true, store: store, floating : true, width : 350, height : 370, centered : true, modal : true, hideOnMaskTap: false }); list.show(); </code></pre> * * <p>Alternatively you can initate the {@link Ext.IndexBar} component manually in a custom component by using something * similar to the following example:<p> * * <code><pre> var indexBar = new Ext.IndexBar({ dock : 'right', overlay : true, alphabet: true }); * </code></pre> * @constructor * Create a new IndexBar * @param {Object} config The config object * @xtype indexbar */ Ext.IndexBar = Ext.extend(Ext.DataView, { /** * @cfg {String} componentCls Base CSS class * Defaults to <tt>'x-indexbar'</tt> */ componentCls: 'x-indexbar', /** * @cfg {String} direction Layout direction, can be either 'vertical' or 'horizontal' * Defaults to <tt>'vertical'</tt> */ direction: 'vertical', /** * @cfg {String} tpl Template for items */ tpl: '<tpl for="."><div class="x-indexbar-item">{value}</div></tpl>', /** * @cfg {String} itemSelector <b>Required</b>. A simple CSS selector (e.g. <tt>div.x-indexbar-item</tt> for items */ itemSelector: 'div.x-indexbar-item', /** * @cfg {Array} letters * The letters to show on the index bar. Defaults to the English alphabet, A-Z. */ letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], /** * @cfg {String} listPrefix * The prefix string to be appended at the beginning of the list. E.g: useful to add a "#" prefix before numbers */ listPrefix: '', /** * @cfg {Boolean} alphabet true to use the {@link #letters} property to show a list of the alphabet. Should <b>not</b> be used * in conjunction with {@link #store}. */ /** * @cfg {Ext.data.Store} store * The store to be used for displaying data on the index bar. The store model must have a <tt>value</tt> field when using the * default {@link #tpl}. If no {@link #store} is defined, it will create a store using the <tt>IndexBarModel</tt> model. */ // We dont want the body of this component to be sized by a DockLayout, thus we set the layout to be an autocomponent layout. componentLayout: 'autocomponent', scroll: false, // @private initComponent : function() { // No docking and no sizing of body! this.componentLayout = this.getComponentLayout(); if (!this.store) { this.store = new Ext.data.Store({ model: 'IndexBarModel' }); } if (this.alphabet == true) { this.ui = this.ui || 'alphabet'; } if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } this.addEvents( /** * @event index * Fires when an item in the index bar display has been tapped * @param {Ext.data.Model} record The record tapped on the indexbar * @param {HTMLElement} target The node on the indexbar that has been tapped * @param {Number} index The index of the record tapped on the indexbar */ 'index' ); Ext.apply(this.renderData, { componentCls: this.componentCls }); Ext.apply(this.renderSelectors, { body: '.' + this.componentCls + '-body' }); Ext.IndexBar.superclass.initComponent.call(this); }, renderTpl : ['<div class="{componentCls}-body"></div>'], getTargetEl : function() { return this.body; }, // @private afterRender : function() { Ext.IndexBar.superclass.afterRender.call(this); if (this.alphabet === true) { this.loadAlphabet(); } if (this.vertical) { this.el.addCls(this.componentCls + '-vertical'); } else if (this.horizontal) { this.el.addCls(this.componentCls + '-horizontal'); } }, // @private loadAlphabet : function() { var letters = this.letters, len = letters.length, data = [], i, letter; for (i = 0; i < len; i++) { letter = letters[i]; data.push({key: letter.toLowerCase(), value: letter}); } this.store.loadData(data); }, /** * Refreshes the view by reloading the data from the store and re-rendering the template. */ refresh: function() { var el = this.getTargetEl(), records = this.store.getRange(); el.update(''); if (records.length < 1) { if (!this.deferEmptyText || this.hasSkippedEmptyText) { el.update(this.emptyText); } this.all.clear(); } else { this.tpl.overwrite(el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, el.dom)); this.updateIndexes(0); } this.hasSkippedEmptyText = true; this.fireEvent('refresh'); }, collectData : function() { var data = Ext.IndexBar.superclass.collectData.apply(this, arguments); if (this.listPrefix.length > 0) { data.unshift({ key: '', value: this.listPrefix }); } return data; }, // @private initEvents : function() { Ext.IndexBar.superclass.initEvents.call(this); this.mon(this.el, { touchstart: this.onTouchStart, touchend: this.onTouchEnd, touchmove: this.onTouchMove, scope: this }); }, // @private onTouchStart : function(e, t) { e.stopEvent(); this.el.addCls(this.componentCls + '-pressed'); this.pageBox = this.el.getPageBox(); this.onTouchMove(e); }, // @private onTouchEnd : function(e, t) { e.stopEvent(); this.el.removeCls(this.componentCls + '-pressed'); }, // @private onTouchMove : function(e) { e.stopEvent(); // Temporary fix since touchstart does not have these properties passed from the gesture Manager if (!e.hasOwnProperty('pageY')) { if (e.hasOwnProperty('event')) e = e.event; e = (e.touches && e.touches.length > 0) ? e.touches[0] : e; } var target, record, pageBox = this.pageBox; if (!pageBox) { pageBox = this.pageBox = this.el.getPageBox(); } if (this.vertical) { if (e.pageY > pageBox.bottom || e.pageY < pageBox.top) { return; } target = Ext.Element.fromPoint(pageBox.left + (pageBox.width / 2), e.pageY); } else if (this.horizontal) { if (e.pageX > pageBox.right || e.pageX < pageBox.left) { return; } target = Ext.Element.fromPoint(e.pageX, pageBox.top + (pageBox.height / 2)); } if (target) { record = this.getRecord(target.dom); if (record) { this.fireEvent('index', record, target, this.indexOf(target)); } } }, /** * Method to determine whether this Sortable is currently disabled. * @return {Boolean} the disabled state of this Sortable. */ isVertical : function() { return this.vertical; }, /** * Method to determine whether this Sortable is currently sorting. * @return {Boolean} the sorting state of this Sortable. */ isHorizontal : function() { return this.horizontal; } }); Ext.reg('indexbar', Ext.IndexBar); Ext.regModel('IndexBarModel', { fields: ['key', 'value'] });
JavaScript
/** * @class Ext.Sheet * @extends Ext.Panel * * <p>A general sheet class. This renderable container provides base support for orientation-aware * transitions for popup or side-anchored sliding Panels.</p> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Sheet/screenshot.png" /></p> * * <h2>Example usage:</h2> * <pre><code> var sheet = new Ext.Sheet({ height : 200, stretchX: true, stretchY: true, layout: { type: 'hbox', align: 'stretch' }, dockedItems: [ { dock : 'bottom', xtype: 'button', text : 'Click me' } ] }); sheet.show(); * </code></pre> * * <p>See {@link Ext.Picker} and {@link Ext.DatePicker}</p> * @xtype sheet */ Ext.Sheet = Ext.extend(Ext.Panel, { baseCls : 'x-sheet', centered : false, floating : true, modal : true, hideOnMaskTap : false, draggable : false, monitorOrientation : true, hidden : true, /** * @cfg {Boolean} stretchX * If true, the width of anchored Sheets are adjusted to fill the entire top/bottom axis width, * or false to center the Sheet along the same axis based upon the sheets current/calculated width. * This option is ignored when {link #centered} is true or x/y coordinates are specified for the Sheet. */ /** * @cfg {Boolean} stretchY * If true, the height of anchored Sheets are adjusted to fill the entire right/left axis height, * or false to center the Sheet along the same axis based upon the sheets current/calculated height. * This option is ignored when {link #centered} is true or x/y coordinates are specified for the Sheet. */ /** * @cfg {String} enter * The viewport side from which to anchor the sheet when made visible (top, bottom, left, right) * Defaults to 'bottom' */ enter : 'bottom', /** * @cfg {String} exit * The viewport side used as the exit point when hidden (top, bottom, left, right) * Applies to sliding animation effects only. Defaults to 'bottom' */ exit : 'bottom', /** * @cfg {String/Object} enterAnimation * the named Ext.anim effect or animation configuration object used for transitions * when the component is shown. Defaults to 'slide' */ enterAnimation : 'slide', /** * * @cfg {String/Object} exitAnimation * the named Ext.anim effect or animation configuration object used for transitions * when the component is hidden. Defaults to 'slide' */ exitAnimation : 'slide', // @private slide direction defaults transitions : { bottom : 'up', top : 'down', right : 'left', left : 'right' }, //@private animSheet : function(animate) { var anim = null, me = this, tr = me.transitions, opposites = Ext.Anim.prototype.opposites || {}; if (animate && this[animate]) { if (animate == 'enter') { anim = (typeof me.enterAnimation == 'string') ? { type : me.enterAnimation || 'slide', direction : tr[me.enter] || 'up' } : me.enterAnimation; } else if (animate == 'exit') { anim = (typeof me.exitAnimation == 'string') ? { type : me.exitAnimation || 'slide', direction : tr[me.exit] || 'down' } : me.exitAnimation; } } return anim; }, // @private orient : function(orientation, w, h) { if(!this.container || this.centered || !this.floating){ return this; } var me = this, cfg = me.initialConfig || {}, //honor metrics (x, y, height, width) initialConfig size = {width : cfg.width, height : cfg.height}, pos = {x : cfg.x, y : cfg.y}, box = me.el.getPageBox(), pageBox, scrollTop = 0; if (me.container.dom == document.body) { pageBox = { width: window.innerWidth, height: window.innerHeight }; scrollTop = document.body.scrollTop; } else { pageBox = me.container.getPageBox(); } pageBox.centerY = pageBox.height / 2; pageBox.centerX = pageBox.width / 2; if(pos.x != undefined || pos.y != undefined){ pos.x = pos.x || 0; pos.y = pos.y || 0; } else { if (/^(bottom|top)/i.test(me.enter)) { size.width = me.stretchX ? pageBox.width : Math.min(200,Math.max(size.width || box.width || pageBox.width, pageBox.width)); size.height = Math.min(size.height || 0, pageBox.height) || undefined; size = me.setSize(size).getSize(); pos.x = pageBox.centerX - size.width / 2; pos.y = me.enter == 'top' ? 0 : pageBox.height - size.height + scrollTop; } else if (/^(left|right)/i.test(me.enter)) { size.height = me.stretchY ? pageBox.height : Math.min(200, Math.max(size.height || box.height || pageBox.height, pageBox.height)); size.width = Math.min(size.width || 0, pageBox.width) || undefined; size = me.setSize(size).getSize(); pos.y = 0; pos.x = me.enter == 'left' ? 0 : pageBox.width - size.width; } } me.setPosition(pos); return this; }, // @private afterRender : function() { Ext.Sheet.superclass.afterRender.apply(this, arguments); this.el.setDisplayMode(Ext.Element.OFFSETS); }, // @private onShow : function(animation) { this.orient(); return Ext.Sheet.superclass.onShow.call(this, animation || this.animSheet('enter')); }, // @private onOrientationChange : function(orientation, w, h) { this.orient(); Ext.Sheet.superclass.onOrientationChange.apply(this, arguments); }, // @private beforeDestroy : function() { delete this.showAnimation; this.hide(false); Ext.Sheet.superclass.beforeDestroy.call(this); } }); Ext.reg('sheet', Ext.Sheet); /** * @class Ext.ActionSheet * @extends Ext.Sheet * * <p>A Button Sheet class designed to popup or slide/anchor a series of buttons.</p> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.ActionSheet/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> var actionSheet = new Ext.ActionSheet({ items: [ { text: 'Delete draft', ui : 'decline' }, { text: 'Save draft' }, { text: 'Cancel', ui : 'confirm' } ] }); actionSheet.show();</code></pre> * @xtype sheet */ Ext.ActionSheet = Ext.extend(Ext.Sheet, { componentCls: 'x-sheet-action', stretchY: true, stretchX: true, defaultType: 'button', constructor : function(config) { config = config || {}; Ext.ActionSheet.superclass.constructor.call(this, Ext.applyIf({ floating : true }, config)); } }); Ext.reg('actionsheet', Ext.ActionSheet);
JavaScript
/** * @class Ext.Container * @extends Ext.lib.Container * <p>Base class for any {@link Ext.BoxComponent} that may contain other Components. Containers handle the * basic behavior of containing items, namely adding, inserting and removing items.</p> * * <p><u><b>Layout</b></u></p> * <p>Container classes delegate the rendering of child Components to a layout * manager class which must be configured into the Container using the * <code><b>{@link #layout}</b></code> configuration property.</p> * <p>When either specifying child <code>{@link #items}</code> of a Container, * or dynamically {@link #add adding} Components to a Container, remember to * consider how you wish the Container to arrange those child elements, and * whether those child elements need to be sized using one of Ext's built-in * <b><code>{@link #layout}</code></b> schemes. By default, Containers use the * {@link Ext.layout.AutoContainerLayout AutoContainerLayout} scheme which only * renders child components, appending them one after the other inside the * Container, and <b>does not apply any sizing</b> at all.</p> * <p>A common mistake is when a developer neglects to specify a * <b><code>{@link #layout}</code></b>. If a Container is left to use the default * {@link Ext.layout.AutoContainerLayout AutoContainerLayout} scheme, none of its * child components will be resized, or changed in any way when the Container * is resized.</p> * @xtype container */ Ext.Container = Ext.extend(Ext.lib.Container, { /** * @cfg {String/Mixed} cardSwitchAnimation * Animation to be used during transitions of cards. Note this only works when this container has a CardLayout. * Any valid value from Ext.anims can be used ('fade', 'slide', 'flip', 'cube', 'pop', 'wipe'). * Defaults to <tt>null</tt>. */ cardSwitchAnimation: null, initComponent: function() { if (this.scroll) { this.fields = new Ext.util.MixedCollection(); this.fields.on({ add: this.onFieldAdd, remove: this.onFieldRemove, scope: this }); this.on({ add: this.onItemAdd, remove: this.onItemRemove, scope: this }); } //<deprecated since="0.99"> if (Ext.isDefined(this.animation)) { console.warn("Container: animation has been removed. Please use cardSwitchAnimation."); this.cardSwitchAnimation = this.animation; } //</deprecated> Ext.Container.superclass.initComponent.apply(this, arguments); }, afterRender: function() { Ext.Container.superclass.afterRender.apply(this, arguments); if (this.scroller) { this.scroller.on('scrollstart', this.onFieldScrollStart, this); } }, onFieldScrollStart: function() { if (this.focusedField && !Ext.is.Android) { this.focusedField.blur(); Ext.Viewport.scrollToTop(); } }, onItemAdd: function(me, item) { this.fields.addAll(Ext.ComponentQuery.query('[isField]', item)); }, onItemRemove: function(me, item) { this.fields.removeAll(Ext.ComponentQuery.query('[isField]', item)); }, onFieldAdd: function(key, field) { this.handleFieldEventListener(true, field); }, onFieldRemove: function(key, field) { this.handleFieldEventListener(false, field); }, handleFieldEventListener: function(isAdding, item) { if (!this.fieldEventWrap) this.fieldEventWrap = {}; //TODO: remove the 'textarea' xtype here for the release of 1.0. This is a backwards-compatibility xtype only if (['textfield', 'passwordfield', 'emailfield', 'textarea', 'textareafield', 'searchfield', 'urlfield', 'numberfield', 'spinnerfield'].indexOf(item.xtype) !== -1) { if (isAdding) { this.fieldEventWrap[item.id] = { beforefocus: function(e) {this.onFieldBeforeFocus(item, e);}, focus: function(e) {this.onFieldFocus(item, e);}, blur: function(e) {this.onFieldBlur(item, e);}, keyup: function(e) {this.onFieldKeyUp(item, e);}, scope: this }; } item[isAdding ? 'on' : 'un'](this.fieldEventWrap[item.id]); if (!isAdding) { delete this.fieldEventWrap[item.id]; } } }, onFieldKeyUp: function(field, e) { this.resetLastWindowScroll(); }, onFieldBeforeFocus: function(field, e) { this.focusingField = field; }, getLastWindowScroll: function() { if (!this.lastWindowScroll) { this.resetLastWindowScroll(); } return {x: this.lastWindowScroll.x, y: this.lastWindowScroll.y}; }, resetLastWindowScroll: function() { this.lastWindowScroll = { x: window.pageXOffset, y: window.pageYOffset }; }, adjustScroller: function(offset) { var me = this, scroller = this.getClosestScroller(), windowScroll = this.getLastWindowScroll(); scroller.setOffset(offset); // Keep the window in the previous scroll position if (Ext.is.Android) { window.scrollTo(windowScroll.x, windowScroll.y || -1); } else { window.scrollTo(windowScroll.x, windowScroll.y); } this.resetLastWindowScroll(); }, onFieldFocus: function(field, e) { if (Ext.is.Android) { this.scroller.setUseCssTransform(false); } Ext.currentlyFocusedField = field; var me = this, scroller = this.getClosestScroller(), containerRegion = Ext.util.Region.from(scroller.containerBox), fieldRegion = field.fieldEl.getPageBox(true), fieldSize = fieldRegion.getSize(); // Focus by mouse click or finger tap if (this.focusingField == field) { var offsetContainerRegion = containerRegion.copy(); offsetContainerRegion.bottom -= fieldSize.height; offsetContainerRegion.right -= fieldSize.width; var outOfBoundDistance = offsetContainerRegion.getOutOfBoundOffset({ x: fieldRegion.left, y: fieldRegion.top }) if (outOfBoundDistance.x != 0 || outOfBoundDistance.y != 0) { this.adjustScroller(new Ext.util.Offset( scroller.offset.x, scroller.offset.y + outOfBoundDistance.y )); } } else { if (this.lastFocusedField) { var deltaY = fieldRegion.top - this.lastFocusedField.fieldEl.getY(), offsetY = scroller.offset.y - deltaY, selfHandling = false; if (!containerRegion.contains(fieldRegion) && (offsetY != 0 || (offsetY == 0 && scroller.offset.y != 0))) { selfHandling = true; } if (offsetY > 0) { offsetY = 0; } if (selfHandling) { this.adjustScroller(new Ext.util.Offset( scroller.offset.x, offsetY )); } } } this.resetLastWindowScroll(); this.lastFocusedField = field; this.focusedField = field; this.focusingField = null; Ext.Viewport.hideStretchEl(); }, getClosestScroller: function() { if (!this.closestScroller) { this.closestScroller = this.scroller || this.el.getScrollParent(); } return this.closestScroller; }, onFieldBlur: function(field, e) { Ext.Viewport.showStretchEl(); Ext.currentlyFocusedField = null; if (this.focusingField == field) { this.focusingField = null; } if (this.focusedField == field) { this.focusedField = null; } }, // @private afterLayout : function(layout) { if (this.floating && this.centered) { this.setCentered(true, true); } if (this.scroller) { this.scroller.updateBoundary(); } Ext.Container.superclass.afterLayout.call(this, layout); }, /** * Returns the current activeItem for the layout (only for a card layout) * @return {activeItem} activeItem Current active component */ getActiveItem : function() { if (this.layout && this.layout.type == 'card') { return this.layout.activeItem; } else { return null; } }, /** * Allows you to set the active card in this container. This * method is only available if the container uses a CardLayout. * Note that a Carousel and TabPanel both get a CardLayout * automatically, so both of those components are able to use this method. * @param {Ext.Component/Number/Object} card The card you want to be made active. A number * is interpreted as a card index. An object will be converted to a Component using the * objects xtype property, then added to the container and made active. Passing a Component * will make sure the component is a child of this container, and then make it active. * @param {String/Object} cardSwitchAnimation (optional) The cardSwitchAnimation used to switch between the cards. * This can be an animation type string or an animation configuration object. * @return {Ext.Container} this */ setActiveItem : function(card, animation) { this.layout.setActiveItem(card, animation); return this; }, //<debug> setCard: function() { throw new Error("Stateful: setCard has been deprecated. Please use setActiveItem."); }, //</debug> /** * A template method that can be implemented by subclasses of * Container. By returning false we can cancel the card switch. * @param {Ext.Component} newCard The card that will be switched to * @param {Ext.Component} oldCard The card that will be switched from * @param {Number} newIndex The Container index position of the selected card * @param {Boolean} animated True if this cardswitch will be animated * @private */ onBeforeCardSwitch : function(newCard, oldCard, newIndex, animated) { return this.fireEvent('beforecardswitch', this, newCard, oldCard, newIndex, animated); }, /** * A template method that can be implemented by subclasses of * Container. If the card is switched using an animation, this method * will be called after the animation has finished. * @param {Ext.Component} newCard The card that has been switched to * @param {Ext.Component} oldCard The card that has been switched from * @param {Number} newIndex The Container index position of the selected card * @param {Boolean} animated True if this cardswitch was animated * @private */ onCardSwitch : function(newCard, oldCard, newIndex, animated) { return this.fireEvent('cardswitch', this, newCard, oldCard, newIndex, animated); }, /** * Disable this container by masking out */ disable: function() { Ext.Container.superclass.disable.call(this); this.el.mask(null, 'x-mask-gray'); }, /** * Enable this container by removing mask */ enable: function() { Ext.Container.superclass.enable.call(this); this.el.unmask(); } }); Ext.reg('container', Ext.Container);
JavaScript
/** * @class Ext.Audio * @extends Ext.Media * * <p>Provides a simple container for HTML5 Audio.</p> * <p><i>Recommended types: Uncompressed WAV and AIF audio, MP3 audio, and AAC-LC or HE-AAC audio</i></p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #url}</li> * <li>{@link #autoPause}</li> * <li>{@link #autoResume}</li> * </ul> * * <h2>Useful Methods</h2> * <ul class="list"> * <li>{@link #pause}</li> * <li>{@link #play}</li> * <li>{@link #toggle}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Audio/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> var pnl = new Ext.Panel({ fullscreen: true, items: [ { xtype: 'audio', url : "who-goingmobile.mp3" } ] });</code></pre> * @xtype audio */ Ext.Audio = Ext.extend(Ext.Media, { /** * @constructor * @param {Object} config * Create a new Audio container. */ /** * @cfg {String} url * Location of the audio to play. */ componentCls: 'x-audio', // @private onActivate: function(){ Ext.Audio.superclass.onActivate.call(this); if (Ext.is.Phone) { this.media.show(); } }, // @private onDeactivate: function(){ Ext.Audio.superclass.onDeactivate.call(this); if (Ext.is.Phone) { this.media.hide(); } }, // @private getConfiguration: function(){ var hidden = !this.enableControls; if (!Ext.supports.AudioTag) { return { tag: 'embed', type: 'audio/mpeg', target: 'myself', controls: 'true', hidden: hidden }; } else { return { tag: 'audio', hidden: hidden }; } } }); Ext.reg('audio', Ext.Audio);
JavaScript
/** * @class Ext.Map * @extends Ext.Component * * <p>Wraps a Google Map in an Ext.Component.<br/> * http://code.google.com/apis/maps/documentation/v3/introduction.html</p> * * <p>To use this component you must include an additional JavaScript file from * Google:</p> * <pre><code>&lt;script type="text/javascript" src="http:&#47;&#47;maps.google.com/maps/api/js?sensor=true"&gt;&lt/script&gt;</code></pre> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Map/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> var pnl = new Ext.Panel({ fullscreen: true, items : [ { xtype : 'map', useCurrentLocation: true } ] });</code></pre> * @xtype map */ Ext.Map = Ext.extend(Ext.Component, { /** * @cfg {String} baseCls * The base CSS class to apply to the Maps's element (defaults to <code>'x-map'</code>). */ baseCls: 'x-map', /** * @cfg {Boolean} useCurrentLocation * Pass in true to center the map based on the geolocation coordinates. */ useCurrentLocation: false, monitorResize : true, /** * @cfg {Object} mapOptions * MapOptions as specified by the Google Documentation: * http://code.google.com/apis/maps/documentation/v3/reference.html */ /** * @type {google.maps.Map} * The wrapped map. */ map: null, /** * @type {Ext.util.GeoLocation} */ geo: null, /** * @cfg {Boolean} maskMap * Masks the map (Defaults to false) */ maskMap: false, /** * @cfg {Strng} maskMapCls * CSS class to add to the map when maskMap is set to true. */ maskMapCls: 'x-mask-map', initComponent : function() { this.mapOptions = this.mapOptions || {}; this.scroll = false; //<deprecated since="0.99"> if (Ext.isDefined(this.getLocation)) { console.warn("SpinnerField: getLocation has been removed. Please use useCurrentLocation."); this.useCurrentLocation = this.getLocation; } //</deprecated> if(!(window.google || {}).maps){ this.html = 'Google Maps API is required'; } else if (this.useCurrentLocation) { this.geo = this.geo || new Ext.util.GeoLocation({autoLoad: false}); this.geo.on({ locationupdate : this.onGeoUpdate, locationerror : this.onGeoError, scope : this }); } Ext.Map.superclass.initComponent.call(this); this.addEvents ( /** * @event maprender * @param {Ext.Map} this * @param {google.maps.Map} map The rendered google.map.Map instance */ 'maprender', /** * @event centerchange * @param {Ext.Map} this * @param {google.maps.Map} map The rendered google.map.Map instance * @param {google.maps.LatLong} center The current LatLng center of the map */ 'centerchange', /** * @event typechange * @param {Ext.Map} this * @param {google.maps.Map} map The rendered google.map.Map instance * @param {Number} mapType The current display type of the map */ 'typechange', /** * @event zoomchange * @param {Ext.Map} this * @param {google.maps.Map} map The rendered google.map.Map instance * @param {Number} zoomLevel The current zoom level of the map */ 'zoomchange' ); if (this.geo){ this.on({ activate: this.onUpdate, scope: this, single: true }); this.geo.updateLocation(); } }, // @private onRender : function(container, position) { Ext.Map.superclass.onRender.apply(this, arguments); this.el.setDisplayMode(Ext.Element.OFFSETS); }, // @private afterRender : function() { Ext.Map.superclass.afterRender.apply(this, arguments); this.renderMap(); }, // @private onResize : function( w, h) { Ext.Map.superclass.onResize.apply(this, arguments); if (this.map) { google.maps.event.trigger(this.map, 'resize'); } }, afterComponentLayout : function() { if (this.maskMap && !this.mask) { this.el.mask(null, this.maskMapCls); this.mask = true; } }, renderMap : function(){ var me = this, gm = (window.google || {}).maps; if (gm) { if (Ext.is.iPad) { Ext.applyIf(me.mapOptions, { navigationControlOptions: { style: gm.NavigationControlStyle.ZOOM_PAN } }); } Ext.applyIf(me.mapOptions, { center: new gm.LatLng(37.381592, -122.135672), // Palo Alto zoom: 12, mapTypeId: gm.MapTypeId.ROADMAP }); if (me.maskMap && !me.mask) { me.el.mask(null, this.maskMapCls); me.mask = true; } if (me.el && me.el.dom && me.el.dom.firstChild) { Ext.fly(me.el.dom.firstChild).remove(); } if (me.map) { gm.event.clearInstanceListeners(me.map); } me.map = new gm.Map(me.el.dom, me.mapOptions); var event = gm.event; //Track zoomLevel and mapType changes event.addListener(me.map, 'zoom_changed', Ext.createDelegate(me.onZoom, me)); event.addListener(me.map, 'maptypeid_changed', Ext.createDelegate(me.onTypeChange, me)); event.addListener(me.map, 'center_changed', Ext.createDelegate(me.onCenterChange, me)); me.fireEvent('maprender', me, me.map); } }, onGeoUpdate : function(coords) { var center; if (coords) { center = this.mapOptions.center = new google.maps.LatLng(coords.latitude, coords.longitude); } if (this.rendered) { this.update(center); } else { this.on('activate', this.onUpdate, this, {single: true, data: center}); } }, onGeoError : function(geo){ }, onUpdate : function(map, e, options) { this.update((options || {}).data); }, /** * Moves the map center to the designated coordinates hash of the form: <code><pre> { latitude : 37.381592, longitude : -122.135672 }</pre></code> * or a google.maps.LatLng object representing to the target location. * @param {Object/google.maps.LatLng} coordinates Object representing the desired Latitude and * longitude upon which to center the map */ update : function(coordinates) { var me = this, gm = (window.google || {}).maps; if (gm) { coordinates = coordinates || me.coords || new gm.LatLng(37.381592, -122.135672); if (coordinates && !(coordinates instanceof gm.LatLng) && 'longitude' in coordinates) { coordinates = new gm.LatLng(coordinates.latitude, coordinates.longitude); } if (!me.hidden && me.rendered) { me.map || me.renderMap(); if (me.map && coordinates instanceof gm.LatLng) { me.map.panTo(coordinates); } } else { me.on('activate', me.onUpdate, me, {single: true, data: coordinates}); } } }, // @private onZoom : function() { this.mapOptions.zoom = (this.map && this.map.getZoom ? this.map.getZoom() : this.mapOptions.zoom) || 10 ; this.fireEvent('zoomchange', this, this.map, this.mapOptions.zoom); }, // @private onTypeChange : function() { this.mapOptions.mapTypeId = this.map && this.map.getMapTypeId ? this.map.getMapTypeId() : this.mapOptions.mapTypeId; this.fireEvent('typechange', this, this.map, this.mapOptions.mapTypeId); }, // @private onCenterChange : function(){ this.mapOptions.center = this.map && this.map.getCenter ? this.map.getCenter() : this.mapOptions.center; this.fireEvent('centerchange', this, this.map, this.mapOptions.center); }, getState : function(){ return this.mapOptions; }, // @private onDestroy : function() { Ext.destroy(this.geo); if (this.maskMap && this.mask) { this.el.unmask(); } if (this.map && (window.google || {}).maps) { google.maps.event.clearInstanceListeners(this.map); } Ext.Map.superclass.onDestroy.call(this); } }); Ext.reg('map', Ext.Map);
JavaScript
/** * @class Ext.DatePicker * @extends Ext.Picker * * <p>A date picker component which shows a DatePicker on the screen. This class extends from {@link Ext.Picker} and {@link Ext.Sheet} so it is a popup.</p> * <p>This component has no required properties.</p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #yearFrom}</li> * <li>{@link #yearTo}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.DatePicker/screenshot.png" /></p> * * <h2>Example code:</h2> * * <pre><code> var datePicker = new Ext.DatePicker(); datePicker.show(); * </code></pre> * * <p>you may want to adjust the {@link #yearFrom} and {@link #yearTo} properties: * <pre><code> var datePicker = new Ext.DatePicker({ yearFrom: 2000, yearTo : 2015 }); datePicker.show(); * </code></pre> * * @constructor * Create a new List * @param {Object} config The config object * @xtype datepicker */ Ext.DatePicker = Ext.extend(Ext.Picker, { /** * @cfg {Number} yearFrom * The start year for the date picker. Defaults to 1980 */ yearFrom: 1980, /** * @cfg {Number} yearTo * The last year for the date picker. Defaults to the current year. */ yearTo: new Date().getFullYear(), /** * @cfg {String} monthText * The label to show for the month column. Defaults to 'Month'. */ monthText: 'Month', /** * @cfg {String} dayText * The label to show for the day column. Defaults to 'Day'. */ dayText: 'Day', /** * @cfg {String} yearText * The label to show for the year column. Defaults to 'Year'. */ yearText: 'Year', /** * @cfg {Object/Date} value * Default value for the field and the internal {@link Ext.DatePicker} component. Accepts an object of 'year', * 'month' and 'day' values, all of which should be numbers, or a {@link Date}. * * Examples: * {year: 1989, day: 1, month: 5} = 1st May 1989. * new Date() = current date */ /** * @cfg {Array} slotOrder * An array of strings that specifies the order of the slots. Defaults to <tt>['month', 'day', 'year']</tt>. */ slotOrder: ['month', 'day', 'year'], initComponent: function() { var yearsFrom = this.yearFrom, yearsTo = this.yearTo, years = [], days = [], months = [], ln, tmp, i, daysInMonth; // swap values if user mixes them up. if (yearsFrom > yearsTo) { tmp = yearsFrom; yearsFrom = yearsTo; yearsTo = tmp; } for (i = yearsFrom; i <= yearsTo; i++) { years.push({ text: i, value: i }); } daysInMonth = this.getDaysInMonth(1, new Date().getFullYear()); for (i = 0; i < daysInMonth; i++) { days.push({ text: i + 1, value: i + 1 }); } for (i = 0, ln = Date.monthNames.length; i < ln; i++) { months.push({ text: Date.monthNames[i], value: i + 1 }); } this.slots = []; this.slotOrder.forEach(function(item){ this.slots.push(this.createSlot(item, days, months, years)); }, this); Ext.DatePicker.superclass.initComponent.call(this); }, afterRender: function() { Ext.DatePicker.superclass.afterRender.apply(this, arguments); this.setValue(this.value); }, createSlot: function(name, days, months, years){ switch (name) { case 'year': return { name: 'year', align: 'center', data: years, title: this.useTitles ? this.yearText : false, flex: 3 }; case 'month': return { name: name, align: 'right', data: months, title: this.useTitles ? this.monthText : false, flex: 4 }; case 'day': return { name: 'day', align: 'center', data: days, title: this.useTitles ? this.dayText : false, flex: 2 }; } }, // @private onSlotPick: function(slot, value) { var name = slot.name, date, daysInMonth, daySlot; if (name === "month" || name === "year") { daySlot = this.child('[name=day]'); date = this.getValue(); daysInMonth = this.getDaysInMonth(date.getMonth()+1, date.getFullYear()); daySlot.store.clearFilter(); daySlot.store.filter({ fn: function(r) { return r.get('extra') === true || r.get('value') <= daysInMonth; } }); daySlot.scroller.updateBoundary(true); } Ext.DatePicker.superclass.onSlotPick.apply(this, arguments); }, /** * Gets the current value as a Date object * @return {Date} value */ getValue: function() { var value = Ext.DatePicker.superclass.getValue.call(this), daysInMonth = this.getDaysInMonth(value.month, value.year), day = Math.min(value.day, daysInMonth); return new Date(value.year, value.month-1, day); }, /** * Sets the values of the DatePicker's slots * @param {Date/Object} value The value either in a {day:'value', month:'value', year:'value'} format or a Date * @param {Boolean} animated True for animation while setting the values * @return {Ext.DatePicker} this This DatePicker */ setValue: function(value, animated) { if (!Ext.isDate(value) && !Ext.isObject(value)) { value = null; } if (Ext.isDate(value)) { this.value = { day : value.getDate(), year: value.getFullYear(), month: value.getMonth() + 1 }; } else { this.value = value; } return Ext.DatePicker.superclass.setValue.call(this, this.value, animated); }, // @private getDaysInMonth: function(month, year) { var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return month == 2 && this.isLeapYear(year) ? 29 : daysInMonth[month-1]; }, // @private isLeapYear: function(year) { return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year))); } }); Ext.reg('datepicker', Ext.DatePicker);
JavaScript
/** * @class Ext.Tab * @extends Ext.Button * * <p>Used in the {@link Ext.TabBar} component. This shouldn't be used directly, instead use {@link Ext.TabBar} or {@link Ext.TabPanel}.</p> * * @xtype tab */ Ext.Tab = Ext.extend(Ext.Button, { isTab: true, baseCls: 'x-tab', /** * @cfg {String} pressedCls * The CSS class to be applied to a Tab when it is pressed. Defaults to 'x-tab-pressed'. * Providing your own CSS for this class enables you to customize the pressed state. */ pressedCls: 'x-tab-pressed', /** * @cfg {String} activeCls * The CSS class to be applied to a Tab when it is active. Defaults to 'x-tab-active'. * Providing your own CSS for this class enables you to customize the active state. */ activeCls: 'x-tab-active', /** * @property Boolean * Read-only property indicating that this tab is currently active. * This is NOT a public configuration. */ active: false, // @private initComponent : function() { this.addEvents( /** * @event activate * @param {Ext.Tab} this */ 'activate', /** * @event deactivate * @param {Ext.Tab} this */ 'deactivate' ); Ext.Tab.superclass.initComponent.call(this); var card = this.card; if (card) { this.card = null; this.setCard(card); } }, /** * Sets the card associated with this tab */ setCard : function(card) { if (this.card) { this.mun(this.card, { activate: this.activate, deactivate: this.deactivate, scope: this }); } this.card = card; if (card) { Ext.apply(this, card.tab || {}); this.setText(this.title || card.title || this.text ); this.setIconClass(this.iconCls || card.iconCls); this.setBadge(this.badgeText || card.badgeText); this.mon(card, { beforeactivate: this.activate, beforedeactivate: this.deactivate, scope: this }); } }, onRender: function() { Ext.Tab.superclass.onRender.apply(this, arguments); if (this.active) { this.el.addCls(this.activeCls); } }, /** * Retrieves a reference to the card associated with this tab * @returns {Mixed} card */ getCard : function() { return this.card; }, // @private activate : function() { this.active = true; if (this.el) { this.el.addCls(this.activeCls); } this.fireEvent('activate', this); }, // @private deactivate : function() { this.active = false; if (this.el) { this.el.removeCls(this.activeCls); } this.fireEvent('deactivate', this); } }); Ext.reg('tab', Ext.Tab);
JavaScript
/** * @class Ext.Media * @extends Ext.Container * * <p>Provides a base class for audio/visual controls. Should not be used directly.</p> * @xtype media */ Ext.Media = Ext.extend(Ext.Container, { /** * @constructor * @param {Object} config * Create a new Media component. */ /** * @cfg {String} url * Location of the media to play. */ url: '', /** * @cfg {Boolean} enableControls * Set this to false to turn off the native media controls * (Defaults to true). */ enableControls: true, /** * @cfg {Boolean} autoResume * Will automatically start playing the media when the container is activated. * (Defaults to false) */ autoResume: false, /** * @cfg {Boolean} autoPause * Will automatically pause the media when the container is deactivated. * (Defaults to true) */ autoPause: true, /** * @cfg {Boolean} preload * Will begin preloading the media immediately. * (Defaults to true) */ preload: true, // @private playing: false, // @private afterRender : function() { var cfg = this.getConfiguration(); Ext.apply(cfg, { src: this.url, preload: this.preload ? 'auto' : 'none' }); if(this.enableControls){ cfg.controls = 'controls'; } if(this.loop){ cfg.loop = 'loop'; } /** * A reference to the underlying audio/video element. * @property media * @type Ext.Element */ this.media = this.el.createChild(cfg); Ext.Media.superclass.afterRender.call(this); this.on({ scope: this, activate: this.onActivate, beforedeactivate: this.onDeactivate }); }, // @private onActivate: function(){ if (this.autoResume && !this.playing) { this.play(); } }, // @private onDeactivate: function(){ if (this.autoPause && this.playing) { this.pause(); } }, /** * Starts or resumes media playback */ play : function() { this.media.dom.play(); this.playing = true; }, /** * Pauses media playback */ pause : function() { this.media.dom.pause(); this.playing = false; }, /** * Toggles the media playback state */ toggle : function() { if(this.playing){ this.pause(); } else { this.play(); } } }); Ext.reg('media', Ext.Media);
JavaScript
/** * @class Ext.Button * @extends Ext.Component * * <p>A simple class to display different styles of buttons.</p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #ui} (defines the style of the button)</li> * </ul> * * <h2>Useful Methods</h2> * <ul class="list"> * <li>{@link #handler} (method to be called when the button is tapped)</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Button/screenshot.png" /></p> * * <h2>Example code:</h2> <pre><code> // an array of buttons (using xtypes) to be included in the panel below var buttons = [ { text: 'Normal' }, { ui : 'round', text: 'Round' }, { ui : 'small', text: 'Small' } ]; var panel = new Ext.Panel({ layout: { type : 'vbox', pack : 'center', align: 'stretch' }, defaults: { layout: { type: 'hbox' }, flex: 1, defaults: { xtype: 'button', cls : 'demobtn', flex : 1 } }, items: [ { items: buttons // buttons array defined above }, { items: [ new Ext.Button({ ui : 'decline', text: 'Drastic' }), { ui : 'decline-round', text: 'Round' }, { ui : 'decline-small', text: 'Small' } ] }, { items: [ { ui : 'confirm', text: 'Confirm' }, { ui : 'confirm-round', text: 'Round' }, { ui : 'confirm-small', text: 'Small' } ] } ] }); </code></pre> */ /** * @constructor * Create a new button * @param {Object} config The config object * @xtype button */ Ext.Button = Ext.extend(Ext.Component, { /** * @cfg {String/Object} autoEvent If provided, a handler function is automatically created that fires * the given event in the configured {@link #scope}. */ initComponent: function(){ this.addEvents( /** * @event tap * Fires when the button is tapped. * @param {Ext.Button} this * @param {Ext.EventObject} e */ 'tap', /** * @event beforetap * Fires when the button is tapped but before we call the handler or fire the tap event. * Return false in a handler to prevent this. * @param {Ext.Button} this * @param {Ext.EventObject} e */ 'beforetap' ); Ext.Button.superclass.initComponent.call(this); this.createAutoHandler(); }, /** * @cfg {String} iconCls * A css class which sets a background image to be used as the icon for this button */ /** * @cfg {String} text The button text to be used as innerHTML (html tags are accepted) */ /** * @cfg {String} icon The path to an image to display in the button (the image will be set as the background-image * CSS property of the button by default, so if you want a mixed icon/text button, set cls:'x-btn-text-icon') */ /** * @cfg {String} iconAlign The alignment of the buttons icon if one has been defined. Valid options * are 'top', 'right', 'bottom', 'left' (defaults to 'left'). */ iconAlign: 'left', /** * @cfg {Function} handler A function called when the button is clicked (can be used instead of click event). * The handler is passed the following parameters:<div class="mdetail-params"><ul> * <li><code>b</code> : Button<div class="sub-desc">This Button.</div></li> * <li><code>e</code> : EventObject<div class="sub-desc">The click event.</div></li> * </ul></div> */ /** * @cfg {Object} scope The scope (<tt><b>this</b></tt> reference) in which the * <code>{@link #handler}</code> and <code>{@link #toggleHandler}</code> is * executed. Defaults to this Button. */ /** * @cfg {Boolean} hidden True to start hidden (defaults to false) */ /** * @cfg {Boolean} disabled True to start disabled (defaults to false) */ /** * @cfg {String} baseCls Base CSS class * Defaults to <tt>'x-button'</tt> */ baseCls: 'x-button', /** * @cfg {String} pressedCls CSS class when the button is in pressed state * Defaults to <tt>'x-button-pressed'</tt> */ pressedCls: 'x-button-pressed', /** * @cfg {String} badgeText The text to be used for a small badge on the button. * Defaults to <tt>''</tt> */ badgeText: '', /** * @cfg {String} badgeCls CSS class for badge * Defaults to <tt>'x-badge'</tt> */ badgeCls: 'x-badge', hasBadgeCls: 'x-hasbadge', labelCls: 'x-button-label', /** * @cfg {String} ui * Determines the UI look and feel of the button. Valid options are 'normal', 'back', 'round', 'action', 'forward'. * Defaults to 'normal'. */ ui: 'normal', isButton: true, /** * @cfg {String} cls * A CSS class string to apply to the button's main element. */ /** * @cfg {Number} pressedDelay * The amount of delay between the tapstart and the moment we add the pressedCls. * Settings this to true defaults to 100ms */ pressedDelay: 0, /** * @cfg {String} iconMaskCls * CSS class to be added to the iconEl when the iconMask config is set to true. * Defaults to 'x-icon-mask' */ iconMaskCls: 'x-icon-mask', /** * @cfg {Boolean} iconMask * Whether or not to mask the icon with the iconMaskCls configuration. Defaults to false. */ iconMask: false, // @private afterRender : function(ct, position) { var me = this; Ext.Button.superclass.afterRender.call(me, ct, position); var text = me.text, icon = me.icon, iconCls = me.iconCls, badgeText = me.badgeText; me.text = me.icon = me.iconCls = me.badgeText = null; me.setText(text); me.setIcon(icon); me.setIconClass(iconCls); if (me.iconMask && me.iconEl) { me.iconEl.addCls(me.iconMaskCls); } me.setBadge(badgeText); }, // @private initEvents : function() { var me = this; Ext.Button.superclass.initEvents.call(me); me.mon(me.el, { scope: me, tap : me.onPress, tapstart : me.onTapStart, tapcancel: me.onTapCancel }); }, // @private onTapStart : function() { var me = this; if (!me.disabled) { if (me.pressedDelay) { me.pressedTimeout = setTimeout(function() { me.el.addCls(me.pressedCls); }, Ext.isNumber(me.pressedDelay) ? me.pressedDelay : 100); } else { me.el.addCls(me.pressedCls); } } }, // @private onTapCancel : function() { var me = this; if (me.pressedTimeout) { clearTimeout(me.pressedTimeout); delete me.pressedTimeout; } me.el.removeCls(me.pressedCls); }, /** * Assigns this Button's click handler * @param {Function} handler The function to call when the button is clicked * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function is executed. * Defaults to this Button. * @return {Ext.Button} this */ setHandler : function(handler, scope) { this.handler = handler; this.scope = scope; return this; }, /** * Sets this Button's text * @param {String} text The button text. If you pass null or undefined the text will be removed. * @return {Ext.Button} this */ setText: function(text) { var me = this; if (me.rendered) { if (!me.textEl && text) { me.textEl = me.el.createChild({ tag: 'span', html: text, cls: this.labelCls }); } else if (me.textEl && text != me.text) { if (text) { me.textEl.setHTML(text); } else { me.textEl.remove(); me.textEl = null; } } } me.text = text; return me; }, /** * Sets the background image (inline style) of the button. This method also changes * the value of the {@link icon} config internally. * @param {String} icon The path to an image to display in the button. If you pass null or undefined the icon will be removed. * @return {Ext.Button} this */ setIcon: function(icon) { var me = this; if (me.rendered) { if (!me.iconEl && icon) { me.iconEl = me.el.createChild({ tag: 'img', src: Ext.BLANK_IMAGE_URL, style: 'background-image: ' + (icon ? 'url(' + icon + ')' : '') }); me.setIconAlign(me.iconAlign); } else if (me.iconEl && icon != me.icon) { if (icon) { me.iconEl.setStyle('background-image', icon ? 'url(' + icon + ')' : ''); me.setIconAlign(me.iconAlign); } else { me.setIconAlign(false); me.iconEl.remove(); me.iconEl = null; } } } me.icon = icon; return me; }, /** * Sets the CSS class that provides a background image to use as the button's icon. This method also changes * the value of the {@link iconCls} config internally. * @param {String} cls The CSS class providing the icon image. If you pass null or undefined the iconCls will be removed. * @return {Ext.Button} this */ setIconClass: function(cls) { var me = this; if (me.rendered) { if (!me.iconEl && cls) { me.iconEl = me.el.createChild({ tag: 'img', src: Ext.BLANK_IMAGE_URL, cls: cls }); me.setIconAlign(me.iconAlign); } else if (me.iconEl && cls != me.iconCls) { if (cls) { if (me.iconCls) { me.iconEl.removeCls(me.iconCls); } me.iconEl.addCls(cls); me.setIconAlign(me.iconAlign); } else { me.setIconAlign(false); me.iconEl.remove(); me.iconEl = null; } } } me.iconCls = cls; return me; }, /** * Adds a CSS class to the button that changes the align of the button's icon (if one has been defined). If no icon or iconClass has * been defined, it will only set the value of the {@link iconAlign} internal config. * @param {String} alignment The alignment you would like to align the button. Valid options are 'top', 'bottom', 'left', 'right'. * If you pass false, it will remove the current iconAlign. If you pass nothing or an invalid alignment, * it will default to the last used/default iconAlign. * @return {Ext.Button} this */ setIconAlign: function(alignment) { var me = this, alignments = ['top', 'right', 'bottom', 'left'], alignment = ((alignments.indexOf(alignment) == -1 || !alignment) && alignment !== false) ? me.iconAlign : alignment, i; if (me.rendered && me.iconEl) { me.el.removeCls('x-iconalign-' + me.iconAlign); if (alignment) me.el.addCls('x-iconalign-' + alignment); } me.iconAlign = (alignment === false) ? me.iconAlign : alignment; return me; }, /** * Creates a badge overlay on the button for displaying notifications. * @param {String} text The text going into the badge. If you pass null or undefined the badge will be removed. * @return {Ext.Button} this */ setBadge : function(text) { var me = this; if (me.rendered) { if (!me.badgeEl && text) { me.badgeEl = me.el.createChild({ tag: 'span', cls: me.badgeCls, html: text }); me.el.addCls(me.hasBadgeCls); } else if (me.badgeEl && text != me.badgeText) { if (text) { me.badgeEl.setHTML(text); me.el.addCls(me.hasBadgeCls); } else { me.badgeEl.remove(); me.badgeEl = null; me.el.removeCls(me.hasBadgeCls); } } } me.badgeText = text; return me; }, /** * Gets the text for this Button * @return {String} The button text */ getText : function() { return this.text; }, /** * Gets the text for this Button's badge * @return {String} The button text */ getBadgeText : function() { return this.badgeText; }, // @private onDisable : function() { this.onDisableChange(true); }, // @private onEnable : function() { this.onDisableChange(false); }, // @private onDisableChange : function(disabled) { var me = this; if (me.el) { me.el[disabled ? 'addCls' : 'removeCls'](me.disabledCls); me.el.dom.disabled = disabled; } me.disabled = disabled; }, // @private onPress : function(e) { var me = this; if (!me.disabled && this.fireEvent('beforetap') !== false) { setTimeout(function() { if (!me.preventCancel) { me.onTapCancel(); } me.callHandler(e); me.fireEvent('tap', me, e); }, 10); } }, // @private callHandler: function(e) { var me = this; if (me.handler) { me.handler.call(me.scope || me, me, e); } }, /** * @private * If {@link #autoEvent} is set, this creates a handler function that automatically fires that configured * event. This is called by initComponent and should never need to be called again. */ createAutoHandler: function() { var me = this, autoEvent = me.autoEvent; if (autoEvent) { if (typeof autoEvent == 'string') { autoEvent = { name: autoEvent, scope: me.scope || me }; } me.addEvents(autoEvent.name); me.setHandler(function() { autoEvent.scope.fireEvent(autoEvent.name, autoEvent.scope, me); }, autoEvent.scope); } } }); Ext.reg('button', Ext.Button);
JavaScript
/** * @class Ext.List * @extends Ext.DataView * <p>A mechanism for displaying data using a list layout template. List uses an {@link Ext.XTemplate} * as its internal templating mechanism, and is bound to an {@link Ext.data.Store} so that as the data * in the store changes the view is automatically updated to reflect the changes.</p> * <p>The view also provides built-in behavior for many common events that can occur for its contained items * including itemtap, containertap, etc. as well as a built-in selection model. <b>In order to use these * features, an {@link #itemSelector} config must be provided for the DataView to determine what nodes it * will be working with.</b></p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #itemTpl}</li> * <li>{@link #store}</li> * <li>{@link #grouped}</li> * <li>{@link #indexBar}</li> * <li>{@link #singleSelect}</li> * <li>{@link #multiSelect}</li> * </ul> * * <h2>Useful Methods</h2> * <ul class="list"> * <li>{@link #bindStore}</li> * <li>{@link #getRecord}</li> * <li>{@link #getRecords}</li> * <li>{@link #getSelectedRecords}</li> * <li>{@link #getSelectedNodes}</li> * <li>{@link #indexOf}</li> * </ul> * * <h2>Useful Events</h2> * <ul class="list"> * <li>{@link #itemtap}</li> * <li>{@link #itemdoubletap}</li> * <li>{@link #itemswipe}</li> * <li>{@link #selectionchange}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.List/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> Ext.regModel('Contact', { fields: ['firstName', 'lastName'] }); var store = new Ext.data.JsonStore({ model : 'Contact', sorters: 'lastName', getGroupString : function(record) { return record.get('lastName')[0]; }, data: [ {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Rob', lastName: 'Dougan'}, {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Jamie', lastName: 'Avins'}, {firstName: 'Aaron', lastName: 'Conran'}, {firstName: 'Dave', lastName: 'Kaneda'}, {firstName: 'Michael', lastName: 'Mullany'}, {firstName: 'Abraham', lastName: 'Elias'}, {firstName: 'Jay', lastName: 'Robinson'} ] }); var list = new Ext.List({ fullscreen: true, itemTpl : '{firstName} {lastName}', grouped : true, indexBar: true, store: store }); list.show(); </code></pre> * @constructor * Create a new List * @param {Object} config The config object * @xtype list */ Ext.List = Ext.extend(Ext.DataView, { componentCls: 'x-list', /** * @cfg {Boolean} pinHeaders * Whether or not to pin headers on top of item groups while scrolling for an iPhone native list experience * Defaults to <tt>true</tt> */ pinHeaders: (Ext.is.Android || Ext.is.Blackberry) ? false : true, /** * @cfg {Boolean/Object} indexBar * True to render an alphabet IndexBar docked on the right. * This can also be a config object that will be passed to {@link Ext.IndexBar} * (defaults to false) */ indexBar: false, /** * @cfg {Boolean} grouped * True to group the list items together (defaults to false). When using grouping, you must specify a method getGroupString * on the store so that grouping can be maintained. * <pre><code> Ext.regModel('Contact', { fields: ['firstName', 'lastName'] }); var store = new Ext.data.JsonStore({ model : 'Contact', sorters: 'lastName', getGroupString : function(record) { // Group by the last name return record.get('lastName')[0]; }, data: [ {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Rob', lastName: 'Dougan'}, {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Jamie', lastName: 'Avins'}, {firstName: 'Aaron', lastName: 'Conran'}, {firstName: 'Dave', lastName: 'Kaneda'}, {firstName: 'Michael', lastName: 'Mullany'}, {firstName: 'Abraham', lastName: 'Elias'}, {firstName: 'Jay', lastName: 'Robinson'}, {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Rob', lastName: 'Dougan'}, {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Jamie', lastName: 'Avins'}, {firstName: 'Aaron', lastName: 'Conran'}, {firstName: 'Dave', lastName: 'Kaneda'}, {firstName: 'Michael', lastName: 'Mullany'}, {firstName: 'Abraham', lastName: 'Elias'}, {firstName: 'Jay', lastName: 'Robinson'} ] }); </code></pre> */ grouped: false, /** * @cfg {Boolean} clearSelectionOnDeactivate * True to clear any selections on the list when the list is deactivated (defaults to true). */ clearSelectionOnDeactivate: true, renderTpl: [ '<tpl if="grouped"><h3 class="x-list-header x-list-header-swap x-hidden-display"></h3></tpl>' ], groupTpl : [ '<tpl for=".">', '<div class="x-list-group x-group-{id}">', '<h3 class="x-list-header">{group}</h3>', '<div class="x-list-group-items">', '{items}', '</div>', '</div>', '</tpl>' ], /** * @cfg {String} itemSelector * @private * @ignore * Not to be used. */ itemSelector: '.x-list-item', /** * @cfg {String/Array} itemTpl * The inner portion of the item template to be rendered. Follows an XTemplate * structure and will be placed inside of a tpl for in the tpl configuration. */ /** * @cfg {Boolean/Function/Object} onItemDisclosure * True to display a disclosure icon on each list item. * This won't bind a listener to the tap event. The list * will still fire the disclose event though. * By setting this config to a function, it will automatically * add a tap event listeners to the disclosure buttons which * will fire your function. * Finally you can specify an object with a 'scope' and 'handler' * property defined. This will also be bound to the tap event listener * and is useful when you want to change the scope of the handler. */ onItemDisclosure: false, // @private initComponent : function() { //<deprecated since=0.99> if (Ext.isDefined(this.dockedItems)) { console.warn("List: List is not a Panel anymore so you can't dock items to it. Please put this list inside a Panel with layout 'fit'"); } //</deprecated> //<deprecated since=0.99> if (Ext.isDefined(this.components)) { console.warn("List: The Experimental components configuration is not currently supported."); } //</deprecated> //<deprecated since=0.99> if (Ext.isDefined(this.disclosure)) { console.warn("List: The disclosure configuration has been renamed to onItemDisclosure and will be removed."); this.onItemDisclosure = this.disclosure; } //</deprecated> var memberFnsCombo = {}; //<deprecated since=0.99> if (this.tpl) { console.warn('Ext.List: The tpl config has been removed and replaced by itemTpl. Please remove tpl and itemSelector from your Lists.'); // convert from array to string if (Ext.isArray(this.tpl)) { this.tpl = this.tpl.join(''); } else if (this.tpl.html) { Ext.apply(memberFnsCombo, this.tpl.initialConfig); this.tpl = this.tpl.html; } this.tpl = Ext.util.Format.trim(this.tpl); if (this.tpl.indexOf("\"x-list-item\"") !== -1) { throw new Error("Ext.List: Using a CSS class of x-list-item within your own tpl will break Ext.Lists. Remove the x-list-item from the tpl/itemTpl"); } var tpl = this.tpl, first = '<tpl for=".">', firstLn = first.length, end = '</tpl>', tplFirst = this.tpl.substr(0, firstLn), tplEndIdx = this.tpl.lastIndexOf(end), stripped; if (tplFirst === first && tplEndIdx !== -1) { this.itemTpl = tpl.substr(firstLn, tplEndIdx - firstLn); this.itemSelector = Ext.List.prototype.itemSelector; } else { throw new Error("Ext.List: tpl to itemTpl conversion failed."); } } //</deprecated> if (Ext.isArray(this.itemTpl)) { this.itemTpl = this.itemTpl.join(''); } else if (this.itemTpl && this.itemTpl.html) { Ext.apply(memberFnsCombo, this.itemTpl.initialConfig); this.itemTpl = this.itemTpl.html; } //<debug> if (!Ext.isDefined(this.itemTpl)) { throw new Error("Ext.List: itemTpl is a required configuration."); } // this check is not enitrely fool proof, does not account for spaces or multiple classes // if the check is done without "s then things like x-list-item-entity would throw exceptions that shouldn't have. if (this.itemTpl && this.itemTpl.indexOf("\"x-list-item\"") !== -1) { throw new Error("Ext.List: Using a CSS class of x-list-item within your own tpl will break Ext.Lists. Remove the x-list-item from the tpl/itemTpl"); } //</debug> this.tpl = '<tpl for="."><div class="x-list-item"><div class="x-list-item-body">' + this.itemTpl + '</div>'; if (this.onItemDisclosure) { this.tpl += '<div class="x-list-disclosure"></div>'; } this.tpl += '</div></tpl>'; this.tpl = new Ext.XTemplate(this.tpl, memberFnsCombo); if (this.grouped) { this.listItemTpl = this.tpl; if (Ext.isString(this.listItemTpl) || Ext.isArray(this.listItemTpl)) { // memberFns will go away after removal of tpl configuration for itemTpl // this copies memberFns by storing the original configuration. this.listItemTpl = new Ext.XTemplate(this.listItemTpl, memberFnsCombo); } if (Ext.isString(this.groupTpl) || Ext.isArray(this.groupTpl)) { this.tpl = new Ext.XTemplate(this.groupTpl); } } else { this.indexBar = false; } if (this.scroll !== false) { this.scroll = { direction: 'vertical', useIndicators: !this.indexBar }; } Ext.List.superclass.initComponent.call(this); if (this.onItemDisclosure) { // disclosure can be a function that will be called when // you tap the disclosure button if (Ext.isFunction(this.onItemDisclosure)) { this.onItemDisclosure = { scope: this, handler: this.onItemDisclosure }; } } this.on('deactivate', this.onDeactivate, this); this.addEvents( /** * @event disclose * Fires when the user taps the disclosure icon on an item * @param {Ext.data.Record} record The record associated with the item * @param {Ext.Element} node The wrapping element of this node * @param {Number} index The index of this list item */ 'disclose' ); }, // @private onRender : function() { if (this.grouped) { Ext.applyIf(this.renderData, { grouped: true }); if (this.scroll) { Ext.applyIf(this.renderSelectors, { header: '.x-list-header-swap' }); } } Ext.List.superclass.onRender.apply(this, arguments); }, // @private onDeactivate : function() { if (this.clearSelectionOnDeactivate) { this.getSelectionModel().deselectAll(); } }, // @private afterRender : function() { if (!this.grouped) { this.el.addCls('x-list-flat'); } this.getTargetEl().addCls('x-list-parent'); if (this.indexBar) { this.indexBar = new Ext.IndexBar(Ext.apply({}, Ext.isObject(this.indexBar) ? this.indexBar : {}, { xtype: 'indexbar', alphabet: true, renderTo: this.el })); this.addCls('x-list-indexed'); } Ext.List.superclass.afterRender.call(this); if (this.onItemDisclosure) { this.mon(this.getTargetEl(), 'singletap', this.handleItemDisclosure, this, {delegate: '.x-list-disclosure'}); } }, // @private initEvents : function() { Ext.List.superclass.initEvents.call(this); if (this.grouped) { if (this.pinHeaders && this.scroll) { this.mon(this.scroller, { scrollstart: this.onScrollStart, scroll: this.onScroll, scope: this }); } if (this.indexBar) { this.mon(this.indexBar, { index: this.onIndex, scope: this }); } } }, //@private handleItemDisclosure : function(e, t) { var node = this.findItemByChild(t), record, index; if (node) { record = this.getRecord(node); index = this.indexOf(node); this.fireEvent('disclose', record, node, index); if (Ext.isObject(this.onItemDisclosure) && this.onItemDisclosure.handler) { this.onItemDisclosure.handler.call(this, record, node, index); } } }, /** * Set the current active group * @param {Object} group The group to set active */ setActiveGroup : function(group) { var me = this; if (group) { if (!me.activeGroup || me.activeGroup.header != group.header) { me.header.setHTML(group.header.getHTML()); me.header.show(); } } else { me.header.hide(); } this.activeGroup = group; }, // @private getClosestGroups : function(pos) { // force update if not already done if (!this.groupOffsets) { this.updateOffsets(); } var groups = this.groupOffsets, ln = groups.length, group, i, current, next; for (i = 0; i < ln; i++) { group = groups[i]; if (group.offset > pos.y) { next = group; break; } current = group; } return { current: current, next: next }; }, updateIndexes : function() { Ext.List.superclass.updateIndexes.apply(this, arguments); this.updateOffsets(); }, afterComponentLayout : function() { Ext.List.superclass.afterComponentLayout.apply(this, arguments); this.updateOffsets(); }, updateOffsets : function() { if (this.grouped) { this.groupOffsets = []; var headers = this.getTargetEl().query('h3.x-list-header'), ln = headers.length, header, i; for (i = 0; i < ln; i++) { header = Ext.get(headers[i]); header.setDisplayMode(Ext.Element.VISIBILITY); this.groupOffsets.push({ header: header, offset: header.dom.offsetTop }); } } }, // @private onScrollStart : function() { var offset = this.scroller.getOffset(); this.closest = this.getClosestGroups(offset); this.setActiveGroup(this.closest.current); }, // @private onScroll : function(scroller, pos, options) { if (!this.closest) { this.closest = this.getClosestGroups(pos); } if (!this.headerHeight) { this.headerHeight = this.header.getHeight(); } if (pos.y <= 0) { if (this.activeGroup) { this.setActiveGroup(false); this.closest.next = this.closest.current; } return; } else if ( (this.closest.next && pos.y > this.closest.next.offset) || (pos.y < this.closest.current.offset) ) { this.closest = this.getClosestGroups(pos); this.setActiveGroup(this.closest.current); } if (this.closest.next && pos.y > 0 && this.closest.next.offset - pos.y <= this.headerHeight) { var transform = this.headerHeight - (this.closest.next.offset - pos.y); Ext.Element.cssTransform(this.header, {translate: [0, -transform]}); this.transformed = true; } else if (this.transformed) { this.header.setStyle('-webkit-transform', null); this.transformed = false; } }, // @private onIndex : function(record, target, index) { var key = record.get('key').toLowerCase(), groups = this.store.getGroups(), ln = groups.length, group, i, closest, id; for (i = 0; i < ln; i++) { group = groups[i]; id = this.getGroupId(group); if (id == key || id > key) { closest = id; break; } else { closest = id; } } closest = this.getTargetEl().down('.x-group-' + id); if (closest) { this.scroller.scrollTo({x: 0, y: closest.getOffsetsTo(this.scrollEl)[1]}, false, null, true); } }, getGroupId : function(group) { return group.name.toLowerCase(); }, // @private collectData : function(records, startIndex) { if (!this.grouped) { return Ext.List.superclass.collectData.call(this, records, startIndex); } var results = [], groups = this.store.getGroups(), ln = groups.length, children, cln, c, group, i; for (i = 0, ln = groups.length; i < ln; i++) { group = groups[i]; children = group.children; for (c = 0, cln = children.length; c < cln; c++) { children[c] = children[c].data; } results.push({ group: group.name, id: this.getGroupId(group), items: this.listItemTpl.apply(children) }); } return results; }, // Because the groups might change by an update/add/remove we refresh the whole dataview // in each one of them // @private onUpdate : function(store, record) { if (this.grouped) { this.refresh(); } else { Ext.List.superclass.onUpdate.apply(this, arguments); } }, // @private onAdd : function(ds, records, index) { if (this.grouped) { this.refresh(); } else { Ext.List.superclass.onAdd.apply(this, arguments); } }, // @private onRemove : function(ds, record, index) { if (this.grouped) { this.refresh(); } else { Ext.List.superclass.onRemove.apply(this, arguments); } } }); Ext.reg('list', Ext.List);
JavaScript
/** * @class Ext.TabBar * @extends Ext.Panel * * <p>Used in the {@link Ext.TabPanel} component to display {@link Ext.Tab} components.</p> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.TabBar/screenshot.png" /></p> * * <h2>Example code:</h2> <pre><code> var bar = new Ext.TabBar({ dock : 'top', ui : 'dark', items: [ { text: '1st Button' }, { text: '2nd Button' } ] }); var myPanel = new Ext.Panel({ dockedItems: [bar], fullscreen : true, html : 'Test Panel' }); </code></pre> * * @xtype tabbar */ Ext.TabBar = Ext.extend(Ext.Panel, { componentCls: 'x-tabbar', /** * @type {Ext.Tab} * Read-only property of the currently active tab. */ activeTab: null, // @private defaultType: 'tab', /** * @cfg {Boolean} sortable * Enable sorting functionality for the TabBar. */ sortable: false, /** * @cfg {Number} sortHoldThreshold * Duration in milliseconds that a user must hold a tab * before dragging. The sortable configuration must be set for this setting * to be used. */ sortHoldThreshold: 350, // @private initComponent : function() { /** * @event change * @param {Ext.TabBar} this * @param {Ext.Tab} tab The Tab button * @param {Ext.Component} card The component that has been activated */ this.addEvents('change'); this.layout = Ext.apply({}, this.layout || {}, { type: 'hbox', align: 'middle' }); Ext.TabBar.superclass.initComponent.call(this); }, // @private initEvents : function() { if (this.sortable) { this.sortable = new Ext.util.Sortable(this.el, { itemSelector: '.x-tab', direction: 'horizontal', delay: this.sortHoldThreshold, constrain: true }); this.mon(this.sortable, 'sortchange', this.onSortChange, this); } this.mon(this.el, { touchstart: this.onTouchStart, scope: this }); Ext.TabBar.superclass.initEvents.call(this); }, // @private onTouchStart : function(e, t) { t = e.getTarget('.x-tab'); if (t) { this.onTabTap(Ext.getCmp(t.id)); } }, // @private onSortChange : function(sortable, el, index) { }, // @private onTabTap : function(tab) { if (!tab.disabled) { if (this.cardLayout) { if (this.cardSwitchAnimation) { var animConfig = { reverse: (this.items.indexOf(tab) < this.items.indexOf(this.activeTab)) ? true : false }; if (Ext.isObject(this.cardSwitchAnimation)) { Ext.apply(animConfig, this.cardSwitchAnimation); } else { Ext.apply(animConfig, { type: this.cardSwitchAnimation }); } } this.cardLayout.setActiveItem(tab.card, animConfig || this.cardSwitchAnimation); } this.activeTab = tab; this.fireEvent('change', this, tab, tab.card); } }, /** * Returns a reference to the TabPanel's layout that wraps around the TabBar. * @private */ getCardLayout : function() { return this.cardLayout; } }); Ext.reg('tabbar', Ext.TabBar);
JavaScript
/** * @class Ext.MessageBox * @extends Ext.Sheet * * <p>Utility class for generating different styles of message boxes. The framework provides a global singleton {@link Ext.Msg} for common usage.<p/> * <p>Note that the MessageBox is asynchronous. Unlike a regular JavaScript <code>alert</code> (which will halt * browser execution), showing a MessageBox will not cause the code to stop. For this reason, if you have code * that should only run <em>after</em> some user feedback from the MessageBox, you must use a callback function * (see the <code>fn</code> configuration option parameter for the {@link #show show} method for more details).</p> * * <h2>Screenshot</h2> * <p><img src="doc_resources/Ext.MessageBox/screenshot.png" /></p> * * <h2>Example usage:</h2> * <pre><code> // Basic alert: Ext.Msg.alert('Title', 'The quick brown fox jumped over the lazy dog.', Ext.emptyFn); // Prompt for user data and process the result using a callback: Ext.Msg.prompt('Name', 'Please enter your name:', function(text) { // process text value and close... }); // Confirmation alert Ext.Msg.confirm("Confirmation", "Are you sure you want to do that?", Ext.emptyFn); * </code></pre> * @xtype messagebox */ Ext.MessageBox = Ext.extend(Ext.Sheet, { // Inherited from Ext.Sheet centered: true, // Inherited renderHidden: true, // Inherited ui: 'dark', /** * @cfg {String} componentCls * Component's Base CSS class */ componentCls: 'x-msgbox', /** * @cfg {String/Mixed} enterAnimation effect when the message box is being displayed (defaults to 'pop') */ enterAnimation: 'pop', /** * @cfg {String/Mixed} exitAnimation effect when the message box is being hidden (defaults to 'pop') */ exitAnimation: 'pop', // Not sure what good this does, so I just comment it out for now // autoHeight : true, /** * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75) * @cfg {Number} defaultTextHeight */ defaultTextHeight : 75, constructor : function(config) { config = config || {}; var ui = config.ui || this.ui || '', baseCls = config.componentCls || this.componentCls; delete config.html; this.titleBar = Ext.create({ xtype : 'toolbar', ui : ui, dock : 'top', cls : baseCls + '-title', title : '&#160;' }); this.buttonBar = Ext.create({ xtype : 'toolbar', ui : ui, dock : 'bottom', layout: { pack: 'center' }, cls : baseCls + '-buttons' }); config = Ext.apply({ ui : ui, dockedItems : [this.titleBar, this.buttonBar], renderSelectors : { body : '.' + baseCls + '-body', iconEl : '.' + baseCls + '-icon', msgContentEl : '.' + baseCls + '-content', msgEl : '.' + baseCls + '-text', inputsEl : '.' + baseCls + '-inputs', inputEl : '.' + baseCls + '-input-single', multiLineEl : '.' + baseCls + '-input-textarea' } }, config || {}); Ext.MessageBox.superclass.constructor.call(this, config); }, renderTpl: [ '<div class="{componentCls}-body"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>>', '<div class="{componentCls}-icon x-hidden-display"></div>', '<div class="{componentCls}-content">', '<div class="{componentCls}-text"></div>', '<div class="{componentCls}-inputs x-hidden-display">', '<input type="text" class="{componentCls}-input {componentCls}-input-single" />', '<textarea class="{componentCls}-input {componentCls}-input-textarea"></textarea>', '</div>', '</div>', '</div>' ], // @private onClick : function(button) { if (button) { var config = button.config || {}; if (typeof config.fn == 'function') { config.fn.call( config.scope || null, button.itemId || button.text, config.input ? config.input.dom.value : null, config ); } if (config.cls) { this.el.removeCls(config.cls); } if (config.input) { config.input.dom.blur(); } } this.hide(); }, /** * Displays a new message box, or reinitializes an existing message box, based on the config options * passed in. All display functions (e.g. prompt, alert, etc.) on MessageBox call this function internally, * although those calls are basic shortcuts and do not support all of the config options allowed here. * @param {Object} config The following config options are supported: <ul> * <li><b>buttons</b> : Object/Array<div class="sub-desc">A button config object or Array of the same(e.g., Ext.MessageBox.OKCANCEL or {text:'Foo', * itemId:'cancel'}), or false to not show any buttons (defaults to false)</div></li> * <li><b>cls</b> : String<div class="sub-desc">A custom CSS class to apply to the message box's container element</div></li> * <li><b>defaultTextHeight</b> : Number<div class="sub-desc">The default height in pixels of the message box's multiline textarea * if displayed (defaults to 75)</div></li> * <li><b>fn</b> : Function<div class="sub-desc">A callback function which is called when the dialog is dismissed * by clicking on the configured buttons. * <p>Parameters passed:<ul> * <li><b>buttonId</b> : String<div class="sub-desc">The itemId of the button pressed, one of:<div class="sub-desc"><ul> * <li><tt>ok</tt></li> * <li><tt>yes</tt></li> * <li><tt>no</tt></li> * <li><tt>cancel</tt></li> * </ul></div></div></li> * <li><b>value</b> : String<div class="sub-desc">Value of the input field if either <tt><a href="#show-option-prompt" ext:member="show-option-prompt" ext:cls="Ext.MessageBox">prompt</a></tt> * or <tt><a href="#show-option-multiLine" ext:member="show-option-multiLine" ext:cls="Ext.MessageBox">multiLine</a></tt> is true</div></li> * <li><b>opt</b> : Object<div class="sub-desc">The config object passed to show.</div></li> * </ul></p></div></li> * <li><b>width</b> : Number<div class="sub-desc">A fixed width for the MessageBox (defaults to 'auto')</div></li> * <li><b>height</b> : Number<div class="sub-desc">A fixed height for the MessageBox (defaults to 'auto')</div></li> * <li><b>scope</b> : Object<div class="sub-desc">The scope of the callback function</div></li> * <li><b>icon</b> : String<div class="sub-desc">A CSS class that provides a background image to be used as the body icon for the * dialog (e.g. Ext.MessageBox.WARNING or 'custom-class') (defaults to '')</div></li> * <li><b>modal</b> : Boolean<div class="sub-desc">False to allow user interaction with the page while the message box is * displayed (defaults to true)</div></li> * <li><b>msg</b> : String<div class="sub-desc">A string that will replace the existing message box body text (defaults to the * XHTML-compliant non-breaking space character '&amp;#160;')</div></li> * <li><a id="show-option-multiline"></a><b>multiLine</b> : Boolean<div class="sub-desc"> * True to prompt the user to enter multi-line text (defaults to false)</div></li> * <li><a id="show-option-prompt"></a><b>prompt</b> : Boolean<div class="sub-desc">True to prompt the user to enter single-line text (defaults to false)</div></li> * <li><b>title</b> : String<div class="sub-desc">The title text</div></li> * <li><b>value</b> : String<div class="sub-desc">The string value to set into the active textbox element if displayed</div></li> * </ul> * Example usage: * <pre><code> Ext.Msg.show({ title: 'Address', msg: 'Please enter your address:', width: 300, buttons: Ext.MessageBox.OKCANCEL, multiLine: true, prompt : { maxlength : 180, autocapitalize : true }, fn: saveAddress, icon: Ext.MessageBox.INFO }); </code></pre> * @return {Ext.MessageBox} this */ show : function(config) { var attrib, attrName, attribs = { autocomplete : 'off', autocapitalize : 'off', autocorrect : 'off', maxlength : 0, autofocus : true, placeholder : '', type : 'text' }, assert = /true|on/i; this.rendered || this.render(document.body); config = Ext.applyIf( config || {}, { multiLine : false, prompt : false, value : '', modal : true } ); if (config.title) { this.titleBar.setTitle(config.title); this.titleBar.show(); } else { this.titleBar.hide(); } if (this.inputsEl && (config.multiLine || config.prompt)) { this.inputsEl.show(); if (this.multiLineEl && config.multiLine) { this.inputEl && this.inputEl.hide(); this.multiLineEl.show().setHeight(Ext.isNumber(config.multiLine) ? parseFloat(config.multiLine) : this.defaultTextHeight); config.input = this.multiLineEl; } else if (this.inputEl) { this.inputEl.show(); this.multiLineEl && this.multiLineEl.hide(); config.input = this.inputEl; } // Assert/default HTML5 input attributes if (Ext.isObject(config.prompt)) { Ext.apply(attribs, config.prompt); } for (attrName in attribs) { if (attribs.hasOwnProperty(attrName)) { attrib = attribs[attrName]; config.input.dom.setAttribute( attrName.toLowerCase(), /^auto/i.test(attrName) ? (assert.test(attrib+'') ? 'on' : 'off' ) : attrib ); } } } else { this.inputsEl && this.inputsEl.hide(); } this.setIcon(config.icon || '', false); this.updateText(config.msg, false); if (config.cls) { this.el.addCls(config.cls); } this.modal = !!config.modal; var bbar = this.buttonBar, bs = []; bbar.removeAll(); Ext.each([].concat(config.buttons || Ext.MessageBox.OK), function(button) { if (button) { bs.push( Ext.applyIf({ config : config, scope : this, handler : this.onClick }, button) ); } }, this); bbar.add(bs); if (bbar.rendered) { bbar.doLayout(); } Ext.MessageBox.superclass.show.call(this, config.animate); if (config.input) { config.input.dom.value = config.value || ''; // For browsers without 'autofocus' attribute support if (assert.test(attribs.autofocus+'') && !('autofocus' in config.input.dom)) { config.input.dom.focus(); } } return this; }, // @private onOrientationChange : function() { this.doComponentLayout(); Ext.MessageBox.superclass.onOrientationChange.apply(this, arguments); }, // @private adjustScale : function(){ Ext.apply(this,{ maxWidth : window.innerWidth, maxHeight : window.innerHeight, minWidth : window.innerWidth * .5, minHeight : window.innerHeight * .5 }); }, // @private doComponentLayout : function() { this.adjustScale(); return Ext.MessageBox.superclass.doComponentLayout.apply(this, arguments); }, /** * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript alert prompt). * If a callback function is passed it will be called after the user clicks the button, and the * itemId of the button that was clicked will be passed as the only parameter to the callback * @param {String} title The title bar text * @param {String} msg The message box body text * @param {Function} fn (optional) The callback function invoked after the message box is closed * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow. * @return {Ext.MessageBox} this */ alert : function(title, msg, fn, scope) { return this.show({ title : title, msg : msg, buttons: Ext.MessageBox.OK, fn : fn, scope : scope, icon : Ext.MessageBox.INFO }); }, /** * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's confirm). * If a callback function is passed it will be called after the user clicks either button, * and the id of the button that was clicked will be passed as the only parameter to the callback * (could also be the top-right close button). * @param {String} title The title bar text * @param {String} msg The message box body text * @param {Function} fn (optional) The callback function invoked when user taps on the OK/Cancel button. * The button is passed as the first argument. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow. * @return {Ext.MessageBox} this */ confirm : function(title, msg, fn, scope) { return this.show({ title : title, msg : msg, buttons: Ext.MessageBox.YESNO, fn: function(button) { fn.call(scope, button); }, scope : scope, icon: Ext.MessageBox.QUESTION }); }, /** * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to JavaScript's prompt). * The prompt can be a single-line or multi-line textbox. If a callback function is passed it will be called after the user * clicks either button, and the id of the button that was clicked (could also be the top-right * close button) and the text that was entered will be passed as the two parameters to the callback. * @param {String} title The title bar text * @param {String} msg The message box body text * @param {Function} fn (optional) The callback function invoked when the user taps on the OK/Cancel button, * the button is passed as the first argument, the entered string value is passed as the second argument * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to the browser wnidow. * @param {Boolean/Number} multiLine (optional) True to create a multiline textbox using the defaultTextHeight * property, or the height in pixels to create the textbox (defaults to false / single-line) * @param {String} value (optional) Default value of the text input element (defaults to '') * @param {Object} promptConfig <div class="sub-desc">(optional) A hash collection of input attribute values.<div class="sub-desc">Specified values may include:<ul> * <li><tt>focus</tt> : Boolean <div class="sub-desc"><tt>true</tt> to assert initial input focus (defaults to false)</div></li> * <li><tt>placeholder</tt> : String <div class="sub-desc">String value rendered when the input field is empty (defaults to empty string)</div></li> * <li><tt>autocapitalize</tt> : String/Boolean <div class="sub-desc"><tt>true/on</tt> to capitalize the first letter of each word in the input value (defaults to 'off')</div></li> * <li><tt>autocorrect</tt> : String/Boolean <div class="sub-desc"><tt>true/on</tt> to enable spell-checking/autocorrect features if supported by the browser (defaults to 'off')</div></li> * <li><tt>autocomplete</tt> : String/Boolean <div class="sub-desc"><tt>true/on</tt> to enable autoCompletion of supplied text input values if supported by the browser (defaults to 'off')</div></li> * <li><tt>maxlength</tt> : Number <div class="sub-desc">Maximum number of characters allowed in the input if supported by the browser (defaults to 0)</div></li> * <li><tt>type</tt> : String <div class="sub-desc">The type of input field. Possible values (if supported by the browser) may include (text, search, number, range, color, tel, url, email, date, month, week, time, datetime) (defaults to 'text')</div></li> * </ul></div></div> * Example usage: * <pre><code> Ext.Msg.prompt( 'Welcome!', 'What\'s your name going to be today?', function(value){ console.log(value) }, null, false, null, { autocapitalize : true, placeholder : 'First-name please...' } ); * </code></pre> * @return {Ext.MessageBox} this */ prompt : function(title, msg, fn, scope, multiLine, value, promptConfig) { return this.show({ title : title, msg : msg, buttons: Ext.MessageBox.OKCANCEL, fn: function(button, inputValue) { fn.call(scope, button, inputValue); }, scope : scope, icon : Ext.MessageBox.QUESTION, prompt: promptConfig || true, multiLine: multiLine, value: value }); }, /** * Updates the message box body text * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to * the XHTML-compliant non-breaking space character '&amp;#160;') * @return {Ext.MessageBox} this */ updateText : function(text, doLayout) { if(this.msgEl) { this.msgEl.update(text ? String(text) : '&#160;'); if(doLayout !== false) { this.doComponentLayout(); } } return this; }, /** * Adds the specified icon to the dialog. By default, the class 'x-msgbox-icon' is applied for default * styling, and the class passed in is expected to supply the background image url. Pass in empty string ('') * to clear any existing icon. This method must be called before the MessageBox is shown. * The following built-in icon classes are supported, but you can also pass in a custom class name: * <pre> Ext.MessageBox.INFO Ext.MessageBox.WARNING Ext.MessageBox.QUESTION Ext.MessageBox.ERROR *</pre> * @param {String} icon A CSS classname specifying the icon's background image url, or empty string to clear the icon * @return {Ext.MessageBox} this */ setIcon : function(icon, doLayout) { if (icon) { this.iconEl.show(); this.iconEl.replaceCls(this.iconCls, icon); } else { this.iconEl.replaceCls(this.iconCls, 'x-hidden-display'); } if (doLayout !== false) { this.doComponentLayout(); } this.iconCls = icon; return this; } }); (function(){ var B = Ext.MessageBox; Ext.apply(B, { OK : {text : 'OK', itemId : 'ok', ui : 'action' }, CANCEL : {text : 'Cancel', itemId : 'cancel'}, YES : {text : 'Yes', itemId : 'yes', ui : 'action' }, NO : {text : 'No', itemId : 'no'}, // Add additional(localized) button configs here // ICON CSS Constants INFO : 'x-msgbox-info', WARNING : 'x-msgbox-warning', QUESTION : 'x-msgbox-question', ERROR : 'x-msgbox-error' }); Ext.apply(B, { OKCANCEL : [B.CANCEL, B.OK], YESNOCANCEL : [B.CANCEL, B.NO, B.YES], YESNO : [B.NO, B.YES] // Add additional button collections here }); })(); Ext.reg('messagebox', Ext.MessageBox); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('msgbox', Ext.MessageBox); /** * @class Ext.Msg * * <p>A global shared singleton instance of the {@link Ext.MessageBox} class. See {@link Ext.MessageBox} for documentation.</p> * * @singleton */ Ext.Msg = new Ext.MessageBox();
JavaScript
/** * @class Ext.TabPanel * @extends Ext.Panel * * TabPanel is a Container which can hold other components to be accessed in a tabbed * interface. It uses a {@link Ext.TabBar} to display a {@link Ext.Tab} for each item defined. * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #ui}</li> * <li>{@link #tabBarDock}</li> * <li>{@link #cardSwitchAnimation}</li> * <li>{@link #sortable}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.TabPanel/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> new Ext.TabPanel({ fullscreen: true, ui : 'dark', sortable : true, items: [ { title: 'Tab 1', html : '1', cls : 'card1' }, { title: 'Tab 2', html : '2', cls : 'card2' }, { title: 'Tab 3', html : '3', cls : 'card3' } ] });</code></pre> * @xtype tabpanel */ Ext.TabPanel = Ext.extend(Ext.Panel, { /** * @cfg {String} cardSwitchAnimation * Animation to be used during transitions of cards. * Any valid value from Ext.anims can be used ('fade', 'slide', 'flip', 'cube', 'pop', 'wipe'), or false. * Defaults to <tt>'slide'</tt>. */ cardSwitchAnimation: 'slide', /** * @cfg {String} tabBarDock * Where to dock the Ext.TabPanel. Valid values are 'top' and 'bottom'. */ tabBarDock: 'top', componentCls: 'x-tabpanel', /** * @cfg {String} ui * Defaults to 'dark'. */ ui: 'dark', /** * @cfg {Object} layout * @hide */ /** * @cfg {Object} tabBar * An Ext.TabBar configuration */ /** * @cfg {Boolean} sortable * Enable sorting functionality for the TabBar. */ // @private initComponent : function() { //<deprecated since=0.99> if (Ext.isDefined(this.tabBarPosition)) { throw new Error("TabPanel: tabBarPosition has been removed. Please use tabBarDock."); } //</deprecated> var layout = new Ext.layout.CardLayout(this.layout || {}); this.layout = null; this.setLayout(layout); this.tabBar = new Ext.TabBar(Ext.apply({}, this.tabBar || {}, { cardLayout: layout, cardSwitchAnimation: this.cardSwitchAnimation, dock: this.tabBarDock, ui: this.ui, sortable: this.sortable })); if (this.dockedItems && !Ext.isArray(this.dockedItems)) { this.dockedItems = [this.dockedItems]; } else if (!this.dockedItems) { this.dockedItems = []; } this.dockedItems.push(this.tabBar); Ext.TabPanel.superclass.initComponent.call(this); }, /** * Retrieves a reference to the Ext.TabBar associated with the TabPanel. * @returns {Ext.TabBar} tabBar */ getTabBar : function() { return this.tabBar; }, // whenever a component is added to the TabPanel, add a // tab into the tabBar onAdd: function(cmp, idx) { var tabBar = this.tabBar; // maintain cross reference between tab and card cmp.tab = tabBar.insert(idx, { xtype: 'tab', card: cmp }); tabBar.doLayout(); }, onRemove: function(cmp, autoDestroy) { // remove the tab from the tabBar this.tabBar.remove(cmp.tab, autoDestroy); this.tabBar.doLayout(); } }); Ext.reg('tabpanel', Ext.TabPanel);
JavaScript
/** * @class Ext.Video * @extends Ext.Media * * <p>Provides a simple Container for HTML5 Video.</p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #url}</li> * <li>{@link #autoPause}</li> * <li>{@link #autoResume}</li> * </ul> * * <h2>Useful Methods</h2> * <ul class="list"> * <li>{@link #pause}</li> * <li>{@link #play}</li> * <li>{@link #toggle}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Video/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> var pnl = new Ext.Panel({ fullscreen: true, items: [ { xtype : 'video', x : 600, y : 300, width : 175, height : 98, url : "porsche911.mov", posterUrl: 'porsche.png' } ] });</code></pre> * @xtype video */ Ext.Video = Ext.extend(Ext.Media, { /** * @constructor * @param {Object} config * Create a new Video Panel. */ /** * @cfg {String} url * Location of the video to play. This should be in H.264 format and in a * .mov file format. */ /** * @cfg {String} posterUrl * Location of a poster image to be shown before showing the video. */ posterUrl: '', // private componentCls: 'x-video', afterRender : function() { Ext.Video.superclass.afterRender.call(this); if (this.posterUrl) { this.media.hide(); this.ghost = this.el.createChild({ cls: 'x-video-ghost', style: 'width: 100%; height: 100%; background: #000 url(' + this.posterUrl + ') center center no-repeat; -webkit-background-size: 100% auto;' }); this.ghost.on('tap', this.onGhostTap, this, {single: true}); } }, onGhostTap: function(){ this.media.show(); this.ghost.hide(); this.play(); }, // private getConfiguration: function(){ return { tag: 'video', width: '100%', height: '100%' }; } }); Ext.reg('video', Ext.Video);
JavaScript
/** * @class Ext.DataView * @extends Ext.Component * A mechanism for displaying data using custom layout templates and formatting. DataView uses an {@link Ext.XTemplate} * as its internal templating mechanism, and is bound to an {@link Ext.data.Store} * so that as the data in the store changes the view is automatically updated to reflect the changes. The view also * provides built-in behavior for many common events that can occur for its contained items including itemtap, itemdoubletap, itemswipe, containertap, * etc. as well as a built-in selection model. <b>In order to use these features, an {@link #itemSelector} * config must be provided for the DataView to determine what nodes it will be working with.</b> * * <p>The example below binds a DataView to a {@link Ext.data.Store} and renders it into an {@link Ext.Panel}.</p> * <pre><code> var store = new Ext.data.JsonStore({ url: 'get-images.php', root: 'images', fields: [ 'name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date', dateFormat:'timestamp'} ] }); store.load(); var tpl = new Ext.XTemplate( '&lt;tpl for="."&gt;', '&lt;div class="thumb-wrap" id="{name}"&gt;', '&lt;div class="thumb"&gt;&lt;img src="{url}" title="{name}"&gt;&lt;/div&gt;', '&lt;span class="x-editable"&gt;{shortName}&lt;/span&gt;&lt;/div&gt;', '&lt;/tpl&gt;', '&lt;div class="x-clear"&gt;&lt;/div&gt;' ); var panel = new Ext.Panel({ id:'images-view', frame:true, width:535, autoHeight:true, collapsible:true, layout:'fit', title:'Simple DataView', items: new Ext.DataView({ store: store, tpl: tpl, autoHeight:true, multiSelect: true, overClass:'x-view-over', itemSelector:'div.thumb-wrap', emptyText: 'No images to display' }) }); panel.render(Ext.getBody()); </code></pre> * @constructor * Create a new DataView * @param {Object} config The config object * @xtype dataview */ Ext.DataView.override({ scroll: 'vertical', /** * @cfg {String} pressedCls * A CSS class to apply to an item on the view while it is being pressed (defaults to 'x-item-pressed'). */ pressedCls : "x-item-pressed", /** * @cfg {Number} pressedDelay * The amount of delay between the tapstart and the moment we add the pressedCls. * Settings this to true defaults to 100ms */ pressedDelay: 100, /** * @cfg {Boolean} allowDeselect Only respected if {@link #singleSelect} is true. If this is set to false, * a selected item will not be deselected when tapped on, ensuring that once an item has been selected at * least one item will always be selected. Defaults to allowed (true). */ allowDeselect: true, /** * @cfg {String} triggerEvent * Defaults to 'singletap'. Other valid options are 'tap' */ triggerEvent: 'singletap', triggerCtEvent: 'containertap', // @private addCmpEvents: function() { //<deprecated since=0.99> if (Ext.isDefined(this.forceSelection)) { throw new Error("DataView: forceSelection has been replaced by allowDeselect."); } //</deprecated> this.addEvents( /** * @event itemtap * Fires when a node is tapped on * @param {Ext.DataView} this The DataView object * @param {Number} index The index of the item that was tapped * @param {Ext.Element} item The item element * @param {Ext.EventObject} e The event object */ 'itemtap', /** * @event itemdoubletap * Fires when a node is double tapped on * @param {Ext.DataView} this The DataView object * @param {Number} index The index of the item that was tapped * @param {Ext.Element} item The item element * @param {Ext.EventObject} e The event object */ 'itemdoubletap', /** * @event itemswipe * Fires when a node is swipped * @param {Ext.DataView} this The DataView object * @param {Number} index The index of the item that was tapped * @param {Ext.Element} item The item element * @param {Ext.EventObject} e The event object */ 'itemswipe', /** * @event containertap * Fires when a tap occurs and it is not on a template node. * @param {Ext.DataView} this * @param {Ext.EventObject} e The raw event object */ "containertap", /** * @event selectionchange * Fires when the selected nodes change. * @param {Ext.DataView} this * @param {Array} selections Array of the selected nodes * @param {Array} records Array of the selected records */ "selectionchange", /** * @event beforeselect * Fires before a selection is made. If any handlers return false, the selection is cancelled. * @param {Ext.DataView} this * @param {HTMLElement} node The node to be selected * @param {Array} selections Array of currently selected nodes */ "beforeselect" ); }, // @private afterRender: function() { var me = this; Ext.DataView.superclass.afterRender.call(me); var eventHandlers = { tapstart : me.onTapStart, tapcancel: me.onTapCancel, touchend : me.onTapCancel, doubletap: me.onDoubleTap, swipe : me.onSwipe, scope : me }; eventHandlers[this.triggerEvent] = me.onTap; me.mon(me.getTargetEl(), eventHandlers); if (this.store) { this.bindStore(this.store, true); } }, // @private onTap: function(e) { var item = this.findTargetByEvent(e); if (item) { Ext.fly(item).removeCls(this.pressedCls); var index = this.indexOf(item); if (this.onItemTap(item, index, e) !== false) { this.fireEvent("itemtap", this, index, item, e); } } else { if(this.fireEvent("containertap", this, e) !== false) { this.onContainerTap(e); } } }, // @private onTapStart: function(e, t) { var me = this, item = this.findTargetByEvent(e); if (item) { if (me.pressedDelay) { if (me.pressedTimeout) { clearTimeout(me.pressedTimeout); } me.pressedTimeout = setTimeout(function() { Ext.fly(item).addCls(me.pressedCls); }, Ext.isNumber(me.pressedDelay) ? me.pressedDelay : 100); } else { Ext.fly(item).addCls(me.pressedCls); } } }, // @private onTapCancel: function(e, t) { var me = this, item = this.findTargetByEvent(e); if (me.pressedTimeout) { clearTimeout(me.pressedTimeout); delete me.pressedTimeout; } if (item) { Ext.fly(item).removeCls(me.pressedCls); } }, // @private onContainerTap: function(e) { //if (this.allowDeselect) { // this.clearSelections(); //} }, // @private onDoubleTap: function(e) { var item = this.findTargetByEvent(e); if (item) { this.fireEvent("itemdoubletap", this, this.indexOf(item), item, e); } }, // @private onSwipe: function(e) { var item = this.findTargetByEvent(e); if (item) { this.fireEvent("itemswipe", this, this.indexOf(item), item, e); } }, // @private onItemTap: function(item, index, e) { if (this.pressedTimeout) { clearTimeout(this.pressedTimeout); delete this.pressedTimeout; } return true; } });
JavaScript
/** * @class Ext.Picker * @extends Ext.Sheet * * <p>A general picker class. Slots are used to organize multiple scrollable slots into a single picker. {@link #slots} is * the only necessary property</p> * * <h2>Example usage:</h2> * <pre><code> var picker = new Ext.Picker({ slots: [ { name : 'limit_speed', title: 'Speed', data : [ {text: '50 KB/s', value: 50}, {text: '100 KB/s', value: 100}, {text: '200 KB/s', value: 200}, {text: '300 KB/s', value: 300} ] } ] }); picker.show(); * </code></pre> * * @constructor * Create a new List * @param {Object} config The config object * @xtype picker */ Ext.Picker = Ext.extend(Ext.Sheet, { /** * @cfg {String} componentCls * The main component class */ componentCls: 'x-picker', stretchX: true, stretchY: true, hideOnMaskTap: false, /** * @cfg {String/Mixed} doneButton * Can be either:<ul> * <li>A {String} text to be used on the Done button</li> * <li>An {Object} as config for {@link Ext.Button}</li> * <li>false or null to hide it</li></ul> * * Defaults to 'Done'. */ doneButton: 'Done', /** * @cfg {String/Mixed} doneButton * Can be either:<ul> * <li>A {String} text to be used on the Done button</li> * <li>An {Object} as config for {@link Ext.Button}</li> * <li>false or null to hide it</li></ul> * * Defaults to 'Done'. */ cancelButton: 'Cancel', /** * @cfg {Number} height * The height of the picker. * Defaults to 220 */ height: 220, /** * @cfg {Boolean} useTitles * Generate a title header for each individual slot and use * the title configuration of the slot. * Defaults to false. */ useTitles: false, /** * @cfg {String} activeCls * CSS class to be applied to individual list items when they have * been chosen. */ // activeCls: 'x-picker-active-item', /** * @cfg {Array} slots * An array of slot configurations. * <ul> * <li>name - {String} - Name of the slot</li> * <li>align - {String} - Alignment of the slot. left, right, or center</li> * <li>items - {Array} - An array of text/value pairs in the format {text: 'myKey', value: 'myValue'}</li> * <li>title - {String} - Title of the slot. This is used in conjunction with useTitles: true.</li> * </ul> */ // // chosenCls: 'x-picker-chosen-item', // private defaultType: 'pickerslot', // private initComponent : function() { //<deprecated since="0.99"> if (Ext.isDefined(this.showDoneButton)) { console.warn("[Ext.Picker] showDoneButton config is deprecated. Please use doneButton instead"); } if (Ext.isDefined(this.doneText)) { console.warn("[Ext.Picker] doneText config is deprecated. Please use doneButton instead"); this.doneButton = this.doneText; } //</deprecated> this.addEvents( /** * @event pick * Fired when a slot has been picked * @param {Ext.Picker} this This Picker * @param {Object} The values of this picker's slots, in {name:'value'} format * @param {Ext.Picker.Slot} slot An instance of Ext.Picker.Slot that has been picked */ 'pick', /** * @event change * Fired when the picked value has changed * @param {Ext.Picker} this This Picker * @param {Object} The values of this picker's slots, in {name:'value'} format */ 'change', /** * @event cancel * Fired when the cancel button is tapped and the values are reverted back to * what they were * @param {Ext.Picker} this This Picker */ 'cancel' ); this.layout = { type: 'hbox', align: 'stretch' }; if (this.slots) { this.items = this.items ? (Ext.isArray(this.items) ? this.items : [this.items]) : []; this.items = this.items.concat(this.slots); } if (this.useTitles) { this.defaults = Ext.applyIf(this.defaults || {}, { title: '' }); } this.on('slotpick', this.onSlotPick, this); if (this.doneButton || this.cancelButton) { var toolbarItems = []; if (this.cancelButton) { toolbarItems.push( Ext.apply( { ui: 'decline', handler: this.onCancelButtonTap, scope: this }, ((Ext.isObject(this.cancelButton) ? this.cancelButton : { text: String(this.cancelButton) })) ) ); } toolbarItems.push({xtype: 'spacer'}); if (this.doneButton) { toolbarItems.push( Ext.apply( { ui: 'action', handler: this.onDoneButtonTap, scope: this }, ((Ext.isObject(this.doneButton) ? this.doneButton : { text: String(this.doneButton) })) ) ); } this.toolbar = new Ext.Toolbar(Ext.applyIf(this.buttonBar || { dock: 'top', items: toolbarItems, defaults: { xtype: 'button' } })); this.dockedItems = this.dockedItems ? (Ext.isArray(this.dockedItems) ? this.dockedItems : [this.dockedItems]) : []; this.dockedItems.push(this.toolbar); } Ext.Picker.superclass.initComponent.call(this); }, // @private afterRender: function() { Ext.Picker.superclass.afterRender.apply(this, arguments); if (this.value) { this.setValue(this.value, false); } }, /** * @private * Called when the done button has been tapped. */ onDoneButtonTap : function() { var anim = this.animSheet('exit'); Ext.apply(anim, { after: function() { this.fireEvent('change', this, this.getValue()); }, scope: this }); this.hide(anim); }, /** * @private * Called when the cancel button has been tapped. */ onCancelButtonTap : function() { var anim = this.animSheet('exit'); Ext.apply(anim, { after: function() { // Set the value back to what it was previously this.setValue(this.values); this.fireEvent('cancel', this); }, scope: this }); this.hide(anim); }, /** * @private * Called when a slot has been picked. */ onSlotPick: function(slot, value, node) { this.fireEvent('pick', this, this.getValue(), slot); return false; }, /** * Sets the values of the pickers slots * @param {Object} values The values in a {name:'value'} format * @param {Boolean} animated True to animate setting the values * @return {Ext.Picker} this This picker */ setValue: function(values, animated) { var slot, items = this.items.items, ln = items.length; // Value is an object with keys mapping to slot names if (!values) { for (var i = 0; i < ln; i++) { items[i].setValue(0); } return this; } Ext.iterate(values, function(key, value) { slot = this.child('[name=' + key + ']'); if (slot) { slot.setValue(value, animated); } }, this); this.values = values; return this; }, /** * Returns the values of each of the pickers slots * @return {Object} The values of the pickers slots */ getValue: function() { var values = {}, items = this.items.items, ln = items.length, item, i; for (i = 0; i < ln; i++) { item = items[i]; values[item.name] = item.getValue(); } return values; } }); Ext.regModel('x-textvalue', { fields: ['text', 'value'] }); /** * @private * @class Ext.Picker.Slot * @extends Ext.DataView * * <p>A general picker slot class. Slots are used to organize multiple scrollable slots into a single picker * See also: {@link Ext.Picker}</p> * * @constructor * Create a new Picker Slot * @param {Object} config The config object * @xtype pickerslot */ Ext.Picker.Slot = Ext.extend(Ext.DataView, { isSlot: true, flex: 1, /** * @cfg {String} name * The name of this slot. This config option is required. */ name: null, /** * @cfg {String} displayField * The display field in the store. * Defaults to 'text'. */ displayField: 'text', /** * @cfg {String} valueField * The value field in the store. * Defaults to 'value'. */ valueField: 'value', /** * @cfg {String} align * The alignment of this slot. * Defaults to 'center' */ align: 'center', /** * @hide * @cfg {String} itemSelector */ itemSelector: 'div.x-picker-item', /** * @private * @cfg {String} componentCls * The main component class */ componentCls: 'x-picker-slot', /** * @private * @cfg {Ext.Template/Ext.XTemplate/Array} renderTpl * The renderTpl of the slot. */ renderTpl : [ '<div class="x-picker-mask">', '<div class="x-picker-bar"></div>', '</div>' ], /** * @private * The current selectedIndex of the picker slot */ selectedIndex: 0, /** * @private */ getElConfig: function() { return { tag: 'div', id: this.id, cls: 'x-picker-' + this.align }; }, /** * @private */ initComponent : function() { // <debug> if (!this.name) { throw new Error('Each picker slot is required to have a name.'); } // </debug> Ext.apply(this.renderSelectors, { mask: '.x-picker-mask', bar: '.x-picker-bar' }); this.scroll = { direction: 'vertical', useIndicators: false, friction: 0.7, acceleration: 25, snapDuration: 150, animationDuration: 150 }; this.tpl = new Ext.XTemplate([ '<tpl for=".">', '<div class="x-picker-item {cls} <tpl if="extra">x-picker-invalid</tpl>">{' + this.displayField + '}</div>', '</tpl>' ]); var data = this.data, parsedData = [], ln = data && data.length, i, item, obj; if (data && Ext.isArray(data) && ln) { for (i = 0; i < ln; i++) { item = data[i]; obj = {}; if (Ext.isArray(item)) { obj[this.valueField] = item[0]; obj[this.displayField] = item[1]; } else if (Ext.isString(item)) { obj[this.valueField] = item; obj[this.displayField] = item; } else if (Ext.isObject(item)) { obj = item; } parsedData.push(obj); } this.store = new Ext.data.Store({ model: 'x-textvalue', data: parsedData }); this.tempStore = true; } else if (this.store) { this.store = Ext.StoreMgr.lookup(this.store); } this.enableBubble('slotpick'); if (this.title) { this.title = new Ext.Component({ dock: 'top', componentCls: 'x-picker-slot-title', html: this.title }); this.dockedItems = this.title; } Ext.Picker.Slot.superclass.initComponent.call(this); if (this.value !== undefined) { this.setValue(this.value, false); } }, /** * @private */ setupBar: function() { this.el.setStyle({padding: ''}); var padding = this.bar.getY() - this.el.getY(); this.barHeight = this.bar.getHeight(); this.el.setStyle({ padding: padding + 'px 0' }); this.slotPadding = padding; this.scroller.updateBoundary(); this.scroller.setSnap(this.barHeight); this.setSelectedNode(this.selectedIndex, false); }, /** * @private */ afterComponentLayout: function() { // Dont call superclass afterComponentLayout since we dont want // the scroller to get a min-height Ext.defer(this.setupBar, 200, this); }, /** * @private */ initEvents: function() { this.mon(this.scroller, { scrollend: this.onScrollEnd, scope: this }); }, /** * @private */ onScrollEnd: function(scroller, offset) { this.selectedNode = this.getNode(Math.round(offset.y / this.barHeight)); this.selectedIndex = this.indexOf(this.selectedNode); this.fireEvent('slotpick', this, this.getValue(), this.selectedNode); }, /** * @private */ scrollToNode: function(node, animate) { var offsetsToBody = Ext.fly(node).getOffsetsTo(this.scrollEl)[1]; this.scroller.scrollTo({ y: offsetsToBody }, animate !== false ? true : false); }, /** * @private * Called when an item has been tapped */ onItemTap: function(node) { Ext.Picker.Slot.superclass.onItemTap.apply(this, arguments); this.setSelectedNode(node); }, /** * */ getSelectedNode: function() { return this.selectedNode; }, /** * */ setSelectedNode: function(selected, animate) { // If it is a number, we assume we are dealing with an index if (Ext.isNumber(selected)) { selected = this.getNode(selected); } else if (selected.isModel) { selected = this.getNode(this.store.indexOf(selected)); } // If its not a model or a number, we assume its a node if (selected) { this.selectedNode = selected; this.selectedIndex = this.indexOf(selected); this.scrollToNode(selected, animate); } }, /** * */ getValue: function() { var record = this.store.getAt(this.selectedIndex); return record ? record.get(this.valueField) : null; }, /** * */ setValue: function(value, animate) { var index = this.store.find(this.valueField, value); if (index != -1) { if (!this.rendered) { this.selectedIndex = index; return; } this.setSelectedNode(index, animate); } }, onDestroy: function() { if (this.tempStore) { this.store.destroyStore(); this.store = null; } Ext.Picker.Slot.superclass.onDestroy.call(this); } }); Ext.reg('pickerslot', Ext.Picker.Slot);
JavaScript
/** * @class Ext.Toolbar * @extends Ext.Container * * <p>Toolbars are most commonly used as dockedItems within an Ext.Panel. They can * be docked at the 'top' or 'bottom' of a Panel by specifying the dock config.</p> * * <p>The {@link #defaultType} of Toolbar's is '{@link Ext.Button button}'.</p> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Toolbar/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> var myToolbar = new Ext.Toolbar({ dock : 'top', title: 'My Toolbar', items: [ { text: 'My Button' } ] }); var myPanel = new Ext.Panel({ dockedItems: [myToolbar], fullscreen : true, html : 'Test Panel' });</code></pre> * @xtype toolbar */ Ext.Toolbar = Ext.extend(Ext.Container, { // private isToolbar: true, /** * @cfg {xtype} defaultType * The default xtype to create. (Defaults to 'button') */ defaultType: 'button', /** * @cfg {String} baseCls * The base CSS class to apply to the Carousel's element (defaults to <code>'x-toolbar'</code>). */ baseCls: 'x-toolbar', /** * @cfg {String} titleCls * The CSS class to apply to the titleEl (defaults to <code>'x-toolbar-title'</code>). */ titleCls: 'x-toolbar-title', /** * @cfg {String} ui * Style options for Toolbar. Default is 'dark'. 'light' is also available. */ ui: 'dark', /** * @cfg {Object} layout (optional) * A layout config object. A string is NOT supported here. */ layout: null, /** * @cfg {String} title (optional) * The title of the Toolbar. */ // properties /** * The title Element * @property titleEl * @type Ext.Element */ titleEl: null, initComponent : function() { this.layout = Ext.apply({}, this.layout || {}, { type: 'hbox', align: 'center' }); Ext.Toolbar.superclass.initComponent.call(this); }, afterRender : function() { Ext.Toolbar.superclass.afterRender.call(this); if (this.title) { this.titleEl = this.el.createChild({ cls: this.titleCls, html: this.title }); } }, /** * Set the title of the Toolbar * @param title {String} This can be arbitrary HTML. */ setTitle : function(title) { this.title = title; if (this.rendered) { if (!this.titleEl) { this.titleEl = this.el.createChild({ cls: this.titleCls, html: this.title }); } this.titleEl.setHTML(title); } }, /** * Show the title if it exists. */ showTitle : function() { if (this.titleEl) { this.titleEl.show(); } }, /** * Hide the title if it exists. */ hideTitle : function() { if (this.titleEl) { this.titleEl.hide(); } } }); Ext.reg('toolbar', Ext.Toolbar); /** * @class Ext.Spacer * @extends Ext.Component * * <p>By default the spacer component will take up a flex of 1 unless a width is set.</p> * * <p>Example usage:</p> * <pre><code> var toolbar = new Ext.Toolbar({ title: 'Toolbar Title', items: [ {xtype: 'spacer'}, { xtype: 'Button', text : 'Button!' } ] }); * </code></pre> * * @xtype spacer */ Ext.Spacer = Ext.extend(Ext.Component, { initComponent : function() { if (!this.width) { this.flex = 1; } Ext.Spacer.superclass.initComponent.call(this); }, onRender : function() { Ext.Spacer.superclass.onRender.apply(this, arguments); if (this.flex) { this.el.setStyle('-webkit-box-flex', this.flex); } } }); Ext.reg('spacer', Ext.Spacer);
JavaScript