code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.BasicDialog
* @extends Ext.util.Observable
* 轻便的 Dialog 类。下面的代码展示了使用已有的 HTML 标签创建一个典型的对话框:
* <pre><code>
var dlg = new Ext.BasicDialog("my-dlg", {
height: 200,
width: 300,
minHeight: 100,
minWidth: 150,
modal: true,
proxyDrag: true,
shadow: true
});
dlg.addKeyListener(27, dlg.hide, dlg); // ESC 也能关闭对话框
dlg.addButton('OK', dlg.hide, dlg); // 可以调用保存function代替隐藏对话框
dlg.addButton('Cancel', dlg.hide, dlg);
dlg.show();
</code></pre>
<b>对话框应该为“body”元素的直系子节点。</b>
* @cfg {Boolean/DomHelper} autoCreate 值为“true”时自动创建,或者使用“DomHelper”对象创建(默认为“false”)。
* @cfg {String} title 标题栏上默认显示的文字(默认为“null”)。
* @cfg {Number} width 对话框的宽度,单位像素(也可以通过 CSS 来设置)。如果未指定则由浏览器决定。
* @cfg {Number} height 对话框的高度,单位像素(也可以通过 CSS 来设置)。如果未指定则由浏览器决定。
* @cfg {Number} x 对话框默认的顶部坐标(默认为屏幕中央)
* @cfg {Number} y 对话框默认的左边坐标(默认为屏幕中央)
* @cfg {String/Element} animateTarget 对话框打开时应用动画的 Id 或者元素(默认值为“null”,表示没有动画)。
* @cfg {Boolean} resizable 值为“false”时禁止手动调整对话框大小(默认为“true”)。
* @cfg {String} 设置显示的调整柄,详见 {@link Ext.Resizable} 中调整柄的可用值(默认为“all”)。
* @cfg {Number} minHeight 对话框高度的最小值(默认为“80”)。
* @cfg {Number} minWidth 对话框宽度的最小值(默认为“200”)。
* @cfg {Boolean} modal 值为“true”时模式显示对话框,防止用户与页面的剩余部分交互(默认为“false”)。
* @cfg {Boolean} autoScroll 值为“true”时允许对话框的主体部分里的内容溢出,并显示滚动条(默认为“false”)。
* @cfg {Boolean} closable 值为“false”时将移除标题栏右上角的关闭按钮(默认为“true”)。
* @cfg {Boolean} collapsible 值为“false”时将移除标题栏右上角的最小化按钮(默认为“true”)。
* @cfg {Boolean} constraintoviewport 值为“true”时将保持对话框限定在可视区的边界内(默认为“true”)。
* @cfg {Boolean} syncHeightBeforeShow 值为“true”时则在对话框显示前重新计算高度(默认为“false”)。
* @cfg {Boolean} draggable 值为“false”时将禁止对话框在可视区内的拖动(默认为“true”)。
* @cfg {Boolean} autoTabs 值为“true”时,所有 class 属性为“x-dlg-tab”的元素将被自动转换为 tabs(默认为“false”)。
* @cfg {String} tabTag “tab”元素的标签名称,当 autoTabs = true 时使用(默认为“div”)。
* @cfg {Boolean} proxyDrag 值为“true”时拖动对话框会显示一个轮廓,当“draggable”为“true”时使用(默认为“false”)。
* @cfg {Boolean} fixedcenter 值为“true”时将确保对话框总是在可视区的中央(默认为“false”)。
* @cfg {Boolean/String} shadow “true”或者“sides”为默认效果,“frame”为4方向阴影,“drop”为右下方阴影(默认为“false”)。
* @cfg {Number} shadowOffset 阴影显示时的偏移量,单位为像素(默认为“5”)。
* @cfg {String} buttonAlign 合法的值为:“left”、“center”和“right”(默认为“right”)。
* @cfg {Number} minButtonWidth 对话框中按钮宽度的最小值(默认为“75”)。
* @cfg {Boolean} shim 值为“true”时将创建一个“iframe”元素以免被“select”穿越(默认为“false”)。
* @constructor
* Create a new BasicDialog.
* @param {String/HTMLElement/Ext.Element} el The container element or DOM node, or its id
* @param {Object} config Configuration options
*/
Ext.BasicDialog = function(el, config){
this.el = Ext.get(el);
var dh = Ext.DomHelper;
if(!this.el && config && config.autoCreate){
if(typeof config.autoCreate == "object"){
if(!config.autoCreate.id){
config.autoCreate.id = el;
}
this.el = dh.append(document.body,
config.autoCreate, true);
}else{
this.el = dh.append(document.body,
{tag: "div", id: el, style:'visibility:hidden;'}, true);
}
}
el = this.el;
el.setDisplayed(true);
el.hide = this.hideAction;
this.id = el.id;
el.addClass("x-dlg");
Ext.apply(this, config);
this.proxy = el.createProxy("x-dlg-proxy");
this.proxy.hide = this.hideAction;
this.proxy.setOpacity(.5);
this.proxy.hide();
if(config.width){
el.setWidth(config.width);
}
if(config.height){
el.setHeight(config.height);
}
this.size = el.getSize();
if(typeof config.x != "undefined" && typeof config.y != "undefined"){
this.xy = [config.x,config.y];
}else{
this.xy = el.getCenterXY(true);
}
/** The header element @type Ext.Element */
this.header = el.child("> .x-dlg-hd");
/** The body element @type Ext.Element */
this.body = el.child("> .x-dlg-bd");
/** The footer element @type Ext.Element */
this.footer = el.child("> .x-dlg-ft");
if(!this.header){
this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
}
if(!this.body){
this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
}
this.header.unselectable();
if(this.title){
this.header.update(this.title);
}
// this element allows the dialog to be focused for keyboard event
this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
this.focusEl.swallowEvent("click", true);
this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
// wrap the body and footer for special rendering
this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
if(this.footer){
this.bwrap.dom.appendChild(this.footer.dom);
}
this.bg = this.el.createChild({
tag: "div", cls:"x-dlg-bg",
html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
});
this.centerBg = this.bg.child("div.x-dlg-bg-center");
if(this.autoScroll !== false && !this.autoTabs){
this.body.setStyle("overflow", "auto");
}
this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
if(this.closable !== false){
this.el.addClass("x-dlg-closable");
this.close = this.toolbox.createChild({cls:"x-dlg-close"});
this.close.on("click", this.closeClick, this);
this.close.addClassOnOver("x-dlg-close-over");
}
if(this.collapsible !== false){
this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
this.collapseBtn.on("click", this.collapseClick, this);
this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
this.header.on("dblclick", this.collapseClick, this);
}
if(this.resizable !== false){
this.el.addClass("x-dlg-resizable");
this.resizer = new Ext.Resizable(el, {
minWidth: this.minWidth || 80,
minHeight:this.minHeight || 80,
handles: this.resizeHandles || "all",
pinned: true
});
this.resizer.on("beforeresize", this.beforeResize, this);
this.resizer.on("resize", this.onResize, this);
}
if(this.draggable !== false){
el.addClass("x-dlg-draggable");
if (!this.proxyDrag) {
var dd = new Ext.dd.DD(el.dom.id, "WindowDrag");
}
else {
var dd = new Ext.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
}
dd.setHandleElId(this.header.id);
dd.endDrag = this.endMove.createDelegate(this);
dd.startDrag = this.startMove.createDelegate(this);
dd.onDrag = this.onDrag.createDelegate(this);
dd.scroll = false;
this.dd = dd;
}
if(this.modal){
this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
this.mask.enableDisplayMode("block");
this.mask.hide();
this.el.addClass("x-dlg-modal");
}
if(this.shadow){
this.shadow = new Ext.Shadow({
mode : typeof this.shadow == "string" ? this.shadow : "sides",
offset : this.shadowOffset
});
}else{
this.shadowOffset = 0;
}
if(Ext.useShims && this.shim !== false){
this.shim = this.el.createShim();
this.shim.hide = this.hideAction;
this.shim.hide();
}else{
this.shim = false;
}
if(this.autoTabs){
this.initTabs();
}
this.addEvents({
/**
* @event keydown
* 按下键盘时触发
* @param {Ext.BasicDialog} this
* @param {Ext.EventObject} e
*/
"keydown" : true,
/**
* @event move
* 用户移动对话框时触发
* @param {Ext.BasicDialog} this
* @param {Number} x 新的 X 坐标
* @param {Number} y 新的 Y 坐标
*/
"move" : true,
/**
* @event resize
* 用户调整对话框大小时触发。
* @param {Ext.BasicDialog} this
* @param {Number} width 新的宽度
* @param {Number} height 新的高度
*/
"resize" : true,
/**
* @event beforehide
* 对话框隐藏前触发。
* @param {Ext.BasicDialog} this
*/
"beforehide" : true,
/**
* @event hide
* 对话框隐藏时触发。
* @param {Ext.BasicDialog} this
*/
"hide" : true,
/**
* @event beforeshow
* 对话框展示前触发。
* @param {Ext.BasicDialog} this
*/
"beforeshow" : true,
/**
* @event show
* 对话框展示时触发。
* @param {Ext.BasicDialog} this
*/
"show" : true
});
el.on("keydown", this.onKeyDown, this);
el.on("mousedown", this.toFront, this);
Ext.EventManager.onWindowResize(this.adjustViewport, this, true);
this.el.hide();
Ext.DialogManager.register(this);
Ext.BasicDialog.superclass.constructor.call(this);
};
Ext.extend(Ext.BasicDialog, Ext.util.Observable, {
shadowOffset: Ext.isIE ? 6 : 5,
minHeight: 80,
minWidth: 200,
minButtonWidth: 75,
defaultButton: null,
buttonAlign: "right",
tabTag: 'div',
firstShow: true,
/**
* 设置对话框的标题文本。
* @param {String} text 显示的标题。
* @return {Ext.BasicDialog} this
*/
setTitle : function(text){
this.header.update(text);
return this;
},
// private
closeClick : function(){
this.hide();
},
// private
collapseClick : function(){
this[this.collapsed ? "expand" : "collapse"]();
},
/**
* 将对话框收缩到最小化状态(仅在标题栏可见时有效)。
* 相当于用户单击了收缩对话框按钮。
*/
collapse : function(){
if(!this.collapsed){
this.collapsed = true;
this.el.addClass("x-dlg-collapsed");
this.restoreHeight = this.el.getHeight();
this.resizeTo(this.el.getWidth(), this.header.getHeight());
}
},
/**
* 将对话框展开到普通状态。
* 相当于用户单击了展开对话框按钮。
*/
expand : function(){
if(this.collapsed){
this.collapsed = false;
this.el.removeClass("x-dlg-collapsed");
this.resizeTo(this.el.getWidth(), this.restoreHeight);
}
},
/**
* 重新初始化 tabs 组件,清除原有的 tabs 并返回新的。
* @return {Ext.TabPanel} tabs组件
*/
initTabs : function(){
var tabs = this.getTabs();
while(tabs.getTab(0)){
tabs.removeTab(0);
}
this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
var dom = el.dom;
tabs.addTab(Ext.id(dom), dom.title);
dom.title = "";
});
tabs.activate(0);
return tabs;
},
// private
beforeResize : function(){
this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
},
// private
onResize : function(){
this.refreshSize();
this.syncBodyHeight();
this.adjustAssets();
this.focus();
this.fireEvent("resize", this, this.size.width, this.size.height);
},
// private
onKeyDown : function(e){
if(this.isVisible()){
this.fireEvent("keydown", this, e);
}
},
/**
* 调整对话框大小。
* @param {Number} 宽度
* @param {Number} 高度
* @return {Ext.BasicDialog} this
*/
resizeTo : function(width, height){
this.el.setSize(width, height);
this.size = {width: width, height: height};
this.syncBodyHeight();
if(this.fixedcenter){
this.center();
}
if(this.isVisible()){
this.constrainXY();
this.adjustAssets();
}
this.fireEvent("resize", this, width, height);
return this;
},
/**
* 将对话框的大小调整到足以填充指定内容的大小。
* @param {Number} 宽度
* @param {Number} 高度
* @return {Ext.BasicDialog} this
*/
setContentSize : function(w, h){
h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
//if(!this.el.isBorderBox()){
h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
//}
if(this.tabs){
h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
}
this.resizeTo(w, h);
return this;
},
/**
* 当对话框显示的时候添加一个键盘监听器。这样将允许当对话框活动时勾住一个函数,并在按下指定的按键时执行。
* @param {Number/Array/Object} key 可以是一个 key code 、key code 数组、或者是含有下列选项的对象:{key: (number/array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
* @param {Function} fn 调用的函数
* @param {Object} scope (可选的)函数的作用域
* @return {Ext.BasicDialog} this
*/
addKeyListener : 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;
}
var handler = function(dlg, e){
if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
var k = e.getKey();
if(keyCode instanceof Array){
for(var i = 0, len = keyCode.length; i < len; i++){
if(keyCode[i] == k){
fn.call(scope || window, dlg, k, e);
return;
}
}
}else{
if(k == keyCode){
fn.call(scope || window, dlg, k, e);
}
}
}
};
this.on("keydown", handler);
return this;
},
/**
* 返回 TabPanel 组件(如果不存在则创建一个)。
* 注意:如果你只是想检查存在的 TabPanel 而不是创建,设置一个值为空的“tabs”属性。
* @return {Ext.TabPanel} tabs组件
*/
getTabs : function(){
if(!this.tabs){
this.el.addClass("x-dlg-auto-tabs");
this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
this.tabs = new Ext.TabPanel(this.body.dom, this.tabPosition == "bottom");
}
return this.tabs;
},
/**
* 在对话框的底部区域添加一个按钮。
* @param {String/Object} config 如果是字串则为按钮的文本,也可以是按钮设置对象或者 Ext.DomHelper 元素设置。
* @param {Function} handler 点击按钮时调用的函数。
* @param {Object} scope (可选的) 调用函数的作用域。
* @return {Ext.Button} 新的按钮
*/
addButton : function(config, handler, scope){
var dh = Ext.DomHelper;
if(!this.footer){
this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
}
if(!this.btnContainer){
var tb = this.footer.createChild({
cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
}, null, true);
this.btnContainer = tb.firstChild.firstChild.firstChild;
}
var bconfig = {
handler: handler,
scope: scope,
minWidth: this.minButtonWidth,
hideParent:true
};
if(typeof config == "string"){
bconfig.text = config;
}else{
if(config.tag){
bconfig.dhconfig = config;
}else{
Ext.apply(bconfig, config);
}
}
var btn = new Ext.Button(
this.btnContainer.appendChild(document.createElement("td")),
bconfig
);
this.syncBodyHeight();
if(!this.buttons){
/**
* 所有通过“addButton”方法添加的按钮数组
* @type Array
*/
this.buttons = [];
}
this.buttons.push(btn);
return btn;
},
/**
* 当对话框显示时将焦点设置在默认的按钮上。
* @param {Ext.BasicDialog.Button} btn 通过{@link #addButton}方法创建的按钮。
* @return {Ext.BasicDialog} this
*/
setDefaultButton : function(btn){
this.defaultButton = btn;
return this;
},
// private
getHeaderFooterHeight : function(safe){
var height = 0;
if(this.header){
height += this.header.getHeight();
}
if(this.footer){
var fm = this.footer.getMargins();
height += (this.footer.getHeight()+fm.top+fm.bottom);
}
height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
height += this.centerBg.getPadding("tb");
return height;
},
// private
syncBodyHeight : function(){
var bd = this.body, cb = this.centerBg, bw = this.bwrap;
var height = this.size.height - this.getHeaderFooterHeight(false);
bd.setHeight(height-bd.getMargins("tb"));
var hh = this.header.getHeight();
var h = this.size.height-hh;
cb.setHeight(h);
bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
bw.setHeight(h-cb.getPadding("tb"));
bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
bd.setWidth(bw.getWidth(true));
if(this.tabs){
this.tabs.syncHeight();
if(Ext.isIE){
this.tabs.el.repaint();
}
}
},
/**
* 如果配置过 Ext.state 则恢复对话框之前的状态。
* @return {Ext.BasicDialog} this
*/
restoreState : function(){
var box = Ext.state.Manager.get(this.stateId || (this.el.id + "-state"));
if(box && box.width){
this.xy = [box.x, box.y];
this.resizeTo(box.width, box.height);
}
return this;
},
// private
beforeShow : function(){
this.expand();
if(this.fixedcenter){
this.xy = this.el.getCenterXY(true);
}
if(this.modal){
Ext.get(document.body).addClass("x-body-masked");
this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
this.mask.show();
}
this.constrainXY();
},
// private
animShow : function(){
var b = Ext.get(this.animateTarget, true).getBox();
this.proxy.setSize(b.width, b.height);
this.proxy.setLocation(b.x, b.y);
this.proxy.show();
this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
true, .35, this.showEl.createDelegate(this));
},
/**
* 展示对话框。
* @param {String/HTMLElement/Ext.Element} animateTarget (可选的) 重置动画的目标
* @return {Ext.BasicDialog} this
*/
show : function(animateTarget){
if (this.fireEvent("beforeshow", this) === false){
return;
}
if(this.syncHeightBeforeShow){
this.syncBodyHeight();
}else if(this.firstShow){
this.firstShow = false;
this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
}
this.animateTarget = animateTarget || this.animateTarget;
if(!this.el.isVisible()){
this.beforeShow();
if(this.animateTarget){
this.animShow();
}else{
this.showEl();
}
}
return this;
},
// private
showEl : function(){
this.proxy.hide();
this.el.setXY(this.xy);
this.el.show();
this.adjustAssets(true);
this.toFront();
this.focus();
// IE peekaboo bug - fix found by Dave Fenwick
if(Ext.isIE){
this.el.repaint();
}
this.fireEvent("show", this);
},
/**
* 将焦点置于对话框上。
* 如果设置了 defaultButton ,则该按钮取得焦点,否则对话框本身取得焦点。
*/
focus : function(){
if(this.defaultButton){
this.defaultButton.focus();
}else{
this.focusEl.focus();
}
},
// private
constrainXY : function(){
if(this.constraintoviewport !== false){
if(!this.viewSize){
if(this.container){
var s = this.container.getSize();
this.viewSize = [s.width, s.height];
}else{
this.viewSize = [Ext.lib.Dom.getViewWidth(),Ext.lib.Dom.getViewHeight()];
}
}
var s = Ext.get(this.container||document).getScroll();
var x = this.xy[0], y = this.xy[1];
var w = this.size.width, h = this.size.height;
var vw = this.viewSize[0], vh = this.viewSize[1];
// only move it if it needs it
var moved = false;
// first validate right/bottom
if(x + w > vw+s.left){
x = vw - w;
moved = true;
}
if(y + h > vh+s.top){
y = vh - h;
moved = true;
}
// then make sure top/left isn't negative
if(x < s.left){
x = s.left;
moved = true;
}
if(y < s.top){
y = s.top;
moved = true;
}
if(moved){
// cache xy
this.xy = [x, y];
if(this.isVisible()){
this.el.setLocation(x, y);
this.adjustAssets();
}
}
}
},
// private
onDrag : function(){
if(!this.proxyDrag){
this.xy = this.el.getXY();
this.adjustAssets();
}
},
// private
adjustAssets : function(doShow){
var x = this.xy[0], y = this.xy[1];
var w = this.size.width, h = this.size.height;
if(doShow === true){
if(this.shadow){
this.shadow.show(this.el);
}
if(this.shim){
this.shim.show();
}
}
if(this.shadow && this.shadow.isVisible()){
this.shadow.show(this.el);
}
if(this.shim && this.shim.isVisible()){
this.shim.setBounds(x, y, w, h);
}
},
// private
adjustViewport : function(w, h){
if(!w || !h){
w = Ext.lib.Dom.getViewWidth();
h = Ext.lib.Dom.getViewHeight();
}
// cache the size
this.viewSize = [w, h];
if(this.modal && this.mask.isVisible()){
this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
}
if(this.isVisible()){
this.constrainXY();
}
},
/**
* 销毁对话框和所有它支持的元素(包括 tabs、 shim、 shadow、 proxy、 mask 等等。)同时也去除所有事件监听器。
* @param {Boolean} removeEl (可选的) 值为 true 时从 DOM 中删除该元素。
*/
destroy : function(removeEl){
if(this.isVisible()){
this.animateTarget = null;
this.hide();
}
Ext.EventManager.removeResizeListener(this.adjustViewport, this);
if(this.tabs){
this.tabs.destroy(removeEl);
}
Ext.destroy(
this.shim,
this.proxy,
this.resizer,
this.close,
this.mask
);
if(this.dd){
this.dd.unreg();
}
if(this.buttons){
for(var i = 0, len = this.buttons.length; i < len; i++){
this.buttons[i].destroy();
}
}
this.el.removeAllListeners();
if(removeEl === true){
this.el.update("");
this.el.remove();
}
Ext.DialogManager.unregister(this);
},
// private
startMove : function(){
if(this.proxyDrag){
this.proxy.show();
}
if(this.constraintoviewport !== false){
this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
}
},
// private
endMove : function(){
if(!this.proxyDrag){
Ext.dd.DD.prototype.endDrag.apply(this.dd, arguments);
}else{
Ext.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
this.proxy.hide();
}
this.refreshSize();
this.adjustAssets();
this.focus();
this.fireEvent("move", this, this.xy[0], this.xy[1]);
},
/**
* 将对话框置于其他可见的对话框的前面。
* @return {Ext.BasicDialog} this
*/
toFront : function(){
Ext.DialogManager.bringToFront(this);
return this;
},
/**
* 将对话框置于其他可见的对话框的后面。
* @return {Ext.BasicDialog} this
*/
toBack : function(){
Ext.DialogManager.sendToBack(this);
return this;
},
/**
* 将对话框于视图居中显示。
* @return {Ext.BasicDialog} this
*/
center : function(){
var xy = this.el.getCenterXY(true);
this.moveTo(xy[0], xy[1]);
return this;
},
/**
* 将对话框的左上角移动到指定的地方。
* @param {Number} x
* @param {Number} y
* @return {Ext.BasicDialog} this
*/
moveTo : function(x, y){
this.xy = [x,y];
if(this.isVisible()){
this.el.setXY(this.xy);
this.adjustAssets();
}
return this;
},
/**
* 将对话框对齐到指定元素上。
* @param {String/HTMLElement/Ext.Element} element 要对齐的元素。
* @param {String} position 对齐到的位置(点击{@link Ext.Element#alignTo}查看详情)。
* @param {Array} offsets (可选的) 位置偏移量,形如:[x, y]
* @return {Ext.BasicDialog} this
*/
alignTo : function(element, position, offsets){
this.xy = this.el.getAlignToXY(element, position, offsets);
if(this.isVisible()){
this.el.setXY(this.xy);
this.adjustAssets();
}
return this;
},
/**
* 将元素与另一个元素绑定,并在调整窗口大小后重新对齐元素。
* @param {String/HTMLElement/Ext.Element} element 要对齐的元素。
* @param {String} position 对齐到的位置(点击{@link Ext.Element#alignTo}查看详情)。
* @param {Array} offsets (可选的) 位置偏移量,形如:[x, y]
* @param {Boolean/Number} monitorScroll (可选的) 值为 true 时监视容器的滚动并重新定位。如果为数值,将用来做为延迟缓冲量(默认为50毫秒)。
* @return {Ext.BasicDialog} this
*/
anchorTo : function(el, alignment, offsets, monitorScroll){
var action = function(){
this.alignTo(el, alignment, offsets);
};
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;
},
/**
* 当对话框可见时返回“true”。
* @return {Boolean}
*/
isVisible : function(){
return this.el.isVisible();
},
// private
animHide : function(callback){
var b = Ext.get(this.animateTarget).getBox();
this.proxy.show();
this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
this.el.hide();
this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
this.hideEl.createDelegate(this, [callback]));
},
/**
* 隐藏对话框。
* @param {Function} callback (可选的) 对话框隐藏时调用的函数。
* @return {Ext.BasicDialog} this
*/
hide : function(callback){
if (this.fireEvent("beforehide", this) === false){
return;
}
if(this.shadow){
this.shadow.hide();
}
if(this.shim) {
this.shim.hide();
}
if(this.animateTarget){
this.animHide(callback);
}else{
this.el.hide();
this.hideEl(callback);
}
return this;
},
// private
hideEl : function(callback){
this.proxy.hide();
if(this.modal){
this.mask.hide();
Ext.get(document.body).removeClass("x-body-masked");
}
this.fireEvent("hide", this);
if(typeof callback == "function"){
callback();
}
},
// private
hideAction : function(){
this.setLeft("-10000px");
this.setTop("-10000px");
this.setStyle("visibility", "hidden");
},
// private
refreshSize : function(){
this.size = this.el.getSize();
this.xy = this.el.getXY();
Ext.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
},
// private
// z-index is managed by the DialogManager and may be overwritten at any time
setZIndex : function(index){
if(this.modal){
this.mask.setStyle("z-index", index);
}
if(this.shim){
this.shim.setStyle("z-index", ++index);
}
if(this.shadow){
this.shadow.setZIndex(++index);
}
this.el.setStyle("z-index", ++index);
if(this.proxy){
this.proxy.setStyle("z-index", ++index);
}
if(this.resizer){
this.resizer.proxy.setStyle("z-index", ++index);
}
this.lastZIndex = index;
},
/**
* 返回对话框元素。
* @return {Ext.Element} 所在的对话框元素
*/
getEl : function(){
return this.el;
}
});
/**
* @class Ext.DialogManager
* Provides global access to BasicDialogs that have been created and
* support for z-indexing (layering) multiple open dialogs.
*/
Ext.DialogManager = function(){
var list = {};
var accessList = [];
var front = null;
// private
var sortDialogs = function(d1, d2){
return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
};
// private
var orderDialogs = function(){
accessList.sort(sortDialogs);
var seed = Ext.DialogManager.zseed;
for(var i = 0, len = accessList.length; i < len; i++){
var dlg = accessList[i];
if(dlg){
dlg.setZIndex(seed + (i*10));
}
}
};
return {
/**
* The starting z-index for BasicDialogs (defaults to 9000)
* @type Number The z-index value
*/
zseed : 9000,
// private
register : function(dlg){
list[dlg.id] = dlg;
accessList.push(dlg);
},
// private
unregister : function(dlg){
delete list[dlg.id];
if(!accessList.indexOf){
for(var i = 0, len = accessList.length; i < len; i++){
if(accessList[i] == dlg){
accessList.splice(i, 1);
return;
}
}
}else{
var i = accessList.indexOf(dlg);
if(i != -1){
accessList.splice(i, 1);
}
}
},
/**
* Gets a registered dialog by id
* @param {String/Object} id The id of the dialog or a dialog
* @return {Ext.BasicDialog} this
*/
get : function(id){
return typeof id == "object" ? id : list[id];
},
/**
* Brings the specified dialog to the front
* @param {String/Object} dlg The id of the dialog or a dialog
* @return {Ext.BasicDialog} this
*/
bringToFront : function(dlg){
dlg = this.get(dlg);
if(dlg != front){
front = dlg;
dlg._lastAccess = new Date().getTime();
orderDialogs();
}
return dlg;
},
/**
* Sends the specified dialog to the back
* @param {String/Object} dlg The id of the dialog or a dialog
* @return {Ext.BasicDialog} this
*/
sendToBack : function(dlg){
dlg = this.get(dlg);
dlg._lastAccess = -(new Date().getTime());
orderDialogs();
return dlg;
},
/**
* Hides all dialogs
*/
hideAll : function(){
for(var id in list){
if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
list[id].hide();
}
}
}
};
}();
/**
* @class Ext.LayoutDialog
* @extends Ext.BasicDialog
* Dialog which provides adjustments for working with a layout in a Dialog.
* Add your necessary layout config options to the dialog's config.<br>
* Example usage (including a nested layout):
* <pre><code>
if(!dialog){
dialog = new Ext.LayoutDialog("download-dlg", {
modal: true,
width:600,
height:450,
shadow:true,
minWidth:500,
minHeight:350,
autoTabs:true,
proxyDrag:true,
// layout config merges with the dialog config
center:{
tabPosition: "top",
alwaysShowTabs: true
}
});
dialog.addKeyListener(27, dialog.hide, dialog);
dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
dialog.addButton("Build It!", this.getDownload, this);
// we can even add nested layouts
var innerLayout = new Ext.BorderLayout("dl-inner", {
east: {
initialSize: 200,
autoScroll:true,
split:true
},
center: {
autoScroll:true
}
});
innerLayout.beginUpdate();
innerLayout.add("east", new Ext.ContentPanel("dl-details"));
innerLayout.add("center", new Ext.ContentPanel("selection-panel"));
innerLayout.endUpdate(true);
var layout = dialog.getLayout();
layout.beginUpdate();
layout.add("center", new Ext.ContentPanel("standard-panel",
{title: "Download the Source", fitToFrame:true}));
layout.add("center", new Ext.NestedLayoutPanel(innerLayout,
{title: "Build your own ext.js"}));
layout.getRegion("center").showPanel(sp);
layout.endUpdate();
}
</code></pre>
* @constructor
* @param {String/HTMLElement/Ext.Element} el The id of or container element
* @param {Object} config configuration options
*/
Ext.LayoutDialog = function(el, config){
config.autoTabs = false;
Ext.LayoutDialog.superclass.constructor.call(this, el, config);
this.body.setStyle({overflow:"hidden", position:"relative"});
this.layout = new Ext.BorderLayout(this.body.dom, config);
this.layout.monitorWindowResize = false;
this.el.addClass("x-dlg-auto-layout");
// fix case when center region overwrites center function
this.center = Ext.BasicDialog.prototype.center;
this.on("show", this.layout.layout, this.layout, true);
};
Ext.extend(Ext.LayoutDialog, Ext.BasicDialog, {
/**
* Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
* @deprecated
*/
endUpdate : function(){
this.layout.endUpdate();
},
/**
* Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
* @deprecated
*/
beginUpdate : function(){
this.layout.beginUpdate();
},
/**
* Get the BorderLayout for this dialog
* @return {Ext.BorderLayout}
*/
getLayout : function(){
return this.layout;
},
showEl : function(){
Ext.LayoutDialog.superclass.showEl.apply(this, arguments);
if(Ext.isIE7){
this.layout.layout();
}
},
// private
// Use the syncHeightBeforeShow config option to control this automatically
syncBodyHeight : function(){
Ext.LayoutDialog.superclass.syncBodyHeight.call(this);
if(this.layout){this.layout.layout();}
}
}); | JavaScript |
/**
* @class Ext.Shadow
* 为所有元素提供投影效果的一个简易类。 注意元素必须为绝对定位,而且投影并没有垫片的效果(shimming)。
* This should be used only in simple cases --
* 这只是适用简单的场合- 如想提供更高阶的投影效果,请参阅{@link Ext.Layer}类。
* @constructor
* Create a new Shadow
* @param {Object} config 配置项对象
*/
Ext.Shadow = function(config){
Ext.apply(this, config);
if(typeof this.mode != "string"){
this.mode = this.defaultMode;
}
var o = this.offset, a = {h: 0};
var rad = Math.floor(this.offset/2);
switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
case "drop":
a.w = 0;
a.l = a.t = o;
a.t -= 1;
if(Ext.isIE){
a.l -= this.offset + rad;
a.t -= this.offset + rad;
a.w -= rad;
a.h -= rad;
a.t += 1;
}
break;
case "sides":
a.w = (o*2);
a.l = -o;
a.t = o-1;
if(Ext.isIE){
a.l -= (this.offset - rad);
a.t -= this.offset + rad;
a.l += 1;
a.w -= (this.offset - rad)*2;
a.w -= rad + 1;
a.h -= 1;
}
break;
case "frame":
a.w = a.h = (o*2);
a.l = a.t = -o;
a.t += 1;
a.h -= 2;
if(Ext.isIE){
a.l -= (this.offset - rad);
a.t -= (this.offset - rad);
a.l += 1;
a.w -= (this.offset + rad + 1);
a.h -= (this.offset + rad);
a.h += 1;
}
break;
};
this.adjusts = a;
};
Ext.Shadow.prototype = {
/**
* @cfg {String} mode
* 投影显示的模式。有下列选项:<br />
* sides: 投影限显示在两边和底部<br />
* frame: 投影在四边均匀出现<br />
* drop: 传统的物理效果的,底部和右边。这是默认值。
*/
/**
* @cfg {String} offset
* 元素和投影之间的偏移象素值(默认为4)
*/
offset: 4,
// private
defaultMode: "drop",
/**
* 在目标元素上显示投影,
* @param {String/HTMLElement/Element} targetEl 指定要显示投影的那个元素
*/
show : function(target){
target = Ext.get(target);
if(!this.el){
this.el = Ext.Shadow.Pool.pull();
if(this.el.dom.nextSibling != target.dom){
this.el.insertBefore(target);
}
}
this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
if(Ext.isIE){
this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
}
this.realign(
target.getLeft(true),
target.getTop(true),
target.getWidth(),
target.getHeight()
);
this.el.dom.style.display = "block";
},
/**
* 返回投影是否在显示
*/
isVisible : function(){
return this.el ? true : false;
},
/**
* 当值可用时直接对称位置。
* Show方法必须至少在调用realign方法之前调用一次,以保证能够初始化。
* @param {Number} left 目标元素left位置
* @param {Number} top 目标元素top位置
* @param {Number} width 目标元素宽度
* @param {Number} height 目标元素高度
*/
realign : function(l, t, w, h){
if(!this.el){
return;
}
var a = this.adjusts, d = this.el.dom, s = d.style;
var iea = 0;
s.left = (l+a.l)+"px";
s.top = (t+a.t)+"px";
var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
if(s.width != sws || s.height != shs){
s.width = sws;
s.height = shs;
if(!Ext.isIE){
var cn = d.childNodes;
var sww = Math.max(0, (sw-12))+"px";
cn[0].childNodes[1].style.width = sww;
cn[1].childNodes[1].style.width = sww;
cn[2].childNodes[1].style.width = sww;
cn[1].style.height = Math.max(0, (sh-12))+"px";
}
}
},
/**
* 隐藏投影
*/
hide : function(){
if(this.el){
this.el.dom.style.display = "none";
Ext.Shadow.Pool.push(this.el);
delete this.el;
}
},
/**
* 调整该投影的z-index
* @param {Number} zindex 新z-index
*/
setZIndex : function(z){
this.zIndex = z;
if(this.el){
this.el.setStyle("z-index", z);
}
}
};
// Private utility class that manages the internal Shadow cache
Ext.Shadow.Pool = function(){
var p = [];
var markup = Ext.isIE ?
'<div class="x-ie-shadow"></div>' :
'<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
return {
pull : function(){
var sh = p.shift();
if(!sh){
sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
sh.autoBoxAdjust = false;
}
return sh;
},
push : function(sh){
p.push(sh);
}
};
}(); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.JsonView
* @extends Ext.View
* 为了方便使用JSON+{@link Ext.UpdateManager},而创建的一个模板视图类。用法:
<pre><code>
var view = new Ext.JsonView("my-element",
'<div id="{id}">{foo} - {bar}</div>', // 自动创建模板
{ multiSelect: true, jsonRoot: "data" }
);
//是否侦听节点的单击事件?
view.on("click", function(vw, index, node, e){
alert('点中节点"' + node.id + '" 位于索引:' + index + "。");
});
// 直接加载JSON数据
view.load("foobar.php");
// JACK博客上的范例
var tpl = new Ext.Template(
'<div class="entry">' +
'<a class="entry-title" href="{link}">{title}</a>' +
"<h4>{date} by {author} | {comments} Comments</h4>{description}" +
"</div><hr />"
);
var moreView = new Ext.JsonView("entry-list", tpl, {
jsonRoot: "posts"
});
moreView.on("beforerender", this.sortEntries, this);
moreView.load({
url: "/blog/get-posts.php",
params: "allposts=true",
text: "Loading Blog Entries..."
});
</code></pre>
* @constructor
* 创建一个新的JSON视图(JSONView)
* @param {String/HTMLElement/Element} container 渲染视图的容器元素。
* @param {Template} tpl 渲染模板
* @param {Object} config 配置项对象
*/
Ext.JsonView = function(container, tpl, config){
Ext.JsonView.superclass.constructor.call(this, container, tpl, config);
var um = this.el.getUpdateManager();
um.setRenderer(this);
um.on("update", this.onLoad, this);
um.on("failure", this.onLoadException, this);
/**
* @event beforerender
* JSON数据已加载好了,view渲染之前触发。
* @param {Ext.JsonView} this
* @param {Object} data 已加载好的JSON数据
*/
/**
* @event load
* 当数据加载后触发。
* @param {Ext.JsonView} this
* @param {Object} data 已加载好的JSON数据
* @param {Object} response 原始的连接对象(从服务区响应回来的)
*/
/**
* @event loadexception
* 当加载失败时触发。
* @param {Ext.JsonView} this
* @param {Object} response 原始的连接对象(从服务区响应回来的)
*/
this.addEvents({
'beforerender' : true,
'load' : true,
'loadexception' : true
});
};
Ext.extend(Ext.JsonView, Ext.View, {
/**
* 包含数据的 JSON 对象的根属性
* @type {String}
*/
jsonRoot : "",
/**
* 刷新 view
*/
refresh : function(){
this.clearSelections();
this.el.update("");
var html = [];
var o = this.jsonData;
if(o && o.length > 0){
for(var i = 0, len = o.length; i < len; i++){
var data = this.prepareData(o[i], i, o);
html[html.length] = this.tpl.apply(data);
}
}else{
html.push(this.emptyText);
}
this.el.update(html.join(""));
this.nodes = this.el.dom.childNodes;
this.updateIndexes(0);
},
/**
* 发起一个异步的 HTTP 请求,然后得到 JSON 的响应.如不指定<i>params</i> 则使用 POST, 否则就是 GET.
* @param {Object/String/Function} 该请求的 URL, 或是可返回 URL 的函数,也可是包含下列选项的配置项对象:
<pre><code>
view.load({
url: "your-url.php",
params: {param1: "foo", param2: "bar"}, // 或是可URL编码的字符串
callback: yourFunction,
scope: yourObject, //(作用域可选)
discardUrl: false,
nocache: false,
text: "加载中...",
timeout: 30,
scripts: false
});
</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 (可选的)请求往返完成后的回调,调用时有参数(oElement, bSuccess)
* @param {Boolean} discardUrl (可选的)默认情况下你执行一次更新后,最后一次url会保存到defaultUrl。如果true的话,将不会保存。
*/
load : function(){
var um = this.el.getUpdateManager();
um.update.apply(um, arguments);
},
render : function(el, response){
this.clearSelections();
this.el.update("");
var o;
try{
o = Ext.util.JSON.decode(response.responseText);
if(this.jsonRoot){
o = eval("o." + this.jsonRoot);
}
} catch(e){
}
/**
* 当前的JSON数据或是null
*/
this.jsonData = o;
this.beforeRender();
this.refresh();
},
/**
* 获取当前JSON数据集的总记录数
* @return {Number}
*/
getCount : function(){
return this.jsonData ? this.jsonData.length : 0;
},
/**
* 指定一个或多个节点返回JSON对象
* @param {HTMLElement/Array} 节点或节点组成的数组
* @return {Object/Array} 如果传入的参数是数组的类型,返回的也是一个数组,反之
* 你得到是节点的 JSON 对象
*/
getNodeData : function(node){
if(node instanceof Array){
var data = [];
for(var i = 0, len = node.length; i < len; i++){
data.push(this.getNodeData(node[i]));
}
return data;
}
return this.jsonData[this.indexOf(node)] || null;
},
beforeRender : function(){
this.snapshot = this.jsonData;
if(this.sortInfo){
this.sort.apply(this, this.sortInfo);
}
this.fireEvent("beforerender", this, this.jsonData);
},
onLoad : function(el, o){
this.fireEvent("load", this, this.jsonData, o);
},
onLoadException : function(el, o){
this.fireEvent("loadexception", this, o);
},
/**
* 指定某个属性,进行数据筛选
* @param {String} 指定JSON对象的某个属性
* @param {String/RegExp} value 既可是属性值的字符串,也可是用来查找属性的正则表达式。
*/
filter : function(property, value){
if(this.jsonData){
var data = [];
var ss = this.snapshot;
if(typeof value == "string"){
var vlen = value.length;
if(vlen == 0){
this.clearFilter();
return;
}
value = value.toLowerCase();
for(var i = 0, len = ss.length; i < len; i++){
var o = ss[i];
if(o[property].substr(0, vlen).toLowerCase() == value){
data.push(o);
}
}
} else if(value.exec){ // regex?
for(var i = 0, len = ss.length; i < len; i++){
var o = ss[i];
if(value.test(o[property])){
data.push(o);
}
}
} else{
return;
}
this.jsonData = data;
this.refresh();
}
},
/**
* 指定一个函数,进行数据筛选。该函数会被当前数据集中的每个对象调用。
* 若函数返回true值,记录值会被保留,否则会被过滤掉,
* otherwise it is filtered.
* @param {Function} fn
* @param {Object} scope (optional) 函数的作用域(默认为JsonView)
*/
filterBy : function(fn, scope){
if(this.jsonData){
var data = [];
var ss = this.snapshot;
for(var i = 0, len = ss.length; i < len; i++){
var o = ss[i];
if(fn.call(scope || this, o)){
data.push(o);
}
}
this.jsonData = data;
this.refresh();
}
},
/**
* 清除当前的筛选
*/
clearFilter : function(){
if(this.snapshot && this.jsonData != this.snapshot){
this.jsonData = this.snapshot;
this.refresh();
}
},
/**
* 对当前的view进行数据排序并刷新
* @param {String} 要排序的那个JSON对象上的属性
* @param {String} (可选的)"升序(desc)"或"降序"(asc)
* @param {Function} 该函数负责将数据转换到可排序的值
*/
sort : function(property, dir, sortType){
this.sortInfo = Array.prototype.slice.call(arguments, 0);
if(this.jsonData){
var p = property;
var dsc = dir && dir.toLowerCase() == "desc";
var f = function(o1, o2){
var v1 = sortType ? sortType(o1[p]) : o1[p];
var v2 = sortType ? sortType(o2[p]) : o2[p];
;
if(v1 < v2){
return dsc ? +1 : -1;
} else if(v1 > v2){
return dsc ? -1 : +1;
} else{
return 0;
}
};
this.jsonData.sort(f);
this.refresh();
if(this.jsonData != this.snapshot){
this.snapshot.sort(f);
}
}
}
}); | JavaScript |
/*
* 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 |
/*
* 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",
'<div id="{0}">{2} - {1}</div>', // 自动创建模板
{
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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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"> </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 |
/*
* 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 = "  ";
}else{
if(Ext.isIE){
v = v.replace(/\n/g, '<p> </p>');
}
v += " \n ";
}
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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 += " ";
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 |
/*
* 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 |
/*
* 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 == ' '){
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 = ' ';
}
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(' ');
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',' ');
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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/**
* @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> </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"> </button></td><td class="x-btn-right"><i> </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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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"> </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"> </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 = " ";
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 = " ";
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 = " ";
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 |
/*
* 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 |
/*
* 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:" "
}, true);
this.proxyBottom = Ext.DomHelper.append(document.body, {
cls:"col-move-bottom", html:" "
}, 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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 " ";
}
return value;
};
// Alias for backwards compatibility
Ext.grid.DefaultColumnModel = Ext.grid.ColumnModel;
| JavaScript |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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: " "}, 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 |
/**
* @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 |
/*
* 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 |
/*
* 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: " "});
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 |
/*
* 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 |
/*
* 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 |
/*
* 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 |
/*
* 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> 可以是除空格、>和<之外的任意字符。
*/
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 |
/*
* 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(
'<div name="{id}">',
'<span class="{cls}">{name:trim} {value:ellipsis(10)}</span>',
'</div>'
);
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 |
/*
* 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&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或'<div class="loading-indicator">加载中...</div>')。
* @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编码的字符串"¶m1=1¶m2=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编码的字符串"¶m1=1¶m2=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,
/**
* 加载指示器显示的内容(默认为'<div class="loading-indicator">Loading...</div>')
* @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 |
/*
* 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 |
/*
* 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 |
/*
* 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&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.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/*
* These classes are derivatives of the similarly named classes in the YUI Library.
* The original license:
* Copyright (c) 2006, Yahoo! Inc. All rights reserved.
* Code licensed under the BSD License:
* http://developer.yahoo.net/yui/license.txt
*/
(function() {
var Event=Ext.EventManager;
var Dom=Ext.lib.Dom;
/**
* 对于可被拖动(drag)或可被放下(drop)的目标,进行接口和各项基本操作的定义。
* 你应该通过继承的方式使用该类,并重写startDrag, onDrag, onDragOver和onDragOut的事件处理器,.
* 共有三种html元素可以被关联到DragDrop实例:
* <ul>
* <li>关联元素(linked element):传入到构造器的元素。
* 这是一个为与其它拖放对象交互定义边界的元素</li>
* <li>执行元素(handle element):只有被点击的元素是执行元素,
* 这个拖动操作才会发生。默认就是关联元素,不过有情况你只是想关联元素的某一部分
* 来初始化拖动操作。可用setHandleElId()方法重新定义</li>
* <li>拖动元素(drag element):表示在拖放过程中,参与和鼠标指针一起的那个元素。
* 默认就是关联元素本身,如{@link Ext.dd.DD},setDragElId()可让你定义一个
* 可移动的独立元素,如{@link Ext.dd.DDProxy}</li>
* </ul>
*/
/**
* 必须在onload事件发生之后才能实例化这个类,以保证关联元素已准备可用。
* 下列语句会将拖放对象放进"group1"的组中,与组内其他拖放对象交互:
* <pre>
* dd = new Ext.dd.DragDrop("div1", "group1");
* </pre>
* 由于没有实现任何的事件处理器,所以上面的代码运行后不会有实际的效果发生。
* 通常的做法是你要先重写这个类或者某个默的实现,但是你可以重写你想出现在这个实例上的方法
* <pre>
* dd.onDragDrop = function(e, id) {
* alert("DD落在" + id+"的身上");
* }
* </pre>
* @constructor
* @param {String} id 关联到这个实例的那个元素的id
* @param {String} sGroup 相关拖放对象的组
* @param {object} config 包含可配置的对象属性
* DragDrop的有效属性:
* padding, isTarget, maintainOffset, primaryButtonOnly
*/
Ext.dd.DragDrop = function(id, sGroup, config) {
if (id) {
this.init(id, sGroup, config);
}
};
Ext.dd.DragDrop.prototype = {
/**
* 关联该对象元素之id,这便是我们所提及的“关联元素”,
* 因为拖动过程中的交互行为取决于该元素的大小和尺寸。
* @property id
* @type String
*/
id: null,
/**
* 传入构造器的配置项对象
* @property config
* @type object
*/
config: null,
/**
* 被拖动的元素id,默认与关联元素相同,但可替换为其他元素,如:Ext.dd.DDProxy
* @property dragElId
* @type String
* @private
*/
dragElId: null,
/**
* 初始化拖动操作的元素id,这是一个关联元素,但可改为这个元素的子元素。
* @property handleElId
* @type String
* @private
*/
handleElId: null,
/**
* 点击时要忽略的HTML标签名称。
* @property invalidHandleTypes
* @type {string: string}
*/
invalidHandleTypes: null,
/**
* 点击时要忽略的元素id。
* @property invalidHandleIds
* @type {string: string}
*/
invalidHandleIds: null,
/**
* 点击时要忽略的元素的css样式类名称所组成的数组。
* @property invalidHandleClasses
* @type string[]
*/
invalidHandleClasses: null,
/**
* 拖动开始时的x绝对位置
* @property startPageX
* @type int
* @private
*/
startPageX: 0,
/**
* 拖动开始时的y绝对位置
* @property startPageY
* @type int
* @private
*/
startPageY: 0,
/**
* 组(Group)定义,相关拖放对象的逻辑集合。
* 实例只能通过事件与同一组下面的其他拖放对象交互。
* 这使得我们可以将多个组定义在同一个子类下面。
* @property groups
* @type {string: string}
*/
groups: null,
/**
* 每个拖动/落下的实例可被锁定。
* 这会禁止onmousedown开始拖动。
* @property locked
* @type boolean
* @private
*/
locked: false,
/**
* 锁定实例
* @method lock
*/
lock: function() { this.locked = true; },
/**
* 解锁实例
* @method unlock
*/
unlock: function() { this.locked = false; },
/**
* 默认地,所有实例可以是降落目标。
* 该项可设置isTarget为false来禁止。
* @method isTarget
* @type boolean
*/
isTarget: true,
/**
* 当拖放对象与落下区域交互时的外补丁配置。
* @method padding
* @type int[]
*/
padding: null,
/**
* 缓存关联元素的引用。
* @property _domRef
* @private
*/
_domRef: null,
/**
* Internal typeof flag
* @property __ygDragDrop
* @private
*/
__ygDragDrop: true,
/**
* 当水平约束应用时为true。
* @property constrainX
* @type boolean
* @private
*/
constrainX: false,
/**
* 当垂直约束应用时为false。
* @property constrainY
* @type boolean
* @private
*/
constrainY: false,
/**
* 左边坐标
* @property minX
* @type int
* @private
*/
minX: 0,
/**
* 右边坐标
* @property maxX
* @type int
* @private
*/
maxX: 0,
/**
* 上方坐标
* @property minY
* @type int
* @type int
* @private
*/
minY: 0,
/**
* 下方坐标
* @property maxY
* @type int
* @private
*/
maxY: 0,
/**
* 当重置限制时(constraints)修正偏移。
* 如果你想在页面变动时,元素的位置与其父级元素的位置不发生变化,可设为true。
* @property maintainOffset
* @type boolean
*/
maintainOffset: false,
/**
* 如果我们指定一个垂直的间隔值,元素会作一个象素位置的取样,放到数组中。
* 如果你定义了一个tick interval,该数组将会自动生成。
* @property xTicks
* @type int[]
*/
xTicks: null,
/**
* 如果我们指定一个水平的间隔值,元素会作一个象素位置的取样,放到数组中。
* 如果你定义了一个tick interval,该数组将会自动生成。
* @property yTicks
* @type int[]
*/
yTicks: null,
/**
* 默认下拖放的实例只会响应主要的按钮键(左键和右键)。
* 设置为true表示开放其他的鼠标的键,只要是浏览器支持的。
* @property primaryButtonOnly
* @type boolean
*/
primaryButtonOnly: true,
/**
* 关联的dom元素访问之后该属性才为false。
* @property available
* @type boolean
*/
available: false,
/**
* 默认状态下,拖动只会是mousedown发生在关联元素的区域才会初始化。
* 但是因为某些浏览器的bug,如果之前的mouseup发生在window外部地方,浏览器会漏报告这个事件。
* 如果已定义外部的处理,这个属性应该设置为true.
* @property hasOuterHandles
* @type boolean
* @default false
*/
hasOuterHandles: false,
/**
* 在startDrag时间之前立即执行的代码。
* @method b4StartDrag
* @private
*/
b4StartDrag: function(x, y) { },
/**
* 抽象方法:在拖放对象被点击后和已跨入拖动或mousedown启动时间的时候调用。
* @method startDrag
* @param {int} X 方向点击位置
* @param {int} Y 方向点击位置
*/
startDrag: function(x, y) { /* override this */ },
/**
* onDrag事件发生之前执行的代码。
* @method b4Drag
* @private
*/
b4Drag: function(e) { },
/**
* 抽象方法:当拖动某个对象时发生onMouseMove时调用。
* @method onDrag
* @param {Event} e mousemove事件
*/
onDrag: function(e) { /* override this */ },
/**
* 抽象方法:在这个元素刚刚开始悬停在其他DD对象身上时调用。
* @method onDragEnter
* @param {Event} e mousemove事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组
*/
onDragEnter: function(e, id) { /* override this */ },
/**
* onDragOver事件发生在前执行的代码。
* @method b4DragOver
* @private
*/
b4DragOver: function(e) { },
/**
* 抽象方法:在这个元素悬停在其他DD对象范围内的调用。
* @method onDragOver
* @param {Event} e mousemove事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组
*/
onDragOver: function(e, id) { /* override this */ },
/**
* onDragOut事件发生之前执行的代码。
* @method b4DragOut
* @private
*/
b4DragOut: function(e) { },
/**
* 抽象方法:当不再有任何悬停DD对象的时候调用。
* @method onDragOut
* @param {Event} e mousemove事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, DD项不再悬浮。
*/
onDragOut: function(e, id) { /* override this */ },
/**
* onDragDrop事件发生之前执行的代码。
* @method b4DragDrop
* @private
*/
b4DragDrop: function(e) { },
/**
* 抽象方法:该项在另外一个DD对象上落下的时候调用。
* @method onDragDrop
* @param {Event} e mouseup事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组
*/
onDragDrop: function(e, id) { /* override this */ },
/**
* 抽象方法:当各项在一个没有置下目标的地方置下时调用。
* @method onInvalidDrop
* @param {Event} e mouseup事件
*/
onInvalidDrop: function(e) { /* override this */ },
/**
* 在endDrag事件触发之前立即执行的代码。
* @method b4EndDrag
* @private
*/
b4EndDrag: function(e) { },
/**
* 当我们完成拖动对象时触发的事件。
* @method endDrag
* @param {Event} e mouseup事件
*/
endDrag: function(e) { /* override this */ },
/**
* 在onMouseDown事件触发之前立即执行的代码。
* @method b4MouseDown
* @param {Event} e mousedown事件
* @private
*/
b4MouseDown: function(e) { },
/**
* 当拖放对象mousedown触发时的事件处理器。
* @method onMouseDown
* @param {Event} e mousedown事件
*/
onMouseDown: function(e) { /* override this */ },
/**
* 当DD对象发生mouseup事件时的事件处理器。
* @method onMouseUp
* @param {Event} e mouseup事件
*/
onMouseUp: function(e) { /* override this */ },
/**
* 重写onAvailable的方法以便我们在初始化之后做所需要的事情
* position was determined.
* @method onAvailable
*/
onAvailable: function () {
},
/*
* 为“constrainTo”的元素提供默认的外补丁限制。默认为{left: 0, right:0, top:0, bottom:0}
* @type Object
*/
defaultPadding : {left:0, right:0, top:0, bottom:0},
/**
*
* 初始化拖放对象的限制,以便控制在某个元的范围内移动
* 举例:
<pre><code>
var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest",
{ dragElId: "existingProxyDiv" });
dd.startDrag = function(){
this.constrainTo("parent-id");
};
</code></pre>
*或者你可以使用 {@link Ext.Element}对象初始化它:
<pre><code>
Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
startDrag : function(){
this.constrainTo("parent-id");
}
});
</code></pre>
* @param {String/HTMLElement/Element} constrainTo 要限制的元素
* @param {Object/Number} pad (可选的) Pad提供了指定“外补丁”的限制的一种方式。
* 例如 {left:4, right:4, top:4, bottom:4})或{right:10, bottom:10}
* @param {Boolean} inContent (可选的) 限制在元素的正文内容内拖动(包含外补丁和边框)
*/
constrainTo : function(constrainTo, pad, inContent){
if(typeof pad == "number"){
pad = {left: pad, right:pad, top:pad, bottom:pad};
}
pad = pad || this.defaultPadding;
var b = Ext.get(this.getEl()).getBox();
var ce = Ext.get(constrainTo);
var s = ce.getScroll();
var c, cd = ce.dom;
if(cd == document.body){
c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight()};
}else{
xy = ce.getXY();
c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
}
var topSpace = b.y - c.y;
var leftSpace = b.x - c.x;
this.resetConstraints();
this.setXConstraint(leftSpace - (pad.left||0), // left
c.width - leftSpace - b.width - (pad.right||0) //right
);
this.setYConstraint(topSpace - (pad.top||0), //top
c.height - topSpace - b.height - (pad.bottom||0) //bottom
);
},
/**
* 返回关联元素的引用
* @method getEl
* @return {HTMLElement} html元素
*/
getEl: function() {
if (!this._domRef) {
this._domRef = Ext.getDom(this.id);
}
return this._domRef;
},
/**
* 返回实际拖动元素的引用,默认时和html element一样,不过它可分配给其他元素,可在这里找到。
* @method getDragEl
* @return {HTMLElement} html元素
*/
getDragEl: function() {
return Ext.getDom(this.dragElId);
},
/**
* 设置拖放对象,须在Ext.dd.DragDrop子类的构造器调用。
* @method init
* @param id 关联元素之id
* @param {String} sGroup 相关项的组
* @param {object} config 配置属性
*/
init: function(id, sGroup, config) {
this.initTarget(id, sGroup, config);
Event.on(this.id, "mousedown", this.handleMouseDown, this);
// Event.on(this.id, "selectstart", Event.preventDefault);
},
/**
* 只是有针对性的初始化目标...对象获取不了mousedown handler
* @method initTarget
* @param id 关联元素之id
* @param {String} sGroup 相关项的组
* @param {object} config 配置属性
*/
initTarget: function(id, sGroup, config) {
// configuration attributes
this.config = config || {};
// create a local reference to the drag and drop manager
this.DDM = Ext.dd.DDM;
// initialize the groups array
this.groups = {};
// assume that we have an element reference instead of an id if the
// parameter is not a string
if (typeof id !== "string") {
id = Ext.id(id);
}
// set the id
this.id = id;
// add to an interaction group
this.addToGroup((sGroup) ? sGroup : "default");
// We don't want to register this as the handle with the manager
// so we just set the id rather than calling the setter.
this.handleElId = id;
// the linked element is the element that gets dragged by default
this.setDragElId(id);
// by default, clicked anchors will not start drag operations.
this.invalidHandleTypes = { A: "A" };
this.invalidHandleIds = {};
this.invalidHandleClasses = [];
this.applyConfig();
this.handleOnAvailable();
},
/**
* 将配置参数应用到构造器。该方法应该在继承链上的每一个环节调用。
* 所以为了获取每个对象的可用参数,配置将会由DDPRoxy实现应用在DDProxy, DD,DragDrop身上。
* @method applyConfig
*/
applyConfig: function() {
// configurable properties:
// padding, isTarget, maintainOffset, primaryButtonOnly
this.padding = this.config.padding || [0, 0, 0, 0];
this.isTarget = (this.config.isTarget !== false);
this.maintainOffset = (this.config.maintainOffset);
this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
},
/**
* 当关联元素有效时执行。
* @method handleOnAvailable
* @private
*/
handleOnAvailable: function() {
this.available = true;
this.resetConstraints();
this.onAvailable();
},
/**
* 配置目标区域的外补丁(px)。
* @method setPadding
* @param {int} iTop Top pad
* @param {int} iRight Right pad
* @param {int} iBot Bot pad
* @param {int} iLeft Left pad
*/
setPadding: function(iTop, iRight, iBot, iLeft) {
// this.padding = [iLeft, iRight, iTop, iBot];
if (!iRight && 0 !== iRight) {
this.padding = [iTop, iTop, iTop, iTop];
} else if (!iBot && 0 !== iBot) {
this.padding = [iTop, iRight, iTop, iRight];
} else {
this.padding = [iTop, iRight, iBot, iLeft];
}
},
/**
* 储存关联元素的初始位置。
* @method setInitialPosition
* @param {int} diffX X偏移,默认为0
* @param {int} diffY Y偏移,默认为0
*/
setInitPosition: function(diffX, diffY) {
var el = this.getEl();
if (!this.DDM.verifyEl(el)) {
return;
}
var dx = diffX || 0;
var dy = diffY || 0;
var p = Dom.getXY( el );
this.initPageX = p[0] - dx;
this.initPageY = p[1] - dy;
this.lastPageX = p[0];
this.lastPageY = p[1];
this.setStartPosition(p);
},
/**
* 设置元素的开始位置。对象初始化时便设置,拖动开始时复位。
* @method setStartPosition
* @param pos 当前位置(利用刚才的lookup)
* @private
*/
setStartPosition: function(pos) {
var p = pos || Dom.getXY( this.getEl() );
this.deltaSetXY = null;
this.startPageX = p[0];
this.startPageY = p[1];
},
/**
* 将该对象加入到相关的拖放组之中。
* 所有组实例至少要分配到一个组,也可以是多个组。
* @method addToGroup
* @param sGroup {string} 组名称
*/
addToGroup: function(sGroup) {
this.groups[sGroup] = true;
this.DDM.regDragDrop(this, sGroup);
},
/**
* 传入一个“交互组” interaction group的参数,从中删除该实例。
* @method removeFromGroup
* @param {string} sGroup 组名称
*/
removeFromGroup: function(sGroup) {
if (this.groups[sGroup]) {
delete this.groups[sGroup];
}
this.DDM.removeDDFromGroup(this, sGroup);
},
/**
* 允许你指定一个不是被移动的关联元素的元素作为拖动处理。
* @method setDragElId
* @param id {string} 将会用于初始拖动的元素id
*/
setDragElId: function(id) {
this.dragElId = id;
},
/**
* 允许你指定一个关联元素下面的子元素以初始化拖动操作。
* 一个例子就是假设你有一段套着div文本和若干连接,点击正文的区域便引发拖动的操作。
* 使用这个方法来指定正文内的div元素,然后拖动操作就会从这个元素开始了。
* @method setHandleElId
* @param id {string} 将会用于初始拖动的元素id
*/
setHandleElId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
this.handleElId = id;
this.DDM.regHandle(this.id, id);
},
/**
* 允许你在关联元素之外设置一个元素作为拖动处理。
* @method setOuterHandleElId
* @param id 将会用于初始拖动的元素id
*/
setOuterHandleElId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
Event.on(id, "mousedown",
this.handleMouseDown, this);
this.setHandleElId(id);
this.hasOuterHandles = true;
},
/**
* 移除所有钩在该元素身上的拖放对象。
* @method unreg
*/
unreg: function() {
Event.un(this.id, "mousedown",
this.handleMouseDown);
this._domRef = null;
this.DDM._remove(this);
},
destroy : function(){
this.unreg();
},
/**
* 返回true表示为该实例已被锁定,或者说是拖放控制器(DD Mgr)被锁定。
* @method isLocked
* @return {boolean} true表示禁止页面上的所有拖放操作,反之为false
*/
isLocked: function() {
return (this.DDM.isLocked() || this.locked);
},
/**
* 当对象单击时触发。
* @method handleMouseDown
* @param {Event} e
* @param {Ext.dd.DragDrop} 单击的 DD 对象(this DD obj)
* @private
*/
handleMouseDown: function(e, oDD){
if (this.primaryButtonOnly && e.button != 0) {
return;
}
if (this.isLocked()) {
return;
}
this.DDM.refreshCache(this.groups);
var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e));
if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
} else {
if (this.clickValidator(e)) {
// set the initial element position
this.setStartPosition();
this.b4MouseDown(e);
this.onMouseDown(e);
this.DDM.handleMouseDown(e, this);
this.DDM.stopEvent(e);
} else {
}
}
},
clickValidator: function(e) {
var target = e.getTarget();
return ( this.isValidHandleChild(target) &&
(this.id == this.handleElId ||
this.DDM.handleWasClicked(target, this.id)) );
},
/**
* 指定某个标签名称(tag Name),这个标签的元素单击时便不会引发拖动的操作。
* 这个设计目的在于某个拖动区域中同时又有链接(links)避免执行拖动的动作。
* @method addInvalidHandleType
* @param {string} tagName 避免执行元素的类型
*/
addInvalidHandleType: function(tagName) {
var type = tagName.toUpperCase();
this.invalidHandleTypes[type] = type;
},
/**
* 可指定某个元素的id,则这个id下的子元素将不会引发拖动的操作。
* @method addInvalidHandleId
* @param {string} id 你希望会被忽略的元素id
*/
addInvalidHandleId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
this.invalidHandleIds[id] = id;
},
/**
* 可指定某个css样式类,则这个css样式类的子元素将不会引发拖动的操作。
* @method addInvalidHandleClass
* @param {string} cssClass 你希望会被忽略的css样式类
*/
addInvalidHandleClass: function(cssClass) {
this.invalidHandleClasses.push(cssClass);
},
/**
* 移除由addInvalidHandleType方法所执行的标签名称。
* @method removeInvalidHandleType
* @param {string} tagName 元素类型
*/
removeInvalidHandleType: function(tagName) {
var type = tagName.toUpperCase();
// this.invalidHandleTypes[type] = null;
delete this.invalidHandleTypes[type];
},
/**
* 移除一个无效的handle id
* @method removeInvalidHandleId
* @param {string} id 要再“激活”的元素id
*/
removeInvalidHandleId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
delete this.invalidHandleIds[id];
},
/**
* 移除一个无效的css class
* @method removeInvalidHandleClass
* @param {string} cssClass 你希望要再“激活”的元素id
* re-enable
*/
removeInvalidHandleClass: function(cssClass) {
for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
if (this.invalidHandleClasses[i] == cssClass) {
delete this.invalidHandleClasses[i];
}
}
},
/**
* 检查这次单击是否属于在标签排除列表里。
* @method isValidHandleChild
* @param {HTMLElement} node 检测的HTML元素
* @return {boolean} true 表示为这是一个有效的标签类型,反之为false
*/
isValidHandleChild: function(node) {
var valid = true;
// var n = (node.nodeName == "#text") ? node.parentNode : node;
var nodeName;
try {
nodeName = node.nodeName.toUpperCase();
} catch(e) {
nodeName = node.nodeName;
}
valid = valid && !this.invalidHandleTypes[nodeName];
valid = valid && !this.invalidHandleIds[node.id];
for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
}
return valid;
},
/**
* 若指定了间隔(interval),将会创建水平点击的标记(horizontal tick marks)的数组。
* @method setXTicks
* @private
*/
setXTicks: function(iStartX, iTickSize) {
this.xTicks = [];
this.xTickSize = iTickSize;
var tickMap = {};
for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
if (!tickMap[i]) {
this.xTicks[this.xTicks.length] = i;
tickMap[i] = true;
}
}
for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
if (!tickMap[i]) {
this.xTicks[this.xTicks.length] = i;
tickMap[i] = true;
}
}
this.xTicks.sort(this.DDM.numericSort) ;
},
/**
* 若指定了间隔(interval),将会创建垂直点击的标记(horizontal tick marks)的数组。
* @method setYTicks
* @private
*/
setYTicks: function(iStartY, iTickSize) {
this.yTicks = [];
this.yTickSize = iTickSize;
var tickMap = {};
for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
if (!tickMap[i]) {
this.yTicks[this.yTicks.length] = i;
tickMap[i] = true;
}
}
for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
if (!tickMap[i]) {
this.yTicks[this.yTicks.length] = i;
tickMap[i] = true;
}
}
this.yTicks.sort(this.DDM.numericSort) ;
},
/**
* 默认情况下,元素可被拖动到屏幕的任何一个位置。
* 使用该方法能限制元素的水平方向上的摇动。
* 如果打算只限制在Y轴的拖动,可传入0,0的参数。
* @method setXConstraint
* @param {int} iLeft 元素向左移动的像素值
* @param {int} iRight 元素向右移动的像素值
* @param {int} iTickSize (可选项)指定每次元素移动的步幅。
*/
setXConstraint: function(iLeft, iRight, iTickSize) {
this.leftConstraint = iLeft;
this.rightConstraint = iRight;
this.minX = this.initPageX - iLeft;
this.maxX = this.initPageX + iRight;
if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
this.constrainX = true;
},
/**
* 清除该实例的所有坐标。
* 也清除ticks,因为这时候已不存在任何的坐标。
* @method clearConstraints
*/
clearConstraints: function() {
this.constrainX = false;
this.constrainY = false;
this.clearTicks();
},
/**
* 清除该实例的所有tick间歇定义。
* @method clearTicks
*/
clearTicks: function() {
this.xTicks = null;
this.yTicks = null;
this.xTickSize = 0;
this.yTickSize = 0;
},
/**
* 默认情况下,元素可被拖动到屏幕的任何一个位置。
* 使用该方法能限制元素的水平方向上的摇动。
* 如果打算只限制在X轴的拖动,可传入0,0的参数。
* @method setYConstraint
* @param {int} iUp 元素向上移动的像素值
* @param {int} iDown 元素向下移动的像素值
* @param {int} iTickSize (可选项)指定每次元素移动的步幅。
*/
setYConstraint: function(iUp, iDown, iTickSize) {
this.topConstraint = iUp;
this.bottomConstraint = iDown;
this.minY = this.initPageY - iUp;
this.maxY = this.initPageY + iDown;
if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
this.constrainY = true;
},
/**
* 坐标复位需在你手动重新定位一个DD元素是调用。
* @method resetConstraints
* @param {boolean} maintainOffset
*/
resetConstraints: function() {
// Maintain offsets if necessary
if (this.initPageX || this.initPageX === 0) {
// figure out how much this thing has moved
var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
this.setInitPosition(dx, dy);
// This is the first time we have detected the element's position
} else {
this.setInitPosition();
}
if (this.constrainX) {
this.setXConstraint( this.leftConstraint,
this.rightConstraint,
this.xTickSize );
}
if (this.constrainY) {
this.setYConstraint( this.topConstraint,
this.bottomConstraint,
this.yTickSize );
}
},
/**
* 通常情况下拖动元素是逐个像素地移动的。
* 不过我们也可以指定一个移动的数值。
* @method getTick
* @param {int} val 打算将对象放到的地方
* @param {int[]} tickArray 已排序的有效点
* @return {int} 最近的点
* @private
*/
getTick: function(val, tickArray) {
if (!tickArray) {
// If tick interval is not defined, it is effectively 1 pixel,
// so we return the value passed to us.
return val;
} else if (tickArray[0] >= val) {
// The value is lower than the first tick, so we return the first
// tick.
return tickArray[0];
} else {
for (var i=0, len=tickArray.length; i<len; ++i) {
var next = i + 1;
if (tickArray[next] && tickArray[next] >= val) {
var diff1 = val - tickArray[i];
var diff2 = tickArray[next] - val;
return (diff2 > diff1) ? tickArray[i] : tickArray[next];
}
}
// The value is larger than the last tick, so we return the last
// tick.
return tickArray[tickArray.length - 1];
}
},
/**
* toString方法
* @method toString
* @return {string} string 表示DD对象之字符
*/
toString: function() {
return ("DragDrop " + this.id);
}
};
})();
/**
* The drag and drop utility provides a framework for building drag and drop
* applications. In addition to enabling drag and drop for specific elements,
* the drag and drop elements are tracked by the manager class, and the
* interactions between the various elements are tracked during the drag and
* the implementing code is notified about these important moments.
*/
// Only load the library once. Rewriting the manager class would orphan
// existing drag and drop instances.
if (!Ext.dd.DragDropMgr) {
/**
* @class Ext.dd.DragDropMgr
* DragDropMgr是一个对窗口内所有拖放项跟踪元素交互过程的单例。
* 一般来说你不会直接调用该类,但是你所实现的拖放中,会提供一些有用的方法。
* @singleton
*/
Ext.dd.DragDropMgr = function() {
var Event = Ext.EventManager;
return {
/**
* 已登记拖放对象的二维数组。
* 第一维是拖放项的组,第二维是拖放对象。
* @property ids
* @type {string: string}
* @private
* @static
*/
ids: {},
/**
* 元素id组成的数组,由拖动处理定义。
* 如果元素触发了mousedown事件实际上是一个处理(handle)而非html元素本身。
* @property handleIds
* @type {string: string}
* @private
* @static
*/
handleIds: {},
/**
* 正在被拖放的DD对象。
* @property dragCurrent
* @type DragDrop
* @private
* @static
**/
dragCurrent: null,
/**
* 正被悬浮着的拖放对象。
* @property dragOvers
* @type Array
* @private
* @static
*/
dragOvers: {},
/**
* 正被拖动对象与指针之间的X间距。
* @property deltaX
* @type int
* @private
* @static
*/
deltaX: 0,
/**
* 正被拖动对象与指针之间的Y间距。
* @property deltaY
* @type int
* @private
* @static
*/
deltaY: 0,
/**
* 一个是否应该阻止我们所定义的默认行为的标识。
* 默认为true,如需默认的行为可设为false(但不推荐)。
* @property preventDefault
* @type boolean
* @static
*/
preventDefault: true,
/**
* 一个是否在该停止事件繁殖的标识(events propagation)。
* 默认下为true,但如果HTML元素包含了其他mouse点击的所需功能,就可设为false。
* @property stopPropagation
* @type boolean
* @static
*/
stopPropagation: true,
/**
* 一个内置使用的标识,True说明拖放已被初始化。
* @property initialized
* @private
* @static
*/
initalized: false,
/**
* 所有拖放的操作可被禁用。
* @property locked
* @private
* @static
*/
locked: false,
/**
* 元素首次注册时调用。
* @method init
* @private
* @static
*/
init: function() {
this.initialized = true;
},
/**
* 由拖放过程中的鼠标指针来定义拖放的交互操作。
* @property POINT
* @type int
* @static
*/
POINT: 0,
/**
* Intersect模式下,拖放的交互是由两个或两个以上的拖放对象的重叠来定义。
* @property INTERSECT
* @type int
* @static
*/
INTERSECT: 1,
/**
* 当前拖放的模式,默认为:POINT
* @property mode
* @type int
* @static
*/
mode: 0,
/**
* 在拖放对象上运行方法
* @method _execOnAll
* @private
* @static
*/
_execOnAll: function(sMethod, args) {
for (var i in this.ids) {
for (var j in this.ids[i]) {
var oDD = this.ids[i][j];
if (! this.isTypeOfDD(oDD)) {
continue;
}
oDD[sMethod].apply(oDD, args);
}
}
},
/**
* 拖放的初始化,设置全局的事件处理器。
* @method _onLoad
* @private
* @static
*/
_onLoad: function() {
this.init();
Event.on(document, "mouseup", this.handleMouseUp, this, true);
Event.on(document, "mousemove", this.handleMouseMove, this, true);
Event.on(window, "unload", this._onUnload, this, true);
Event.on(window, "resize", this._onResize, this, true);
// Event.on(window, "mouseout", this._test);
},
/**
* 重置拖放对象身上的全部限制。
* @method _onResize
* @private
* @static
*/
_onResize: function(e) {
this._execOnAll("resetConstraints", []);
},
/**
* 锁定拖放的功能。
* @method lock
* @static
*/
lock: function() { this.locked = true; },
/**
* 解锁拖放的功能。
* @method unlock
* @static
*/
unlock: function() { this.locked = false; },
/**
* 拖放是否已锁定?
* @method isLocked
* @return {boolean} True 表示为拖放已锁定,反之为false。
* @static
*/
isLocked: function() { return this.locked; },
/**
* 拖动一开始,就会有“局部缓存”伴随着拖放对象,而拖动完毕就会清除。
* @property locationCache
* @private
* @static
*/
locationCache: {},
/**
* 设置useCache为false的话,表示你想强制对象不断在每个拖放关联对象中轮询。
* @property useCache
* @type boolean
* @static
*/
useCache: true,
/**
* 在mousedown之后,拖动初始化之前,鼠标需要移动的像素值。默认值为3
* @property clickPixelThresh
* @type int
* @static
*/
clickPixelThresh: 3,
/**
* 在mousedown事件触发之后,接着开始拖动但不想触发mouseup的事件的毫秒数。默认值为1000
* @property clickTimeThresh
* @type int
* @static
*/
clickTimeThresh: 350,
/**
* 每当满足拖动像素或mousedown时间的标识。
* @property dragThreshMet
* @type boolean
* @private
* @static
*/
dragThreshMet: false,
/**
* 开始点击的超时时限。
* @property clickTimeout
* @type Object
* @private
* @static
*/
clickTimeout: null,
/**
* 拖动动作刚开始,保存mousedown事件的X位置。
* @property startX
* @type int
* @private
* @static
*/
startX: 0,
/**
* 拖动动作刚开始,保存mousedown事件的Y位置。
* @property startY
* @type int
* @private
* @static
*/
startY: 0,
/**
* 每个拖放实例必须在DragDropMgr登记好的。
* @method regDragDrop
* @param {DragDrop} oDD 要登记的拖动对象
* @param {String} sGroup 元素所属的组名称
* @static
*/
regDragDrop: function(oDD, sGroup) {
if (!this.initialized) { this.init(); }
if (!this.ids[sGroup]) {
this.ids[sGroup] = {};
}
this.ids[sGroup][oDD.id] = oDD;
},
/**
* 传入两个参数oDD、sGroup,从传入的组之中删除DD实例。
* 由DragDrop.removeFromGroup执行,所以不会直接调用这个函数。
* @method removeDDFromGroup
* @private
* @static
*/
removeDDFromGroup: function(oDD, sGroup) {
if (!this.ids[sGroup]) {
this.ids[sGroup] = {};
}
var obj = this.ids[sGroup];
if (obj && obj[oDD.id]) {
delete obj[oDD.id];
}
},
/**
* 注销拖放项,由DragDrop.unreg所调用,直接使用那个方法即可。
* @method _remove
* @private
* @static
*/
_remove: function(oDD) {
for (var g in oDD.groups) {
if (g && this.ids[g][oDD.id]) {
delete this.ids[g][oDD.id];
}
}
delete this.handleIds[oDD.id];
},
/**
* 每个拖放处理元素必须先登记。
* 执行DragDrop.setHandleElId()时会自动完成这工作。
* @method regHandle
* @param {String} sDDId 处理拖放对象的id
* @param {String} sHandleId 在拖动的元素id
* handle
* @static
*/
regHandle: function(sDDId, sHandleId) {
if (!this.handleIds[sDDId]) {
this.handleIds[sDDId] = {};
}
this.handleIds[sDDId][sHandleId] = sHandleId;
},
/**
* 确认一个元素是否属于已注册的拖放项的实用函数。
* @method isDragDrop
* @param {String} id 要检查的元素id
* @return {boolean} true 表示为该元素是一个拖放项,反之为false
* @static
*/
isDragDrop: function(id) {
return ( this.getDDById(id) ) ? true : false;
},
/**
* 传入一个拖放实例的参数,返回在这个实例“组”下面的全部其他拖放实例。
* @method getRelated
* @param {DragDrop} p_oDD 获取相关数据的对象
* @param {boolean} bTargetsOnly if true 表示为只返回目标对象
* @return {DragDrop[]} 相关的实例
* @static
*/
getRelated: function(p_oDD, bTargetsOnly) {
var oDDs = [];
for (var i in p_oDD.groups) {
for (j in this.ids[i]) {
var dd = this.ids[i][j];
if (! this.isTypeOfDD(dd)) {
continue;
}
if (!bTargetsOnly || dd.isTarget) {
oDDs[oDDs.length] = dd;
}
}
}
return oDDs;
},
/**
* 针对某些特定的拖动对象,如果传入的dd目标是合法的目标,返回ture。
* @method isLegalTarget
* @param {DragDrop} 拖动对象
* @param {DragDrop} 目标
* @return {boolean} true 表示为目标是dd对象合法
* @static
*/
isLegalTarget: function (oDD, oTargetDD) {
var targets = this.getRelated(oDD, true);
for (var i=0, len=targets.length;i<len;++i) {
if (targets[i].id == oTargetDD.id) {
return true;
}
}
return false;
},
/**
* My goal is to be able to transparently determine if an object is
* typeof DragDrop, and the exact subclass of DragDrop. typeof
* returns "object", oDD.constructor.toString() always returns
* "DragDrop" and not the name of the subclass. So for now it just
* evaluates a well-known variable in DragDrop.
* @method isTypeOfDD
* @param {Object} 要计算的对象
* @return {boolean} true 表示为typeof oDD = DragDrop
* @static
*/
isTypeOfDD: function (oDD) {
return (oDD && oDD.__ygDragDrop);
},
/**
* 指定拖放对象,检测给出的元素是否属于已登记的拖放处理中的一员。
* @method isHandle
* @param {String} id 要检测的对象
* @return {boolean} True表示为元素是拖放的处理
* @static
*/
isHandle: function(sDDId, sHandleId) {
return ( this.handleIds[sDDId] &&
this.handleIds[sDDId][sHandleId] );
},
/**
* 指定一个id,返回该id的拖放实例。
* @method getDDById
* @param {String} id 拖放对象的id
* @return {DragDrop} 拖放对象,null表示为找不到
* @static
*/
getDDById: function(id) {
for (var i in this.ids) {
if (this.ids[i][id]) {
return this.ids[i][id];
}
}
return null;
},
/**
* 在一个已登记的拖放对象上发生mousedown事件之后触发。
* @method handleMouseDown
* @param {Event} e 事件
* @param oDD 被拖动的拖放对象
* @private
* @static
*/
handleMouseDown: function(e, oDD) {
if(Ext.QuickTips){
Ext.QuickTips.disable();
}
this.currentTarget = e.getTarget();
this.dragCurrent = oDD;
var el = oDD.getEl();
// track start position
this.startX = e.getPageX();
this.startY = e.getPageY();
this.deltaX = this.startX - el.offsetLeft;
this.deltaY = this.startY - el.offsetTop;
this.dragThreshMet = false;
this.clickTimeout = setTimeout(
function() {
var DDM = Ext.dd.DDM;
DDM.startDrag(DDM.startX, DDM.startY);
},
this.clickTimeThresh );
},
/**
* 当拖动象素开始启动或mousedown保持事件正好发生的时候发生。
* @method startDrag
* @param x {int} 原始mousedown发生的X位置
* @param y {int} 原始mousedown发生的Y位置
* @static
*/
startDrag: function(x, y) {
clearTimeout(this.clickTimeout);
if (this.dragCurrent) {
this.dragCurrent.b4StartDrag(x, y);
this.dragCurrent.startDrag(x, y);
}
this.dragThreshMet = true;
},
/**
* 处理MouseUp事件的内置函数,会涉及文档的上下文内容。
* @method handleMouseUp
* @param {Event} e 事件
* @private
* @static
*/
handleMouseUp: function(e) {
if(Ext.QuickTips){
Ext.QuickTips.enable();
}
if (! this.dragCurrent) {
return;
}
clearTimeout(this.clickTimeout);
if (this.dragThreshMet) {
this.fireEvents(e, true);
} else {
}
this.stopDrag(e);
this.stopEvent(e);
},
/**
* 如果停止事件值和默认(event propagation)的一项被打开,要执行的实用函数。
* @method stopEvent
* @param {Event} e 由this.getEvent()返回的事件
* @static
*/
stopEvent: function(e){
if(this.stopPropagation) {
e.stopPropagation();
}
if (this.preventDefault) {
e.preventDefault();
}
},
/**
* 内置函数,用于在拖动操作完成后清理事件处理器(event handlers)
* @method stopDrag
* @param {Event} e 事件
* @private
* @static
*/
stopDrag: function(e) {
// Fire the drag end event for the item that was dragged
if (this.dragCurrent) {
if (this.dragThreshMet) {
this.dragCurrent.b4EndDrag(e);
this.dragCurrent.endDrag(e);
}
this.dragCurrent.onMouseUp(e);
}
this.dragCurrent = null;
this.dragOvers = {};
},
/**
* 处理mousemove事件的内置函数,会涉及html元素的上下文内容。
* @TODO figure out what we can do about mouse events lost when the
* user drags objects beyond the window boundary. Currently we can
* detect this in internet explorer by verifying that the mouse is
* down during the mousemove event. Firefox doesn't give us the
* button state on the mousemove event.
* @method handleMouseMove
* @param {Event} e 事件
* @private
* @static
*/
handleMouseMove: function(e) {
if (! this.dragCurrent) {
return true;
}
// var button = e.which || e.button;
// check for IE mouseup outside of page boundary
if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
this.stopEvent(e);
return this.handleMouseUp(e);
}
if (!this.dragThreshMet) {
var diffX = Math.abs(this.startX - e.getPageX());
var diffY = Math.abs(this.startY - e.getPageY());
if (diffX > this.clickPixelThresh ||
diffY > this.clickPixelThresh) {
this.startDrag(this.startX, this.startY);
}
}
if (this.dragThreshMet) {
this.dragCurrent.b4Drag(e);
this.dragCurrent.onDrag(e);
if(!this.dragCurrent.moveOnly){
this.fireEvents(e, false);
}
}
this.stopEvent(e);
return true;
},
/**
* 遍历所有的拖放对象找出我们悬浮或落下的那一个。
* @method fireEvents
* @param {Event} e 事件
* @param {boolean} isDrop 是drop还是mouseover?
* @private
* @static
*/
fireEvents: function(e, isDrop) {
var dc = this.dragCurrent;
// If the user did the mouse up outside of the window, we could
// get here even though we have ended the drag.
if (!dc || dc.isLocked()) {
return;
}
var pt = e.getPoint();
// cache the previous dragOver array
var oldOvers = [];
var outEvts = [];
var overEvts = [];
var dropEvts = [];
var enterEvts = [];
// Check to see if the object(s) we were hovering over is no longer
// being hovered over so we can fire the onDragOut event
for (var i in this.dragOvers) {
var ddo = this.dragOvers[i];
if (! this.isTypeOfDD(ddo)) {
continue;
}
if (! this.isOverTarget(pt, ddo, this.mode)) {
outEvts.push( ddo );
}
oldOvers[i] = true;
delete this.dragOvers[i];
}
for (var sGroup in dc.groups) {
if ("string" != typeof sGroup) {
continue;
}
for (i in this.ids[sGroup]) {
var oDD = this.ids[sGroup][i];
if (! this.isTypeOfDD(oDD)) {
continue;
}
if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
if (this.isOverTarget(pt, oDD, this.mode)) {
// look for drop interactions
if (isDrop) {
dropEvts.push( oDD );
// look for drag enter and drag over interactions
} else {
// initial drag over: dragEnter fires
if (!oldOvers[oDD.id]) {
enterEvts.push( oDD );
// subsequent drag overs: dragOver fires
} else {
overEvts.push( oDD );
}
this.dragOvers[oDD.id] = oDD;
}
}
}
}
}
if (this.mode) {
if (outEvts.length) {
dc.b4DragOut(e, outEvts);
dc.onDragOut(e, outEvts);
}
if (enterEvts.length) {
dc.onDragEnter(e, enterEvts);
}
if (overEvts.length) {
dc.b4DragOver(e, overEvts);
dc.onDragOver(e, overEvts);
}
if (dropEvts.length) {
dc.b4DragDrop(e, dropEvts);
dc.onDragDrop(e, dropEvts);
}
} else {
// fire dragout events
var len = 0;
for (i=0, len=outEvts.length; i<len; ++i) {
dc.b4DragOut(e, outEvts[i].id);
dc.onDragOut(e, outEvts[i].id);
}
// fire enter events
for (i=0,len=enterEvts.length; i<len; ++i) {
// dc.b4DragEnter(e, oDD.id);
dc.onDragEnter(e, enterEvts[i].id);
}
// fire over events
for (i=0,len=overEvts.length; i<len; ++i) {
dc.b4DragOver(e, overEvts[i].id);
dc.onDragOver(e, overEvts[i].id);
}
// fire drop events
for (i=0, len=dropEvts.length; i<len; ++i) {
dc.b4DragDrop(e, dropEvts[i].id);
dc.onDragDrop(e, dropEvts[i].id);
}
}
// notify about a drop that did not find a target
if (isDrop && !dropEvts.length) {
dc.onInvalidDrop(e);
}
},
/**
* 当INTERSECT模式时,通过拖放事件返回拖放对象的列表。
* 这个辅助函数的作用是在这份列表中获取最适合的配对。
* 有时返回指鼠标下方的第一个对象,有时返回与拖动对象重叠的最大一个对象。
* @method getBestMatch
* @param {DragDrop[]} dds 拖放对象之数组
* targeted
* @return {DragDrop} 最佳的单个配对
* @static
*/
getBestMatch: function(dds) {
var winner = null;
// Return null if the input is not what we expect
//if (!dds || !dds.length || dds.length == 0) {
// winner = null;
// If there is only one item, it wins
//} else if (dds.length == 1) {
var len = dds.length;
if (len == 1) {
winner = dds[0];
} else {
// Loop through the targeted items
for (var i=0; i<len; ++i) {
var dd = dds[i];
// If the cursor is over the object, it wins. If the
// cursor is over multiple matches, the first one we come
// to wins.
if (dd.cursorIsOver) {
winner = dd;
break;
// Otherwise the object with the most overlap wins
} else {
if (!winner ||
winner.overlap.getArea() < dd.overlap.getArea()) {
winner = dd;
}
}
}
}
return winner;
},
/**
* 在指定组中,刷新位于左上方和右下角的点的缓存。
* 这是保存在拖放实例中的格式。所以典型的用法是:
* <code>
* Ext.dd.DragDropMgr.refreshCache(ddinstance.groups);
* </code>
* 也可这样:
* <code>
* Ext.dd.DragDropMgr.refreshCache({group1:true, group2:true});
* </code>
* @TODO this really should be an indexed array. Alternatively this
* method could accept both.
* @method refreshCache
* @param {Object} groups 要刷新的关联组的数组
* @static
*/
refreshCache: function(groups) {
for (var sGroup in groups) {
if ("string" != typeof sGroup) {
continue;
}
for (var i in this.ids[sGroup]) {
var oDD = this.ids[sGroup][i];
if (this.isTypeOfDD(oDD)) {
// if (this.isTypeOfDD(oDD) && oDD.isTarget) {
var loc = this.getLocation(oDD);
if (loc) {
this.locationCache[oDD.id] = loc;
} else {
delete this.locationCache[oDD.id];
// this will unregister the drag and drop object if
// the element is not in a usable state
// oDD.unreg();
}
}
}
}
},
/**
* 检验一个元素是否存在DOM树中,该方法用于innerHTML。
* @method verifyEl
* @param {HTMLElement} el 要检测的元素
* @return {boolean} true 表示为元素似乎可用
* @static
*/
verifyEl: function(el) {
if (el) {
var parent;
if(Ext.isIE){
try{
parent = el.offsetParent;
}catch(e){}
}else{
parent = el.offsetParent;
}
if (parent) {
return true;
}
}
return false;
},
/**
* 返回一个区域对象(Region Object)。
* 这个区域包含拖放元素位置、大小、和针对其配置好的内补丁(padding)
* @method getLocation
* @param {DragDrop} oDD 要获取所在位置的拖放对象
* @return {Ext.lib.Region} 区域对象,包括元素占位,该实例配置的外补丁。
* @static
*/
getLocation: function(oDD) {
if (! this.isTypeOfDD(oDD)) {
return null;
}
var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
try {
pos= Ext.lib.Dom.getXY(el);
} catch (e) { }
if (!pos) {
return null;
}
x1 = pos[0];
x2 = x1 + el.offsetWidth;
y1 = pos[1];
y2 = y1 + el.offsetHeight;
t = y1 - oDD.padding[0];
r = x2 + oDD.padding[1];
b = y2 + oDD.padding[2];
l = x1 - oDD.padding[3];
return new Ext.lib.Region( t, r, b, l );
},
/**
* 检查鼠标指针是否位于目标的上方。
* @method isOverTarget
* @param {Ext.lib.Point} pt 要检测的点
* @param {DragDrop} oTarget 要检测的拖放对象
* @return {boolean} true 表示为鼠标位于目标上方
* @private
* @static
*/
isOverTarget: function(pt, oTarget, intersect) {
// use cache if available
var loc = this.locationCache[oTarget.id];
if (!loc || !this.useCache) {
loc = this.getLocation(oTarget);
this.locationCache[oTarget.id] = loc;
}
if (!loc) {
return false;
}
oTarget.cursorIsOver = loc.contains( pt );
// DragDrop is using this as a sanity check for the initial mousedown
// in this case we are done. In POINT mode, if the drag obj has no
// contraints, we are also done. Otherwise we need to evaluate the
// location of the target as related to the actual location of the
// dragged element.
var dc = this.dragCurrent;
if (!dc || !dc.getTargetCoord ||
(!intersect && !dc.constrainX && !dc.constrainY)) {
return oTarget.cursorIsOver;
}
oTarget.overlap = null;
// Get the current location of the drag element, this is the
// location of the mouse event less the delta that represents
// where the original mousedown happened on the element. We
// need to consider constraints and ticks as well.
var pos = dc.getTargetCoord(pt.x, pt.y);
var el = dc.getDragEl();
var curRegion = new Ext.lib.Region( pos.y,
pos.x + el.offsetWidth,
pos.y + el.offsetHeight,
pos.x );
var overlap = curRegion.intersect(loc);
if (overlap) {
oTarget.overlap = overlap;
return (intersect) ? true : oTarget.cursorIsOver;
} else {
return false;
}
},
/**
* 卸下事件处理器。
* @method _onUnload
* @private
* @static
*/
_onUnload: function(e, me) {
Ext.dd.DragDropMgr.unregAll();
},
/**
* 清除拖放事件和对象。
* @method unregAll
* @private
* @static
*/
unregAll: function() {
if (this.dragCurrent) {
this.stopDrag();
this.dragCurrent = null;
}
this._execOnAll("unreg", []);
for (i in this.elementCache) {
delete this.elementCache[i];
}
this.elementCache = {};
this.ids = {};
},
/**
* DOM元素的缓存。
* @property elementCache
* @private
* @static
*/
elementCache: {},
/**
* 返回DOM元素所指定的包装器。
* @method getElWrapper
* @param {String} id 要获取的元素id
* @return {Ext.dd.DDM.ElementWrapper} 包装好的元素
* @private
* @deprecated 该包装器用途较小
* @static
*/
getElWrapper: function(id) {
var oWrapper = this.elementCache[id];
if (!oWrapper || !oWrapper.el) {
oWrapper = this.elementCache[id] =
new this.ElementWrapper(Ext.getDom(id));
}
return oWrapper;
},
/**
* 返回实际的DOM元素。
* @method getElement
* @param {String} id 要获取的元素的id
* @return {Object} 元素
* @deprecated 推荐使用Ext.lib.Ext.getDom
* @static
*/
getElement: function(id) {
return Ext.getDom(id);
},
/**
* 返回该DOM元素的样式属性。
* @method getCss
* @param {String} id 要获取元素的id
* @return {Object} 元素样式属性
* @deprecated 推荐使用Ext.lib.Dom
* @static
*/
getCss: function(id) {
var el = Ext.getDom(id);
return (el) ? el.style : null;
},
/**
* 缓冲元素的内置类
* @class DragDropMgr.ElementWrapper
* @for DragDropMgr
* @private
* @deprecated
*/
ElementWrapper: function(el) {
/**
* The element
* @property el
*/
this.el = el || null;
/**
* The element id
* @property id
*/
this.id = this.el && el.id;
/**
* A reference to the style property
* @property css
*/
this.css = this.el && el.style;
},
/**
* 返回html元素的X坐标。
* @method getPosX
* @param el 指获取坐标的元素
* @return {int} x坐标
* @for DragDropMgr
* @deprecated 推荐使用Ext.lib.Dom.getX
* @static
*/
getPosX: function(el) {
return Ext.lib.Dom.getX(el);
},
/**
* 返回html元素的Y坐标。
* @method getPosY
* @param el 指获取坐标的元素
* @return {int} y坐标
* @deprecated 推荐使用Ext.lib.Dom.getY
* @static
*/
getPosY: function(el) {
return Ext.lib.Dom.getY(el);
},
/**
* 调换两个节点,对于IE,我们使用原生的方法。
* @method swapNode
* @param n1 要调换的第一个节点
* @param n2 要调换的其他节点
* @static
*/
swapNode: function(n1, n2) {
if (n1.swapNode) {
n1.swapNode(n2);
} else {
var p = n2.parentNode;
var s = n2.nextSibling;
if (s == n1) {
p.insertBefore(n1, n2);
} else if (n2 == n1.nextSibling) {
p.insertBefore(n2, n1);
} else {
n1.parentNode.replaceChild(n2, n1);
p.insertBefore(n1, s);
}
}
},
/**
* 返回当前滚动位置。
* @method getScroll
* @private
* @static
*/
getScroll: function () {
var t, l, dde=document.documentElement, db=document.body;
if (dde && (dde.scrollTop || dde.scrollLeft)) {
t = dde.scrollTop;
l = dde.scrollLeft;
} else if (db) {
t = db.scrollTop;
l = db.scrollLeft;
} else {
}
return { top: t, left: l };
},
/**
* 指定一个元素,返回其样式的某个属性。
* @method getStyle
* @param {HTMLElement} el 元素
* @param {string} styleProp 样式名称
* @return {string} 样式值
* @deprecated use Ext.lib.Dom.getStyle
* @static
*/
getStyle: function(el, styleProp) {
return Ext.fly(el).getStyle(styleProp);
},
/**
* 获取scrollTop
* @method getScrollTop
* @return {int} 文档的scrollTop
* @static
*/
getScrollTop: function () { return this.getScroll().top; },
/**
* 获取scrollLeft
* @method getScrollLeft
* @return {int} 文档的scrollTop
* @static
*/
getScrollLeft: function () { return this.getScroll().left; },
/**
* 根据目标元素的位置,设置元素的X/Y位置。
* @method moveToEl
* @param {HTMLElement} moveEl 要移动的元素
* @param {HTMLElement} targetEl 引用元素的位置
* @static
*/
moveToEl: function (moveEl, targetEl) {
var aCoord = Ext.lib.Dom.getXY(targetEl);
Ext.lib.Dom.setXY(moveEl, aCoord);
},
/**
* 数组排列函数
* @method numericSort
* @static
*/
numericSort: function(a, b) { return (a - b); },
/**
* 局部计算器
* @property _timeoutCount
* @private
* @static
*/
_timeoutCount: 0,
/**
* 试着押后加载,这样便不会在Event Utility文件加载之前出现的错误。
* @method _addListeners
* @private
* @static
*/
_addListeners: function() {
var DDM = Ext.dd.DDM;
if ( Ext.lib.Event && document ) {
DDM._onLoad();
} else {
if (DDM._timeoutCount > 2000) {
} else {
setTimeout(DDM._addListeners, 10);
if (document && document.body) {
DDM._timeoutCount += 1;
}
}
}
},
/**
* 递归搜索最靠近的父、子元素,以便确定处理的元素是否被单击。
* @method handleWasClicked
* @param node 要检测的html元素
* @static
*/
handleWasClicked: function(node, id) {
if (this.isHandle(id, node.id)) {
return true;
} else {
// check to see if this is a text node child of the one we want
var p = node.parentNode;
while (p) {
if (this.isHandle(id, p.id)) {
return true;
} else {
p = p.parentNode;
}
}
}
return false;
}
};
}();
// shorter alias, save a few bytes
Ext.dd.DDM = Ext.dd.DragDropMgr;
Ext.dd.DDM._addListeners();
}
/**
* @class Ext.dd.DD
* 在拖动过程中随伴鼠标指针关联元素的一个播放实现。
* @extends Ext.dd.DragDrop
* @constructor
* @param {String} id 关联元素的id
* @param {String} sGroup 关联拖放项的组
* @param {object} config 包含DD的有效配置属性:
* scroll
*/
Ext.dd.DD = function(id, sGroup, config) {
if (id) {
this.init(id, sGroup, config);
}
};
Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, {
/**
* 设置为true时,游览器窗口会自动滚动,如果拖放元素被拖到视图的边界,默认为true。
* @property scroll
* @type boolean
*/
scroll: true,
/**
* 在关联元素的左上角和元素点击所在位置之间设置一个指针偏移的距离。
* @method autoOffset
* @param {int} iPageX 点击的X坐标
* @param {int} iPageY 点击的Y坐标
*/
autoOffset: function(iPageX, iPageY) {
var x = iPageX - this.startPageX;
var y = iPageY - this.startPageY;
this.setDelta(x, y);
},
/**
* 设置指针偏移,你可以直接调用以强制偏移到新特殊的位置(像传入0,0,即设置成为对象的一角)。
* @method setDelta
* @param {int} iDeltaX 从左边算起的距离
* @param {int} iDeltaY 从上面算起的距离
*/
setDelta: function(iDeltaX, iDeltaY) {
this.deltaX = iDeltaX;
this.deltaY = iDeltaY;
},
/**
* 设置拖动元素到mousedown或点击事件的位置继续保持指针相关联元素点击的位置。
* 如果打算将元素放到某个位置而非指针位置,你可重写该方法。
* @method setDragElPos
* @param {int} iPageX mousedown或拖动事件的X坐标
* @param {int} iPageY mousedown或拖动事件的Y坐标
*/
setDragElPos: function(iPageX, iPageY) {
// the first time we do this, we are going to check to make sure
// the element has css positioning
var el = this.getDragEl();
this.alignElWithMouse(el, iPageX, iPageY);
},
/**
* 设置元素到mousedown或点击事件的位置继续保持指针相关联元素点击的位置。
* 如果打算将元素放到某个位置而非指针位置,你可重写该方法。
* @method alignElWithMouse
* @param {HTMLElement} el the element to move
* @param {int} iPageX mousedown或拖动事件的X坐标
* @param {int} iPageY mousedown或拖动事件的Y坐标
*/
alignElWithMouse: function(el, iPageX, iPageY) {
var oCoord = this.getTargetCoord(iPageX, iPageY);
var fly = el.dom ? el : Ext.fly(el);
if (!this.deltaSetXY) {
var aCoord = [oCoord.x, oCoord.y];
fly.setXY(aCoord);
var newLeft = fly.getLeft(true);
var newTop = fly.getTop(true);
this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
} else {
fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
}
this.cachePosition(oCoord.x, oCoord.y);
this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
return oCoord;
},
/**
* 保存最近的位置,以便我们重量限制和所需要的点击标记。
* 我们需要清楚这些以便计算元素偏移原来位置的像素值。
* @method cachePosition
* @param iPageX 当前X位置(可选的),只要为了以后不用再查询
* @param iPageY 当前Y位置(可选的),只要为了以后不用再查询
*/
cachePosition: function(iPageX, iPageY) {
if (iPageX) {
this.lastPageX = iPageX;
this.lastPageY = iPageY;
} else {
var aCoord = Ext.lib.Dom.getXY(this.getEl());
this.lastPageX = aCoord[0];
this.lastPageY = aCoord[1];
}
},
/**
* 如果拖动对象移动到可视窗口之外的区域,就自动滚动window。
* @method autoScroll
* @param {int} x 拖动元素X坐标
* @param {int} y 拖动元素Y坐标
* @param {int} h 拖动元素的高度
* @param {int} w 拖动元素的宽度
* @private
*/
autoScroll: function(x, y, h, w) {
if (this.scroll) {
// The client height
var clientH = Ext.lib.Dom.getViewWidth();
// The client width
var clientW = Ext.lib.Dom.getViewHeight();
// The amt scrolled down
var st = this.DDM.getScrollTop();
// The amt scrolled right
var sl = this.DDM.getScrollLeft();
// Location of the bottom of the element
var bot = h + y;
// Location of the right of the element
var right = w + x;
// The distance from the cursor to the bottom of the visible area,
// adjusted so that we don't scroll if the cursor is beyond the
// element drag constraints
var toBot = (clientH + st - y - this.deltaY);
// The distance from the cursor to the right of the visible area
var toRight = (clientW + sl - x - this.deltaX);
// How close to the edge the cursor must be before we scroll
// var thresh = (document.all) ? 100 : 40;
var thresh = 40;
// How many pixels to scroll per autoscroll op. This helps to reduce
// clunky scrolling. IE is more sensitive about this ... it needs this
// value to be higher.
var scrAmt = (document.all) ? 80 : 30;
// Scroll down if we are near the bottom of the visible page and the
// obj extends below the crease
if ( bot > clientH && toBot < thresh ) {
window.scrollTo(sl, st + scrAmt);
}
// Scroll up if the window is scrolled down and the top of the object
// goes above the top border
if ( y < st && st > 0 && y - st < thresh ) {
window.scrollTo(sl, st - scrAmt);
}
// Scroll right if the obj is beyond the right border and the cursor is
// near the border.
if ( right > clientW && toRight < thresh ) {
window.scrollTo(sl + scrAmt, st);
}
// Scroll left if the window has been scrolled to the right and the obj
// extends past the left border
if ( x < sl && sl > 0 && x - sl < thresh ) {
window.scrollTo(sl - scrAmt, st);
}
}
},
/**
* 找到元素应该放下的位置。
* @method getTargetCoord
* @param {int} iPageX 点击的X坐标
* @param {int} iPageY 点击的Y坐标
* @return 包含坐标的对象(Object.x和Object.y)
* @private
*/
getTargetCoord: function(iPageX, iPageY) {
var x = iPageX - this.deltaX;
var y = iPageY - this.deltaY;
if (this.constrainX) {
if (x < this.minX) { x = this.minX; }
if (x > this.maxX) { x = this.maxX; }
}
if (this.constrainY) {
if (y < this.minY) { y = this.minY; }
if (y > this.maxY) { y = this.maxY; }
}
x = this.getTick(x, this.xTicks);
y = this.getTick(y, this.yTicks);
return {x:x, y:y};
},
/*
* 为该类配置指定的选项,这样重写Ext.dd.DragDrop,注意该方法的所有版本都会被调用。
*/
applyConfig: function() {
Ext.dd.DD.superclass.applyConfig.call(this);
this.scroll = (this.config.scroll !== false);
},
/*
* 触发优先的onMouseDown事件。
* 重写Ext.dd.DragDrop.
*/
b4MouseDown: function(e) {
// this.resetConstraints();
this.autoOffset(e.getPageX(),
e.getPageY());
},
/*
* 触发优先的onDrag事件。
* 重写Ext.dd.DragDrop.
*/
b4Drag: function(e) {
this.setDragElPos(e.getPageX(),
e.getPageY());
},
toString: function() {
return ("DD " + this.id);
}
//////////////////////////////////////////////////////////////////////////
// Debugging ygDragDrop events that can be overridden
//////////////////////////////////////////////////////////////////////////
/*
startDrag: function(x, y) {
},
onDrag: function(e) {
},
onDragEnter: function(e, id) {
},
onDragOver: function(e, id) {
},
onDragOut: function(e, id) {
},
onDragDrop: function(e, id) {
},
endDrag: function(e) {
}
*/
});
/**
* @class Ext.dd.DDProxy
* 一种拖放的实现,把一个空白的、带边框的div插入到文档,并会伴随着鼠标指针移动。
* 当点击那一下发生,边框div会调整大小到关联html元素的尺寸大小,然后移动到关联元素的位置。
* “边框”元素的引用指的是页面上我们创建能够被DDProxy元素拖动到的地方的单个代理元素。
* @extends Ext.dd.DD
* @constructor
* @param {String} id 关联html元素之id
* @param {String} sGroup 相关拖放对象的组
* @param {object} config 配置项对象属性
* DDProxy可用的属性有:
* resizeFrame, centerFrame, dragElId
*/
Ext.dd.DDProxy = function(id, sGroup, config) {
if (id) {
this.init(id, sGroup, config);
this.initFrame();
}
};
/**
* 默认的拖动框架div之id
* @property Ext.dd.DDProxy.dragElId
* @type String
* @static
*/
Ext.dd.DDProxy.dragElId = "ygddfdiv";
Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, {
/**
*默认下,我们将实际拖动元素调整大小到与打算拖动的那个元素的大小一致(这就是加边框的效果)。
* 但如果我们想实现另外一种效果可关闭选项。
* @property resizeFrame
* @type boolean
*/
resizeFrame: true,
/**
* 默认下,frame是正好处于拖动元素的位置。
* 因此我们可使Ext.dd.DD来偏移指针。
* 另外一个方法就是,你没有让做任何限制在对象上,然后设置center Frame为true。
* @property centerFrame
* @type boolean
*/
centerFrame: false,
/**
* 如果代理元素仍然不存在,就创建一个。
* @method createFrame
*/
createFrame: function() {
var self = this;
var body = document.body;
if (!body || !body.firstChild) {
setTimeout( function() { self.createFrame(); }, 50 );
return;
}
var div = this.getDragEl();
if (!div) {
div = document.createElement("div");
div.id = this.dragElId;
var s = div.style;
s.position = "absolute";
s.visibility = "hidden";
s.cursor = "move";
s.border = "2px solid #aaa";
s.zIndex = 999;
// appendChild can blow up IE if invoked prior to the window load event
// while rendering a table. It is possible there are other scenarios
// that would cause this to happen as well.
body.insertBefore(div, body.firstChild);
}
},
/**
* 拖动框架元素的初始化,必须在子类的构造器里调用。
* @method initFrame
*/
initFrame: function() {
this.createFrame();
},
applyConfig: function() {
Ext.dd.DDProxy.superclass.applyConfig.call(this);
this.resizeFrame = (this.config.resizeFrame !== false);
this.centerFrame = (this.config.centerFrame);
this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId);
},
/**
* 调查拖动frame的大小到点击对象的尺寸大小、位置,最后显示它。
* @method showFrame
* @param {int} iPageX 点击X位置
* @param {int} iPageY 点击Y位置
* @private
*/
showFrame: function(iPageX, iPageY) {
var el = this.getEl();
var dragEl = this.getDragEl();
var s = dragEl.style;
this._resizeProxy();
if (this.centerFrame) {
this.setDelta( Math.round(parseInt(s.width, 10)/2),
Math.round(parseInt(s.height, 10)/2) );
}
this.setDragElPos(iPageX, iPageY);
Ext.fly(dragEl).show();
},
/**
* 拖动开始时,代理与关联元素自适应尺寸,除非resizeFrame设为false。
* @method _resizeProxy
* @private
*/
_resizeProxy: function() {
if (this.resizeFrame) {
var el = this.getEl();
Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
}
},
// overrides Ext.dd.DragDrop
b4MouseDown: function(e) {
var x = e.getPageX();
var y = e.getPageY();
this.autoOffset(x, y);
this.setDragElPos(x, y);
},
// overrides Ext.dd.DragDrop
b4StartDrag: function(x, y) {
// show the drag frame
this.showFrame(x, y);
},
// overrides Ext.dd.DragDrop
b4EndDrag: function(e) {
Ext.fly(this.getDragEl()).hide();
},
// overrides Ext.dd.DragDrop
// By default we try to move the element to the last location of the frame.
// This is so that the default behavior mirrors that of Ext.dd.DD.
endDrag: function(e) {
var lel = this.getEl();
var del = this.getDragEl();
// Show the drag frame briefly so we can get its position
del.style.visibility = "";
this.beforeMove();
// Hide the linked element before the move to get around a Safari
// rendering bug.
lel.style.visibility = "hidden";
Ext.dd.DDM.moveToEl(lel, del);
del.style.visibility = "hidden";
lel.style.visibility = "";
this.afterDrag();
},
beforeMove : function(){
},
afterDrag : function(){
},
toString: function() {
return ("DDProxy " + this.id);
}
});
/**
* @class Ext.dd.DDTarget
* 一种拖放的实现,不能移动,但可以置下目标,对于事件回调,省略一些简单的实现也可得到相同的结果。
* 但这样降低了event listener和回调的处理成本。
* @extends Ext.dd.DragDrop
* @constructor
* @param {String} id 置下目标的那个元素的id
* @param {String} sGroup 相关拖放对象的组
* @param {object} config 包括配置属性的对象
* 可用的DDTarget属性有DragDrop:
* none
*/
Ext.dd.DDTarget = function(id, sGroup, config) {
if (id) {
this.initTarget(id, sGroup, config);
}
};
// Ext.dd.DDTarget.prototype = new Ext.dd.DragDrop();
Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, {
toString: function() {
return ("DDTarget " + this.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.dd.DragSource
* @extends Ext.dd.DDProxy
* 一个简单的基础类,该实现使得任何元素变成为拖动,以便让拖动的元素放到其身上。
* @constructor
* @param {String/HTMLElement/Element} el 容器元素
* @param {Object} config
*/
Ext.dd.DragSource = function(el, config){
this.el = Ext.get(el);
this.dragData = {};
Ext.apply(this, config);
if(!this.proxy){
this.proxy = new Ext.dd.StatusProxy();
}
Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
{dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
this.dragging = false;
};
Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, {
/**
* @cfg {String} dropAllowed
* 当落下被允许的时候返回到拖动源的样式(默认为"x-dd-drop-ok")。
*/
dropAllowed : "x-dd-drop-ok",
/**
* @cfg {String} dropNotAllowed
* 当落下不允许的时候返回到拖动源的样式(默认为"x-dd-drop-nodrop")。
*/
dropNotAllowed : "x-dd-drop-nodrop",
/**
* 返回与拖动源关联的数据对象
* @return {Object} data 包含自定义数据的对象
*/
getDragData : function(e){
return this.dragData;
},
// private
onDragEnter : function(e, id){
var target = Ext.dd.DragDropMgr.getDDById(id);
this.cachedTarget = target;
if(this.beforeDragEnter(target, e, id) !== false){
if(target.isNotifyTarget){
var status = target.notifyEnter(this, e, this.dragData);
this.proxy.setStatus(status);
}else{
this.proxy.setStatus(this.dropAllowed);
}
if(this.afterDragEnter){
/**
* 默认为一空函数,但你可提供一个自定义动作的实现,这个实现在拖动条目进入落下目标的时候。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @method afterDragEnter
*/
this.afterDragEnter(target, e, id);
}
}
},
/**
* 默认是一个空函数,在拖动项进入落下目标时,你应该提供一个自定义的动作。
* 该动作可被取消onDragEnter。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragEnter : function(target, e, id){
return true;
},
// private
alignElWithMouse: function() {
Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
this.proxy.sync();
},
// private
onDragOver : function(e, id){
var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
if(this.beforeDragOver(target, e, id) !== false){
if(target.isNotifyTarget){
var status = target.notifyOver(this, e, this.dragData);
this.proxy.setStatus(status);
}
if(this.afterDragOver){
/**
* 默认是一个空函数,在拖动项位于落下目标上方时(由实现促成的),你应该提供一个自定义的动作。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @method afterDragOver
*/
this.afterDragOver(target, e, id);
}
}
},
/**
* 默认是一个空函数,在拖动项位于落下目标上方时,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragOver : function(target, e, id){
return true;
},
// private
onDragOut : function(e, id){
var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
if(this.beforeDragOut(target, e, id) !== false){
if(target.isNotifyTarget){
target.notifyOut(this, e, this.dragData);
}
this.proxy.reset();
if(this.afterDragOut){
/**
* 默认是一个空函数,在拖动项离开目标而没有落下之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @method afterDragOut
*/
this.afterDragOut(target, e, id);
}
}
this.cachedTarget = null;
},
/**
* 默认是一个空函数,在拖动项离开目标而没有落下之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragOut : function(target, e, id){
return true;
},
// private
onDragDrop : function(e, id){
var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
if(this.beforeDragDrop(target, e, id) !== false){
if(target.isNotifyTarget){
if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
this.onValidDrop(target, e, id);
}else{
this.onInvalidDrop(target, e, id);
}
}else{
this.onValidDrop(target, e, id);
}
if(this.afterDragDrop){
/**
* 默认是一个空函数,在由实现促成的有效拖放发生之后,你应该提供一个自定义的动作。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 落下元素的id
* @method afterDragDrop
*/
this.afterDragDrop(target, e, id);
}
}
},
/**
* 默认是一个空函数,在拖动项被放下到目标之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragDrop : function(target, e, id){
return true;
},
// private
onValidDrop : function(target, e, id){
this.hideProxy();
if(this.afterValidDrop){
/**
* 默认是一个空函数,在由实现促成的有效落下发生之后,你应该提供一个自定义的动作。
* @param {Object} target DD目标
* @param {Event} e 事件对象
* @param {String} id 落下元素的id
* @method afterInvalidDrop
*/
this.afterValidDrop(target, e, id);
}
},
// private
getRepairXY : function(e, data){
return this.el.getXY();
},
// private
onInvalidDrop : function(target, e, id){
this.beforeInvalidDrop(target, e, id);
if(this.cachedTarget){
if(this.cachedTarget.isNotifyTarget){
this.cachedTarget.notifyOut(this, e, this.dragData);
}
this.cacheTarget = null;
}
this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
if(this.afterInvalidDrop){
/**
* 默认是一个空函数,在由实现促成的无效落下发生之后,你应该提供一个自定义的动作。
* @param {Event} e 事件对象
* @param {String} id 落下元素的id
* @method afterInvalidDrop
*/
this.afterInvalidDrop(e, id);
}
},
// private
afterRepair : function(){
if(Ext.enableFx){
this.el.highlight(this.hlColor || "c3daf9");
}
this.dragging = false;
},
/**
* 默认是一个空函数,在一次无效的落下发生之后,你应该提供一个自定义的动作。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 拖动元素的id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeInvalidDrop : function(target, e, id){
return true;
},
// private
handleMouseDown : function(e){
if(this.dragging) {
return;
}
var data = this.getDragData(e);
if(data && this.onBeforeDrag(data, e) !== false){
this.dragData = data;
this.proxy.stop();
Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
}
},
/**
* 默认是一个空函数,在初始化拖动事件之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Object} data 与落下目标共享的自定义数据对象
* @param {Event} e 事件对象
* @return {Boolean} isValid True的话拖动事件有效,否则false取消
*/
onBeforeDrag : function(data, e){
return true;
},
/**
* 默认是一个空函数,一旦拖动事件开始,你应该提供一个自定义的动作。
* 不能在该函数中取消拖动。
* @param {Number} x 在拖动对象身上单击点的x值
* @param {Number} y 在拖动对象身上单击点的y值
*/
onStartDrag : Ext.emptyFn,
// private - YUI override
startDrag : function(x, y){
this.proxy.reset();
this.dragging = true;
this.proxy.update("");
this.onInitDrag(x, y);
this.proxy.show();
},
// private
onInitDrag : function(x, y){
var clone = this.el.dom.cloneNode(true);
clone.id = Ext.id(); // prevent duplicate ids
this.proxy.update(clone);
this.onStartDrag(x, y);
return true;
},
/**
* 返回拖动源所在的{@link Ext.dd.StatusProxy}
* @return {Ext.dd.StatusProxy} proxy StatusProxy对象
*/
getProxy : function(){
return this.proxy;
},
/**
* 隐藏拖动源的{@link Ext.dd.StatusProxy}
*/
hideProxy : function(){
this.proxy.hide();
this.proxy.reset(true);
this.dragging = false;
},
// private
triggerCacheRefresh : function(){
Ext.dd.DDM.refreshCache(this.groups);
},
// private - override to prevent hiding
b4EndDrag: function(e) {
},
// private - override to prevent moving
endDrag : function(e){
this.onEndDrag(this.dragData, e);
},
// private
onEndDrag : function(data, e){
},
// private - pin to cursor
autoOffset : function(x, y) {
this.setDelta(-12, -20);
}
}); | 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.dd.ScrollManager
* 执行拖动操作时,自动在页面溢出的区域滚动
* <b>注:该类使用的是”Point模式”,而"Interest模式"未经测试。</b>
* @singleton
*/
Ext.dd.ScrollManager = function(){
var ddm = Ext.dd.DragDropMgr;
var els = {};
var dragEl = null;
var proc = {};
var onStop = function(e){
dragEl = null;
clearProc();
};
var triggerRefresh = function(){
if(ddm.dragCurrent){
ddm.refreshCache(ddm.dragCurrent.groups);
}
};
var doScroll = function(){
if(ddm.dragCurrent){
var dds = Ext.dd.ScrollManager;
if(!dds.animate){
if(proc.el.scroll(proc.dir, dds.increment)){
triggerRefresh();
}
}else{
proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
}
}
};
var clearProc = function(){
if(proc.id){
clearInterval(proc.id);
}
proc.id = 0;
proc.el = null;
proc.dir = "";
};
var startProc = function(el, dir){
clearProc();
proc.el = el;
proc.dir = dir;
proc.id = setInterval(doScroll, Ext.dd.ScrollManager.frequency);
};
var onFire = function(e, isDrop){
if(isDrop || !ddm.dragCurrent){ return; }
var dds = Ext.dd.ScrollManager;
if(!dragEl || dragEl != ddm.dragCurrent){
dragEl = ddm.dragCurrent;
// 拖动开始时刷新regions
dds.refreshCache();
}
var xy = Ext.lib.Event.getXY(e);
var pt = new Ext.lib.Point(xy[0], xy[1]);
for(var id in els){
var el = els[id], r = el._region;
if(r && r.contains(pt) && el.isScrollable()){
if(r.bottom - pt.y <= dds.thresh){
if(proc.el != el){
startProc(el, "down");
}
return;
}else if(r.right - pt.x <= dds.thresh){
if(proc.el != el){
startProc(el, "left");
}
return;
}else if(pt.y - r.top <= dds.thresh){
if(proc.el != el){
startProc(el, "up");
}
return;
}else if(pt.x - r.left <= dds.thresh){
if(proc.el != el){
startProc(el, "right");
}
return;
}
}
}
clearProc();
};
ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
return {
/**
* 登记新溢出元素,以准备自动滚动
* @param {String/HTMLElement/Element/Array} el 要被滚动的元素id或是数组
*/
register : function(el){
if(el instanceof Array){
for(var i = 0, len = el.length; i < len; i++) {
this.register(el[i]);
}
}else{
el = Ext.get(el);
els[el.id] = el;
}
},
/**
* 注销溢出元素,不可再被滚动
* @param {String/HTMLElement/Element/Array} el 要被滚动的元素id或是数组
*/
unregister : function(el){
if(el instanceof Array){
for(var i = 0, len = el.length; i < len; i++) {
this.unregister(el[i]);
}
}else{
el = Ext.get(el);
delete els[el.id];
}
},
/**
* 需要指针翻转滚动的容器边缘的像素(默认为25)
* @type Number
*/
thresh : 25,
/**
* 每次滚动的幅度,单位:像素(默认为50)
* @type Number
*/
increment : 100,
/**
* 滚动的频率,单位:毫秒(默认为500)
* @type Number
*/
frequency : 500,
/**
* 是否有动画效果(默认为true)
* @type Boolean
*/
animate: true,
/**
* 动画持续时间,单位:秒
* 改值勿少于Ext.dd.ScrollManager.frequency!(默认为.4)
* @type Number
*/
animDuration: .4,
/**
* 手动切换刷新缓冲。
*/
refreshCache : function(){
for(var id in els){
if(typeof els[id] == 'object'){ // for people extending the object prototype
els[id]._region = els[id].getRegion();
}
}
}
};
}(); | 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.dd.StatusProxy
* 一个特殊的拖动代理,可支持落下状态时的图标,{@link Ext.Layer} 样式和自动修复。
* Ext.dd components默认都是使用这个代理
* @constructor
* @param {Object} config
*/
Ext.dd.StatusProxy = function(config){
Ext.apply(this, config);
this.id = this.id || Ext.id();
this.el = new Ext.Layer({
dh: {
id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
{tag: "div", cls: "x-dd-drop-icon"},
{tag: "div", cls: "x-dd-drag-ghost"}
]
},
shadow: !config || config.shadow !== false
});
this.ghost = Ext.get(this.el.dom.childNodes[1]);
this.dropStatus = this.dropNotAllowed;
};
Ext.dd.StatusProxy.prototype = {
/**
* @cfg {String} dropAllowed
* 当拖动源到达落下目标上方时的CSS class
*/
dropAllowed : "x-dd-drop-ok",
/**
* @cfg {String} dropNotAllowed
* 当不可以被落下时拖动源的样式(默认为"x-dd-drop-nodrop")。
*/
dropNotAllowed : "x-dd-drop-nodrop",
/**
* 更新代理的可见元素,用来指明在当前元素上可否落下的状态。
* @param {String} cssClass 对指示器图象的新CSS样式
*/
setStatus : function(cssClass){
cssClass = cssClass || this.dropNotAllowed;
if(this.dropStatus != cssClass){
this.el.replaceClass(this.dropStatus, cssClass);
this.dropStatus = cssClass;
}
},
/**
* 对默认dropNotAllowed值的状态提示器进行复位
* @param {Boolean} clearGhost true的话移除所有ghost的内容,false的话保留
*/
reset : function(clearGhost){
this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
this.dropStatus = this.dropNotAllowed;
if(clearGhost){
this.ghost.update("");
}
},
/**
* 更新ghost元素的内容
* @param {String} html 替换当前ghost元素的innerHTML的那个html
*/
update : function(html){
if(typeof html == "string"){
this.ghost.update(html);
}else{
this.ghost.update("");
html.style.margin = "0";
this.ghost.dom.appendChild(html);
}
},
/**
* 返所在在的代理{@link Ext.Layer}
* @return {Ext.Layer} el
*/
getEl : function(){
return this.el;
},
/**
* 返回ghost元素
* @return {Ext.Element} el
*/
getGhost : function(){
return this.ghost;
},
/**
* 隐藏代理
* @param {Boolean} clear True的话复位状态和清除ghost内容,false的话就保留
*/
hide : function(clear){
this.el.hide();
if(clear){
this.reset(true);
}
},
/**
* 如果运行中就停止修复动画
*/
stop : function(){
if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
this.anim.stop();
}
},
/**
* 显示代理
*/
show : function(){
this.el.show();
},
/**
* 迫使层同步阴影和闪烁元素的位置
*/
sync : function(){
this.el.sync();
},
/**
* 通过动画让代理返回到原来位置。
* 应由拖动项在完成一次无效的落下动作之后调用.
* @param {Array} xy 元素的XY位置([x, y])
* @param {Function} callback 完成修复之后的回调函数
* @param {Object} scope 执行回调函数的作用域
*/
repair : function(xy, callback, scope){
this.callback = callback;
this.scope = scope;
if(xy && this.animRepair !== false){
this.el.addClass("x-dd-drag-repair");
this.el.hideUnders(true);
this.anim = this.el.shift({
duration: this.repairDuration || .5,
easing: 'easeOut',
xy: xy,
stopFx: true,
callback: this.afterRepair,
scope: this
});
}else{
this.afterRepair();
}
},
// private
afterRepair : function(){
this.hide(true);
if(typeof this.callback == "function"){
this.callback.call(this.scope || this);
}
this.callback = null;
this.scope = 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.dd.DropTarget
* @extends Ext.dd.DDTarget.
* 一个简单的基础类,该实现使得任何元素变成为可落下的目标,以便让拖动的元素放到其身上。
* 落下(drop)过程没有特别效果,除非提供了notifyDrop的实现
* @constructor
* @param {String/HTMLElement/Element} el 容器元素
* @param {Object} config
*/
Ext.dd.DropTarget = function(el, config){
this.el = Ext.get(el);
Ext.apply(this, config);
if(this.containerScroll){
Ext.dd.ScrollManager.register(this.el);
}
Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
{isTarget: true});
};
Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, {
/**
* @cfg {String} overClass
* 当拖动源到达落下目标上方时的CSS class
*/
/**
* @cfg {String} dropAllowed
* 当可以被落下时拖动源的样式(默认为"x-dd-drop-ok")。
*/
dropAllowed : "x-dd-drop-ok",
/**
* @cfg {String} dropNotAllowed
* 当不可以被落下时拖动源的样式(默认为"x-dd-drop-nodrop")。
*/
dropNotAllowed : "x-dd-drop-nodrop",
// private
isTarget : true,
// private
isNotifyTarget : true,
/**
* 当源{@link Ext.dd.DragSource}进入到目标的范围内,它执行通知落下目标的那个函数。
* 默认的实现是,如存在overClass(或其它)的样式,将其加入到落下元素(drop element),并返回dropAllowed配置的值。
* 如需对落下验证(drop validation)的话可重写该方法。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyEnter : function(dd, e, data){
if(this.overClass){
this.el.addClass(this.overClass);
}
return this.dropAllowed;
},
/**
* 当源{@link Ext.dd.DragSource}进入到目标的范围内,每一下移动鼠标,它不断执行通知落下目标的那个函数。
* 默认的实现是返回dropAllowed配置值而已
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyOver : function(dd, e, data){
return this.dropAllowed;
},
/**.
* 当源{@link Ext.dd.DragSource}移出落下目标的范围后,它执行通知落下目标的那个函数。
* 默认的实现仅是移除由overClass(或其它)指定的CSS class。
* @param {Ext.dd.DragSource} dd 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
notifyOut : function(dd, e, data){
if(this.overClass){
this.el.removeClass(this.overClass);
}
},
/**
* 当源{@link Ext.dd.DragSource}在落下目标身上完成落下动作后,它执行通知落下目标的那个函数。
* 该方法没有默认的实现并返回false,所以你必须提供处理落下事件的实现并返回true,才能修复拖动源没有运行的动作。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
notifyDrop : function(dd, e, data){
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.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.DropZone
* @extends Ext.dd.DropTarget
* 对于多个子节点的目标,该类提供一个DD实例的容器(扮演代理角色)。<br />
* 默认地,该类需要一个可拖动的子节点,并且需在{@link Ext.dd.Registry}登记好的。
* @constructor
* @param {String/HTMLElement/Element} el
* @param {Object} config
*/
Ext.dd.DropZone = function(el, config){
Ext.dd.DropZone.superclass.constructor.call(this, el, config);
};
Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, {
/**
* 返回一个自定义数据对象,与事件对象的那个DOM节点关联。
* 默认地,该方法会在事件目标{@link Ext.dd.Registry}中查找对象,
* 但是你亦可以根据自身的需求,重写该方法。
* @param {Event} e 事件对象
* @return {Object} data 自定义数据
*/
getTargetFromEvent : function(e){
return Ext.dd.Registry.getTargetFromEvent(e);
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经进入一个已登记的落下节点(drop node)的范围内,就会调用。
* 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
onNodeEnter : function(n, dd, e, data){
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经位于一个已登记的落下节点(drop node)的上方时,就会调用。
* 默认的实现是返回this.dropAllowed。因此应该重写它以便提供合适的反馈。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
onNodeOver : function(n, dd, e, data){
return this.dropAllowed;
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经离开一个已登记的落下节点(drop node)的范围内,就会调用。
* 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
onNodeOut : function(n, dd, e, data){
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经在一个已登记的落下节点(drop node)落下的时候,就会调用。
* 默认的方法返回false,应提供一个合适的实现来处理落下的事件,重写该方法,
* 并返回true值,说明拖放行为有效,拖动源的修复动作便不会进行。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
onNodeDrop : function(n, dd, e, data){
return false;
},
/**
* 内部调用。当DrapZone发现有一个{@link Ext.dd.DragSource}正处于其上方时,但是没有放下任何落下的节点时调用。
* 默认的实现是返回this.dropNotAllowed,如需提供一些合适的反馈,应重写该函数。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
onContainerOver : function(dd, e, data){
return this.dropNotAllowed;
},
/**
* 内部调用。当DrapZone确定{@link Ext.dd.DragSource}落下的动作已经执行,但是没有放下任何落下的节点时调用。
* 欲将DropZone本身也可接收落下的行为,应提供一个合适的实现来处理落下的事件,重写该方法,并返回true值,
* 说明拖放行为有效,拖动源的修复动作便不会进行。默认的实现返回false。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
onContainerDrop : function(dd, e, data){
return false;
},
/**
* 通知DropZone源已经在Zone上方的函数。
* 默认的实现返回this.dropNotAllowed,一般说只有登记的落下节点可以处理拖放操作。
* 欲将DropZone本身也可接收落下的行为,应提供一个自定义的实现,重写该方法,
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyEnter : function(dd, e, data){
return this.dropNotAllowed;
},
/**
* 当{@link Ext.dd.DragSource}在DropZone范围内时,拖动过程中不断调用的函数。
* 拖动源进入DropZone后,进入每移动一下鼠标都会调用该方法。
* 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onNodeOver},
* 如果拖动源进入{@link #onNodeEnter}, {@link #onNodeOut}这样已登记的节点,通知过程会按照需要自动进行指定的节点处理,
* 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onContainerOver}。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyOver : function(dd, e, data){
var n = this.getTargetFromEvent(e);
if(!n){ // 不在有效的drop target上
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
this.lastOverNode = null;
}
return this.onContainerOver(dd, e, data);
}
if(this.lastOverNode != n){
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
}
this.onNodeEnter(n, dd, e, data);
this.lastOverNode = n;
}
return this.onNodeOver(n, dd, e, data);
},
/**
* 通知DropZone源已经离开Zone上方{@link Ext.dd.DragSource}所调用的函数。
* 如果拖动源当前在已登记的节点上,通知过程会委托{@link #onNodeOut}进行指定的节点处理,
* 否则的话会被忽略。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
notifyOut : function(dd, e, data){
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
this.lastOverNode = null;
}
},
/**
* 通知DropZone源已经在Zone放下item后{@link Ext.dd.DragSource}所调用的函数。
* 传入事件的参数,DragZone以此查找目标节点,若是事件已登记的节点的话,便会委托{@link #onNodeDrop}进行指定的节点处理。
* 否则的话调用{@link #onContainerDrop}.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
notifyDrop : function(dd, e, data){
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
this.lastOverNode = null;
}
var n = this.getTargetFromEvent(e);
return n ?
this.onNodeDrop(n, dd, e, data) :
this.onContainerDrop(dd, e, data);
},
// private
triggerCacheRefresh : function(){
Ext.dd.DDM.refreshCache(this.groups);
}
}); | 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.dd.Registry
* 为在页面上已登记好的拖放组件提供简易的访问。
* 可按照DOM节点的id的方式直接提取组件,或者是按照传入的拖放事件,事件触发后,在事件目标(event target)里查找。
* @singleton
*/
Ext.dd.Registry = function(){
var elements = {};
var handles = {};
var autoIdSeed = 0;
var getId = function(el, autogen){
if(typeof el == "string"){
return el;
}
var id = el.id;
if(!id && autogen !== false){
id = "extdd-" + (++autoIdSeed);
el.id = id;
}
return id;
};
return {
/**
* 登记一个拖放元素
* @param {String/HTMLElement) element 要登记的id或DOM节点
* @param {Object} data (optional) 在拖放过程中,用于在各元素传递的这么一个自定义数据对象
* 你可以按自身需求定义这个对象,另外有些特定的属性是便于与Registry交互的(如可以的话):
* <pre>
值 描述<br />
--------- ------------------------------------------<br />
handles 由DOM节点组成的数组,即被拖动元素,都是已登记好的<br />
isHandle True表示元素传入后已是翻转的拖动本身,否则false<br />
</pre>
*/
register : function(el, data){
data = data || {};
if(typeof el == "string"){
el = document.getElementById(el);
}
data.ddel = el;
elements[getId(el)] = data;
if(data.isHandle !== false){
handles[data.ddel.id] = data;
}
if(data.handles){
var hs = data.handles;
for(var i = 0, len = hs.length; i < len; i++){
handles[getId(hs[i])] = data;
}
}
},
/**
* 注销一个拖放元素
* @param {String/HTMLElement) element 要注销的id或DOM节点
*/
unregister : function(el){
var id = getId(el, false);
var data = elements[id];
if(data){
delete elements[id];
if(data.handles){
var hs = data.handles;
for(var i = 0, len = hs.length; i < len; i++){
delete handles[getId(hs[i], false)];
}
}
}
},
/**
* 按id返回已登记的DOM节点处理
* @param {String/HTMLElement} id 要查找的id或DOM节点
* @return {Object} handle 自定义处理数据
*/
getHandle : function(id){
if(typeof id != "string"){ // 规定是元素?
id = id.id;
}
return handles[id];
},
/**
* 按事件目标返回已登记的DOM节点处理
* @param {Event} e 事件对象
* @return {Object} handle 自定义处理数据
*/
getHandleFromEvent : function(e){
var t = Ext.lib.Event.getTarget(e);
return t ? handles[t.id] : null;
},
/**
* 按id返回已登记的自定义处理对象
* @param {String/HTMLElement} id 要查找的id或DOM节点
* @return {Object} handle 自定义处理数据
*/
getTarget : function(id){
if(typeof id != "string"){ // 规定是元素?
id = id.id;
}
return elements[id];
},
/**
* 按事件目标返回已登记的自定义处理对象
* @param {Event} e 事件对象
* @return {Object} handle 自定义处理数据
*/
getTargetFromEvent : function(e){
var t = Ext.lib.Event.getTarget(e);
return t ? elements[t.id] || handles[t.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.dd.DragZone
* 该类继承了Ext.dd.DragSource,对于多节点的源,该类提供了一个DD实理容器来代理.<br/>
* 默认情况下,该类要求可拖动的子节点全都在类(Ext.dd.Registry )中己注册
* @constructor
* @param {String/HTMLElement/Element} el 第一个参数为容器元素
* @param {Object} config 第二个参数为配置对象
*/
Ext.dd.DragZone = function(el, config){
Ext.dd.DragZone.superclass.constructor.call(this, el, config);
if(this.containerScroll){
Ext.dd.ScrollManager.register(this.el);
}
};
Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, {
/**
* @cfg {Boolean} containerScroll
*第一个参数:containerScroll 设为True 用来将此容器在Scrollmanager上注册,使得在拖动操作发生时可以自动卷动.
*/
/**
* @cfg {String} hlColor
*第二个参数:hlColor 用于在一次失败的拖动操作后调用afterRepair方法会用在此设定的颜色(默认颜色为亮蓝"c3daf9")来标识可见的拽源<br/>
*/
/**
* 该方法在鼠标在该容器中按下时激发,参照类(Ext.dd.Registry),因为有效的拖动目标是基于鼠标按下事件获取的.<br/>
* 如果想想实现自己的查找方式(如根据类名查找子对象),可以重载这个主法.但是得确保该方法返回的对象有一个"ddel"属性(即返回一个HTML element),以便别的函数能正常工作<br/>
* @param {EventObject} e 鼠标按下事件
* @return {Object} 被拖拽对象
*/
getDragData : function(e){
return Ext.dd.Registry.getHandleFromEvent(e);
},
/**
* 该方法在拖拽动作开始,初始化代理元素时调用,默认情况下,它克隆this.dragData.ddel.
* @param {Number} x 被点击的拖拽对象的X坐标
* @param {Number} y 被点击的拖拽对象的y坐标
* @return {Boolean} 该方法返回一个布尔常量,当返回true时,表示继续(保持)拖拽,返回false时,表示取消拖拽<br/>
*/
onInitDrag : function(x, y){
this.proxy.update(this.dragData.ddel.cloneNode(true));
this.onStartDrag(x, y);
return true;
},
/**
* 该方法在修复无效的drop操作后调用.默认情况下.高亮显示this.dragData.ddel
*/
afterRepair : function(){
if(Ext.enableFx){
Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
}
this.dragging = false;
},
/**
* 该方法在修复无效的drop操作之前调用,用来获取XY对象来激活(使用对象),默认情况下返回this.dragData.ddel的XY属性
* @param {EventObject} e 鼠标松开事件
* @return {Array} 区域的xy位置 (例如: [100, 200])
*/
getRepairXY : function(e){
return Ext.Element.fly(this.dragData.ddel).getXY();
}
}); | 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.data.Tree
* @extends Ext.util.Observable
* Represents a tree data structure and bubbles all the events for its nodes. The nodes
* in the tree have most standard DOM functionality.
* @constructor
* @param {Node} root (optional) The root node
*/
/**
* @ Ext.data.Tree类
* @extends Ext.util.Observable
* 代表一个树的数据结构并且向上传递它结点事件.树上的节点有绝大多数的标准dom的功能
* @构造器
* @param {Node} root (optional) 根节点
*/
Ext.data.Tree = function(root){
this.nodeHash = {};
/**
* The root node for this tree
* @type Node
*/
this.root = null;
if(root){
this.setRootNode(root);
}
this.addEvents({
/**
* @event append
* Fires when a new child node is appended to a node in this tree.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The newly appended node
* @param {Number} index The index of the newly appended node
*/
/**
* @ append事件
* 当一个新子节点挂到树上某一切点时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 新的被挂上的节点
* @param {Number} index 新的被挂上的节点的索引
*/
"append" : true,
/**
* @event remove
* Fires when a child node is removed from a node in this tree.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node removed
*/
/**
* @remove 移除事件
* 当一个子节点被从树上的某节点移除时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被移除的子节点
*/
"remove" : true,
/**
* @event move
* Fires when a node is moved to a new location in the tree
* @param {Tree} tree The owner tree
* @param {Node} node The node moved
* @param {Node} oldParent The old parent of this node
* @param {Node} newParent The new parent of this node
* @param {Number} index The index it was moved to
*/
/**
* @ move事件
* 当树上的某一节点移动到新的位置时触发该事件
* @param {Tree} tree 该树
* @param {Node} node 移动的节点
* @param {Node} oldParent 该移动节点的原父
* @param {Node} newParent 移动的节点的新父
* @param {Number} index 移动的节点的在新父下的索引
*/
"move" : true,
/**
* @event insert
* Fires when a new child node is inserted in a node in this tree.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node inserted
* @param {Node} refNode The child node the node was inserted before
*/
/**
* @insert事件
* 当一个新子节点被插入到树中某个节点下时触发该事件
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入后的子节点
* @param {Node} refNode 插入前的子节点
*/
"insert" : true,
/**
* @event beforeappend
* Fires before a new child is appended to a node in this tree, return false to cancel the append.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node to be appended
*/
/**
* @beforeappend 事件
* 在一子点被接挂到树之前触发,如果返回false,则取消接挂.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被接挂的子节点
*/
"beforeappend" : true,
/**
* @event beforeremove
* Fires before a child is removed from a node in this tree, return false to cancel the remove.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node to be removed
*/
/**
* @beforeremove事件
* 当一个子节点被从树某一个节点被移除时触发该事件,返回false时取消移除.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 将被移除的子节点
*/
"beforeremove" : true,
/**
* @event beforemove
* Fires before a node is moved to a new location in the tree. Return false to cancel the move.
* @param {Tree} tree The owner tree
* @param {Node} node The node being moved
* @param {Node} oldParent The parent of the node
* @param {Node} newParent The new parent the node is moving to
* @param {Number} index The index it is being moved to
*/
/**
* @ beforemove事件
* 当树上一节点被移动到树上的新位置之前触发,返回false时取消移动
* @param {Tree} tree The owner tree
* @param {Node} node The node being moved
* @param {Node} oldParent The parent of the node
* @param {Node} newParent The new parent the node is moving to
* @param {Number} index The index it is being moved to
*/
"beforemove" : true,
/**
* @event beforeinsert
* Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node to be inserted
* @param {Node} refNode The child node the node is being inserted before
*/
/**
* @ beforeinsert事件
* 当一新子节点被插入到树上某一节点之前触发该事件,返回false时取消插入
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入的子节点
* @param {Node} refNode 插入之前的子节点
*/
"beforeinsert" : true
});
Ext.data.Tree.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Tree, Ext.util.Observable, {
pathSeparator: "/",
proxyNodeEvent : function(){
return this.fireEvent.apply(this, arguments);
},
/**
* Returns the root node for this tree.
* @return {Node}
*/
/**
* 返回树的根节点.
* @return {Node}
*/
getRootNode : function(){
return this.root;
},
/**
* Sets the root node for this tree.
* @param {Node} node
* @return {Node}
*/
/**
* 设置树的根节点
* @param {Node} node
* @return {Node}
*/
setRootNode : function(node){
this.root = node;
node.ownerTree = this;
node.isRoot = true;
this.registerNode(node);
return node;
},
/**
* Gets a node in this tree by its id.
* @param {String} id
* @return {Node}
*/
/**
* 根据节点 ID在树里获取节点
* @param {String} id
* @return {Node}
*/
getNodeById : function(id){
return this.nodeHash[id];
},
registerNode : function(node){
this.nodeHash[node.id] = node;
},
unregisterNode : function(node){
delete this.nodeHash[node.id];
},
toString : function(){
return "[Tree"+(this.id?" "+this.id:"")+"]";
}
});
/**
* @class Ext.data.Node
* @extends Ext.util.Observable
* @cfg {Boolean} leaf true if this node is a leaf and does not have children
* @cfg {String} id The id for this node. If one is not specified, one is generated.
* @constructor
* @param {Object} attributes The attributes/config for the node
*/
/**
* @ Ext.data.Node类
* @extends Ext.util.Observable
* @cfg {Boolean} 该节点是否为叶节点
* @cfg {String}该节点的ID.如果没有指定,则自动生成.
* @constructor
* @param {Object} attributes 该节点的属性集或配置
*/
Ext.data.Node = function(attributes){
/**
* The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
* @type {Object}
*/
/**
* 该节点所支持的属性,你可以用此属性访问任一你指定的客户端属性
* @type {Object}
*/
this.attributes = attributes || {};
this.leaf = this.attributes.leaf;
/**
* The node id. @type String
*/
this.id = this.attributes.id;
if(!this.id){
this.id = Ext.id(null, "ynode-");
this.attributes.id = this.id;
}
/**
* All child nodes of this node. @type Array
*/
/**
* 该节点的所有子节点. @type 类型为数组
*/
this.childNodes = [];
if(!this.childNodes.indexOf){ // indexOf is a must
this.childNodes.indexOf = function(o){
for(var i = 0, len = this.length; i < len; i++){
if(this[i] == o) return i;
}
return -1;
};
}
/**
* The parent node for this node. @type Node
*/
/**
* 该节点的父节点. @type 类型为节点
*/
this.parentNode = null;
/**
* The first direct child node of this node, or null if this node has no child nodes. @type Node
*/
/**
* 第一个子节点,如果没有则返回为空. @type 类型为节点
*/
this.firstChild = null;
/**
* The last direct child node of this node, or null if this node has no child nodes. @type Node
*/
/**
* 该节点的最后一个子节点,如果没有,则返回为空.@type 类型为节点
*/
this.lastChild = null;
/**
* The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
*/
/**
* 返回该节点前一个兄弟节点.如果没有,则返回空. @type 类型为节点
*/
this.previousSibling = null;
/**
* The node immediately following this node in the tree, or null if there is no sibling node. @type Node
*/
/**
* 返回该节点的后一个兄弟节点.如果没有,则返回空. @type 类型为节点
*/
this.nextSibling = null;
this.addEvents({
/**
* @event append
* Fires when a new child node is appended
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The newly appended node
* @param {Number} index The index of the newly appended node
*/
/**
* @ append事件
* 当一个新子节点挂到树上某一切点时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 新的被挂上的节点
* @param {Number} index 新的被挂上的节点的索引
*/
"append" : true,
/**
* @event remove
* Fires when a child node is removed
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The removed node
*/
/**
* @remove 移除事件
* 当一个子节点被从树上的某节点移除时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被移除的子节点
*/
"remove" : true,
/**
* @event move
* Fires when this node is moved to a new location in the tree
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} oldParent The old parent of this node
* @param {Node} newParent The new parent of this node
* @param {Number} index The index it was moved to
*/
/**
* @ move事件
* 当树上的某一节点移动到新的位置时触发该事件
* @param {Tree} tree 该树
* @param {Node} node 移动的节点
* @param {Node} oldParent 该移动节点的原父
* @param {Node} newParent 移动的节点的新父
* @param {Number} index 移动的节点的在新父下的索引
*/
"move" : true,
/**
* @event insert
* Fires when a new child node is inserted.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node inserted
* @param {Node} refNode The child node the node was inserted before
*/
/**
* @insert事件
* 当一个新子节点被插入到树中某个节点下时触发该事件
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入后的子节点
* @param {Node} refNode 插入前的子节点
*/
"insert" : true,
/**
* @event beforeappend
* Fires before a new child is appended, return false to cancel the append.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node to be appended
*/
/**
* @beforeappend 事件
* 在一子点被接挂到树之前触发,如果返回false,则取消接挂.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被接挂的子节点
*/
"beforeappend" : true,
/**
* @event beforeremove
* Fires before a child is removed, return false to cancel the remove.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node to be removed
*/
/**
* @beforeremove事件
* 当一个子节点被从树某一个节点被移除时触发该事件,返回false时取消移除.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 将被移除的子节点
*/
"beforeremove" : true,
/**
* @event beforemove
* Fires before this node is moved to a new location in the tree. Return false to cancel the move.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} oldParent The parent of this node
* @param {Node} newParent The new parent this node is moving to
* @param {Number} index The index it is being moved to
*/
/**
* @ beforemove事件
* 当树上一节点被移动到树上的新位置之前触发,返回false时取消移动
* @param {Tree} tree The owner tree
* @param {Node} node The node being moved
* @param {Node} oldParent The parent of the node
* @param {Node} newParent The new parent the node is moving to
* @param {Number} index The index it is being moved to
*/
"beforemove" : true,
/**
* @event beforeinsert
* Fires before a new child is inserted, return false to cancel the insert.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node to be inserted
* @param {Node} refNode The child node the node is being inserted before
*/
/**
* @ beforeinsert事件
* 当一新子节点被插入到树上某一节点之前触发该事件,返回false时取消插入
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入的子节点
* @param {Node} refNode 插入之前的子节点
*/
"beforeinsert" : true
});
this.listeners = this.attributes.listeners;
Ext.data.Node.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Node, Ext.util.Observable, {
fireEvent : function(evtName){
// first do standard event for this node
// 首先响应该节点的标准事件
if(Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false){
return false;
}
// then bubble it up to the tree if the event wasn't cancelled
// 然后在树中向上传递(只要事件未被取消)
var ot = this.getOwnerTree();
if(ot){
if(ot.proxyNodeEvent.apply(ot, arguments) === false){
return false;
}
}
return true;
},
/**
* Returns true if this node is a leaf
* @return {Boolean}
*/
/**
* 如果该节点为叶子节点,则返回true
* @return {Boolean}
*/
isLeaf : function(){
return this.leaf === true;
},
// private
setFirstChild : function(node){
this.firstChild = node;
},
//private
setLastChild : function(node){
this.lastChild = node;
},
/**
* Returns true if this node is the last child of its parent
* @return {Boolean}
*/
/**
* 如果该节点是父节点的子节点中最后一个节点时返回true
* @return {Boolean}
*/
isLast : function(){
return (!this.parentNode ? true : this.parentNode.lastChild == this);
},
/**
* Returns true if this node is the first child of its parent
* @return {Boolean}
*/
/**
* 如果该节点是父节点的子节点的第一个节点时返回true
* @return {Boolean}
*/
isFirst : function(){
return (!this.parentNode ? true : this.parentNode.firstChild == this);
},
hasChildNodes : function(){
return !this.isLeaf() && this.childNodes.length > 0;
},
/**
* Insert node(s) as the last child node of this node.
* @param {Node/Array} node The node or Array of nodes to append
* @return {Node} The appended node if single append, or null if an array was passed
*/
/**
* 插入节点作为该节点的最后一个子节点
* @param {Node/Array} node 要接挂进来的节点或节点数组
* @return {Node} 接挂一个则返回之.接挂多个则返回空
*/
appendChild : function(node){
var multi = false;
if(node instanceof Array){
multi = node;
}else if(arguments.length > 1){
multi = arguments;
}
// if passed an array or multiple args do them one by one
// 如果传入的是数组.或多个参数.则一个一个的加
if(multi){
for(var i = 0, len = multi.length; i < len; i++) {
this.appendChild(multi[i]);
}
}else{
if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
return false;
}
var index = this.childNodes.length;
var oldParent = node.parentNode;
// it's a move, make sure we move it cleanly
// 这里移动.确保我们移动它cleanly
if(oldParent){
if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
return false;
}
oldParent.removeChild(node);
}
index = this.childNodes.length;
if(index == 0){
this.setFirstChild(node);
}
this.childNodes.push(node);
node.parentNode = this;
var ps = this.childNodes[index-1];
if(ps){
node.previousSibling = ps;
ps.nextSibling = node;
}else{
node.previousSibling = null;
}
node.nextSibling = null;
this.setLastChild(node);
node.setOwnerTree(this.getOwnerTree());
this.fireEvent("append", this.ownerTree, this, node, index);
if(oldParent){
node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
}
return node;
}
},
/**
* Removes a child node from this node.
* @param {Node} node The node to remove
* @return {Node} The removed node
*/
/**
* 移队该节点的某一子节点
* @param {Node} node 要被移除的节点
* @return {Node} 被移除的节点
*/
removeChild : function(node){
var index = this.childNodes.indexOf(node);
if(index == -1){
return false;
}
if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
return false;
}
// remove it from childNodes collection
// 从子节点集合中移除掉
this.childNodes.splice(index, 1);
// update siblings
// 更新兄弟
if(node.previousSibling){
node.previousSibling.nextSibling = node.nextSibling;
}
if(node.nextSibling){
node.nextSibling.previousSibling = node.previousSibling;
}
// update child refs
// 更新子节点的引用
if(this.firstChild == node){
this.setFirstChild(node.nextSibling);
}
if(this.lastChild == node){
this.setLastChild(node.previousSibling);
}
node.setOwnerTree(null);
// clear any references from the node
// 清除任何到该节点的引用
node.parentNode = null;
node.previousSibling = null;
node.nextSibling = null;
this.fireEvent("remove", this.ownerTree, this, node);
return node;
},
/**
* Inserts the first node before the second node in this nodes childNodes collection.
* @param {Node} node The node to insert
* @param {Node} refNode The node to insert before (if null the node is appended)
* @return {Node} The inserted node
*/
/**
* 在该节点的子节点集合中插入第一个节点于第二个个节点之前
* @param {Node} node 要插入的节点
* @param {Node} refNode 插入之前的节点 (如果为空.该节点被接挂)
* @return {Node} 返回这插入的节点
*/
insertBefore : function(node, refNode){
if(!refNode){ // like standard Dom, refNode can be null for append
return this.appendChild(node);
}
// nothing to do
if(node == refNode){
return false;
}
if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
return false;
}
var index = this.childNodes.indexOf(refNode);
var oldParent = node.parentNode;
var refIndex = index;
// when moving internally, indexes will change after remove
// 当移动在内部进行时,索引将会在移动之后改变
if(oldParent == this && this.childNodes.indexOf(node) < index){
refIndex--;
}
// it's a move, make sure we move it cleanly
// 这里移动.确保移动cleanly
if(oldParent){
if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
return false;
}
oldParent.removeChild(node);
}
if(refIndex == 0){
this.setFirstChild(node);
}
this.childNodes.splice(refIndex, 0, node);
node.parentNode = this;
var ps = this.childNodes[refIndex-1];
if(ps){
node.previousSibling = ps;
ps.nextSibling = node;
}else{
node.previousSibling = null;
}
node.nextSibling = refNode;
refNode.previousSibling = node;
node.setOwnerTree(this.getOwnerTree());
this.fireEvent("insert", this.ownerTree, this, node, refNode);
if(oldParent){
node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
}
return node;
},
/**
* Returns the child node at the specified index.
* @param {Number} index
* @return {Node}
*/
/**
* 返回指定索引的子节点.
* @param {Number} 索引
* @return {Node}
*/
item : function(index){
return this.childNodes[index];
},
/**
* Replaces one child node in this node with another.
* @param {Node} newChild The replacement node
* @param {Node} oldChild The node to replace
* @return {Node} The replaced node
*/
/**
* 用另一个节点来替换该节点的一个子节点
* @param {Node} 新节点
* @param {Node} 被替的子节点
* @return {Node} 被替的子节点
*/
replaceChild : function(newChild, oldChild){
this.insertBefore(newChild, oldChild);
this.removeChild(oldChild);
return oldChild;
},
/**
* Returns the index of a child node
* @param {Node} node
* @return {Number} The index of the node or -1 if it was not found
*/
/**
* 返回子节点的索引
* @param {Node} node
* @return {Number} 返回指定子节点的索引,如果未找到则返回空
*/
indexOf : function(child){
return this.childNodes.indexOf(child);
},
/**
* Returns the tree this node is in.
* @return {Tree}
*/
/**
* Returns 返回该节点所在的树.
* @return {Tree}
*/
getOwnerTree : function(){
// if it doesn't have one, look for one
// 如果当前结点直接没有此属性.则向上找
if(!this.ownerTree){
var p = this;
while(p){
if(p.ownerTree){
this.ownerTree = p.ownerTree;
break;
}
p = p.parentNode;
}
}
return this.ownerTree;
},
/**
* Returns depth of this node (the root node has a depth of 0)
* @return {Number}
*/
/**
* 返回节点的深度,根节点深度为0
* @return {Number}
*/
getDepth : function(){
var depth = 0;
var p = this;
while(p.parentNode){
++depth;
p = p.parentNode;
}
return depth;
},
// private
setOwnerTree : function(tree){
// if it's move, we need to update everyone
// 如果移动.我们需要更新所有节点
if(tree != this.ownerTree){
if(this.ownerTree){
this.ownerTree.unregisterNode(this);
}
this.ownerTree = tree;
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].setOwnerTree(tree);
}
if(tree){
tree.registerNode(this);
}
}
},
/**
* Returns the path for this node. The path can be used to expand or select this node programmatically.
* @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
* @return {String} The path
*/
/**
* 返回该节点的路径.路径能被用来扩展或选择节点
* @param {String} attr (可选项) 为路径服务的属性 (默认为节点的ID)
* @return {String} 路径
*/
getPath : function(attr){
attr = attr || "id";
var p = this.parentNode;
var b = [this.attributes[attr]];
while(p){
b.unshift(p.attributes[attr]);
p = p.parentNode;
}
var sep = this.getOwnerTree().pathSeparator;
return sep + b.join(sep);
},
/**
* Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
* function call will be the scope provided or the current node. The arguments to the function
* will be the args provided or the current node. If the function returns false at any point,
* the bubble is stopped.
* @param {Function} fn The function to call
* @param {Object} scope (optional) The scope of the function (defaults to current node)
* @param {Array} args (optional) The args to call the function with (default to passing the current node)
*/
/**
* 在树中.从该节点往上的各节点调用指定的函数, 该函数的作用域为提供的作用域或当前节点.该函数的参数为提供的
* 参数或当前节点作参数.如果该函数在任一点返回false,则停上bubble
* @param {Function} fn 要调用的函数
* @param {Object} scope (可选项) 函数的作用域 (默认为当前节点)
* @param {Array} args (可选项) 调用函数时所带的参数 (默认值为传递当前节点)
*/
bubble : function(fn, scope, args){
var p = this;
while(p){
if(fn.call(scope || p, args || p) === false){
break;
}
p = p.parentNode;
}
},
/**
* Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
* function call will be the scope provided or the current node. The arguments to the function
* will be the args provided or the current node. If the function returns false at any point,
* the cascade is stopped on that branch.
* @param {Function} fn The function to call
* @param {Object} scope (optional) The scope of the function (defaults to current node)
* @param {Array} args (optional) The args to call the function with (default to passing the current node)
*/
/**
* 在树中.从该节点往下的各节点调用指定的函数, 该函数的作用域为提供的作用域或当前节点.该函数的参数为提供的
* 参数或当前节点作参数.如果该函数在任一点返回false,则停上该分支下的遍历
* @param {Function} fn 要调用的函数
* @param {Object} scope (可选项) 函数的作用域 (默认为当前节点)
* @param {Array} args (可选项) 调用函数时所带的参数 (默认值为传递当前节点)
*/
cascade : function(fn, scope, args){
if(fn.call(scope || this, args || this) !== false){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].cascade(fn, scope, args);
}
}
},
/**
* Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
* function call will be the scope provided or the current node. The arguments to the function
* will be the args provided or the current node. If the function returns false at any point,
* the iteration stops.
* @param {Function} fn The function to call
* @param {Object} scope (optional) The scope of the function (defaults to current node)
* @param {Array} args (optional) The args to call the function with (default to passing the current node)
*/
/**
* 遍历该节点的子节点, 各节点调用指定的函数. 该函数的作用域是提供的作用域,或是当前节点. 该函数的参数是提供的参数.或当前节点.当任何一点该函数返回false则停止遍历
* @param {Function} fn 调用的函数
* @param {Object} scope (可选项) 函数的作用域 (默认为当前节点)
* @param {Array} args (可选项) 调用函数时所带的参数 (默认值为传递当前节点)
*/
eachChild : function(fn, scope, args){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(fn.call(scope || this, args || cs[i]) === false){
break;
}
}
},
/**
* Finds the first child that has the attribute with the specified value.
* @param {String} attribute The attribute name
* @param {Mixed} value The value to search for
* @return {Node} The found child or null if none was found
*/
/**
* 返回子节点中第一个匹配指字属性值的子切点.
* @param {String} attribute 属性名
* @param {Mixed} value 属性值
* @return {Node} 如果找到则返回之.未找到返回空
*/
findChild : function(attribute, value){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(cs[i].attributes[attribute] == value){
return cs[i];
}
}
return null;
},
/**
* Finds the first child by a custom function. The child matches if the function passed
* returns true.
* @param {Function} fn
* @param {Object} scope (optional)
* @return {Node} The found child or null if none was found
*/
/**
* 根据客户函数找到第一个匹配的子节点. 子节点匹配函数时返回true.
* @param {Function} 函数
* @param {Object} scope (可选项)
* @return {Node} 如果找到则返回之.未找到返回空
*/
findChildBy : function(fn, scope){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(fn.call(scope||cs[i], cs[i]) === true){
return cs[i];
}
}
return null;
},
/**
* Sorts this nodes children using the supplied sort function
* @param {Function} fn
* @param {Object} scope (optional)
*/
/**
* 使用指定的函数为该节点的子节点排序
* @param {Function} fn
* @param {Object} scope (optional)
*/
sort : function(fn, scope){
var cs = this.childNodes;
var len = cs.length;
if(len > 0){
var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
cs.sort(sortFn);
for(var i = 0; i < len; i++){
var n = cs[i];
n.previousSibling = cs[i-1];
n.nextSibling = cs[i+1];
if(i == 0){
this.setFirstChild(n);
}
if(i == len-1){
this.setLastChild(n);
}
}
}
},
/**
* Returns true if this node is an ancestor (at any point) of the passed node.
* @param {Node} node
* @return {Boolean}
*/
/**
* 如果该节点是传入的节点的祖先,则返回true.
* @param {Node} node
* @return {Boolean}
*/
contains : function(node){
return node.isAncestor(this);
},
/**
* Returns true if the passed node is an ancestor (at any point) of this node.
* @param {Node} node
* @return {Boolean}
*/
/**
* 如果传入的节点是该节点的祖先,则返回true.
* @param {Node} node
* @return {Boolean}
*/
isAncestor : function(node){
var p = this.parentNode;
while(p){
if(p == node){
return true;
}
p = p.parentNode;
}
return false;
},
toString : function(){
return "[Node"+(this.id?" "+this.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.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.DataProxy
* This class is an abstract base class for implementations which provide retrieval of
* unformatted data objects.<br>
* <p>
* DataProxy implementations are usually used in conjunction with an implementation of Ext.data.DataReader
* (of the appropriate type which knows how to parse the data object) to provide a block of
* {@link Ext.data.Records} to an {@link Ext.data.Store}.<br>
* <p>
* Custom implementations must implement the load method as described in
* {@link Ext.data.HttpProxy#load}.
*/
/**
* @ Ext.data.DataProxy类
* 该类是所有实现例的一抽象基类.该实现例能重获未格式化数据对象<br>
* <p>
* 数据代理实现类通常被用来与一Ext.data.DataReader实现(适当类型的DataReader实现类知道如何去解析数据对象)
* 例协作向一Ext.data.Store类提供Ext.data.Records块
* <p>
* 如Ext.data.HttpProxy的load方法要求.客户实现类必须实现load方法
*/
Ext.data.DataProxy = function(){
this.addEvents({
/**
* @event beforeload
* Fires before a network request is made to retrieve a data object.
* @param {Object} This DataProxy object.
* @param {Object} params The params parameter to the load function.
*/
/**
* @ beforeload 事件
* 在一个网络请求(该请求为了获得数据对象)之前触发
* @param {Object} 该 DataProxy 对象.
* @param {Object} params 装载函数的参数
*/
beforeload : true,
/**
* @event load
* Fires before the load method's callback is called.
* @param {Object} This DataProxy object.
* @param {Object} o The data object.
* @param {Object} arg The callback argument object passed to the load function.
*/
/**
* @ load 事件
* 在load方法的回调函数被调用之前触发该事件
* @param {Object} 该 DataProxy 对象.
* @param {Object} o 数据对象
* @param {Object} arg 传入load 函数的回调参数对象
*/
load : true,
/**
* @event loadexception
* Fires if an Exception occurs during data retrieval.
* @param {Object} This DataProxy object.
* @param {Object} o The data object.
* @param {Object} arg The callback argument object passed to the load function.
* @param {Object} e The Exception.
*/
/**
* @ loadexception 事件
* 在获取数据期间有民常发生时触发该事件
* @param {Object} 该 DataProxy 对象.
* @param {Object} o 数据对象.
* @param {Object} arg 传入load 函数的回调参数对象
* @param {Object} e 异常
*/
loadexception : true
});
Ext.data.DataProxy.superclass.constructor.call(this);
};
Ext.extend(Ext.data.DataProxy, Ext.util.Observable); | 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.data.Store
* @extends Ext.util.Observable
* The Store class encapsulates a client side cache of {@link Ext.data.Record} objects which provide input data
* for widgets such as the Ext.grid.Grid, or the Ext.form.ComboBox.<br>
* <p>
* A Store object uses an implementation of {@link Ext.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
* has no knowledge of the format of the data returned by the Proxy.<br>
* <p>
* A Store object uses its configured implementation of {@link Ext.data.DataReader} to create {@link Ext.data.Record}
* instances from the data object. These records are cached and made available through accessor functions.
* @constructor
* Creates a new Store.
* @param {Object} config A config object containing the objects needed for the Store to access data,
* and read the data into Records.
*/
/**
* @ Ext.data.Store类
* @继承了 Ext.util.Observable
* 该类封装了一个客户端的Ext.data.Record对象的缓存.该缓存为窗口小部件如grid,combobox等提供了填充数据<br>
* <p>
* 一个store对象使用一个Ext.data.Proxy的实现类来访问一数据对象.直到你调用loadData()直接地传入你的数据.<br>
* <p>
* 该类使用配置的一个Ext.data.DataReader的实例类来从数据对象创建Ext.data.Record实例.这些records都被缓存并且
* 通过访问器函数可利用到
* @构建器
* 创建一新Store
* @param {Object} config 一配置对象,包含了Store用来访问数据,及读数据至Records的对象
*/
Ext.data.Store = function(config){
this.data = new Ext.util.MixedCollection(false);
this.data.getKey = function(o){
return o.id;
};
this.baseParams = {};
// private
this.paramNames = {
"start" : "start",
"limit" : "limit",
"sort" : "sort",
"dir" : "dir"
};
if(config && config.data){
this.inlineData = config.data;
delete config.data;
}
Ext.apply(this, config);
if(this.reader){ // reader passed
if(!this.recordType){
this.recordType = this.reader.recordType;
}
if(this.reader.onMetaChange){
this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
}
}
if(this.recordType){
this.fields = this.recordType.prototype.fields;
}
this.modified = [];
this.addEvents({
/**
* @event datachanged
* Fires when the data cache has changed, and a widget which is using this Store
* as a Record cache should refresh its view.
* @param {Store} this
*/
/**
* @event datachanged
* 当数据缓存有改变时触发该事件.使用了该Store作为Record缓存的窗口部件应当更新
* @param {Store} this
*/
datachanged : true,
/**
* @event metachange
* Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
* @param {Store} this
* @param {Object} meta The JSON metadata
*/
/**
* @event metachange
* 当store的reader 提供新的元数据字段时触发.这目前仅支持jsonReader
* @param {Store} this
* @param {Object} meta JSON 元数据
*/
metachange : true,
/**
* @event add
* Fires when Records have been added to the Store
* @param {Store} this
* @param {Ext.data.Record[]} records The array of Records added
* @param {Number} index The index at which the record(s) were added
*/
/**
* @event add
* 当Records被添加到store时激发
* @param {Store} this
* @param {Ext.data.Record[]} records The 要被加入的Record数组
* @param {Number} index 被添加进去的record的索引
*/
add : true,
/**
* @event remove
* Fires when a Record has been removed from the Store
* @param {Store} this
* @param {Ext.data.Record} record The Record that was removed
* @param {Number} index The index at which the record was removed
*/
/**
* @event remove
* 当一个record被从store里移出时激发
* @param {Store} this
* @param {Ext.data.Record} record 被移出的对Record象
* @param {Number} index 被移出的record的索引值
*/
remove : true,
/**
* @event update
* Fires when a Record has been updated
* @param {Store} this
* @param {Ext.data.Record} record The Record that was updated
* @param {String} operation The update operation being performed. Value may be one of:
* <pre><code>
Ext.data.Record.EDIT
Ext.data.Record.REJECT
Ext.data.Record.COMMIT
* </code></pre>
*/
/**
* @event update
* 当有record被更新时激发
* @param {Store} this
* @param {Ext.data.Record} record 被更新的记录
* @param {String} operation 更新操作将要执行时的操作. 可能是下列值:
* <pre><code>
Ext.data.Record.EDIT
Ext.data.Record.REJECT
Ext.data.Record.COMMIT
* </code></pre>
*/
update : true,
/**
* @event clear
* Fires when the data cache has been cleared.
* @param {Store} this
*/
/**
* @event clear
* 当数据缓存被清除时激发
* @param {Store} this
*/
clear : true,
/**
* @event beforeload
* Fires before a request is made for a new data object. If the beforeload handler returns false
* the load action will be canceled.
* @param {Store} this
* @param {Object} options The loading options that were specified (see {@link #load} for details)
*/
/**
* @event beforeload
* 在一个请求新数据的请求发起之前触发 ,如果beforeload事件句柄返回false.装载动作将会被取消
* @param {Store} this
* @param {Object} options 指定的loading选项 (从 {@link #load} 查看更多细节)
*/
beforeload : true,
/**
* @event load
* 在一个新的数据集被装载之后激发该事件
* @param {Store} this
* @param {Ext.data.Record[]} records 被载入的records
* @param {Object} options The 指定的loading选项 (从 {@link #load} 查看更多细节)
*/
load : true,
/**
* @event loadexception
* Fires if an exception occurs in the Proxy during loading.
* Called with the signature of the Proxy's "loadexception" event.
*/
/**
* @event loadexception
* 在装载过程中有错误发生在代理中时触发该事件
* 调用代理的"loadexception"事件的签名
*/
loadexception : true
});
if(this.proxy){
this.relayEvents(this.proxy, ["loadexception"]);
}
this.sortToggle = {};
Ext.data.Store.superclass.constructor.call(this);
if(this.inlineData){
this.loadData(this.inlineData);
delete this.inlineData;
}
};
Ext.extend(Ext.data.Store, Ext.util.Observable, {
/**
* @cfg {Ext.data.DataProxy} proxy The Proxy object which provides access to a data object.
*/
/**
* @cfg {Ext.data.DataProxy} proxy 提供访问数据对象的代理对象
*/
/**
* @cfg {Array} data Inline data to be loaded when the store is initialized.
*/
/**
* @cfg {Array} data 当store被初使化时,将被装载的inline 数据.
*/
/**
* @cfg {Ext.data.Reader} reader The Reader object which processes the data object and returns
* an Array of Ext.data.record objects which are cached keyed by their <em>id</em> property.
*/
/**
* @cfg {Ext.data.Reader} 处理数据对象并返回通过他的id属性映射的被缓存的Ext.data.record对象数组的Reader对象.
*/
/**
* @cfg {Object} baseParams An object containing properties which are to be sent as parameters
* on any HTTP request
*/
/**
* @cfg {Object} baseParams 一个包含属性的对象.这些属性在http请求时作为参数被发送出去
*/
/**
* @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
*/
/**
* @cfg {Object} sortInfo 一个有着类似如下格式的配置对象: {field: "fieldName", direction: "ASC|DESC"}
*/
/**
* @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
* version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
*/
/**
* @cfg {boolean} remoteSort 如果设置为true,在排序命定时排序被请求的代理(用来提供一个制新了的版本的数据对象)处理.
* 如果不想对Record缓存排序则设为false,默认为false.
*/
remoteSort : false,
/**
* @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
* loaded or when a record is removed. (defaults to false).
*/
/**
* @cfg {boolean} pruneModifiedRecords 设置为true,则每次当store装载或有record被移除时,清空所有修改了的record信息.
* 默认为false.
*/
pruneModifiedRecords : false,
// private
lastOptions : null,
/**
* Add Records to the Store and fires the add event.
* @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
*/
/**
* 在触发add事件时添加一个Records进Store.
* @param {Ext.data.Record[]} records 被添加到缓存中的Ext.data.Record对象或其数组对象
*/
add : function(records){
records = [].concat(records);
for(var i = 0, len = records.length; i < len; i++){
records[i].join(this);
}
var index = this.data.length;
this.data.addAll(records);
this.fireEvent("add", this, records, index);
},
/**
* Remove a Record from the Store and fires the remove event.
* @param {Ext.data.Record} record Th Ext.data.Record object to remove from the cache.
*/
/**
* 在触发移除事件时从Store中移除一Record对象
* @param {Ext.data.Record} record 被从缓存中移除的Ext.data.Record对象.
*/
remove : function(record){
var index = this.data.indexOf(record);
this.data.removeAt(index);
if(this.pruneModifiedRecords){
this.modified.remove(record);
}
this.fireEvent("remove", this, record, index);
},
/**
* Remove all Records from the Store and fires the clear event.
*/
/**
* 在清除事件触发时从Store移除所有Record
*/
removeAll : function(){
this.data.clear();
if(this.pruneModifiedRecords){
this.modified = [];
}
this.fireEvent("clear", this);
},
/**
* Inserts Records to the Store at the given index and fires the add event.
* @param {Number} index The start index at which to insert the passed Records.
* @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
*/
/**
* 触发添加事件时插入records到指定的store位置
* @param {Number} index The 传入的Records插入的开始位置
* @param {Ext.data.Record[]} records.
*/
insert : function(index, records){
records = [].concat(records);
for(var i = 0, len = records.length; i < len; i++){
this.data.insert(index, records[i]);
records[i].join(this);
}
this.fireEvent("add", this, records, index);
},
/**
* Get the index within the cache of the passed Record.
* @param {Ext.data.Record} record The Ext.data.Record object to to find.
* @return {Number} The index of the passed Record. Returns -1 if not found.
*/
/**
* 获取传入的Record在缓存中的索引
* @param {Ext.data.Record} record 要找寻的Ext.data.Record.
* @return {Number} 被传入的Record的索引,如果未找到返回-1.
*/
indexOf : function(record){
return this.data.indexOf(record);
},
/**
* Get the index within the cache of the Record with the passed id.
* @param {String} id The id of the Record to find.
* @return {Number} The index of the Record. Returns -1 if not found.
*/
/**
* 根据传入的id查询缓存里的Record的索引
* @param {String} id 要找到Record的id.
* @return {Number} 被找到的Record的索引. 如果未找到返回-1.
*/
indexOfId : function(id){
return this.data.indexOfKey(id);
},
/**
* Get the Record with the specified id.
* @param {String} id The id of the Record to find.
* @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
*/
/**
* 根据指定的id找到Record.
* @param {String} id 要找的Record的id
* @return {Ext.data.Record} 返回找到的指定id的Record,如果未找到则返回underfined.
*/
getById : function(id){
return this.data.key(id);
},
/**
* Get the Record at the specified index.
* @param {Number} index The index of the Record to find.
* @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
*/
/**
* 根据指定的索引找到Record.
* @param {Number} index 要找的Record的索引.
* @return {Ext.data.Record} 返回找到的指定索引的Record,如果未找到则返回undefined.
*/
getAt : function(index){
return this.data.itemAt(index);
},
/**
* Returns a range of Records between specified indices.
* @param {Number} startIndex (optional) The starting index (defaults to 0)
* @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
* @return {Ext.data.Record[]} An array of Records
*/
/**
* 返回指定范围里的Records.
* @param {Number} startIndex (可选项) 开始索引 (默认为 0)
* @param {Number} endIndex (可选项) 结束的索引 (默认是Store中最后一个Record的索引)
* @return {Ext.data.Record[]} 返回一个Record数组
*/
getRange : function(start, end){
return this.data.getRange(start, end);
},
// private
storeOptions : function(o){
o = Ext.apply({}, o);
delete o.callback;
delete o.scope;
this.lastOptions = o;
},
/**
* Loads the Record cache from the configured Proxy using the configured Reader.
* <p>
* If using remote paging, then the first load call must specify the <em>start</em>
* and <em>limit</em> properties in the options.params property to establish the initial
* position within the dataset, and the number of Records to cache on each read from the Proxy.
* <p>
* <strong>It is important to note that for remote data sources, loading is asynchronous,
* and this call will return before the new data has been loaded. Perform any post-processing
* in a callback function, or in a "load" event handler.</strong>
* <p>
* @param {Object} options An object containing properties which control loading options:<ul>
* <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
* <li>callback {Function} A function to be called after the Records have been loaded. The callback is
* passed the following arguments:<ul>
* <li>r : Ext.data.Record[]</li>
* <li>options: Options object from the load call</li>
* <li>success: Boolean success indicator</li></ul></li>
* <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
* <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
* </ul>
*/
/**
* 使用配置的Record从配置的代理中装载Record缓存.
* <p>
* 如果使用远程(服务端)分页, 在第一次装载调用时必须在配置项中指定start,和limit属性.
* 参数的属性确定在数据集初使化位置,和每次从代理的缓存中的Record的数目.
* <p>
* <strong>这是很重要的,对于远程数据源,请注意:装载是异步的,而且此次调用将会在新数据被装载之前返回.
* 在回调函数中执行后处理,或者在"load"事件中处理</strong>
* <p>
* @param {Object} options 包含控制装载的可选项作为属性的对象:<ul>
* <li>params {Object} 包含了一组属性的对象.这些属性作为向http参数传入远程数据源.</li>
* <li>callback {Function} 当Record被传入后被调用的参数,该函数传入如下参数:<ul>
* <li>r : Ext.data.Record[]</li>
* <li>options: 来自装载调用的可选项对象</li>
* <li>success: 布尔值的成功指示器</li></ul></li>
* <li>scope {Object} 调用回调函数的作用域 (默认为Store对象)</li>
* <li>add {Boolean} 追加装载的records而不是代替当前缓存的布尔指示器.</li>
* </ul>
*/
load : function(options){
options = options || {};
if(this.fireEvent("beforeload", this, options) !== false){
this.storeOptions(options);
var p = Ext.apply(options.params || {}, this.baseParams);
if(this.sortInfo && this.remoteSort){
var pn = this.paramNames;
p[pn["sort"]] = this.sortInfo.field;
p[pn["dir"]] = this.sortInfo.direction;
}
this.proxy.load(p, this.reader, this.loadRecords, this, options);
}
},
/**
* Reloads the Record cache from the configured Proxy using the configured Reader and
* the options from the last load operation performed.
* @param {Object} options (optional) An object containing properties which may override the options
* used in the last load operation. See {@link #load} for details (defaults to null, in which case
* the most recently used options are reused).
*/
/**
* 使用被配置的reader和可选项从最后一次装载操作任务从配置的proxy中装载record缓存
* @param {Object} options (optional) An object containing properties which may override the options
* used in the last load operation. See {@link #load} for details (defaults to null, in which case
* the most recently used options are reused).
*/
reload : function(options){
this.load(Ext.applyIf(options||{}, this.lastOptions));
},
// private
// Called as a callback by the Reader during a load operation.
// 在装载操作时,被Reader作为回调函数来调用
loadRecords : function(o, options, success){
if(!o || success === false){
if(success !== false){
this.fireEvent("load", this, [], options);
}
if(options.callback){
options.callback.call(options.scope || this, [], options, false);
}
return;
}
var r = o.records, t = o.totalRecords || r.length;
if(!options || options.add !== true){
if(this.pruneModifiedRecords){
this.modified = [];
}
for(var i = 0, len = r.length; i < len; i++){
r[i].join(this);
}
if(this.snapshot){
this.data = this.snapshot;
delete this.snapshot;
}
this.data.clear();
this.data.addAll(r);
this.totalLength = t;
this.applySort();
this.fireEvent("datachanged", this);
}else{
this.totalLength = Math.max(t, this.data.length+r.length);
this.add(r);
}
this.fireEvent("load", this, r, options);
if(options.callback){
options.callback.call(options.scope || this, r, options, true);
}
},
/**
* Loads data from a passed data block. A Reader which understands the format of the data
* must have been configured in the constructor.
* @param {Object} data The data block from which to read the Records. The format of the data expected
* is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
* @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
*/
/**
* 从传入的数据块中装载数据,了解数据格式的reader必须被配置在构建器中
* @param {Object} data 从该处读取record的数据块. 预期数据的格式由被配置的reader的类型决定.它应该符合reader的readRecords参数
* @param {Boolean} append (可选项) 设置为true,追加一新记录而不是代替己存在的缓存
*/
loadData : function(o, append){
var r = this.reader.readRecords(o);
this.loadRecords(r, {add: append}, true);
},
/**
* Gets the number of cached records.
* <p>
* <em>If using paging, this may not be the total size of the dataset. If the data object
* used by the Reader contains the dataset size, then the getTotalCount() function returns
* the data set size</em>
*/
/**
* 获取缓存记录的数
* <p>
* <em>如果分页.这里将不再是数据集的总数. 如果Reader使用的数据对象里包含了数据的总数,则可用
* getTotalCount() 方法返回总计录数</em>
*/
getCount : function(){
return this.data.length || 0;
},
/**
* Gets the total number of records in the dataset as returned by the server.
* <p>
* <em>If using paging, for this to be accurate, the data object used by the Reader must contain
* the dataset size</em>
*/
/**
*获取作为服务端返回的数据集中记录的总数.
* <p>
* <em>如果分页,这将要计算.Reader使用的数据对象必须包含数据集的大小</em>
*/
getTotalCount : function(){
return this.totalLength || 0;
},
/**
* Returns the sort state of the Store as an object with two properties:
* <pre><code>
field {String} The name of the field by which the Records are sorted
direction {String} The sort order, "ASC" or "DESC"
* </code></pre>
*/
/**
*以对象的形式返回排序的状态.它包含两属性:
* <pre><code>
field {String} 一个是排序字段
direction {String} 一个是排序方向
* </code></pre>
*/
getSortState : function(){
return this.sortInfo;
},
// private
applySort : function(){
if(this.sortInfo && !this.remoteSort){
var s = this.sortInfo, f = s.field;
var st = this.fields.get(f).sortType;
var fn = function(r1, r2){
var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
};
this.data.sort(s.direction, fn);
if(this.snapshot && this.snapshot != this.data){
this.snapshot.sort(s.direction, fn);
}
}
},
/**
* Sets the default sort column and order to be used by the next load operation.
* @param {String} fieldName The name of the field to sort by.
* @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
/**
* 设置默认的排序列,以便下次load操作时使用
* @param {String} fieldName The name of the field to sort by.
* @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
setDefaultSort : function(field, dir){
this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
},
/**
* Sort the Records.
* If remote sorting is used, the sort is performed on the server, and the cache is
* reloaded. If local sorting is used, the cache is sorted internally.
* @param {String} fieldName The name of the field to sort by.
* @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
/**
* 为Records排序.
* 如果使用了远程排序, 排序在服务端执行, 然后重新载入缓存.
* 如果只是客户端排序, 只是缓存内部排序.
* @param {String} fieldName 排序字段.
* @param {String} dir (optional) 排序方向.(默认升序 "ASC")
*/
sort : function(fieldName, dir){
var f = this.fields.get(fieldName);
if(!dir){
if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
}else{
dir = f.sortDir;
}
}
this.sortToggle[f.name] = dir;
this.sortInfo = {field: f.name, direction: dir};
if(!this.remoteSort){
this.applySort();
this.fireEvent("datachanged", this);
}else{
this.load(this.lastOptions);
}
},
/**
* Calls the specified function for each of the Records in the cache.
* @param {Function} fn The function to call. The Record is passed as the first parameter.
* Returning <em>false</em> aborts and exits the iteration.
* @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
*/
/**
* 缓存的的每一个record调用的指定函数
* @param {Function} fn 要调用的函数. 该Record作为第一个参数被传入
* 返回 <em>false</em> 中断或退出循环.
* @param {Object} scope (可选项) 调用函数的作用域 (默认为 Record).
*/
each : function(fn, scope){
this.data.each(fn, scope);
},
/**
* Gets all records modified since the last commit. Modified records are persisted across load operations
* (e.g., during paging).
* @return {Ext.data.Record[]} An array of Records containing outstanding modifications.
*/
/**
* 获取所有的自从最后一次提交后被修改的record. 被修改的记录通过load操作来持久化
* (例如,在分页期间).
* @return {Ext.data.Record[]} 包含了显注修改的record数组.
*/
getModifiedRecords : function(){
return this.modified;
},
// private
createFilterFn : function(property, value, anyMatch){
if(!value.exec){ // not a regex
value = String(value);
if(value.length == 0){
return false;
}
value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), "i");
}
return function(r){
return value.test(r.data[property]);
};
},
/**
* Sums the value of <i>property</i> for each record between start and end and returns the result.
* @param {String} property A field on your records
* @param {Number} start The record index to start at (defaults to 0)
* @param {Number} end The last record index to include (defaults to length - 1)
* @return {Number} The sum
*/
/**
* 为每个记录的(开始和结束)属性求和并返回结果.
* @param {String} property 记录的某个字段
* @param {Number} start 该record的开始索引(默认为0)
* @param {Number} end The 该record的结束索引 (默认为 - 1)
* @return {Number} 和
*/
sum : function(property, start, end){
var rs = this.data.items, v = 0;
start = start || 0;
end = (end || end === 0) ? end : rs.length-1;
for(var i = start; i <= end; i++){
v += (rs[i].data[property] || 0);
}
return v;
},
/**
* Filter the records by a specified property.
* @param {String} field A field on your records
* @param {String/RegExp} value Either a string that the field
* should start with or a RegExp to test against the field
* @param {Boolean} anyMatch True to match any part not just the beginning
*/
/**
* 通过指定的属性过滤records
* @param {String} field records的字段
* @param {String/RegExp} value 任意一个字符串(即以该字符串打头的字段)或匹配字段的规则式
* @param {Boolean} anyMatch 设置true,则全文匹配,而不仅是以**打头的匹配
*/
filter : function(property, value, anyMatch){
var fn = this.createFilterFn(property, value, anyMatch);
return fn ? this.filterBy(fn) : this.clearFilter();
},
/**
* Filter by a function. The specified function will be called with each
* record in this data source. If the function returns true the record is included,
* otherwise it is filtered.
* @param {Function} fn The function to be called, it will receive 2 args (record, id)
* @param {Object} scope (optional) The scope of the function (defaults to this)
*/
/**
* 通过函数过滤,该数据源里的所有record将会调用该函数.
* 如果该函数返回true,结果里也包含了record,否则它被过滤掉了
* @param {Function} fn 将被调用的函数,它将接受两个参数 (record, id)
* @param {Object} scope (可选项)该函数的作用域.默认为本函数
*/
filterBy : function(fn, scope){
this.snapshot = this.snapshot || this.data;
this.data = this.queryBy(fn, scope||this);
this.fireEvent("datachanged", this);
},
/**
* Query the records by a specified property.
* @param {String} field A field on your records
* @param {String/RegExp} value Either a string that the field
* should start with or a RegExp to test against the field
* @param {Boolean} anyMatch True to match any part not just the beginning
* @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
*/
/**
* 通过指定的属性查询record
* @param {String} field 你records里的字段名
* @param {String/RegExp} value 任意一个字符串(即以该字符串打头的字段)或匹配字段的规则式
* @param {Boolean} anyMatch 设置true,则全文匹配,而不仅是以**打头的匹配
* @return {MixedCollection} 返回匹配的record的一个 Ext.util.MixedCollection
*/
query : function(property, value, anyMatch){
var fn = this.createFilterFn(property, value, anyMatch);
return fn ? this.queryBy(fn) : this.data.clone();
},
/**
* Query by a function. The specified function will be called with each
* record in this data source. If the function returns true the record is included
* in the results.
* @param {Function} fn The function to be called, it will receive 2 args (record, id)
* @param {Object} scope (optional) The scope of the function (defaults to this)
@return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
**/
/**
* 通过一函数查询. 指定的函数将会被该数据源里的每个record调用.
* 如果该函数返回true,该record被包含在结果中
* @param {Function} fn 将被调用的函数,它将接受两个参数 (record, id)
* @param {Object} scope (可选项)该函数的作用域.默认为本函数
* @return {MixedCollection} 返回匹配的record的一个 Ext.util.MixedCollection
**/
queryBy : function(fn, scope){
var data = this.snapshot || this.data;
return data.filterBy(fn, scope||this);
},
/**
* Collects unique values for a particular dataIndex from this store.
* @param {String} dataIndex The property to collect
* @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
* @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
* @return {Array} An array of the unique values
**/
/**
* 从该store中为精确的数据索引搜集独一无二的值
* @param {String} dataIndex 搜集的一属性
* @param {Boolean} allowNull (可选项) 传入为true,则否许为空或未定义或空字符串值
* @param {Boolean} bypassFilter (可选项) 传入为true,则搜集所有记录,偶数项被过滤掉
* @return {Array} 返回一独一无二的值
**/
collect : function(dataIndex, allowNull, bypassFilter){
var d = (bypassFilter === true && this.snapshot) ?
this.snapshot.items : this.data.items;
var v, sv, r = [], l = {};
for(var i = 0, len = d.length; i < len; i++){
v = d[i].data[dataIndex];
sv = String(v);
if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
l[sv] = true;
r[r.length] = v;
}
}
return r;
},
/**
* Revert to a view of the Record cache with no filtering applied.
* @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
*/
/**
* 不应用过滤回复record缓存的视图
* @param {Boolean} suppressEvent 如果设置为true,该过滤器清空,并且不会通知监听器
*/
clearFilter : function(suppressEvent){
if(this.snapshot && this.snapshot != this.data){
this.data = this.snapshot;
delete this.snapshot;
if(suppressEvent !== true){
this.fireEvent("datachanged", this);
}
}
},
// private
afterEdit : function(record){
if(this.modified.indexOf(record) == -1){
this.modified.push(record);
}
this.fireEvent("update", this, record, Ext.data.Record.EDIT);
},
// private
afterReject : function(record){
this.modified.remove(record);
this.fireEvent("update", this, record, Ext.data.Record.REJECT);
},
// private
afterCommit : function(record){
this.modified.remove(record);
this.fireEvent("update", this, record, Ext.data.Record.COMMIT);
},
/**
* Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
* Store's "update" event, and perform updating when the third parameter is Ext.data.Record.COMMIT.
*/
/**
* 有显注改变时提交所有Record,为了处理更新这些改变.订阅store的update事件.在执行更新时使用第三参数为
* data.Record.COMMIT
*/
commitChanges : function(){
var m = this.modified.slice(0);
this.modified = [];
for(var i = 0, len = m.length; i < len; i++){
m[i].commit();
}
},
/**
* Cancel outstanding changes on all changed records.
*/
rejectChanges : function(){
var m = this.modified.slice(0);
this.modified = [];
for(var i = 0, len = m.length; i < len; i++){
m[i].reject();
}
},
onMetaChange : function(meta, rtype, o){
this.recordType = rtype;
this.fields = rtype.prototype.fields;
delete this.snapshot;
this.sortInfo = meta.sortInfo;
this.modified = [];
this.fireEvent('metachange', this, this.reader.meta);
}
}); | 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
*/
Ext.data.Field = function(config){
if(typeof config == "string"){
config = {name: config};
}
Ext.apply(this, config);
if(!this.type){
this.type = "auto";
}
var st = Ext.data.SortTypes;
// named sortTypes are supported, here we look them up
//支持指定的排序类型,这里我们来查找它们
if(typeof this.sortType == "string"){
this.sortType = st[this.sortType];
}
// set default sortType for strings and dates
// 为strings和dates设置默认的排序类型
if(!this.sortType){
switch(this.type){
case "string":
this.sortType = st.asUCString;
break;
case "date":
this.sortType = st.asDate;
break;
default:
this.sortType = st.none;
}
}
// define once
var stripRe = /[\$,%]/g;
// prebuilt conversion function for this field, instead of
// switching every time we're reading a value
// 为字段预先建立转换函数,来代替每次我们读取值时再选择
if(!this.convert){
var cv, dateFormat = this.dateFormat;
switch(this.type){
case "":
case "auto":
case undefined:
cv = function(v){ return v; };
break;
case "string":
cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
break;
case "int":
cv = function(v){
return v !== undefined && v !== null && v !== '' ?
parseInt(String(v).replace(stripRe, ""), 10) : '';
};
break;
case "float":
cv = function(v){
return v !== undefined && v !== null && v !== '' ?
parseFloat(String(v).replace(stripRe, ""), 10) : '';
};
break;
case "bool":
case "boolean":
cv = function(v){ return v === true || v === "true" || v == 1; };
break;
case "date":
cv = function(v){
if(!v){
return '';
}
if(v instanceof Date){
return v;
}
if(dateFormat){
if(dateFormat == "timestamp"){
return new Date(v*1000);
}
return Date.parseDate(v, dateFormat);
}
var parsed = Date.parse(v);
return parsed ? new Date(parsed) : null;
};
break;
}
this.convert = cv;
}
};
Ext.data.Field.prototype = {
dateFormat: null,
defaultValue: "",
mapping: null,
sortType : null,
sortDir : "ASC"
}; | 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.data.MemoryProxy
* An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor
* to the Reader when its load method is called.
* @constructor
* @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.
*/
/**
* 一个Ext.data.DataProxy的实现类,当它的load方法调用时简单的传入它的构建器指定的数据到Reader
* @构建器
* @param {Object} data Reader用来构建Ext.data.Records 块的数据对象
*/
Ext.data.MemoryProxy = function(data){
Ext.data.MemoryProxy.superclass.constructor.call(this);
this.data = data;
};
Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {
/**
* Load data from the requested source (in this case an in-memory
* data object passed to the constructor), read the data object into
* a block of Ext.data.Records using the passed Ext.data.DataReader implementation, and
* process that block using the passed callback.
* @param {Object} params This parameter is not used by the MemoryProxy class.
* @param {Ext.data.DataReader) reader The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
/**
* 从请求的源装载数据(在这种情况下在内存里的数据对象被传入构建器),使用传入的Ext.data.DataReader的实现
* 将数据对象读入Ext.data.Records块.并使用传入的回调函数处理该块.
* @param {Object} params 这些参数不是MemoryProxy 类用到的参数.
* @param {Ext.data.DataReader) reader 将数据对象转换成Ext.data.Records块对象的读取器.
* @param {Function} callback 传入到Ext.data.records块的函数.
* 该函数必须被传入 <ul>
* <li>Record 块对象</li>
* <li>来自装载函数的参数</li>
* <li>布尔变量的成功指示器</li>
* </ul>
* @param {Object} scope 回调函数的作用域
* @param {Object} arg 被传处回调函数作为第二参数码的可选参数.
*/
load : function(params, reader, callback, scope, arg){
params = params || {};
var result;
try {
result = reader.readRecords(this.data);
}catch(e){
this.fireEvent("loadexception", this, arg, null, e);
callback.call(scope, null, arg, false);
return;
}
callback.call(scope, result, arg, true);
},
// private
update : function(params, records){
}
}); | 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.data.XmlReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
* based on mappings in a provided Ext.data.Record constructor.<br><br>
* xmlReader类,继承Ext.data.DataReader类.基于Ext.data.Record的构建器提供的映射,从一xml document
* 中创建一Ext.data.Record对象的数组 的数据读取器
* <p>
* <em>Note that in order for the browser to parse a returned XML document, the Content-Type
* header in the HTTP response must be set to "text/xml".</em>
* 注意:为了浏览器解析返回来的xml document, http response的content-type 头必须被设成text/xml
* <p>
* Example code:
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
{name: 'occupation'} // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.XmlReader({
totalRecords: "results", // The element which contains the total dataset size (optional)
record: "row", // The repeated element which contains row information
id: "id" // The element within the row that provides an ID for the record (optional)
}, RecordDef);
</code></pre>
* <p>
* This would consume an XML file like this:
* <pre><code>
<?xml?>
<dataset>
<results>2</results>
<row>
<id>1</id>
<name>Bill</name>
<occupation>Gardener</occupation>
</row>
<row>
<id>2</id>
<name>Ben</name>
<occupation>Horticulturalist</occupation>
</row>
</dataset>
</code></pre>
* @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
* in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
* paged from the remote server.
* @cfg {String} record The DomQuery path to the repeated element which contains record information.
* @cfg {String} success The DomQuery path to the success attribute used by forms.
* @cfg {String} id The DomQuery path relative from the record element to the element that contains
* a record identifier value.
* @constructor
* Create a new XmlReader
* @param {Object} meta Metadata configuration options
* @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
* Record subclass created with {@link Ext.data.Record#create}, or an array of objects with which to call
* Ext.data.Record.create. See the {@link Ext.data.Record} class for more details.
*/
/*
* @cfg {String} totalRecords domQuery 路径,据此可以找到数据集里的记录总行数.该属性仅当整个数据集里被一次性
* 拿出(而不是远程肥务器分页后的数据)时有用.
* @cfg {String} record 包含记录信息的多个重复元素的DomQurey路径
* @cfg {String} success 被forms使用的成功属性的DomQuery 路径
* @cfg {String} id 关联记录元素到包含记录标识值元素的domQuery路径
* @构建器
* 创建一新xmlReader
* @param {Object} meta 元数据配置项
* @param {Mixed} recordType 用于产生数据记录类型的定义.这既可以是通过Ext.data.Record的create方法产生的一个有效的Record
* 子类,也可以是一个通过调用Ext.data.Record的create方法产生的对象数组.从Ext.data.Record类可以了解更多细节
*/
Ext.data.XmlReader = function(meta, recordType){
meta = meta || {};
Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response The XHR object which contains the parsed XML document. The response is expected
* to contain a method called 'responseXML' that returns an XML document object.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
/**
* 该方法仅仅被DataProxy用来从远程服务器找回数据
* @param {Object} response 包含了解析的xml document的xhr对象
* 该response 被期望包含一方法调用responseXML来返回xml document对象
* @return {Object} records 被Ext.data.Store作为Ext.data.Records缓存的数据块.
*/
read : function(response){
var doc = response.responseXML;
if(!doc) {
throw {message: "XmlReader.read: XML Document not available"};
}
return this.readRecords(doc);
},
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} doc A parsed XML document.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
/**
* 通过xml document创建一包含Ext.data.Records的数据块
* @param {Object} doc 一个被解析的 XML document.
* @return {Object} 被Ext.data.Store当作Ext.data.Records缓存的数据块
*/
readRecords : function(doc){
/**
* After any data loads/reads, the raw XML Document is available for further custom processing.
* @type XMLDocument
*/
/**
* 当有数据loads或reads后,原始的xml Document对于后面的客户操作不可用!
* @type XMLDocument
*/
this.xmlData = doc;
var root = doc.documentElement || doc;
var q = Ext.DomQuery;
var recordType = this.recordType, fields = recordType.prototype.fields;
var sid = this.meta.id;
var totalRecords = 0, success = true;
if(this.meta.totalRecords){
totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
}
if(this.meta.success){
var sv = q.selectValue(this.meta.success, root, true);
success = sv !== false && sv !== 'false';
}
var records = [];
var ns = q.select(this.meta.record, root);
for(var i = 0, len = ns.length; i < len; i++) {
var n = ns[i];
var values = {};
var id = sid ? q.selectValue(sid, n) : undefined;
for(var j = 0, jlen = fields.length; j < jlen; j++){
var f = fields.items[j];
var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
v = f.convert(v);
values[f.name] = v;
}
var record = new recordType(values, id);
record.node = n;
records[records.length] = record;
}
return {
success : success,
records : records,
totalRecords : totalRecords || records.length
};
}
}); | 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.data.Record
* Instances of this class encapsulate both record <em>definition</em> information, and record
* <em>value</em> information for use in {@link Ext.data.Store} objects, or any code which needs
* to access Records cached in an {@link Ext.data.Store} object.<br>
* <p>
* Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
* Instances are usually only created by {@link Ext.data.Reader} implementations when processing unformatted data
* objects.<br>
* <p>
* Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.
* @constructor
* This constructor should not be used to create Record objects. Instead, use the constructor generated by
* {@link #create}. The parameters are the same.
* @param {Array} data An associative Array of data values keyed by the field name.
* @param {Object} id (Optional) The id of the record. This id should be unique, and is used by the
* {@link Ext.data.Store} object which owns the Record to index its collection of Records. If
* not specified an integer id is generated.
*/
/**
* @Ext.data.Record 类
* 该类的实例包含了Record的定义信息和(在Ext.data.Store对象里使用的,或在Ext.data.Store对象里的其它任何代码需要访问Records缓存的)值信息<br>
* <p>
* 传入的字段定义对象数组生成该类的构建器,当Ext.data.Reader的实现例处理未格式化数据对象时创建了实例<br>
* <p>
* 通过该构建器生成的Record继承了所有如下列出的Ext.data.Record方法.
* @构建器
* 该构建器不能被用来创建Record对象。取而代之的,是用create 方法生成的构建器。参数都是一样的!
* @param {Array} data 数据值与字段名对应的联合数组.
* @param {Object} id (可选项) 记录的标识.该标识应当是独一无二的。能被Ext.data.Store对象使用的,Ext.data.Store有Record标识它的records集合,
* 如果没有指定将自动生成
*/
Ext.data.Record = function(data, id){
this.id = (id || id === 0) ? id : ++Ext.data.Record.AUTO_ID;
this.data = data;
};
/**
* Generate a constructor for a specific record layout.
* @param {Array} o An Array of field definition objects which specify field names, and optionally,
* data types, and a mapping for an {@link Ext.data.Reader} to extract the field's value from a data object.
* Each field definition object may contain the following properties: <ul>
* <li><b>name</b> : String<p style="margin-left:1em">The name by which the field is referenced within the Record. This is referenced by,
* for example the <em>dataIndex</em> property in column definition objects passed to {@link Ext.grid.ColumnModel}</p></li>
* <li><b>mapping</b> : String<p style="margin-left:1em">(Optional) A path specification for use by the {@link Ext.data.Reader} implementation
* that is creating the Record to access the data value from the data object. If an {@link Ext.data.JsonReader}
* is being used, then this is a string containing the javascript expression to reference the data relative to
* the record item's root. If an {@link Ext.data.XmlReader} is being used, this is an {@link Ext.DomQuery} path
* to the data item relative to the record element. If the mapping expression is the same as the field name,
* this may be omitted.</p></li>
* 为指定的record布局生成一构建器
* @param {Array} o 一字段定义对象的数组,其指定了字段名,随意的数据类型。及Ext.dataReader从一数据对象选取字段值的映射。
* 每一个字段字义对象可以包含下列属性: <ul>
* <li><b>name</b> : String<p style="margin-left:1em">一个名字(通过该名字,在record中引用字段).
* 如例 <em>dataIndex</em> 属性 在列定义对象中传到 Ext.grid.ColumnModel</p></li>
* <li><b>mapping</b> : String<p style="margin-left:1em">(可选项) Ext.data.Reader的实现使用的路径规范,它创建Record来访问数据对象中的数据值
* 如果一Ext.data.JsonReader被使用,那么该字符串包含javascript 表达式来引用record条目的根与数据的关系
* 如果使用Ext.data.XmlReader, 这将是个数据条目与记录对象关系的Ext.DomQuery路径,如果映射表达式与字段名相同。则可省略</p></li>
* <li><b>type</b> : String<p style="margin-left:1em">(可选项) 转换成显示值的数据类型. 可能的值是
* <ul><li>auto (默认情况下不作转换)</li>
* <li>string</li>
* <li>int</li>
* <li>float</li>
* <li>boolean</li>
* <li>date</li></ul></p></li>
* <li><b>sortType</b> : Mixed<p style="margin-left:1em">(可选项) Ext.data.SortTypes的数值</p></li>
* <li><b>sortDir</b> : String<p style="margin-left:1em">(可选项) 初始化排序方向 "ASC" or "DESC"</p></li>
* <li><b>convert</b> : Function<p style="margin-left:1em">(可选项)一个函数用来转换由reader提供的值成一个将被存入Reader中的对象,
* 它将有如下参数被传入:<ul>
* <li><b>v</b> : Mixed<p style="margin-left:1em">被Reader读取的数值.</p></li>
* </ul></p></li>
* <li><b>dateFormat</b> : String<p style="margin-left:1em">(可选项) Date.parseDate函数的一格式.</p></li>
* </ul>
* <br>usage:<br><pre><code>
var TopicRecord = Ext.data.Record.create(
{name: 'title', mapping: 'topic_title'},
{name: 'author', mapping: 'username'},
{name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
{name: 'lastPost', mapping: 'post_time', type: 'date'},
{name: 'lastPoster', mapping: 'user2'},
{name: 'excerpt', mapping: 'post_text'}
);
var myNewRecord = new TopicRecord({
title: 'Do my job please',
author: 'noobie',
totalPosts: 1,
lastPost: new Date(),
lastPoster: 'Animal',
excerpt: 'No way dude!'
});
myStore.add(myNewRecord);
</code></pre>
* @method create
* @static
*/
Ext.data.Record.create = function(o){
var f = function(){
f.superclass.constructor.apply(this, arguments);
};
Ext.extend(f, Ext.data.Record);
var p = f.prototype;
p.fields = new Ext.util.MixedCollection(false, function(field){
return field.name;
});
for(var i = 0, len = o.length; i < len; i++){
p.fields.add(new Ext.data.Field(o[i]));
}
f.getField = function(name){
return p.fields.get(name);
};
return f;
};
Ext.data.Record.AUTO_ID = 1000;
Ext.data.Record.EDIT = 'edit';
Ext.data.Record.REJECT = 'reject';
Ext.data.Record.COMMIT = 'commit';
Ext.data.Record.prototype = {
/**
* Readonly flag - true if this record has been modified.
* @type Boolean
*/
/**
* 只读(是否为脏数据标)志 - 如果数据被修改。则为treu.
* @type Boolean
*/
dirty : false,
editing : false,
error: null,
modified: null,
// private
join : function(store){
this.store = store;
},
/**
* Set the named field to the specified value.
* @param {String} name The name of the field to set.
* @param {Object} value The value to set the field to.
*/
/**
* 设置命名的字段为指定的指
* @param {String} name 要设置值的字段名
* @param {Object} value 要设置的值
*/
set : function(name, value){
if(this.data[name] == value){
return;
}
this.dirty = true;
if(!this.modified){
this.modified = {};
}
if(typeof this.modified[name] == 'undefined'){
this.modified[name] = this.data[name];
}
this.data[name] = value;
if(!this.editing){
this.store.afterEdit(this);
}
},
/**
* Get the value of the named field.
* @param {String} name The name of the field to get the value of.
* @return {Object} The value of the field.
*/
/**
* 获取指字名字的字段的值
* @param {String} name 指字要获取值的字段的名字
* @return {Object} 字段的值
*/
get : function(name){
return this.data[name];
},
// private
beginEdit : function(){
this.editing = true;
this.modified = {};
},
// private
cancelEdit : function(){
this.editing = false;
delete this.modified;
},
// private
endEdit : function(){
this.editing = false;
if(this.dirty && this.store){
this.store.afterEdit(this);
}
},
/**
* Usually called by the {@link Ext.data.Store} which owns the Record.
* Rejects all changes made to the Record since either creation, or the last commit operation.
* Modified fields are reverted to their original values.
* <p>
* Developers should subscribe to the {@link Ext.data.Store#update} event to have their code notified
* of reject operations.
*/
/**
* 通常地被 Ext.data.Store调用,其拥有Record.
* 在record自创建或最后一次提交操作之后。拒绝所有的修改。
* 修改的字段被恢复到他们原始值。
* <p>
* 开发者应当订阅 Ext.data.Store的update事件。使得他们用代码来执行记录事拒绝操作
*/
reject : function(){
var m = this.modified;
for(var n in m){
if(typeof m[n] != "function"){
this.data[n] = m[n];
}
}
this.dirty = false;
delete this.modified;
this.editing = false;
if(this.store){
this.store.afterReject(this);
}
},
/**
* Usually called by the {@link Ext.data.Store} which owns the Record.
* Commits all changes made to the Record since either creation, or the last commit operation.
* <p>
* Developers should subscribe to the {@link Ext.data.Store#update} event to have their code notified
* of commit operations.
*/
/**
* 通常地被 Ext.data.Store调用,其拥有Record.
* 在record自创建或最后一次提交操作之后。提交所有的修改。
* 修改的字段被恢复到他们原始值。
* <p>
* 开发者应当订阅 Ext.data.Store的update事件。使得他们用代码来执行记录事拒绝操作
*/
commit : function(){
this.dirty = false;
delete this.modified;
this.editing = false;
if(this.store){
this.store.afterCommit(this);
}
},
// private
hasError : function(){
return this.error != null;
},
// private
clearError : function(){
this.error = null;
},
/**
* Creates a copy of this record.
* @param {String} id (optional) A new record id if you don't want to use this record's id
* @return {Record}
*/
/**
* 创建该record的副本
* @param {String} id (可选项) 如果你不想用该record的标识,可以用个新的标识
* @return {Record}
*/
copy : function(newId) {
return new this.constructor(Ext.apply({}, this.data), newId || this.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.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.SortTypes
* @singleton
* Defines the default sorting (casting?) comparison functions used when sorting data.
*/
/**
* @ Ext.data.SortTypes类
* @单例
* 定义在排序数据时一个默认的排序比较函数
*/
Ext.data.SortTypes = {
/**
* Default sort that does nothing
* @param {Mixed} s The value being converted
* @return {Mixed} The comparison value
*/
/**
* 默认的排序即什么也不做
* @param {Mixed} s 将被转换的值
* @return {Mixed} 用来比较的值
*/
none : function(s){
return s;
},
/**
* The regular expression used to strip tags
* @type {RegExp}
* @property
*/
/**
* 用来去掉标签的规则表达式
* @type {RegExp}
* @property
*/
stripTagsRE : /<\/?[^>]+>/gi,
/**
* Strips all HTML tags to sort on text only
* @param {Mixed} s The value being converted
* @return {String} The comparison value
*/
/**
* 去掉所有html标签来基于纯文本排序
* @param {Mixed} s 将被转换的值
* @return {String} 用来比较的值
*/
asText : function(s){
return String(s).replace(this.stripTagsRE, "");
},
/**
* Strips all HTML tags to sort on text only - Case insensitive
* @param {Mixed} s The value being converted
* @return {String} The comparison value
*/
/**
* 去掉所有html标签来基于无大小写区别的文本的排序
* @param {Mixed} s 将被转换的值
* @return {String} 所比较的值
*/
asUCText : function(s){
return String(s).toUpperCase().replace(this.stripTagsRE, "");
},
/**
* Case insensitive string
* @param {Mixed} s The value being converted
* @return {String} The comparison value
*/
/**
* 无大小写区别的字符串
* @param {Mixed} s 将被转换的值
* @return {String} 所比较的值
*/
asUCString : function(s) {
return String(s).toUpperCase();
},
/**
* Date sorting
* @param {Mixed} s The value being converted
* @return {Number} The comparison value
*/
/**
* 日期排序
* @param {Mixed} s 将被转换的值
* @return {Number} 所比较的值
*/
asDate : function(s) {
if(!s){
return 0;
}
if(s instanceof Date){
return s.getTime();
}
return Date.parse(String(s));
},
/**
* Float sorting
* @param {Mixed} s The value being converted
* @return {Float} The comparison value
*/
/**
* 浮点数的排序
* @param {Mixed} s 将被转换的值
* @return {Float} 所比较的值
*/
asFloat : function(s) {
var val = parseFloat(String(s).replace(/,/g, ""));
if(isNaN(val)) val = 0;
return val;
},
/**
* Integer sorting
* @param {Mixed} s The value being converted
* @return {Number} The comparison value
*/
/**
* 整数的排序
* @param {Mixed} s 将被转换的值
* @return {Number} 所比较的值
*/
asInt : function(s) {
var val = parseInt(String(s).replace(/,/g, ""));
if(isNaN(val)) val = 0;
return val;
}
}; | 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.data.JsonStore
* @extends Ext.data.Store
* Small helper class to make creating Stores for JSON data easier. <br/>
* Ext.data.JsonStore类,继承Ext.data.Store.一小帮助类,使得创建json 数据 store更加容易
<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'}]
});
</code></pre>
* <b>Note: Although they are not listed, this class inherits all of the config options of Store,
* JsonReader and HttpProxy (unless inline data is provided).</b>
* @cfg {Array} fields An array of field definition objects, or field name strings.
* @constructor
* @param {Object} config
*/
/*
* <b>注意: 尽管他们没有列出来.除非内在数据己提供,否则该类继承了所有store,jsonReader,和heepProxy的配置项.</b>
* @cfg {Array} fields 一字段定义的对象,或字段名 数组
* @constructor
* @param {Object} config
*/
Ext.data.JsonStore = function(c){
Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(c, {
proxy: !c.data ? new Ext.data.HttpProxy({url: c.url}) : undefined,
reader: new Ext.data.JsonReader(c, c.fields)
}));
};
Ext.extend(Ext.data.JsonStore, Ext.data.Store); | 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.data.Connection
* @extends Ext.util.Observable
* 该类压缩了一个页面到当前域的连接,以响应(来自配置文件中的url或请求时指定的url)请求
* 通过该类产生的请求都是异步的,并且会立刻返回,紧根其后的request调用将得不到数据
* 可以使用在request配置项一个回调函数,或事件临听器来处理返回来的数据.
* The class encapsulates a connection to the page's originating domain, allowing requests to be made
* either to a configured URL, or to a URL specified at request time.<br><br>
* <p>
* Requests made by this class are asynchronous, and will return immediately. No data from
* the server will be available to the statement immediately following the {@link #request} call.
* To process returned data, use a callback in the request options object, or an event listener.</p><br>
* <p>
* 注意:如果你正在上传文件,你将不会有一正常的响应对象送回到你的回调或事件名柄中,因为上传是通过iframe来处理的.
* 这里没有xmlhttpRequest对象.response对象是通过iframe的document的innerTHML作为responseText属性,如果存在,
* 该iframe的xml document作为responseXML属性
* 这意味着一个有效的xml或html document必须被返回,如果json数据是被需要的,这次意味着它将放到
* html document的textarea元素内(通过某种规则可以从responseText重新得到)或放到一个元数据区内(通过标准的dom方法可以重新得到)
*
* Note: If you are doing a file upload, you will not get a normal response object sent back to
* your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
* The response object is created using the innerHTML of the IFRAME's document as the responseText
* property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
* This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
* that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
* using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
* standard DOM methods.
* @constructor 构建器
* @param {Object} config a configuration object. 配置对象
*/
Ext.data.Connection = function(config){
Ext.apply(this, config);
this.addEvents({
/**
* @ beforrequest 事件
* 在一网络请求要求返回数据对象之前触发该事件
* @param {Connection} conn 该Connection对象
* @param {Object} options 传入reauest 方法的配置对象
* @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" : true,
/**
* @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 {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
/**
* @ requestcomplete 事件
* 当请求成功完成时触发该事件
* @param {Connection} conn 该Connection对象
* @param {Object} response 包含返回数据的XHR对象
* 去 {@link http://www.w3.org/TR/XMLHttpRequest/} 获取更多信息
* @param {Object} options 传入reauest 方法的配置对象
*/
"requestcomplete" : true,
/**
* @event requestexception
* Fires if an error HTTP status was returned from the server.
* See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
* @param {Connection} conn This Connection object.
* @param {Object} response The XHR object containing the response data.
* See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
/**
* @ requestexception 事件
* 当服务器端返回代表错误的http状态时触发该事件
* 去 {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} 获取更多关于HTTP status codes信息.
* @param {Connection} conn 该Connection对象
* @param {Object} response 包含返回数据的XHR对象
* 去 {@link http://www.w3.org/TR/XMLHttpRequest/} 获取更多信息.
* @param {Object} 传入reauest 方法的配置对象.
*/
"requestexception" : true
});
Ext.data.Connection.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Connection, Ext.util.Observable, {
/**
* @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
*/
/**
* @cfg {String} url (可选项) 被用来向服务发起请求默认的url,默认值为undefined
*/
/**
* @cfg {Object} extraParams (Optional) An object containing properties which are used as
* extra parameters to each request made by this object. (defaults to undefined)
*/
/**
* @cfg {Object} extraParams (可选项) 一个包含属性值的对象(这些属性在该Connection发起的每次请求中作为外部参数)
*/
/**
* @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
* to each request made by this object. (defaults to undefined)
*/
/**
* @cfg {Object} defaultHeaders (可选项) 一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中)
*/
/**
* @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
*/
/**
* @cfg {String} method (可选项) 请求时使用的默认的http方法(默认为undefined;
* 如果存在参数但没有设值.则值为post,否则为get)
*/
/**
* @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
*/
/**
* @cfg {Number} timeout (可选项) 一次请求超时的毫秒数.(默认为30秒钟)
*/
timeout : 30000,
/**
* @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
* @type Boolean
*/
/**
* @cfg {Boolean} autoAbort (可选项) 该request是否应当中断挂起的请求.(默认值为false)
* @type Boolean
*/
autoAbort:false,
/**
* @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
* @type Boolean
*/
/**
* @cfg {Boolean} disableCaching (可选项) 设置为true就会添加一个独一无二的cache-buster参数来获取请求(默认值为true)
* @type Boolean
*/
disableCaching: true,
/**
* 向远程服务器发送一http请求
* @param {Object} options 包含如下属性的一对象<ul>
* <li><b>url</b> {String} (可选项) 发送请求的url.默认为配置的url</li>
* <li><b>params</b> {Object/String/Function} (可选项) 一包含属性的对象(这些属性被用作request的参数)或一个编码后的url字串或一个能调用其中任一一属性的函数.</li>
* <li><b>method</b> {String} (可选项) 该请求所用的http方面,默认值为配置的方法,或者当没有方法被配置时,如果没有发送参数时用get,有参数时用post.</li>
* <li><b>callback</b> {Function} (可选项) 该方法被调用时附上返回的http response 对象.
* 不管成功还是失败,该回调函数都将被调用,该函数中传入了如下参数:<ul>
* <li>options {Object} 该request调用的参数.</li>
* <li>success {Boolean} 请求成功则为true.</li>
* <li>response {Object} 包含返回数据的xhr对象.</li>
* </ul></li>
* <li><b>success</b> {Function} (可选项) 该函数被调用取决于请求成功.
* 该回调函数被传入如下参数:<ul>
* <li>response {Object} 包含了返回数据的xhr对象.</li>
* <li>options {Object} 请求所调用的参数.</li>
* </ul></li>
* <li><b>failure</b> {Function} (可选项) 该函数被调用取决于请求失败.
* 该回调函数被传入如下参数:<ul>
* <li>response {Object} 包含了数据的xhr对象.</li>
* <li>options {Object} 请求所调用的参数.</li>
* </ul></li>
* <li><b>scope</b> {Object} (可选项) 回调函数的作用域: "this" 指代回调函数本身
* 默认值为浏览器窗口</li>
* <li><b>form</b> {Object/String} (可选项) 用来压入参数的一个form对象或 form的标识</li>
* <li><b>isUpload</b> {Boolean} (可选项)如果该form对象是上传form,为true, (通常情况下会自动探测).</li>
* <li><b>headers</b> {Object} (可选项) 为请求所加的请求头.</li>
* <li><b>xmlData</b> {Object} (可选项) 用于发送的xml document.注意:它将会被用来在发送数据中代替参数
* 任务参数将会被追加在url中.</li>
* <li><b>disableCaching</b> {Boolean} (可选项) 设置为True,则添加一个独一无二的 cache-buster参数来获取请求.</li>
* </ul>
* Sends an HTTP request to a remote server.
* @param {Object} options An object which may contain the following properties:<ul>
* <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
* <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
* request, a url encoded string or a function to call to get either.</li>
* <li><b>method</b> {String} (Optional) 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.</li>
* <li><b>callback</b> {Function} (Optional) 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>options {Object} The parameter to the request call.</li>
* <li>success {Boolean} True if the request succeeded.</li>
* <li>response {Object} The XMLHttpRequest object containing the response data.</li>
* </ul></li>
* <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
* The callback is passed the following parameters:<ul>
* <li>response {Object} The XMLHttpRequest object containing the response data.</li>
* <li>options {Object} The parameter to the request call.</li>
* </ul></li>
* <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
* The callback is passed the following parameters:<ul>
* <li>response {Object} The XMLHttpRequest object containing the response data.</li>
* <li>options {Object} The parameter to the request call.</li>
* </ul></li>
* <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
* for the callback function. Defaults to the browser window.</li>
* <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
* <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
* <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
* <li><b>xmlData</b> {Object} (Optional) 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.</li>
* <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
* </ul>
* @return {Number} transactionId
*/
request : function(o){
if(this.fireEvent("beforerequest", this, o) !== false){
var p = o.params;
if(typeof p == "function"){
p = p.call(o.scope||window, o);
}
if(typeof p == "object"){
p = Ext.urlEncode(o.params);
}
if(this.extraParams){
var extras = Ext.urlEncode(this.extraParams);
p = p ? (p + '&' + extras) : extras;
}
var url = o.url || this.url;
if(typeof url == 'function'){
url = url.call(o.scope||window, o);
}
if(o.form){
var form = Ext.getDom(o.form);
url = url || form.action;
var enctype = form.getAttribute("enctype");
if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
return this.doFormUpload(o, p, url);
}
var f = Ext.lib.Ajax.serializeForm(form);
p = p ? (p + '&' + f) : f;
}
var hs = o.headers;
if(this.defaultHeaders){
hs = Ext.apply(hs || {}, this.defaultHeaders);
if(!o.headers){
o.headers = hs;
}
}
var cb = {
success: this.handleResponse,
failure: this.handleFailure,
scope: this,
argument: {options: o},
timeout : this.timeout
};
var method = o.method||this.method||(p ? "POST" : "GET");
if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
}
if(typeof o.autoAbort == 'boolean'){ // options gets top priority
if(o.autoAbort){
this.abort();
}
}else if(this.autoAbort !== false){
this.abort();
}
if((method == 'GET' && p) || o.xmlData){
url += (url.indexOf('?') != -1 ? '&' : '?') + p;
p = '';
}
this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
return this.transId;
}else{
Ext.callback(o.callback, o.scope, [o, null, null]);
return null;
}
},
/**
* Determine whether this object has a request outstanding.
* @param {Number} transactionId (Optional) defaults to the last transaction
* @return {Boolean} True if there is an outstanding request.
*/
/**
* 确认该对象是否有显注的请求
* @param {Number} transactionId (可选项) 默认是最后一次事务
* @return {Boolean} 如果这是个显注的请求的话,返回true.
*/
isLoading : function(transId){
if(transId){
return Ext.lib.Ajax.isCallInProgress(transId);
}else{
return this.transId ? true : false;
}
},
/**
* Aborts any outstanding request.
* @param {Number} transactionId (Optional) defaults to the last transaction
*/
/**
* 中断任何显注的请求.
* @param {Number} transactionId (或选项) 默认值为最后一次事务
*/
abort : function(transId){
if(transId || this.isLoading()){
Ext.lib.Ajax.abort(transId || this.transId);
}
},
// private
handleResponse : function(response){
this.transId = false;
var options = response.argument.options;
response.argument = options ? options.argument : null;
this.fireEvent("requestcomplete", this, response, options);
Ext.callback(options.success, options.scope, [response, options]);
Ext.callback(options.callback, options.scope, [options, true, response]);
},
// private
handleFailure : function(response, e){
this.transId = false;
var options = response.argument.options;
response.argument = options ? options.argument : null;
this.fireEvent("requestexception", this, response, options, e);
Ext.callback(options.failure, options.scope, [response, options]);
Ext.callback(options.callback, options.scope, [options, false, response]);
},
// private
doFormUpload : function(o, ps, url){
var id = Ext.id();
var frame = document.createElement('iframe');
frame.id = id;
frame.name = id;
frame.className = 'x-hidden';
if(Ext.isIE){
frame.src = Ext.SSL_SECURE_URL;
}
document.body.appendChild(frame);
if(Ext.isIE){
document.frames[id].name = id;
}
var form = Ext.getDom(o.form);
form.target = id;
form.method = 'POST';
form.enctype = form.encoding = 'multipart/form-data';
if(url){
form.action = url;
}
var hiddens, hd;
if(ps){ // add dynamic params
hiddens = [];
ps = Ext.urlDecode(ps, false);
for(var k in ps){
if(ps.hasOwnProperty(k)){
hd = document.createElement('input');
hd.type = 'hidden';
hd.name = k;
hd.value = ps[k];
form.appendChild(hd);
hiddens.push(hd);
}
}
}
function cb(){
var r = { // bogus response object
responseText : '',
responseXML : null
};
r.argument = o ? o.argument : null;
try { //
var doc;
if(Ext.isIE){
doc = frame.contentWindow.document;
}else {
doc = (frame.contentDocument || window.frames[id].document);
}
if(doc && doc.body){
r.responseText = doc.body.innerHTML;
}
if(doc && doc.XMLDocument){
r.responseXML = doc.XMLDocument;
}else {
r.responseXML = doc;
}
}
catch(e) {
// ignore
}
Ext.EventManager.removeListener(frame, 'load', cb, this);
this.fireEvent("requestcomplete", this, r, o);
Ext.callback(o.success, o.scope, [r, o]);
Ext.callback(o.callback, o.scope, [o, true, r]);
setTimeout(function(){document.body.removeChild(frame);}, 100);
}
Ext.EventManager.on(frame, 'load', cb, this);
form.submit();
if(hiddens){ // remove dynamic params
for(var i = 0, len = hiddens.length; i < len; i++){
form.removeChild(hiddens[i]);
}
}
}
});
/**
* @class Ext.Ajax
* @extends Ext.data.Connection
* Global Ajax request class.
* Ext.Ajax类,继承了Ext.data.Connection,全局的ajax请求类
* @singleton单例
*/
Ext.Ajax = new Ext.data.Connection({
// fix up the docs
/**
* @cfg {String} url @hide
*/
/**
* @cfg {String} url @hide
*/
/**
* @cfg {Object} extraParams @hide
*/
/**
* @cfg {Object} 外部参数 @hide
*/
/**
* @cfg {Object} defaultHeaders @hide
*/
/**
* @cfg {Object} 默认请求头 @hide
*/
/**
* @cfg {String} method (Optional) @hide
*/
/**
* @cfg {String} 请求的方法 (可选项) @hide
*/
/**
* @cfg {Number} timeout (Optional) @hide
*/
/**
* @cfg {Number} 超时时间 (可选项) @hide
*/
/**
* @cfg {Boolean} autoAbort (Optional) @hide
*/
/**
* @cfg {Boolean} 自动中断 (可选项) @hide
*/
/**
* @cfg {Boolean} disableCaching (Optional) @hide
*/
/**
* @cfg {Boolean} 不启用缓存 (可选项) @hide
*/
/**
* @property disableCaching
* True to add a unique cache-buster param to GET requests. (defaults to true)
* @type Boolean
*/
/**
* @property disableCaching
* 设置为true使得增加一cache-buster参数来获取请求. (默认为true)
* @type Boolean
*/
/**
* @property url
* The default URL to be used for requests to the server. (defaults to undefined)
* @type String
*/
/**
* @property url
* 默认的被用来向服务器发起请求的url. (默认为 undefined)
* @type String
*/
/**
* @property extraParams
* An object containing properties which are used as
* extra parameters to each request made by this object. (defaults to undefined)
* @type Object
*/
/**
* @property 外部参数
* 一个包含属性的对象(这些属性在该Connection发起的每次请求中作为外部参数)
* @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 默认的请求头
* 一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中)
* @type Object
*/
/**
* @property method
* The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
* @type String
*/
/**
* @property method
* 请求时使用的默认的http方法(默认为undefined;
* 如果存在参数但没有设值.则值为post,否则为get)
* @type String
*/
/**
* @property timeout
* 请求的超时豪秒数. (默认为30秒)
* @type Number
*/
/**
* @property autoAbort
* Whether a new request should abort any pending requests. (defaults to false)
* @type Boolean
*/
/**
* @property autoAbort
* 该request是否应当中断挂起的请求.(默认值为false)
* @type Boolean
*/
autoAbort : false,
/**
* Serialize the passed form into a url encoded string
* @param {String/HTMLElement} form
* @return {String}
*/
/**
* 续列化传入的form为编码后的url字符串
* @param {String/HTMLElement} form
* @return {String}
*/
serializeForm : function(form){
return Ext.lib.Ajax.serializeForm(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.data.SimpleStore
* @extends Ext.data.Store
* Small helper class to make creating Stores from Array data easier.
* @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
* @cfg {Array} fields An array of field definition objects, or field name strings.
* @cfg {Array} data The multi-dimensional array of data
* @constructor
* @param {Object} config
*/
/**
* @Ext.data.SimpleStore类
* @继承Ext.data.Store
* 使得从数组创建stores更为方便的简单帮助类
* @cfg {Number} id 记录索引的数组ID.不填则自动生成
* @cfg {Array} fields 字段定义对象的数组,或字段名字符串.
* @cfg {Array} data 多维数据数组
* @constructor
* @param {Object} config
*/
Ext.data.SimpleStore = function(config){
Ext.data.SimpleStore.superclass.constructor.call(this, {
reader: new Ext.data.ArrayReader({
id: config.id
},
Ext.data.Record.create(config.fields)
),
proxy : new Ext.data.MemoryProxy(config.data)
});
this.load();
};
Ext.extend(Ext.data.SimpleStore, Ext.data.Store); | 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.data.JsonReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of Ext.data.Record objects from a JSON response
* based on mappings in a provided Ext.data.Record constructor.
* <p>
* json数据读取器,继承数据读取器,基于Ext.data.Record提供的构造器映射方式,
* 将json response对象构建成Ext.data.Record对象的数组
* Example code:
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
{name: 'occupation'} // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.JsonReader({
totalProperty: "results", // The property which contains the total dataset size (optional)
root: "rows", // The property which contains an Array of row objects
id: "id" // The property within each row object that provides an ID for the record (optional)
}, RecordDef);
</code></pre>
* <p>
* This would consume a JSON file like this:
* <pre><code>
{ 'results': 2, 'rows': [
{ 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
{ 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
}
</code></pre>
* @cfg {String} totalProperty 一属性名,通过该属性可以得到数据集中记录总条数
* 该属性仅当整个数据集一口气传过来时需要.而不是被远程主机分过页的
* @cfg {String} 属性名,通过该属性能得到被forms使用的成功属性
* @cfg {String} 一属性的名字,该属性包含一行对象的数组
* @cfg {String} 行对象的一属性的名字,该属性包含记录的标识值
* @构建器
* 创建一新的JsonReader
* @param {Object} meta 元数据配置项
* @param {Object} recordType 字段的定义的数组,或由Ext.daa.Record的create方法创建的一个Ext.data.Record对象
*/
/* @cfg {String}
* in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
* paged from the remote server.
* @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
* @cfg {String} root name of the property which contains the Array of row objects.
* @cfg {String} id Name of the property within a row object that contains a record identifier value.
* @constructor
* Create a new JsonReader
* @param {Object} meta Metadata configuration options
* @param {Object} recordType Either an Array of field definition objects,
* or an {@link Ext.data.Record} object created using {@link Ext.data.Record#create}.
*/
Ext.data.JsonReader = function(meta, recordType){
meta = meta || {};
Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response The XHR object which contains the JSON data in its responseText.
* @return {Object} data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
/**
* 该方法仅当一DataProxy从远程主机被找回时使用
* @param {Object} response 其responseText中包含json 数据的XmlHttpRequest对象
* @return {Object} data 被Ext.data.Store对象当作Ext.data.Records的缓存数据块
*/
read : function(response){
var json = response.responseText;
var o = eval("("+json+")");
if(!o) {
throw {message: "JsonReader.read: Json object not found"};
}
if(o.metaData){
delete this.ef;
this.meta = o.metaData;
this.recordType = Ext.data.Record.create(o.metaData.fields);
this.onMetaChange(this.meta, this.recordType, o);
}
return this.readRecords(o);
},
// private function a store will implement
//私有的方法.store将会来实现
onMetaChange : function(meta, recordType, o){
},
/**
* @ignore
*/
simpleAccess: function(obj, subsc) {
return obj[subsc];
},
/**
* @ignore
*/
getJsonAccessor: function(){
var re = /[\[\.]/;
return function(expr) {
try {
return(re.test(expr))
? new Function("obj", "return obj." + expr)
: function(obj){
return obj[expr];
};
} catch(e){}
return Ext.emptyFn;
};
}(),
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} o An object which contains an Array of row objects in the property specified
* in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
* which contains the total size of the dataset.
* @return {Object} data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
/**
* 从xml document创建一包含Ext.data.Records的数据块
* @param {Object} o 一包含行对象组数的对象(在配置文件中作为root)包含数据集记录总数的随意属性(在配置文件中作为totalProperty)
* @return {Object} data 被Ext.data.Store对象当作Ext.data.Records缓存的一数据块
*/
readRecords : function(o){
/**
* After any data loads, the raw JSON data is available for further custom processing.
* @type Object
*/
/**
* 在数据装载后,原始的json数据对于更远的客户端不可再操作
* @type Object
*/
this.jsonData = o;
var s = this.meta, Record = this.recordType,
f = Record.prototype.fields, fi = f.items, fl = f.length;
// Generate extraction functions for the totalProperty, the root, the id, and for each field
// 为totalProperty ,root,id,及其它字段生成的提取函数
if (!this.ef) {
if(s.totalProperty) {
this.getTotal = this.getJsonAccessor(s.totalProperty);
}
if(s.successProperty) {
this.getSuccess = this.getJsonAccessor(s.successProperty);
}
this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
if (s.id) {
var g = this.getJsonAccessor(s.id);
this.getId = function(rec) {
var r = g(rec);
return (r === undefined || r === "") ? null : r;
};
} else {
this.getId = function(){return null;};
}
this.ef = [];
for(var i = 0; i < fl; i++){
f = fi[i];
var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
this.ef[i] = this.getJsonAccessor(map);
}
}
var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
if(s.totalProperty){
var v = parseInt(this.getTotal(o), 10);
if(!isNaN(v)){
totalRecords = v;
}
}
if(s.successProperty){
var v = this.getSuccess(o);
if(v === false || v === 'false'){
success = false;
}
}
var records = [];
for(var i = 0; i < c; i++){
var n = root[i];
var values = {};
var id = this.getId(n);
for(var j = 0; j < fl; j++){
f = fi[j];
var v = this.ef[j](n);
values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
}
var record = new Record(values, id);
record.json = n;
records[i] = record;
}
return {
success : success,
records : records,
totalRecords : totalRecords
};
}
}); | 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.data.ArrayReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of Ext.data.Record objects from an Array.
* Each element of that Array represents a row of data fields. The
* fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
* of the field definition if it exists, or the field's ordinal position in the definition.<br>
* <p>
* 数组读到器,继承数据读取器
* 该类作用是将一个数组(该数组中的每个元素代表着一行数据字段,字段被放到Record对象中作为子脚本使用)转换成
* Ext.data.Record的对象数组,字段定义的mapping属性如果存在.或字段在定义中的原始位置
*
* Example code:.
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
{name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
]); //"mapping"仅当有"id"字段出现时(排除了使用原始位置作为索引)需要
var myReader = new Ext.data.ArrayReader({
id: 0 // The subscript within row Array that provides an ID for the Record (optional)
}, RecordDef); //下面的行数组内提供了该记录的id
</code></pre>
* <p>
* This would consume an Array like this:
* <pre><code>
[ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
</code></pre>
* @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
* @constructor
* Create a new JsonReader
* @param {Object} meta Metadata configuration options.
* @param {Object} recordType Either an Array of field definition objects
* as specified to {@link Ext.data.Record#create},
* or an {@link Ext.data.Record} object
* created using {@link Ext.data.Record#create}.
*/
/*
* @cfg {String} id (可选项) 下面的行数组内提供了该记录的id
* @构建器
* 创建一新的JsonReader
* @param {Object} meta 元数据配置项.
* @param {Object} recordType 既是一字段的字义指定对象的数组,又是通过Ext.data.Record的create方法创建的Ext.data.Record对象
*/
Ext.data.ArrayReader = function(meta, recordType){
Ext.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
};
Ext.extend(Ext.data.ArrayReader, Ext.data.JsonReader, {
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} o An Array of row objects which represents the dataset.
* @return {Object} data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
/**
* 从xml document创建一包含Ext.data.Records的数据块
* @param {Object} o 一代表着数据集的行对象数组
* @return {Object} data 被Ext.data.Store对象当作Ext.data.Records 缓存的数据块
*/
readRecords : function(o){
var sid = this.meta ? this.meta.id : null;
var recordType = this.recordType, fields = recordType.prototype.fields;
var records = [];
var root = o;
for(var i = 0; i < root.length; i++){
var n = root[i];
var values = {};
var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
for(var j = 0, jlen = fields.length; j < jlen; j++){
var f = fields.items[j];
var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
var v = n[k] !== undefined ? n[k] : f.defaultValue;
v = f.convert(v);
values[f.name] = v;
}
var record = new recordType(values, id);
record.json = n;
records[records.length] = record;
}
return {
records : records,
totalRecords : records.length
};
}
}); | 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
*/
// Base class for reading structured data from a data source. This class is intended to be
// extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
// 从数据源读取结构化数据的基础类,(从数组读取器.json数据读取器和xml数据读取器可以知道)该类被规定为被继承类而不是被直接创建
Ext.data.DataReader = function(meta, recordType){
this.meta = meta;
this.recordType = recordType instanceof Array ?
Ext.data.Record.create(recordType) : recordType;
};
Ext.data.DataReader.prototype = {
}; | 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.data.HttpProxy
* An implementation of {@link Ext.data.DataProxy} that reads a data object from an {@link Ext.data.Connection} object
* configured to reference a certain URL.<br><br>
* <p>
* <em>Note that this class cannot be used to retrieve data from a domain other than the domain
* from which the running page was served.<br><br>
* <p>
* For cross-domain access to remote data, use an {@link Ext.data.ScriptTagProxy}.</em><br><br>
* <p>
* Be aware that to enable the browser to parse an XML document, the server must set
* the Content-Type header in the HTTP response to "text/xml".
* @constructor
* @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
* an {@link Ext.data.Connection} object. If a Connection config is passed, the singleton {@link Ext.Ajax} object
* will be used to make the request.
*/
/**
* @ Ext.data.HttpProxy 类
* Ext.data.DataProxy类的一个实现类,能从Ext.data.Connection(对某一url有着引用的)对象读取数据 <br><br>
* <p>
* <em>注意:该类不能够被用来从非本域(本域指为提供当前页面服务的域)的其它域外获取数据<br><br>
* <p>
* 使用Ext.data.ScriptTagProxy,从交叉域访问远程数据.</em><br><br>
* <p>
* 必须要明白,为了使浏览器能够解析一xml document,该服务器必须将http 响应头的content-type的值为"text/xml"
* @构建器
* @param {Object} conn 添加入每个请求中的Connection配置项(如{url:'foo.php'}) 或者 一个Ext.data.Connection对象.
* 如果一个Connection配置被传入,该单例Ext.Ajax对象将会被用来创建请求
*/
Ext.data.HttpProxy = function(conn){
Ext.data.HttpProxy.superclass.constructor.call(this);
// is conn a conn config or a real conn?
this.conn = conn;
this.useAjax = !conn || !conn.events;
};
Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {
/**
* Return the {@link Ext.data.Connection} object being used by this Proxy.
* @return {Connection} The Connection object. This object may be used to subscribe to events on
* a finer-grained basis than the DataProxy events.
*/
/**
* 返回该Proxy使用的Ext.data.Connection对象.
* @return {Connection} 该Connection对象.该对象可以被用来订阅事件
*/
getConnection : function(){
return this.useAjax ? Ext.Ajax : this.conn;
},
/**
* Load data from the configured {@link Ext.data.Connection}, read the data object into
* a block of Ext.data.Records using the passed {@link Ext.data.DataReader} implementation, and
* process that block using the passed callback.
* @param {Object} params An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
/**
* 从Ext.data.Connection的配置装载数据,使用传入的Ext.data.DataReader实现类将数据对象读入到
* Ext.data.Records数据块中,并通过传入的回调函数处理该数据块
* @param {Object} params 一个包含请求远程主机的http 参数作为属性的对象
* @param {Ext.data.DataReader} reader 一个能将数据对象转换成Ext.data.Record块的数据读取器
* @param {Function} callback 该函数在传入的Ext.data.Record块中.该函数必须被传入 <ul>
* <li>Record 块对象</li>
* <li>来自装载函数中的参数</li>
* <li>成功指示器</li>
* </ul>
* @param {Object} scope 回调函数的作用域
* @param {Object} arg 一可选参数.被传入回调函中中作为它的第二个参数
*/
load : function(params, reader, callback, scope, arg){
if(this.fireEvent("beforeload", this, params) !== false){
var o = {
params : params || {},
request: {
callback : callback,
scope : scope,
arg : arg
},
reader: reader,
callback : this.loadResponse,
scope: this
};
if(this.useAjax){
Ext.applyIf(o, this.conn);
if(this.activeRequest){
Ext.Ajax.abort(this.activeRequest);
}
this.activeRequest = Ext.Ajax.request(o);
}else{
this.conn.request(o);
}
}else{
callback.call(scope||this, null, arg, false);
}
},
// private
loadResponse : function(o, success, response){
delete this.activeRequest;
if(!success){
this.fireEvent("loadexception", this, o, response);
o.request.callback.call(o.request.scope, null, o.request.arg, false);
return;
}
var result;
try {
result = o.reader.read(response);
}catch(e){
this.fireEvent("loadexception", this, o, response, e);
o.request.callback.call(o.request.scope, null, o.request.arg, false);
return;
}
this.fireEvent("load", this, o, o.request.arg);
o.request.callback.call(o.request.scope, result, o.request.arg, true);
},
// private
update : function(dataSet){
},
// private
updateResponse : function(dataSet){
}
}); | 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.data.ScriptTagProxy
* An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain
* other than the originating domain of the running page.<br><br>
* <p>
* <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
* of the running page, you must use this class, rather than DataProxy.</em><br><br>
* <p>
* The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
* source code that is used as the source inside a <script> tag.<br><br>
* <p>
* In order for the browser to process the returned data, the server must wrap the data object
* with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
* Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
* depending on whether the callback name was passed:
* <p>
/**
* @ Ext.data.ScriptTagProxy类
* Ext.data.DataProxy实现类,从原始域(原始域指当前运行页所在的域)而是其它域读取数据对象<br><br>
* <p>
* <em>注意:如果你从一非本域运行的页面获取的数据与从本域获取数据不同,你必须使用此类来操作,而不是使用DataProxy.</em><br><br>
* <p>
* 被一ScriptTagProxy请求的从服务器资源传回的内容是可执行的javascript脚本,在<script>标签中被当作源.<br><br>
* <p>
* 为了使浏览器能处理返回的数据,服务器必须用对回调函数的调用来封装数据对象.它的名字为作为参数被scriptTagProxy传入
* 下面是一个java的小程序例子.它将返回数据到scriptTagProxy或httpProxy,取决于是否有回调函数名
* <p>
* <pre><code>
boolean scriptTag = false;
String cb = request.getParameter("callback");
if (cb != null) {
scriptTag = true;
response.setContentType("text/javascript");
} else {
response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (scriptTag) {
out.write(cb + "(");
}
out.print(dataBlock.toJsonString());
if (scriptTag) {
out.write(");");
}
</pre></code>
*
* @constructor
* @param {Object} config A configuration object.
*/
/*
* @constructor
* @param {Object} config一配置对象
*/
Ext.data.ScriptTagProxy = function(config){
Ext.data.ScriptTagProxy.superclass.constructor.call(this);
Ext.apply(this, config);
this.head = document.getElementsByTagName("head")[0];
};
Ext.data.ScriptTagProxy.TRANS_ID = 1000;
Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
/**
* @cfg {String} url The URL from which to request the data object.
*/
/**
* @cfg {String} url从该处请求数据的url.
*/
/**
* @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
*/
/**
* @cfg {Number} timeout (可选项) 等待响应的毫秒数.默认为30秒
*/
timeout : 30000,
/**
* @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
* the server the name of the callback function set up by the load call to process the returned data object.
* Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
* javascript output which calls this named function passing the data object as its only parameter.
*/
/**
* @cfg {String} callbackParam (可选项) 传到服务器的参数的名字.通过这名字告诉服各器回调函数的名字,装载时装配该函数来
* 处理返回的数据对象,默认值为"callback". 服务器端处理必须读取该参数值.然后生成javascript输出.该javascript调用
* 该名字的函数作为自己的参数传递数据对象
*/
callbackParam : "callback",
/**
* @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
* name to the request.
*/
/**
* @cfg {Boolean} nocache (可选项) 默认值为true,添加一个独一无二的参数名到请求中来取消缓存
*/
nocache : true,
/**
* Load data from the configured URL, read the data object into
* a block of Ext.data.Records using the passed Ext.data.DataReader implementation, and
* process that block using the passed callback.
* @param {Object} params An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
/**
* 从配置的url中装载数据,使用传入的Ext.data.DataReader实现来读取数据对象到Ext.data.Records块中.
* 并通过传入的回调函数处理该数据块
* @param {Object} params 一包含属性的对象,这些属性被用来当作向远程服务器发送的请求http 参数.
* @param {Ext.data.DataReader} reader 转换数据对象到Ext.data.Records块的Reader对象.
* @param {Function} callback 传入Ext.data.Record的函数.
* 该函数必须被传入<ul>
* <li>记录块对象</li>
* <li>来自load函数的参数</li>
* <li>布尔值的成功指示器</li>
* </ul>
* @param {Object} scope 回调函数的作用域
* @param {Object} arg 被传到回调函数中作为第二参数的可选参数.
*/
load : function(params, reader, callback, scope, arg){
if(this.fireEvent("beforeload", this, params) !== false){
var p = Ext.urlEncode(Ext.apply(params, this.extraParams));
var url = this.url;
url += (url.indexOf("?") != -1 ? "&" : "?") + p;
if(this.nocache){
url += "&_dc=" + (new Date().getTime());
}
var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
var trans = {
id : transId,
cb : "stcCallback"+transId,
scriptId : "stcScript"+transId,
params : params,
arg : arg,
url : url,
callback : callback,
scope : scope,
reader : reader
};
var conn = this;
window[trans.cb] = function(o){
conn.handleResponse(o, trans);
};
url += String.format("&{0}={1}", this.callbackParam, trans.cb);
if(this.autoAbort !== false){
this.abort();
}
trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
var script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", trans.scriptId);
this.head.appendChild(script);
this.trans = trans;
}else{
callback.call(scope||this, null, arg, false);
}
},
// private
isLoading : function(){
return this.trans ? true : false;
},
/**
* Abort the current server request.
*/
/**
* 中断当前的服务器请求
*/
abort : function(){
if(this.isLoading()){
this.destroyTrans(this.trans);
}
},
// private
destroyTrans : function(trans, isLoaded){
this.head.removeChild(document.getElementById(trans.scriptId));
clearTimeout(trans.timeoutId);
if(isLoaded){
window[trans.cb] = undefined;
try{
delete window[trans.cb];
}catch(e){}
}else{
// if hasn't been loaded, wait for load to remove it to prevent script error
// 如果没有被装载,等待装载来移除前面的脚本错误
window[trans.cb] = function(){
window[trans.cb] = undefined;
try{
delete window[trans.cb];
}catch(e){}
};
}
},
// private
handleResponse : function(o, trans){
this.trans = false;
this.destroyTrans(trans, true);
var result;
try {
result = trans.reader.readRecords(o);
}catch(e){
this.fireEvent("loadexception", this, o, trans.arg, e);
trans.callback.call(trans.scope||window, null, trans.arg, false);
return;
}
this.fireEvent("load", this, o, trans.arg);
trans.callback.call(trans.scope||window, result, trans.arg, true);
},
// private
handleFailure : function(trans){
this.trans = false;
this.destroyTrans(trans, false);
this.fireEvent("loadexception", this, null, trans.arg);
trans.callback.call(trans.scope||window, null, trans.arg, 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.menu.Item
* @extends Ext.menu.BaseItem
* ������˵�������صģ��磺�Ӳ˵����Լ��Ǿ�̬��ʾ�IJ˵���Ļ��ࡣItem ��̳��� {@link Ext.menu.BaseItem}
* ��Ļ������ܣ�������˲˵������еĶ����͵���¼��Ĵ������
* @constructor
* ����һ�� Item ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.Item = function(config){
Ext.menu.Item.superclass.constructor.call(this, config);
if(this.menu){
this.menu = Ext.menu.MenuMgr.get(this.menu);
}
};
Ext.extend(Ext.menu.Item, Ext.menu.BaseItem, {
/**
* @cfg {String} icon
* ָ���ò˵�����ʾ��ͼ���·����Ĭ��Ϊ Ext.BLANK_IMAGE_URL��
*/
/**
* @cfg {String} itemCls �˵���ʹ�õ�Ĭ��CSS��ʽ�ࣨĬ��Ϊ "x-menu-item"��
*/
itemCls : "x-menu-item",
/**
* @cfg {Boolean} canActivate ֵΪ True ʱ��ѡ���ܹ��ڿɼ�������±����Ĭ��Ϊ true��
*/
canActivate : true,
/**
* @cfg {Number} showDelay �˵�����ʾ֮ǰ����ʱʱ�䣨Ĭ��Ϊ200��
*/
showDelay: 200,
// doc'd in BaseItem
hideDelay: 200,
// private
ctype: "Ext.menu.Item",
// private
onRender : function(container, position){
var el = document.createElement("a");
el.hideFocus = true;
el.unselectable = "on";
el.href = this.href || "#";
if(this.hrefTarget){
el.target = this.hrefTarget;
}
el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : "");
el.innerHTML = String.format(
'<img src="{0}" class="x-menu-item-icon {2}" />{1}',
this.icon || Ext.BLANK_IMAGE_URL, this.text, this.iconCls || '');
this.el = el;
Ext.menu.Item.superclass.onRender.call(this, container, position);
},
/**
* ���øò˵�����ʾ���ı�
* @param {String} text ��ʾ���ı�
*/
setText : function(text){
this.text = text;
if(this.rendered){
this.el.update(String.format(
'<img src="{0}" class="x-menu-item-icon {2}">{1}',
this.icon || Ext.BLANK_IMAGE_URL, this.text, this.iconCls || ''));
this.parentMenu.autoWidth();
}
},
// private
handleClick : function(e){
if(!this.href){ // if no link defined, stop the event automatically
e.stopEvent();
}
Ext.menu.Item.superclass.handleClick.apply(this, arguments);
},
// private
activate : function(autoExpand){
if(Ext.menu.Item.superclass.activate.apply(this, arguments)){
this.focus();
if(autoExpand){
this.expandMenu();
}
}
return true;
},
// private
shouldDeactivate : function(e){
if(Ext.menu.Item.superclass.shouldDeactivate.call(this, e)){
if(this.menu && this.menu.isVisible()){
return !this.menu.getEl().getRegion().contains(e.getPoint());
}
return true;
}
return false;
},
// private
deactivate : function(){
Ext.menu.Item.superclass.deactivate.apply(this, arguments);
this.hideMenu();
},
// private
expandMenu : function(autoActivate){
if(!this.disabled && this.menu){
clearTimeout(this.hideTimer);
delete this.hideTimer;
if(!this.menu.isVisible() && !this.showTimer){
this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]);
}else if (this.menu.isVisible() && autoActivate){
this.menu.tryActivate(0, 1);
}
}
},
// private
deferExpand : function(autoActivate){
delete this.showTimer;
this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu);
if(autoActivate){
this.menu.tryActivate(0, 1);
}
},
// private
hideMenu : function(){
clearTimeout(this.showTimer);
delete this.showTimer;
if(!this.hideTimer && this.menu && this.menu.isVisible()){
this.hideTimer = this.deferHide.defer(this.hideDelay, this);
}
},
// private
deferHide : function(){
delete this.hideTimer;
this.menu.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
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.menu.ColorMenu
* @extends Ext.menu.Menu
* һ������ {@link Ext.menu.ColorItem} ����IJ˵����ṩ�˻�������ɫѡ��������
* @constructor
* ����һ�� ColorMenu ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.ColorMenu = function(config){
Ext.menu.ColorMenu.superclass.constructor.call(this, config);
this.plain = true;
var ci = new Ext.menu.ColorItem(config);
this.add(ci);
/**
* �ò˵��� {@link Ext.ColorPalette} ���ʵ��
* @type ColorPalette
*/
this.palette = ci.palette;
/**
* @event select
* @param {ColorPalette} palette
* @param {String} color
*/
this.relayEvents(ci, ["select"]);
};
Ext.extend(Ext.menu.ColorMenu, Ext.menu.Menu); | 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.menu.DateItem
* @extends Ext.menu.Adapter
* һ��ͨ����װ {@link Ext.DatPicker} ������ɵIJ˵��
* @constructor
* ����һ�� DateItem ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.DateItem = function(config){
Ext.menu.DateItem.superclass.constructor.call(this, new Ext.DatePicker(config), config);
/** The Ext.DatePicker object @type Ext.DatePicker */
this.picker = this.component;
this.addEvents({select: true});
this.picker.on("render", function(picker){
picker.getEl().swallowEvent("click");
picker.container.addClass("x-menu-date-item");
});
this.picker.on("select", this.onSelect, this);
};
Ext.extend(Ext.menu.DateItem, Ext.menu.Adapter, {
// private
onSelect : function(picker, date){
this.fireEvent("select", this, date, picker);
Ext.menu.DateItem.superclass.handleClick.call(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
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.menu.TextItem
* @extends Ext.menu.BaseItem
* ���һ����̬�ı����˵��У�ͨ��������Ϊ���������ָ����
* @constructor
* ����һ�� TextItem ����
* @param {String} text Ҫ��ʾ���ı�
*/
Ext.menu.TextItem = function(text){
this.text = text;
Ext.menu.TextItem.superclass.constructor.call(this);
};
Ext.extend(Ext.menu.TextItem, Ext.menu.BaseItem, {
/**
* @cfg {Boolean} hideOnClick ֵΪ True ʱ�����������ذ����IJ˵���Ĭ��Ϊ false��
*/
hideOnClick : false,
/**
* @cfg {String} itemCls �ı���ʹ�õ�Ĭ��CSS��ʽ�ࣨĬ��Ϊ "x-menu-text"��
*/
itemCls : "x-menu-text",
// private
onRender : function(){
var s = document.createElement("span");
s.className = this.itemCls;
s.innerHTML = this.text;
this.el = s;
Ext.menu.TextItem.superclass.onRender.apply(this, arguments);
}
}); | 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.menu.MenuMgr
* �ṩһ��ҳ�������в˵���Ĺ���ע�����Ա��������ܹ�������ͨ��ID�����ʡ�
* @singleton
*/
Ext.menu.MenuMgr = function(){
var menus, active, groups = {}, attached = false, lastShow = new Date();
// private -���˵���һ�δ���ʱ����
function init(){
menus = {}, active = new Ext.util.MixedCollection();
Ext.get(document).addKeyListener(27, function(){
if(active.length > 0){
hideAll();
}
});
}
// private
function hideAll(){
if(active.length > 0){
var c = active.clone();
c.each(function(m){
m.hide();
});
}
}
// private
function onHide(m){
active.remove(m);
if(active.length < 1){
Ext.get(document).un("mousedown", onMouseDown);
attached = false;
}
}
// private
function onShow(m){
var last = active.last();
lastShow = new Date();
active.add(m);
if(!attached){
Ext.get(document).on("mousedown", onMouseDown);
attached = true;
}
if(m.parentMenu){
m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3);
m.parentMenu.activeChild = m;
}else if(last && last.isVisible()){
m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3);
}
}
// private
function onBeforeHide(m){
if(m.activeChild){
m.activeChild.hide();
}
if(m.autoHideTimer){
clearTimeout(m.autoHideTimer);
delete m.autoHideTimer;
}
}
// private
function onBeforeShow(m){
var pm = m.parentMenu;
if(!pm && !m.allowOtherMenus){
hideAll();
}else if(pm && pm.activeChild){
pm.activeChild.hide();
}
}
// private
function onMouseDown(e){
if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){
hideAll();
}
}
// private
function onBeforeCheck(mi, state){
if(state){
var g = groups[mi.group];
for(var i = 0, l = g.length; i < l; i++){
if(g[i] != mi){
g[i].setChecked(false);
}
}
}
}
return {
/**
* �������е�ǰ�ɼ��IJ˵�
*/
hideAll : function(){
hideAll();
},
// private
register : function(menu){
if(!menus){
init();
}
menus[menu.id] = menu;
menu.on("beforehide", onBeforeHide);
menu.on("hide", onHide);
menu.on("beforeshow", onBeforeShow);
menu.on("show", onShow);
var g = menu.group;
if(g && menu.events["checkchange"]){
if(!groups[g]){
groups[g] = [];
}
groups[g].push(menu);
menu.on("checkchange", onCheck);
}
},
/**
* ����һ�� {@link Ext.menu.Menu} ����
* @param {String/Object} menu ���ֵΪ�ַ�����ʽ�IJ˵�ID���ش��ڵĶ������á������ Menu �������ѡ��������������ɲ�����һ���µ� Menu ʵ����
*/
get : function(menu){
if(typeof menu == "string"){ // menu id
return menus[menu];
}else if(menu.events){ // menu instance
return menu;
}else if(typeof menu.length == 'number'){ // array of menu items?
return new Ext.menu.Menu({items:menu});
}else{ // otherwise, must be a config
return new Ext.menu.Menu(menu);
}
},
// private
unregister : function(menu){
delete menus[menu.id];
menu.un("beforehide", onBeforeHide);
menu.un("hide", onHide);
menu.un("beforeshow", onBeforeShow);
menu.un("show", onShow);
var g = menu.group;
if(g && menu.events["checkchange"]){
groups[g].remove(menu);
menu.un("checkchange", onCheck);
}
},
// private
registerCheckable : function(menuItem){
var g = menuItem.group;
if(g){
if(!groups[g]){
groups[g] = [];
}
groups[g].push(menuItem);
menuItem.on("beforecheckchange", onBeforeCheck);
}
},
// private
unregisterCheckable : function(menuItem){
var g = menuItem.group;
if(g){
groups[g].remove(menuItem);
menuItem.un("beforecheckchange", onBeforeCheck);
}
}
};
}();
| 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.menu.CheckItem
* @extends Ext.menu.Item
* ���һ��Ĭ��Ϊ��ѡ��IJ˵�ѡ�Ҳ�����ǵ�ѡ�����е�һ����Ա��
* @constructor
* ����һ�� CheckItem ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.CheckItem = function(config){
Ext.menu.CheckItem.superclass.constructor.call(this, config);
this.addEvents({
/**
* @event beforecheckchange
* �� checked ���Ա��趨֮ǰ�������ṩһ��ȡ���Ļ��ᣨ�����Ҫ�Ļ���
* @param {Ext.menu.CheckItem} this
* @param {Boolean} checked �������õ��µ� checked ����ֵ
*/
"beforecheckchange" : true,
/**
* @event checkchange
* checked ���Ա����ú�
* @param {Ext.menu.CheckItem} this
* @param {Boolean} checked �����õ� checked ����ֵ
*/
"checkchange" : true
});
if(this.checkHandler){
this.on('checkchange', this.checkHandler, this.scope);
}
};
Ext.extend(Ext.menu.CheckItem, Ext.menu.Item, {
/**
* @cfg {String} group
* ���� group ������ͬ��ѡ������Զ�����֯��һ����ѡ��ť���У�Ĭ��Ϊ ''��
*/
/**
* @cfg {String} itemCls ѡ����ʹ�õ�Ĭ��CSS��ʽ�ࣨĬ��Ϊ "x-menu-item x-menu-check-item"��
*/
itemCls : "x-menu-item x-menu-check-item",
/**
* @cfg {String} groupClass ��ѡ������ѡ����ʹ�õ�Ĭ��CSS��ʽ�ࣨĬ��Ϊ "x-menu-group-item"��
*/
groupClass : "x-menu-group-item",
/**
* @cfg {Boolean} checked ֵΪ True ʱ��ѡ���ʼΪѡ��״̬��Ĭ��Ϊ false����
* ע�⣺���ѡ����Ϊ��ѡ�����е�һԱ��group Ϊ trueʱ����ֻ������ѡ����ű���ʼΪѡ��״̬��
*/
checked: false,
// private
ctype: "Ext.menu.CheckItem",
// private
onRender : function(c){
Ext.menu.CheckItem.superclass.onRender.apply(this, arguments);
if(this.group){
this.el.addClass(this.groupClass);
}
Ext.menu.MenuMgr.registerCheckable(this);
if(this.checked){
this.checked = false;
this.setChecked(true, true);
}
},
// private
destroy : function(){
if(this.rendered){
Ext.menu.MenuMgr.unregisterCheckable(this);
}
Ext.menu.CheckItem.superclass.destroy.apply(this, arguments);
},
/**
* ���ø�ѡ��� checked ����״̬
* @param {Boolean} checked �µ� checked ����ֵ
* @param {Boolean} suppressEvent ����ѡ� ֵΪ True ʱ����ֹ checkchange �¼��Ĵ�����Ĭ��Ϊ false��
*/
setChecked : function(state, suppressEvent){
if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){
if(this.container){
this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked");
}
this.checked = state;
if(suppressEvent !== true){
this.fireEvent("checkchange", this, state);
}
}
},
// private
handleClick : function(e){
if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item
this.setChecked(!this.checked);
}
Ext.menu.CheckItem.superclass.handleClick.apply(this, arguments);
}
}); | 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.menu.Menu
* @extends Ext.util.Observable
* һ���˵�����������������ӵIJ˵����������Menu ��Ҳ���Ե��������������������ɵIJ˵��Ļ��ࣨ���磺{@link Ext.menu.DateMenu}����
* @constructor
* ����һ�� Menu ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.Menu = function(config){
Ext.apply(this, config);
this.id = this.id || Ext.id();
this.addEvents({
/**
* @event beforeshow
* �ڸò˵���ʾ֮ǰ����
* @param {Ext.menu.Menu} this
*/
beforeshow : true,
/**
* @event beforehide
* �ڸò˵�����֮ǰ����
* @param {Ext.menu.Menu} this
*/
beforehide : true,
/**
* @event show
* �ڸò˵���ʾ֮��
* @param {Ext.menu.Menu} this
*/
show : true,
/**
* @event hide
* �ڸò˵�����֮��
* @param {Ext.menu.Menu} this
*/
hide : true,
/**
* @event click
* ������ò˵�ʱ���������ߵ��ò˵����ڻ״̬�һس���������ʱ������
* @param {Ext.menu.Menu} this
* @param {Ext.menu.Item} menuItem ������� Item ����
* @param {Ext.EventObject} e
*/
click : true,
/**
* @event mouseover
* ����꾭���ò˵�ʱ����
* @param {Ext.menu.Menu} this
* @param {Ext.EventObject} e
* @param {Ext.menu.Item} menuItem ������� Item ����
*/
mouseover : true,
/**
* @event mouseout
* ������뿪�ò˵�ʱ����
* @param {Ext.menu.Menu} this
* @param {Ext.EventObject} e
* @param {Ext.menu.Item} menuItem ������� Item ����
*/
mouseout : true,
/**
* @event itemclick
* ���ò˵��������IJ˵�����ʱ����
* @param {Ext.menu.BaseItem} baseItem ������� BaseItem ����
* @param {Ext.EventObject} e
*/
itemclick: true
});
Ext.menu.MenuMgr.register(this);
var mis = this.items;
this.items = new Ext.util.MixedCollection();
if(mis){
this.add.apply(this, mis);
}
};
Ext.extend(Ext.menu.Menu, Ext.util.Observable, {
/**
* @cfg {Number} minWidth ������Ϊ��λ���õIJ˵���С���ֵ��Ĭ��Ϊ 120��
*/
minWidth : 120,
/**
* @cfg {Boolean/String} shadow ��ֵΪ True ���� "sides" ʱΪĬ��Ч����"frame" ʱΪ4��������Ӱ��"drop" ʱΪ���½�����Ӱ��Ĭ��Ϊ "sides"��
*/
shadow : "sides",
/**
* @cfg {String} subMenuAlign �ò˵����Ӳ˵��� {@link Ext.Element#alignTo} ��λê���ֵ��Ĭ��Ϊ "tl-tr?"��
*/
subMenuAlign : "tl-tr?",
/**
* @cfg {String} defaultAlign �ò˵����������ԭʼԪ�ص� {@link Ext.Element#alignTo) ��λê���Ĭ��ֵ��Ĭ��Ϊ "tl-bl?"��
*/
defaultAlign : "tl-bl?",
/**
* @cfg {Boolean} allowOtherMenus ֵΪ True ʱ����ͬʱ��ʾ����˵���Ĭ��Ϊ false��
*/
allowOtherMenus : false,
hidden:true,
// private
render : function(){
if(this.el){
return;
}
var el = this.el = new Ext.Layer({
cls: "x-menu",
shadow:this.shadow,
constrain: false,
parentEl: this.parentEl || document.body,
zindex:15000
});
this.keyNav = new Ext.menu.MenuNav(this);
if(this.plain){
el.addClass("x-menu-plain");
}
if(this.cls){
el.addClass(this.cls);
}
// generic focus element
this.focusEl = el.createChild({
tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1"
});
var ul = el.createChild({tag: "ul", cls: "x-menu-list"});
ul.on("click", this.onClick, this);
ul.on("mouseover", this.onMouseOver, this);
ul.on("mouseout", this.onMouseOut, this);
this.items.each(function(item){
var li = document.createElement("li");
li.className = "x-menu-list-item";
ul.dom.appendChild(li);
item.render(li, this);
}, this);
this.ul = ul;
this.autoWidth();
},
// private
autoWidth : function(){
var el = this.el, ul = this.ul;
if(!el){
return;
}
var w = this.width;
if(w){
el.setWidth(w);
}else if(Ext.isIE){
el.setWidth(this.minWidth);
var t = el.dom.offsetWidth; // force recalc
el.setWidth(ul.getWidth()+el.getFrameWidth("lr"));
}
},
// private
delayAutoWidth : function(){
if(this.rendered){
if(!this.awTask){
this.awTask = new Ext.util.DelayedTask(this.autoWidth, this);
}
this.awTask.delay(20);
}
},
// private
findTargetItem : function(e){
var t = e.getTarget(".x-menu-list-item", this.ul, true);
if(t && t.menuItemId){
return this.items.get(t.menuItemId);
}
},
// private
onClick : function(e){
var t;
if(t = this.findTargetItem(e)){
t.onClick(e);
this.fireEvent("click", this, t, e);
}
},
// private
setActiveItem : function(item, autoExpand){
if(item != this.activeItem){
if(this.activeItem){
this.activeItem.deactivate();
}
this.activeItem = item;
item.activate(autoExpand);
}else if(autoExpand){
item.expandMenu();
}
},
// private
tryActivate : function(start, step){
var items = this.items;
for(var i = start, len = items.length; i >= 0 && i < len; i+= step){
var item = items.get(i);
if(!item.disabled && item.canActivate){
this.setActiveItem(item, false);
return item;
}
}
return false;
},
// private
onMouseOver : function(e){
var t;
if(t = this.findTargetItem(e)){
if(t.canActivate && !t.disabled){
this.setActiveItem(t, true);
}
}
this.fireEvent("mouseover", this, e, t);
},
// private
onMouseOut : function(e){
var t;
if(t = this.findTargetItem(e)){
if(t == this.activeItem && t.shouldDeactivate(e)){
this.activeItem.deactivate();
delete this.activeItem;
}
}
this.fireEvent("mouseout", this, e, t);
},
/**
* ֻ���������ǰ��ʾ���Ǹò˵��� true������ false��
* @type Boolean
*/
isVisible : function(){
return this.el && !this.hidden;
},
/**
* ���������Ԫ����ʾ�ò˵�
* @param {String/HTMLElement/Ext.Element} element Ҫ���뵽��Ԫ��
* @param {String} position ����ѡ�� ����Ԫ��ʱʹ�õ�{@link Ext.Element#alignTo} ��λê�㣨Ĭ��Ϊ this.defaultAlign��
* @param {Ext.menu.Menu} parentMenu ����ѡ�� �ò˵��ĸ����˵�������еĻ���Ĭ��Ϊ undefined��
*/
show : function(el, pos, parentMenu){
this.parentMenu = parentMenu;
if(!this.el){
this.render();
}
this.fireEvent("beforeshow", this);
this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false);
},
/**
* ��ָ����λ����ʾ�ò˵�
* @param {Array} xyPosition ��ʾ�˵�ʱ���õİ��� X �� Y [x, y] ������ֵ�������ǻ���ҳ��ģ�
* @param {Ext.menu.Menu} parentMenu ����ѡ�� �ò˵��ĸ����˵�������еĻ���Ĭ��Ϊ undefined��
*/
showAt : function(xy, parentMenu, /* private: */_e){
this.parentMenu = parentMenu;
if(!this.el){
this.render();
}
if(_e !== false){
this.fireEvent("beforeshow", this);
xy = this.el.adjustForConstraints(xy);
}
this.el.setXY(xy);
this.el.show();
this.hidden = false;
this.focus();
this.fireEvent("show", this);
},
focus : function(){
if(!this.hidden){
this.doFocus.defer(50, this);
}
},
doFocus : function(){
if(!this.hidden){
this.focusEl.focus();
}
},
/**
* ���ظò˵���������ĸ����˵�
* @param {Boolean} deep ����ѡ�� ֵΪ True ʱ��ݹ��������и����˵�������еĻ���Ĭ��Ϊ false��
*/
hide : function(deep){
if(this.el && this.isVisible()){
this.fireEvent("beforehide", this);
if(this.activeItem){
this.activeItem.deactivate();
this.activeItem = null;
}
this.el.hide();
this.hidden = true;
this.fireEvent("hide", this);
}
if(deep === true && this.parentMenu){
this.parentMenu.hide(true);
}
},
/**
* ���һ������ Menu ��֧�ֵIJ˵�����߿��Ա�ת��Ϊ�˵���Ķ���
* ����������һ�������ɣ�
* <ul>
* <li>�κλ��� {@link Ext.menu.Item} �IJ˵������</li>
* <li>���Ա�ת��Ϊ�˵���� HTML Ԫ�ض���</li>
* <li>���Ա�����Ϊһ���˵������IJ˵�������ѡ�����</li>
* <li>�����ַ�������ֵΪ '-' �� 'separator' ʱ���ڲ˵������һ���ָ���������������»ᱻת����Ϊһ�� {@link Ext.menu.TextItem} ������ӵ��˵���</li>
* </ul>
* �÷���
* <pre><code>
// ����һ���˵�
var menu = new Ext.menu.Menu();
// ͨ�����췽������һ���˵���
var menuItem = new Ext.menu.Item({ text: 'New Item!' });
// ͨ����ͬ�ķ���һ�����һ��˵��
// �����ӵIJ˵���Żᱻ���ء�
var item = menu.add(
menuItem, // ���һ���Ѿ�������IJ˵���
'Dynamic Item', // ���һ�� TextItem ����
'-', // ���һ���ָ���
{ text: 'Config Item' } // ������ѡ��������ɵIJ˵���
);
</code></pre>
* @param {Mixed} args һ�������˵���˵�������ѡ����������Ա�ת��Ϊ�˵���Ķ���
* @return {Ext.menu.Item} ����ӵIJ˵�����߶������ӵIJ˵����е����һ��
*/
add : function(){
var a = arguments, l = a.length, item;
for(var i = 0; i < l; i++){
var el = a[i];
if(el.render){ // some kind of Item
item = this.addItem(el);
}else if(typeof el == "string"){ // string
if(el == "separator" || el == "-"){
item = this.addSeparator();
}else{
item = this.addText(el);
}
}else if(el.tagName || el.el){ // element
item = this.addElement(el);
}else if(typeof el == "object"){ // must be menu item config?
item = this.addMenuItem(el);
}
}
return item;
},
/**
* ���ظò˵������ڵ� {@link Ext.Element} ����
* @return {Ext.Element} Ԫ�ض���
*/
getEl : function(){
if(!this.el){
this.render();
}
return this.el;
},
/**
* ���һ���ָ������˵�
* @return {Ext.menu.Item} ����ӵIJ˵���
*/
addSeparator : function(){
return this.addItem(new Ext.menu.Separator());
},
/**
* ���һ�� {@link Ext.Element} ���˵�
* @param {String/HTMLElement/Ext.Element} el ����ӵ�Ԫ�ػ��� DOM �ڵ㣬��������ID
* @return {Ext.menu.Item} ����ӵIJ˵���
*/
addElement : function(el){
return this.addItem(new Ext.menu.BaseItem(el));
},
/**
* ���һ���Ѿ����ڵĻ��� {@link Ext.menu.Item} �Ķ��˵�
* @param {Ext.menu.Item} item ����ӵIJ˵���
* @return {Ext.menu.Item} ����ӵIJ˵���
*/
addItem : function(item){
this.items.add(item);
if(this.ul){
var li = document.createElement("li");
li.className = "x-menu-list-item";
this.ul.dom.appendChild(li);
item.render(li, this);
this.delayAutoWidth();
}
return item;
},
/**
* ���ݸ���������ѡ���һ�� {@link Ext.menu.Item} ������ӵ��˵�
* @param {Object} config �˵�����ѡ�����
* @return {Ext.menu.Item} ����ӵIJ˵���
*/
addMenuItem : function(config){
if(!(config instanceof Ext.menu.Item)){
if(typeof config.checked == "boolean"){ // must be check menu item config?
config = new Ext.menu.CheckItem(config);
}else{
config = new Ext.menu.Item(config);
}
}
return this.addItem(config);
},
/**
* ���ݸ������ı�����һ�� {@link Ext.menu.TextItem} ������ӵ��˵�
* @param {String} text �˵�������ʾ���ı�
* @return {Ext.menu.Item} ����ӵIJ˵���
*/
addText : function(text){
return this.addItem(new Ext.menu.TextItem(text));
},
/**
* ��ָ����λ�ò���һ���Ѿ����ڵĻ��� {@link Ext.menu.Item} �Ķ��˵�
* @param {Number} index Ҫ����Ķ����ڲ˵��в˵����б��λ�õ�����ֵ
* @param {Ext.menu.Item} item Ҫ��ӵIJ˵���
* @return {Ext.menu.Item} ����ӵIJ˵���
*/
insert : function(index, item){
this.items.insert(index, item);
if(this.ul){
var li = document.createElement("li");
li.className = "x-menu-list-item";
this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]);
item.render(li, this);
this.delayAutoWidth();
}
return item;
},
/**
* �Ӳ˵���ɾ��������һ�� {@link Ext.menu.Item} ����
* @param {Ext.menu.Item} item Ҫɾ���IJ˵���
*/
remove : function(item){
this.items.removeKey(item.id);
item.destroy();
},
/**
* �Ӳ˵���ɾ�����������в˵���
*/
removeAll : function(){
var f;
while(f = this.items.first()){
this.remove(f);
}
}
});
// MenuNav ��һ���� Menu ʹ�õ��ڲ�˽����
Ext.menu.MenuNav = function(menu){
Ext.menu.MenuNav.superclass.constructor.call(this, menu.el);
this.scope = this.menu = menu;
};
Ext.extend(Ext.menu.MenuNav, Ext.KeyNav, {
doRelay : function(e, h){
var k = e.getKey();
if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){
this.menu.tryActivate(0, 1);
return false;
}
return h.call(this.scope || this, e, this.menu);
},
up : function(e, m){
if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){
m.tryActivate(m.items.length-1, -1);
}
},
down : function(e, m){
if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){
m.tryActivate(0, 1);
}
},
right : function(e, m){
if(m.activeItem){
m.activeItem.expandMenu(true);
}
},
left : function(e, m){
m.hide();
if(m.parentMenu && m.parentMenu.activeItem){
m.parentMenu.activeItem.activate();
}
},
enter : function(e, m){
if(m.activeItem){
e.stopPropagation();
m.activeItem.onClick(e);
m.fireEvent("click", this, m.activeItem);
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.menu.DateMenu
* @extends Ext.menu.Menu
* һ������ {@link Ext.menu.DateItem} ����IJ˵����ṩ������ѡ��������
* @constructor
* ����һ�� DateMenu ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.DateMenu = function(config){
Ext.menu.DateMenu.superclass.constructor.call(this, config);
this.plain = true;
var di = new Ext.menu.DateItem(config);
this.add(di);
/**
* �ò˵��� {@link Ext.DatePicker} ���ʵ��
* @type DatePicker
*/
this.picker = di.picker;
/**
* @event select
* @param {DatePicker} picker
* @param {Date} date
*/
this.relayEvents(di, ["select"]);
this.on('beforeshow', function(){
if(this.picker){
this.picker.hideMonthPicker(true);
}
}, this);
};
Ext.extend(Ext.menu.DateMenu, Ext.menu.Menu, {
cls:'x-date-menu'
}); | 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.menu.BaseItem
* @extends Ext.Component
* �˵�����а���������ѡ��Ļ��ࡣBaseItem �ṩĬ�ϵ���Ⱦ���״̬������ɲ˵��������Ļ������á�
* @constructor
* ����һ�� BaseItem ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.BaseItem = function(config){
Ext.menu.BaseItem.superclass.constructor.call(this, config);
this.addEvents({
/**
* @event click
* ����ѡ����ʱ����
* @param {Ext.menu.BaseItem} this
* @param {Ext.EventObject} e
*/
click: true,
/**
* @event activate
* ����ѡ�����ʱ����
* @param {Ext.menu.BaseItem} this
*/
activate : true,
/**
* @event deactivate
* ����ѡ��ͷ��ﴥ��
* @param {Ext.menu.BaseItem} this
*/
deactivate : true
});
if(this.handler){
this.on("click", this.handler, this.scope, true);
}
};
Ext.extend(Ext.menu.BaseItem, Ext.Component, {
/**
* @cfg {Function} handler
* ���������ѡ����¼��ĺ�����Ĭ��Ϊ undefined��
*/
/**
* @cfg {Boolean} canActivate ֵΪ True ʱ��ѡ���ܹ��ڿɼ�������±�����
*/
canActivate : false,
/**
* @cfg {String} activeClass ����ѡ���Ϊ����״̬ʱ��ʹ�õ�CSS��ʽ�ࣨĬ��Ϊ "x-menu-item-active"��
*/
activeClass : "x-menu-item-active",
/**
* @cfg {Boolean} hideOnClick ֵΪ True ʱ��ѡ����������������IJ˵���Ĭ��Ϊ true��
*/
hideOnClick : true,
/**
* @cfg {Number} hideDelay �Ժ���Ϊ��λ��ʾ�ĵ��������ص��ӳ�ʱ�䣨Ĭ��Ϊ 100��
*/
hideDelay : 100,
// private
ctype: "Ext.menu.BaseItem",
// private
actionMode : "container",
// private
render : function(container, parentMenu){
this.parentMenu = parentMenu;
Ext.menu.BaseItem.superclass.render.call(this, container);
this.container.menuItemId = this.id;
},
// private
onRender : function(container, position){
this.el = Ext.get(this.el);
container.dom.appendChild(this.el.dom);
},
// private
onClick : function(e){
if(!this.disabled && this.fireEvent("click", this, e) !== false
&& this.parentMenu.fireEvent("itemclick", this, e) !== false){
this.handleClick(e);
}else{
e.stopEvent();
}
},
// private
activate : function(){
if(this.disabled){
return false;
}
var li = this.container;
li.addClass(this.activeClass);
this.region = li.getRegion().adjust(2, 2, -2, -2);
this.fireEvent("activate", this);
return true;
},
// private
deactivate : function(){
this.container.removeClass(this.activeClass);
this.fireEvent("deactivate", this);
},
// private
shouldDeactivate : function(e){
return !this.region || !this.region.contains(e.getPoint());
},
// private
handleClick : function(e){
if(this.hideOnClick){
this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]);
}
},
// private
expandMenu : function(autoActivate){
// do nothing
},
// private
hideMenu : function(){
// do nothing
}
}); | 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.menu.ColorItem
* @extends Ext.menu.Adapter
* һ��ͨ����װ {@link Ext.ColorPalette} ������ɵIJ˵��
* @constructor
* ����һ�� ColorItem ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.ColorItem = function(config){
Ext.menu.ColorItem.superclass.constructor.call(this, new Ext.ColorPalette(config), config);
/** The Ext.ColorPalette object @type Ext.ColorPalette */
this.palette = this.component;
this.relayEvents(this.palette, ["select"]);
if(this.selectHandler){
this.on('select', this.selectHandler, this.scope);
}
};
Ext.extend(Ext.menu.ColorItem, Ext.menu.Adapter); | 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.menu.Adapter
* @extends Ext.menu.BaseItem
* һ�������Ļ��࣬����ʹԭ���˵�������ܹ����˵�ѡ���װ����������ӵ��˵���ȥ��
* ���ṩ�˲˵����������Ļ�������Ⱦ������������/���������ܡ�
* @constructor
* ����һ�� Adapter ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.Adapter = function(component, config){
Ext.menu.Adapter.superclass.constructor.call(this, config);
this.component = component;
};
Ext.extend(Ext.menu.Adapter, Ext.menu.BaseItem, {
// private
canActivate : true,
// private
onRender : function(container, position){
this.component.render(container);
this.el = this.component.getEl();
},
// private
activate : function(){
if(this.disabled){
return false;
}
this.component.focus();
this.fireEvent("activate", this);
return true;
},
// private
deactivate : function(){
this.fireEvent("deactivate", this);
},
// private
disable : function(){
this.component.disable();
Ext.menu.Adapter.superclass.disable.call(this);
},
// private
enable : function(){
this.component.enable();
Ext.menu.Adapter.superclass.enable.call(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
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.menu.Separator
* @extends Ext.menu.BaseItem
* ���һ���ָ������˵��У��������ֲ˵���������顣ͨ��������ڵ��� add() ����ʱ�����ڲ˵��������ѡ����ʹ�� "-" ����ֱ�Ӵ���һ���ָ�����
* @constructor
* ����һ�� Separator ����
* @param {Object} config ����ѡ�����
*/
Ext.menu.Separator = function(config){
Ext.menu.Separator.superclass.constructor.call(this, config);
};
Ext.extend(Ext.menu.Separator, Ext.menu.BaseItem, {
/**
* @cfg {String} itemCls �ָ���ʹ�õ�Ĭ��CSS��ʽ�ࣨĬ��Ϊ "x-menu-sep"��
*/
itemCls : "x-menu-sep",
/**
* @cfg {Boolean} hideOnClick ֵΪ True ʱ�����������ذ����IJ˵���Ĭ��Ϊ false��
*/
hideOnClick : false,
// private
onRender : function(li){
var s = document.createElement("span");
s.className = this.itemCls;
s.innerHTML = " ";
this.el = s;
li.addClass("x-menu-sep-li");
Ext.menu.Separator.superclass.onRender.apply(this, arguments);
}
}); | 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.DatePicker
* @extends Ext.Component
* 简单的日期拾取器类。
* @constructor
* 创建一个 DatePicker 对象
* @param {Object} config 配置项对象
*/
Ext.DatePicker = function(config){
Ext.DatePicker.superclass.constructor.call(this, config);
this.value = config && config.value ?
config.value.clearTime() : new Date().clearTime();
this.addEvents({
/**
* @event select
* 在日期被选中后触发
* @param {DatePicker} this
* @param {Date} date 选中的日期
*/
select: true
});
if(this.handler){
this.on("select", this.handler, this.scope || this);
}
// build the disabledDatesRE
if(!this.disabledDatesRE && 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.disabledDatesRE = new RegExp(re + ")");
}
};
Ext.extend(Ext.DatePicker, Ext.Component, {
/**
* @cfg {String} todayText
* 选取当前日期按钮上显示的文本(默认为 "Today")
*/
todayText : "Today",
/**
* @cfg {String} okText
* ok 按钮上显示的文本
*/
okText : " OK ", //   可以给用户更多的点击空间
/**
* @cfg {String} cancelText
* cancel 按钮上显示的文本
*/
cancelText : "Cancel",
/**
* @cfg {String} todayTip
* 选取当前日期按钮上的快捷工具提示(默认为 "{current date} (Spacebar)")
*/
todayTip : "{0} (Spacebar)",
/**
* @cfg {Date} minDate
* 允许的最小日期(JavaScript 日期对象, 默认为 null)
*/
minDate : null,
/**
* @cfg {Date} maxDate
* 允许的最大日期(JavaScript 日期对象, 默认为 null)
*/
maxDate : null,
/**
* @cfg {String} minText
* minDate 效验失败时显示的错误文本(默认为 "This date is before the minimum date")
*/
minText : "This date is before the minimum date",
/**
* @cfg {String} maxText
* maxDate 效验失败时显示的错误文本(默认为 "This date is after the maximum date")
*/
maxText : "This date is after the maximum date",
/**
* @cfg {String} format
* 默认的日期格式化字串, 本地化时可以被覆写。格式化字串必须为 {@link Date#parseDate} 中描述的有效项(默认为 'm/d/y').
*/
format : "m/d/y",
/**
* @cfg {Array} disabledDays
* 一个禁用星期数组, 以 0 开始。例如, [0, 6] 禁用周日和周六(默认为 null).
*/
disabledDays : null,
/**
* @cfg {String} disabledDaysText
* 禁用星期上的快捷工具提示(默认为 "")
*/
disabledDaysText : "",
/**
* @cfg {RegExp} disabledDatesRE
* 一个用来匹配禁用日期的 JavaScript 正则表达式(默认为 null)
*/
disabledDatesRE : null,
/**
* @cfg {String} disabledDatesText
* 禁用日期上的快捷工具提示(默认为 "")
*/
disabledDatesText : "",
/**
* @cfg {Boolean} constrainToViewport
* 设为 true 则将日期拾取器限定在 viewport 内(默认为 true)
*/
constrainToViewport : true,
/**
* @cfg {Array} monthNames
* 一个由月份名称组成的数组, 本地化时可以被覆写(默认为 Date.monthNames)
*/
monthNames : Date.monthNames,
/**
* @cfg {Array} dayNames
* 一个由星期名称组成的数组, 本地化时可以被覆写(默认为 Date.dayNames)
*/
dayNames : Date.dayNames,
/**
* @cfg {String} nextText
* 下一月导航按钮的快捷工具提示(默认为 'Next Month (Control+Right)')
*/
nextText: 'Next Month (Control+Right)',
/**
* @cfg {String} prevText
* 上一月导航按钮的快捷工具提示(默认为 'Previous Month (Control+Left)')
*/
prevText: 'Previous Month (Control+Left)',
/**
* @cfg {String} monthYearText
* 月份选择头部的快捷工具提示(默认为 'Choose a month (Control+Up/Down to move years)')
*/
monthYearText: 'Choose a month (Control+Up/Down to move years)',
/**
* @cfg {Number} startDay
* 指定每周开始的星期索引数, 以 0 开始(默认为 0, 表示以周日开始)
*/
startDay : 0,
/**
* 设置日期字段的值
* @param {Date} value 设置的日期
*/
setValue : function(value){
var old = this.value;
this.value = value.clearTime(true);
if(this.el){
this.update(this.value);
}
},
/**
* 取得日期字段的当前值
* @return {Date} 选中的日期
*/
getValue : function(){
return this.value;
},
// private
focus : function(){
if(this.el){
this.update(this.activeDate);
}
},
// private
onRender : function(container, position){
var m = [
'<table cellspacing="0">',
'<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
'<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
var dn = this.dayNames;
for(var i = 0; i < 7; i++){
var d = this.startDay+i;
if(d > 6){
d = d-7;
}
m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
}
m[m.length] = "</tr></thead><tbody><tr>";
for(var i = 0; i < 42; i++) {
if(i % 7 == 0 && i != 0){
m[m.length] = "</tr><tr>";
}
m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
}
m[m.length] = '</tr></tbody></table></td></tr><tr><td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
var el = document.createElement("div");
el.className = "x-date-picker";
el.innerHTML = m.join("");
container.dom.insertBefore(el, position);
this.el = Ext.get(el);
this.eventEl = Ext.get(el.firstChild);
new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), {
handler: this.showPrevMonth,
scope: this,
preventDefault:true,
stopDefault:true
});
new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), {
handler: this.showNextMonth,
scope: this,
preventDefault:true,
stopDefault:true
});
this.eventEl.on("mousewheel", this.handleMouseWheel, this);
this.monthPicker = this.el.down('div.x-date-mp');
this.monthPicker.enableDisplayMode('block');
var kn = new Ext.KeyNav(this.eventEl, {
"left" : function(e){
e.ctrlKey ?
this.showPrevMonth() :
this.update(this.activeDate.add("d", -1));
},
"right" : function(e){
e.ctrlKey ?
this.showNextMonth() :
this.update(this.activeDate.add("d", 1));
},
"up" : function(e){
e.ctrlKey ?
this.showNextYear() :
this.update(this.activeDate.add("d", -7));
},
"down" : function(e){
e.ctrlKey ?
this.showPrevYear() :
this.update(this.activeDate.add("d", 7));
},
"pageUp" : function(e){
this.showNextMonth();
},
"pageDown" : function(e){
this.showPrevMonth();
},
"enter" : function(e){
e.stopPropagation();
return true;
},
scope : this
});
this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this);
this.el.unselectable();
this.cells = this.el.select("table.x-date-inner tbody td");
this.textNodes = this.el.query("table.x-date-inner tbody span");
this.mbtn = new Ext.Button(this.el.child("td.x-date-middle", true), {
text: " ",
tooltip: this.monthYearText
});
this.mbtn.on('click', this.showMonthPicker, this);
this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
var today = (new Date()).dateFormat(this.format);
var todayBtn = new Ext.Button(this.el.child("td.x-date-bottom", true), {
text: String.format(this.todayText, today),
tooltip: String.format(this.todayTip, today),
handler: this.selectToday,
scope: this
});
if(Ext.isIE){
this.el.repaint();
}
this.update(this.value);
},
createMonthPicker : function(){
if(!this.monthPicker.dom.firstChild){
var buf = ['<table border="0" cellspacing="0">'];
for(var i = 0; i < 6; i++){
buf.push(
'<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
'<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
i == 0 ?
'<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
'<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
);
}
buf.push(
'<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
this.okText,
'</button><button type="button" class="x-date-mp-cancel">',
this.cancelText,
'</button></td></tr>',
'</table>'
);
this.monthPicker.update(buf.join(''));
this.monthPicker.on('click', this.onMonthClick, this);
this.monthPicker.on('dblclick', this.onMonthDblClick, this);
this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
this.mpYears = this.monthPicker.select('td.x-date-mp-year');
this.mpMonths.each(function(m, a, i){
i += 1;
if((i%2) == 0){
m.dom.xmonth = 5 + Math.round(i * .5);
}else{
m.dom.xmonth = Math.round((i-1) * .5);
}
});
}
},
showMonthPicker : function(){
this.createMonthPicker();
var size = this.el.getSize();
this.monthPicker.setSize(size);
this.monthPicker.child('table').setSize(size);
this.mpSelMonth = (this.activeDate || this.value).getMonth();
this.updateMPMonth(this.mpSelMonth);
this.mpSelYear = (this.activeDate || this.value).getFullYear();
this.updateMPYear(this.mpSelYear);
this.monthPicker.slideIn('t', {duration:.2});
},
updateMPYear : function(y){
this.mpyear = y;
var ys = this.mpYears.elements;
for(var i = 1; i <= 10; i++){
var td = ys[i-1], y2;
if((i%2) == 0){
y2 = y + Math.round(i * .5);
td.firstChild.innerHTML = y2;
td.xyear = y2;
}else{
y2 = y - (5-Math.round(i * .5));
td.firstChild.innerHTML = y2;
td.xyear = y2;
}
this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
}
},
updateMPMonth : function(sm){
this.mpMonths.each(function(m, a, i){
m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
});
},
selectMPMonth: function(m){
},
onMonthClick : function(e, t){
e.stopEvent();
var el = new Ext.Element(t), pn;
if(el.is('button.x-date-mp-cancel')){
this.hideMonthPicker();
}
else if(el.is('button.x-date-mp-ok')){
this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
else if(pn = el.up('td.x-date-mp-month', 2)){
this.mpMonths.removeClass('x-date-mp-sel');
pn.addClass('x-date-mp-sel');
this.mpSelMonth = pn.dom.xmonth;
}
else if(pn = el.up('td.x-date-mp-year', 2)){
this.mpYears.removeClass('x-date-mp-sel');
pn.addClass('x-date-mp-sel');
this.mpSelYear = pn.dom.xyear;
}
else if(el.is('a.x-date-mp-prev')){
this.updateMPYear(this.mpyear-10);
}
else if(el.is('a.x-date-mp-next')){
this.updateMPYear(this.mpyear+10);
}
},
onMonthDblClick : function(e, t){
e.stopEvent();
var el = new Ext.Element(t), pn;
if(pn = el.up('td.x-date-mp-month', 2)){
this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
else if(pn = el.up('td.x-date-mp-year', 2)){
this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
},
hideMonthPicker : function(disableAnim){
if(this.monthPicker){
if(disableAnim === true){
this.monthPicker.hide();
}else{
this.monthPicker.slideOut('t', {duration:.2});
}
}
},
// private
showPrevMonth : function(e){
this.update(this.activeDate.add("mo", -1));
},
// private
showNextMonth : function(e){
this.update(this.activeDate.add("mo", 1));
},
// private
showPrevYear : function(){
this.update(this.activeDate.add("y", -1));
},
// private
showNextYear : function(){
this.update(this.activeDate.add("y", 1));
},
// private
handleMouseWheel : function(e){
var delta = e.getWheelDelta();
if(delta > 0){
this.showPrevMonth();
e.stopEvent();
} else if(delta < 0){
this.showNextMonth();
e.stopEvent();
}
},
// private
handleDateClick : function(e, t){
e.stopEvent();
if(t.dateValue && !Ext.fly(t.parentNode).hasClass("x-date-disabled")){
this.setValue(new Date(t.dateValue));
this.fireEvent("select", this, this.value);
}
},
// private
selectToday : function(){
this.setValue(new Date().clearTime());
this.fireEvent("select", this, this.value);
},
// private
update : function(date){
var vd = this.activeDate;
this.activeDate = date;
if(vd && this.el){
var t = date.getTime();
if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
this.cells.removeClass("x-date-selected");
this.cells.each(function(c){
if(c.dom.firstChild.dateValue == t){
c.addClass("x-date-selected");
setTimeout(function(){
try{c.dom.firstChild.focus();}catch(e){}
}, 50);
return false;
}
});
return;
}
}
var days = date.getDaysInMonth();
var firstOfMonth = date.getFirstDateOfMonth();
var startingPos = firstOfMonth.getDay()-this.startDay;
if(startingPos <= this.startDay){
startingPos += 7;
}
var pm = date.add("mo", -1);
var prevStart = pm.getDaysInMonth()-startingPos;
var cells = this.cells.elements;
var textEls = this.textNodes;
days += startingPos;
// convert everything to numbers so it's fast
var day = 86400000;
var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
var today = new Date().clearTime().getTime();
var sel = date.clearTime().getTime();
var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
var ddMatch = this.disabledDatesRE;
var ddText = this.disabledDatesText;
var ddays = this.disabledDays ? this.disabledDays.join("") : false;
var ddaysText = this.disabledDaysText;
var format = this.format;
var setCellClass = function(cal, cell){
cell.title = "";
var t = d.getTime();
cell.firstChild.dateValue = t;
if(t == today){
cell.className += " x-date-today";
cell.title = cal.todayText;
}
if(t == sel){
cell.className += " x-date-selected";
setTimeout(function(){
try{cell.firstChild.focus();}catch(e){}
}, 50);
}
// disabling
if(t < min) {
cell.className = " x-date-disabled";
cell.title = cal.minText;
return;
}
if(t > max) {
cell.className = " x-date-disabled";
cell.title = cal.maxText;
return;
}
if(ddays){
if(ddays.indexOf(d.getDay()) != -1){
cell.title = ddaysText;
cell.className = " x-date-disabled";
}
}
if(ddMatch && format){
var fvalue = d.dateFormat(format);
if(ddMatch.test(fvalue)){
cell.title = ddText.replace("%0", fvalue);
cell.className = " x-date-disabled";
}
}
};
var i = 0;
for(; i < startingPos; i++) {
textEls[i].innerHTML = (++prevStart);
d.setDate(d.getDate()+1);
cells[i].className = "x-date-prevday";
setCellClass(this, cells[i]);
}
for(; i < days; i++){
intDay = i - startingPos + 1;
textEls[i].innerHTML = (intDay);
d.setDate(d.getDate()+1);
cells[i].className = "x-date-active";
setCellClass(this, cells[i]);
}
var extraDays = 0;
for(; i < 42; i++) {
textEls[i].innerHTML = (++extraDays);
d.setDate(d.getDate()+1);
cells[i].className = "x-date-nextday";
setCellClass(this, cells[i]);
}
this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
if(!this.internalRender){
var main = this.el.dom.firstChild;
var w = main.offsetWidth;
this.el.setWidth(w + this.el.getBorderWidth("lr"));
Ext.fly(main).setWidth(w);
this.internalRender = true;
// opera does not respect the auto grow header center column
// then, after it gets a width opera refuses to recalculate
// without a second pass
if(Ext.isOpera && !this.secondPass){
main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
this.secondPass = true;
this.update.defer(10, this, [date]);
}
}
}
}); | 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.Button
* @extends Ext.util.Observable
* 简单的按钮类
* @cfg {String} text 按钮的文本
* @cfg {String} icon 要显示要按钮上的图片的路径 (要显示的图片将会被设置成背景图片
* 这是按钮默认的CSS属性, 所以你若想得到一个图标与文字混合的按钮, 设置cls:"x-btn-text-icon")
* @cfg {Function} handler 当按钮被单击时调用一个函数(可以代替单击事件)
* @cfg {Object} scope handler的作用范围
* @cfg {Number} minWidth 按钮最小的宽度 (用于给一系列的按钮一个共同的宽度)
* @cfg {String/Object} tooltip 按钮的提示小标签 - 可以是一个字符串或者QuickTips配置对象
* @cfg {Boolean} hidden 设置为True,一开始便隐藏 (默认为false)
* @cfg {Boolean} disabled 设置为True,按钮一开始就不可用 (默认为false)
* @cfg {Boolean} pressed 设置为True,按钮一开始就被按下 (只有enableToggle = true 时才有效)
* @cfg {String} toggleGroup toggle按扭的按钮组名称(一个组中,只会有一个按钮被按下, 并且只有
* enableToggle = true 时才起作用)
* @cfg {Boolean/Object} repeat 设置为true,当按钮被按下时会反复激发单击事件。它也可以是一个
{@link Ext.util.ClickRepeater} 配置对象(默认为false).
* @constructor
* 创建一个新的按钮
* @param {String/HTMLElement/Element} renderTo 需要添加按钮的elemnet对象
* @param {Object} config 配置对象
*/
Ext.Button = function(renderTo, config){
Ext.apply(this, config);
this.addEvents({
/**
* @event click
* 当按钮被单击的时候执行
* @param {Button} this
* @param {EventObject} e 单击事件
*/
"click" : true,
/**
* @event toggle
* 当按钮的"pressed"状态发生改变时执行(只有当enableToggle = true)
* @param {Button} this
* @param {Boolean} pressed
*/
"toggle" : true,
/**
* @event mouseover
* 当鼠标在按钮上方的时候执行
* @param {Button} this
* @param {Event} e 事件对象
*/
'mouseover' : true,
/**
* @event mouseout
* 当鼠标离开按钮的时候执行
* @param {Button} this
* @param {Event} e The event object
*/
'mouseout': true
});
if(this.menu){
this.menu = Ext.menu.MenuMgr.get(this.menu);
}
if(renderTo){
this.render(renderTo);
}
Ext.Button.superclass.constructor.call(this);
};
Ext.extend(Ext.Button, Ext.util.Observable, {
/**
* 只读. 如果按钮隐藏则为true
* @type Boolean
*/
hidden : false,
/**
* 只读. 如果按钮不可用则为true
* @type Boolean
*/
disabled : false,
/**
* 只读. 当按钮被按下时为true(只有enableToggle = true时可用)
* @type Boolean
*/
pressed : false,
/**
* @cfg {Number} tabIndex
* DOM模型中按钮的tabIndex(默认为 undefined)
*/
tabIndex : undefined,
/**
* @cfg {Boolean} enableToggle
* 设置为true则按钮允许pressed/不pressed时为toggling(默认为false)
*/
enableToggle: false,
/**
* @cfg {Mixed} menu
* 由一个菜单对象、id或config组成的标准的菜单属性(默认为undefined).
*/
menu : undefined,
/**
* @cfg {String} menuAlign
* The position to align the menu to (see {@link Ext.Element#alignTo} for more details, defaults to 'tl-bl?').
*/
menuAlign : "tl-bl?",
/**
* @cfg {String} iconCls
* 一个可以设置这个按钮的icon背景图片的css类(默认为undefined).
*/
iconCls : undefined,
/**
* @cfg {String} type
* 按钮的类型,符合DOM的input元素不的type属性规范。可以是任何一个"submit," "reset" or "button" (默认).
*/
type : 'button',
// private
menuClassTarget: 'tr',
/**
* @cfg {String} clickEvent
* The type of event to map to the button's event handler (默认为 'click')
*/
clickEvent : 'click',
/**
* @cfg {Boolean} handleMouseEvents
* False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
*/
handleMouseEvents : true,
/**
* @cfg {String} tooltipType
* tooltip的类型。 可以是任何一个 "qtip" (默认) 快速提示 or "title" for title attribute.
*/
tooltipType : 'qtip',
/**
* @cfg {String} cls
* A CSS class to apply to the button's main element.
*/
/**
* @cfg {Ext.Template} template (Optional)
* An {@link Ext.Template} with which to create the Button's main element. This Template must
* contain numeric substitution parameter 0 if it is to display the text property. Changing the template could
* require code modifications if required elements (e.g. a button) aren't present.
*/
// private
render : function(renderTo){
var btn;
if(this.hideParent){
this.parentEl = Ext.get(renderTo);
}
if(!this.dhconfig){
if(!this.template){
if(!Ext.Button.buttonTemplate){
// hideous table template ->丑恶的表格模板
Ext.Button.buttonTemplate = new Ext.Template(
'<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
'<td class="x-btn-left"><i> </i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i> </i></td>',
"</tr></tbody></table>");
}
this.template = Ext.Button.buttonTemplate;
}
btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
var btnEl = btn.child("button:first");
btnEl.on('focus', this.onFocus, this);
btnEl.on('blur', this.onBlur, this);
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');
}
}
if(this.tabIndex !== undefined){
btnEl.dom.tabIndex = this.tabIndex;
}
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;
}
}
}else{
btn = Ext.DomHelper.append(Ext.get(renderTo).dom, this.dhconfig, true);
}
this.el = btn;
if(this.id){
this.el.dom.id = this.el.id = this.id;
}
if(this.menu){
this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
this.menu.on("show", this.onMenuShow, this);
this.menu.on("hide", this.onMenuHide, this);
}
btn.addClass("x-btn");
if(Ext.isIE && !Ext.isIE7){
this.autoWidth.defer(1, this);
}else{
this.autoWidth();
}
if(this.handleMouseEvents){
btn.on("mouseover", this.onMouseOver, this);
btn.on("mouseout", this.onMouseOut, this);
btn.on("mousedown", this.onMouseDown, this);
}
btn.on(this.clickEvent, this.onClick, this);
//btn.on("mouseup", this.onMouseUp, this);
if(this.hidden){
this.hide();
}
if(this.disabled){
this.disable();
}
Ext.ButtonToggleMgr.register(this);
if(this.pressed){
this.el.addClass("x-btn-pressed");
}
if(this.repeat){
var repeater = new Ext.util.ClickRepeater(btn,
typeof this.repeat == "object" ? this.repeat : {}
);
repeater.on("click", this.onClick, this);
}
},
/**
* 返回按钮下面的元素
* @return {Ext.Element} The element
*/
getEl : function(){
return this.el;
},
/**
* 销毁按钮对象并且移除所有的监听器.
*/
destroy : function(){
Ext.ButtonToggleMgr.unregister(this);
this.el.removeAllListeners();
this.purgeListeners();
this.el.remove();
},
// private
autoWidth : function(){
if(this.el){
this.el.setWidth("auto");
if(Ext.isIE7 && Ext.isStrict){
var ib = this.el.child('button');
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(this.el.getWidth() < this.minWidth){
this.el.setWidth(this.minWidth);
}
if(this.hidden){
this.el.endMeasure();
}
}
}
},
/**
* 分配这个按钮的点击处理程序
* @param {Function} handler 当按钮被点击时就调用此函数
* @param {Object} scope (optional) Scope for the function passed in
*/
setHandler : function(handler, scope){
this.handler = handler;
this.scope = scope;
},
/**
* 设置这个按钮的Text
* @param {String} text 按钮的Text
*/
setText : function(text){
this.text = text;
if(this.el){
this.el.child("td.x-btn-center button.x-btn-text").update(text);
}
this.autoWidth();
},
/**
* 取得按钮的Text
* @return {String} 按钮的text
*/
getText : function(){
return this.text;
},
/**
* 显示这个按钮
*/
show: function(){
this.hidden = false;
if(this.el){
this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
}
},
/**
* 隐藏这个按钮
*/
hide: function(){
this.hidden = true;
if(this.el){
this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
}
},
/**
* 为隐藏或显示提供方便的函数
* @param {Boolean} visible设置为 True 显示, false 则隐藏
*/
setVisible: function(visible){
if(visible) {
this.show();
}else{
this.hide();
}
},
/**
* 如果它的状态为passed,它将变为passed状态,否则当前的装态为toggled。
* @param {Boolean} state (可选的) 强制一个独特的状态
*/
toggle : function(state){
state = state === undefined ? !this.pressed : state;
if(state != this.pressed){
if(state){
this.el.addClass("x-btn-pressed");
this.pressed = true;
this.fireEvent("toggle", this, true);
}else{
this.el.removeClass("x-btn-pressed");
this.pressed = false;
this.fireEvent("toggle", this, false);
}
if(this.toggleHandler){
this.toggleHandler.call(this.scope || this, this, state);
}
}
},
/**
* 使按钮得到焦点
*/
focus : function(){
this.el.child('button:first').focus();
},
/**
* 使按钮不可用
*/
disable : function(){
if(this.el){
this.el.addClass("x-btn-disabled");
}
this.disabled = true;
},
/**
* 使按钮可用
*/
enable : function(){
if(this.el){
this.el.removeClass("x-btn-disabled");
}
this.disabled = false;
},
/**
* 为设置按钮可用/不可用提供方便设置的函数
* @param {Boolean} enabled True 为可用, false 为不可用
*/
setDisabled : function(v){
this[v !== true ? "enable" : "disable"]();
},
// private
onClick : function(e){
if(e){
e.preventDefault();
}
if(e.button != 0){
return;
}
if(!this.disabled){
if(this.enableToggle){
this.toggle();
}
if(this.menu && !this.menu.isVisible()){
this.menu.show(this.el, this.menuAlign);
}
this.fireEvent("click", this, e);
if(this.handler){
this.el.removeClass("x-btn-over");
this.handler.call(this.scope || this, this, e);
}
}
},
// private
onMouseOver : function(e){
if(!this.disabled){
this.el.addClass("x-btn-over");
this.fireEvent('mouseover', this, e);
}
},
// private
onMouseOut : function(e){
if(!e.within(this.el, true)){
this.el.removeClass("x-btn-over");
this.fireEvent('mouseout', this, e);
}
},
// private
onFocus : function(e){
if(!this.disabled){
this.el.addClass("x-btn-focus");
}
},
// private
onBlur : function(e){
this.el.removeClass("x-btn-focus");
},
// private
onMouseDown : function(e){
if(!this.disabled && e.button == 0){
this.el.addClass("x-btn-click");
Ext.get(document).on('mouseup', this.onMouseUp, this);
}
},
// private
onMouseUp : function(e){
if(e.button == 0){
this.el.removeClass("x-btn-click");
Ext.get(document).un('mouseup', this.onMouseUp, this);
}
},
// private
onMenuShow : function(e){
this.el.addClass("x-btn-menu-active");
},
// private
onMenuHide : function(e){
this.el.removeClass("x-btn-menu-active");
}
});
// 用于按钮的私有类
Ext.ButtonToggleMgr = function(){
var groups = {};
function toggleGroup(btn, state){
if(state){
var g = groups[btn.toggleGroup];
for(var i = 0, l = g.length; i < l; i++){
if(g[i] != btn){
g[i].toggle(false);
}
}
}
}
return {
register : function(btn){
if(!btn.toggleGroup){
return;
}
var g = groups[btn.toggleGroup];
if(!g){
g = groups[btn.toggleGroup] = [];
}
g.push(btn);
btn.on("toggle", toggleGroup);
},
unregister : function(btn){
if(!btn.toggleGroup){
return;
}
var g = groups[btn.toggleGroup];
if(g){
g.remove(btn);
btn.un("toggle", toggleGroup);
}
}
};
}(); | 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.BoxComponent
* @extends Ext.Component
* 任何使用矩形容器的作可视化组件{@link Ext.Component}的基类。
* 所有的容器类都应从BoxComponent继承,从而每个嵌套的Ext布局容器都会紧密地协调工作。
* @constructor
* @param {Ext.Element/String/Object} config 配置选项
*/
Ext.BoxComponent = function(config){
Ext.BoxComponent.superclass.constructor.call(this, config);
this.addEvents({
/**
* @event resize
* 当组件调节过大小后触发。
* @param {Ext.Component} this
* @param {Number} adjWidth 矩形调整过后的宽度
* @param {Number} adjHeight 矩形调整过后的高度
* @param {Number} rawWidth 原来设定的宽度
* @param {Number} rawHeight 原来设定的高度
*/
resize : true,
/**
* @event move
* 当组件被移动过之后触发。
* @param {Ext.Component} this
* @param {Number} x 新x位置
* @param {Number} y 新y位置
*/
move : true
});
};
Ext.extend(Ext.BoxComponent, Ext.Component, {
// private, set in afterRender to signify that the component has been rendered
boxReady : false,
// private, used to defer height settings to subclasses
deferHeight: false,
/**
* 设置组件的宽度和高度。
* 该方法会触发resize事件。
* 该方法既可接受单独的数字类型的参数,也可以传入一个size的对象,如 {width:10, height:20}。
* @param {Number/Object} width 要设置的宽度,或一个size对象,格式是{width, height}
* @param {Number} height 要设置的高度(如第一参数是size对象的那第二个参数经不需要了)
* @return {Ext.BoxComponent} this
*/
setSize : function(w, h){
// support for standard size objects
if(typeof w == 'object'){
h = w.height;
w = w.width;
}
// not rendered
if(!this.boxReady){
this.width = w;
this.height = h;
return this;
}
// prevent recalcs when not needed
if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
return this;
}
this.lastSize = {width: w, height: h};
var adj = this.adjustSize(w, h);
var aw = adj.width, ah = adj.height;
if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
var rz = this.getResizeEl();
if(!this.deferHeight && aw !== undefined && ah !== undefined){
rz.setSize(aw, ah);
}else if(!this.deferHeight && ah !== undefined){
rz.setHeight(ah);
}else if(aw !== undefined){
rz.setWidth(aw);
}
this.onResize(aw, ah, w, h);
this.fireEvent('resize', this, aw, ah, w, h);
}
return this;
},
/**
* 返回当前组件所属元素的大小。
* @return {Object} 包含元素大小的对象,格式为{width: (元素宽度), height:(元素高度)}
*/
getSize : function(){
return this.el.getSize();
},
/**
* 对组件所在元素当前的XY位置
* @param {Boolean} local (可选的)如为真返回的是元素的left和top而非XY(默认为false)
* @return {Array} 元素的XY位置(如[100, 200])
*/
getPosition : function(local){
if(local === true){
return [this.el.getLeft(true), this.el.getTop(true)];
}
return this.xy || this.el.getXY();
},
/**
* 返回对组件所在元素的测量矩形大小。
* @param {Boolean} local (可选的) 如为真返回的是元素的left和top而非XY(默认为false)
* @returns {Object} 格式为{x, y, width, height}的对象(矩形)
*/
getBox : function(local){
var s = this.el.getSize();
if(local){
s.x = this.el.getLeft(true);
s.y = this.el.getTop(true);
}else{
var xy = this.xy || this.el.getXY();
s.x = xy[0];
s.y = xy[1];
}
return s;
},
/**
* 对组件所在元素的测量矩形大小,然后根据此值设置组件的大小。
* @param {Object} box 格式为{x, y, width, height}的对象
* @returns {Ext.BoxComponent} this
*/
updateBox : function(box){
this.setSize(box.width, box.height);
this.setPagePosition(box.x, box.y);
return this;
},
// protected
getResizeEl : function(){
return this.resizeEl || this.el;
},
// protected
getPositionEl : function(){
return this.positionEl || this.el;
},
/**
* 设置组件的left和top值。
* 要设置基于页面的XY位置,可使用{@link #setPagePosition}。
* 该方法触发move事件。
* @param {Number} left 新left
* @param {Number} top 新top
* @returns {Ext.BoxComponent} this
*/
setPosition : function(x, y){
this.x = x;
this.y = y;
if(!this.boxReady){
return this;
}
var adj = this.adjustPosition(x, y);
var ax = adj.x, ay = adj.y;
var el = this.getPositionEl();
if(ax !== undefined || ay !== undefined){
if(ax !== undefined && ay !== undefined){
el.setLeftTop(ax, ay);
}else if(ax !== undefined){
el.setLeft(ax);
}else if(ay !== undefined){
el.setTop(ay);
}
this.onPosition(ax, ay);
this.fireEvent('move', this, ax, ay);
}
return this;
},
/**
* 设置组件页面上的left和top值。
* 要设置left、top的位置,可使用{@link #setPosition}。
* 该方法触发move事件。
* @param {Number} x 新x位置
* @param {Number} y 新y位置
* @returns {Ext.BoxComponent} this
*/
setPagePosition : function(x, y){
this.pageX = x;
this.pageY = y;
if(!this.boxReady){
return;
}
if(x === undefined || y === undefined){ // cannot translate undefined points
return;
}
var p = this.el.translatePoints(x, y);
this.setPosition(p.left, p.top);
return this;
},
// private
onRender : function(ct, position){
Ext.BoxComponent.superclass.onRender.call(this, ct, position);
if(this.resizeEl){
this.resizeEl = Ext.get(this.resizeEl);
}
if(this.positionEl){
this.positionEl = Ext.get(this.positionEl);
}
},
// private
afterRender : function(){
Ext.BoxComponent.superclass.afterRender.call(this);
this.boxReady = true;
this.setSize(this.width, this.height);
if(this.x || this.y){
this.setPosition(this.x, this.y);
}
if(this.pageX || this.pageY){
this.setPagePosition(this.pageX, this.pageY);
}
},
/**
* 强制重新计算组件的大小尺寸,这个尺寸是基于所属元素当前的高度和宽度。
* @returns {Ext.BoxComponent} this
*/
syncSize : function(){
delete this.lastSize;
this.setSize(this.el.getWidth(), this.el.getHeight());
return this;
},
/**
* 组件大小调节过后调用的函数,这是个空函数,可由一个子类来实现,执行一些调节大小过后的自定义逻辑。
* @param {Number} x 新X值
* @param {Number} y 新y值
* @param {Number} adjWidth 矩形调整过后的宽度
* @param {Number} adjHeight 矩形调整过后的高度
* @param {Number} rawWidth 原本设定的宽度
* @param {Number} rawHeight 原本设定的高度
*/
onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
},
/**
* 组件移动过后调用的函数,这是个空函数,可由一个子类来实现,执行一些移动过后的自定义逻辑。
* @param {Number} x 新X值
* @param {Number} y 新y值
*/
onPosition : function(x, y){
},
// private
adjustSize : function(w, h){
if(this.autoWidth){
w = 'auto';
}
if(this.autoHeight){
h = 'auto';
}
return {width : w, height: h};
},
// private
adjustPosition : function(x, y){
return {x : x, y: y};
}
}); | 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.Editor
* @extends Ext.Component
* 一个基础性的字段编辑器,内建按需的显示、隐藏控制和一些内建的调节大小及事件句柄逻辑。
* @constructor
* 创建一个新的编辑器
* @param {Ext.form.Field} field 字段对象(或后代descendant)
* @param {Object} config 配置项对象
*/
Ext.Editor = function(field, config){
Ext.Editor.superclass.constructor.call(this, config);
this.field = field;
this.addEvents({
/**
* @event beforestartedit
* 编辑器开始初始化,但在修改值之前触发。若事件句柄返回false则取消整个编辑事件。
* @param {Editor} this
* @param {Ext.Element} boundEl 编辑器绑定的所属元素
* @param {Mixed} value 正被设置的值
*/
"beforestartedit" : true,
/**
* @event startedit
* 当编辑器显示时触发
* @param {Ext.Element} boundEl 编辑器绑定的所属元素
* @param {Mixed} value 原始字段值
*/
"startedit" : true,
/**
* @event beforecomplete
* 修改已提交到字段,但修改未真正反映在所属的字段上之前触发。
* 若事件句柄返回false则取消整个编辑事件。
* 注意如果值没有变动的话并且ignoreNoChange = true的情况下,
* 编辑依然会结束但因为没有真正的编辑所以不会触发事件。
* @param {Editor} this
* @param {Mixed} value 当前字段的值
* @param {Mixed} startValue 原始字段的值
*/
"beforecomplete" : true,
/**
* @event complete
* 当编辑完成过后,任何的改变写入到所属字段时触发。
* @param {Editor} this
* @param {Mixed} value 当前字段的值
* @param {Mixed} startValue 原始字段的值
*/
"complete" : true,
/**
* @event specialkey
* 用于导航的任意键被按下触发(arrows、 tab、 enter、esc等等)
* 你可检查{@link Ext.EventObject#getKey}以确定哪个键被按了。
* @param {Ext.form.Field} this
* @param {Ext.EventObject} e 事件对象
*/
"specialkey" : true
});
};
Ext.extend(Ext.Editor, Ext.Component, {
/**
* @cfg {Boolean/String} autosize
* True表示为编辑器的大小尺寸自适应到所属的字段,设置“width”表示单单适应宽度,
* 设置“height”表示单单适应高度(默认为fasle)
*/
/**
* @cfg {Boolean} revertInvalid
* True表示为当用户完成编辑但字段验证失败后,自动恢复原始值,然后取消这次编辑(默认为true)
*/
/**
* @cfg {Boolean} ignoreNoChange
* True表示为如果用户完成一次编辑但值没有改变时,中止这次编辑的操作(不保存,不触发事件)(默认为false)。
* 只对字符类型的值有效,其它编辑的数据类型将会被忽略。
*/
/**
* @cfg {Boolean} hideEl
* False表示为当编辑器显示时,保持绑定的元素可见(默认为true)。
*/
/**
* @cfg {Mixed} value
* 所属字段的日期值(默认为"")
*/
value : "",
/**
* @cfg {String} alignment
* 对齐的位置(参见{@link Ext.Element#alignTo}了解详细,默认为"c-c?")。
*/
alignment: "c-c?",
/**
* @cfg {Boolean/String} shadow属性为"sides"是四边都是向上阴影, "frame"表示四边外发光, "drop"表示
* 从右下角开始投影(默认为"frame")
*/
shadow : "frame",
/**
* @cfg {Boolean} constrain 表示为约束编辑器到视图
*/
constrain : false,
/**
* @cfg {Boolean} completeOnEnter True表示为回车按下之后就完成编辑(默认为false)
*/
completeOnEnter : false,
/**
* @cfg {Boolean} cancelOnEsc True表示为escape键按下之后便取消编辑(默认为false)
*/
cancelOnEsc : false,
/**
* @cfg {Boolean} updateEl True表示为当更新完成之后同时更新绑定元素的innerHTML(默认为false)
*/
updateEl : false,
// private
onRender : function(ct, position){
this.el = new Ext.Layer({
shadow: this.shadow,
cls: "x-editor",
parentEl : ct,
shim : this.shim,
shadowOffset:4,
id: this.id,
constrain: this.constrain
});
this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden");
if(this.field.msgTarget != 'title'){
this.field.msgTarget = 'qtip';
}
this.field.render(this.el);
if(Ext.isGecko){
this.field.el.dom.setAttribute('autocomplete', 'off');
}
this.field.on("specialkey", this.onSpecialKey, this);
if(this.swallowKeys){
this.field.el.swallowEvent(['keydown','keypress']);
}
this.field.show();
this.field.on("blur", this.onBlur, this);
if(this.field.grow){
this.field.on("autosize", this.el.sync, this.el, {delay:1});
}
},
onSpecialKey : function(field, e){
if(this.completeOnEnter && e.getKey() == e.ENTER){
e.stopEvent();
this.completeEdit();
}else if(this.cancelOnEsc && e.getKey() == e.ESC){
this.cancelEdit();
}else{
this.fireEvent('specialkey', field, e);
}
},
/**
* 进入编辑状态并显示编辑器
* @param {String/HTMLElement/Element} el 要编辑的元素
* @param {String} value (optional) 编辑器初始化的值,如不设置该值便是元素的innerHTML
*/
startEdit : function(el, value){
if(this.editing){
this.completeEdit();
}
this.boundEl = Ext.get(el);
var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
if(!this.rendered){
this.render(this.parentEl || document.body);
}
if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
return;
}
this.startValue = v;
this.field.setValue(v);
if(this.autoSize){
var sz = this.boundEl.getSize();
switch(this.autoSize){
case "width":
this.setSize(sz.width, "");
break;
case "height":
this.setSize("", sz.height);
break;
default:
this.setSize(sz.width, sz.height);
}
}
this.el.alignTo(this.boundEl, this.alignment);
this.editing = true;
if(Ext.QuickTips){
Ext.QuickTips.disable();
}
this.show();
},
/**
* 设置编辑器高、宽
* @param {Number} width 新宽度
* @param {Number} height 新高度
*/
setSize : function(w, h){
this.field.setSize(w, h);
if(this.el){
this.el.sync();
}
},
/**
* 按照当前的最齐设置,把编辑器重新对齐到所绑定的字段。
*/
realign : function(){
this.el.alignTo(this.boundEl, this.alignment);
},
/**
* 结束编辑状态,提交变化的内容到所属的字段,并隐藏编辑器。
* @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false)
*/
completeEdit : function(remainVisible){
if(!this.editing){
return;
}
var v = this.getValue();
if(this.revertInvalid !== false && !this.field.isValid()){
v = this.startValue;
this.cancelEdit(true);
}
if(String(v) === String(this.startValue) && this.ignoreNoChange){
this.editing = false;
this.hide();
return;
}
if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
this.editing = false;
if(this.updateEl && this.boundEl){
this.boundEl.update(v);
}
if(remainVisible !== true){
this.hide();
}
this.fireEvent("complete", this, v, this.startValue);
}
},
// private
onShow : function(){
this.el.show();
if(this.hideEl !== false){
this.boundEl.hide();
}
this.field.show();
if(Ext.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
this.fixIEFocus = true;
this.deferredFocus.defer(50, this);
}else{
this.field.focus();
}
this.fireEvent("startedit", this.boundEl, this.startValue);
},
deferredFocus : function(){
if(this.editing){
this.field.focus();
}
},
/**
* 取消编辑状态并返回到原始值,不作任何的修改,
* @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false)
*/
cancelEdit : function(remainVisible){
if(this.editing){
this.setValue(this.startValue);
if(remainVisible !== true){
this.hide();
}
}
},
// private
onBlur : function(){
if(this.allowBlur !== true && this.editing){
this.completeEdit();
}
},
// private
onHide : function(){
if(this.editing){
this.completeEdit();
return;
}
this.field.blur();
if(this.field.collapse){
this.field.collapse();
}
this.el.hide();
if(this.hideEl !== false){
this.boundEl.show();
}
if(Ext.QuickTips){
Ext.QuickTips.enable();
}
},
/**
* 设置编辑器的数据。
* @param {Mixed} value 所属field可支持的任意值
*/
setValue : function(v){
this.field.setValue(v);
},
/**
* 获取编辑器的数据。
* @return {Mixed} 数据值
*/
getValue : function(){
return this.field.getValue();
}
}); | 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.Layer
* @extends Ext.Element
* 一个由{@link Ext.Element}扩展的对象,支持阴影和shim,受视图限制和自动修复阴影/shim位置。
* @cfg {Boolean} shim False表示为禁用iframe的shim,在某些浏览器里需用到(默认为true)
* @cfg {String/Boolean} shadow True表示为创建元素的阴影,采用样式类"x-layer-shadow",或者你可以传入一个字符串指定一个CSS样式类,False表示为关闭阴影。
* @cfg {Object} dh DomHelper配置格式的对象,来创建元素(默认为{tag: "div", cls: "x-layer"})
* @cfg {Boolean} constrain False表示为不受视图的限制(默认为true)
* @cfg {String} cls 元素要添加的CSS样式类
* @cfg {Number} zindex 开始的z-index(默认为1100)
* @cfg {Number} shadowOffset 阴影偏移的像素值(默认为3)
* @constructor
* @param {Object} config 配置项对象
* @param {String/HTMLElement} existingEl (可选的)使用现有的DOM的元素。 如找不到就创建一个。
*/
(function(){
Ext.Layer = function(config, existingEl){
config = config || {};
var dh = Ext.DomHelper;
var cp = config.parentEl, pel = cp ? Ext.getDom(cp) : document.body;
if(existingEl){
this.dom = Ext.getDom(existingEl);
}
if(!this.dom){
var o = config.dh || {tag: "div", cls: "x-layer"};
this.dom = dh.append(pel, o);
}
if(config.cls){
this.addClass(config.cls);
}
this.constrain = config.constrain !== false;
this.visibilityMode = Ext.Element.VISIBILITY;
if(config.id){
this.id = this.dom.id = config.id;
}else{
this.id = Ext.id(this.dom);
}
this.zindex = config.zindex || this.getZIndex();
this.position("absolute", this.zindex);
if(config.shadow){
this.shadowOffset = config.shadowOffset || 4;
this.shadow = new Ext.Shadow({
offset : this.shadowOffset,
mode : config.shadow
});
}else{
this.shadowOffset = 0;
}
this.useShim = config.shim !== false && Ext.useShims;
this.useDisplay = config.useDisplay;
this.hide();
};
var supr = Ext.Element.prototype;
// shims are shared among layer to keep from having 100 iframes
var shims = [];
Ext.extend(Ext.Layer, Ext.Element, {
getZIndex : function(){
return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
},
getShim : function(){
if(!this.useShim){
return null;
}
if(this.shim){
return this.shim;
}
var shim = shims.shift();
if(!shim){
shim = this.createShim();
shim.enableDisplayMode('block');
shim.dom.style.display = 'none';
shim.dom.style.visibility = 'visible';
}
var pn = this.dom.parentNode;
if(shim.dom.parentNode != pn){
pn.insertBefore(shim.dom, this.dom);
}
shim.setStyle('z-index', this.getZIndex()-2);
this.shim = shim;
return shim;
},
hideShim : function(){
if(this.shim){
this.shim.setDisplayed(false);
shims.push(this.shim);
delete this.shim;
}
},
disableShadow : function(){
if(this.shadow){
this.shadowDisabled = true;
this.shadow.hide();
this.lastShadowOffset = this.shadowOffset;
this.shadowOffset = 0;
}
},
enableShadow : function(show){
if(this.shadow){
this.shadowDisabled = false;
this.shadowOffset = this.lastShadowOffset;
delete this.lastShadowOffset;
if(show){
this.sync(true);
}
}
},
// private
// this code can execute repeatedly in milliseconds (i.e. during a drag) so
// code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
sync : function(doShow){
var sw = this.shadow;
if(!this.updating && this.isVisible() && (sw || this.useShim)){
var sh = this.getShim();
var w = this.getWidth(),
h = this.getHeight();
var l = this.getLeft(true),
t = this.getTop(true);
if(sw && !this.shadowDisabled){
if(doShow && !sw.isVisible()){
sw.show(this);
}else{
sw.realign(l, t, w, h);
}
if(sh){
if(doShow){
sh.show();
}
// fit the shim behind the shadow, so it is shimmed too
var a = sw.adjusts, s = sh.dom.style;
s.left = (Math.min(l, l+a.l))+"px";
s.top = (Math.min(t, t+a.t))+"px";
s.width = (w+a.w)+"px";
s.height = (h+a.h)+"px";
}
}else if(sh){
if(doShow){
sh.show();
}
sh.setSize(w, h);
sh.setLeftTop(l, t);
}
}
},
// private
destroy : function(){
this.hideShim();
if(this.shadow){
this.shadow.hide();
}
this.removeAllListeners();
var pn = this.dom.parentNode;
if(pn){
pn.removeChild(this.dom);
}
Ext.Element.uncache(this.id);
},
remove : function(){
this.destroy();
},
// private
beginUpdate : function(){
this.updating = true;
},
// private
endUpdate : function(){
this.updating = false;
this.sync(true);
},
// private
hideUnders : function(negOffset){
if(this.shadow){
this.shadow.hide();
}
this.hideShim();
},
// private
constrainXY : function(){
if(this.constrain){
var vw = Ext.lib.Dom.getViewWidth(),
vh = Ext.lib.Dom.getViewHeight();
var s = Ext.get(document).getScroll();
var xy = this.getXY();
var x = xy[0], y = xy[1];
var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
// only move it if it needs it
var moved = false;
// first validate right/bottom
if((x + w) > vw+s.left){
x = vw - w - this.shadowOffset;
moved = true;
}
if((y + h) > vh+s.top){
y = vh - h - this.shadowOffset;
moved = true;
}
// then make sure top/left isn't negative
if(x < s.left){
x = s.left;
moved = true;
}
if(y < s.top){
y = s.top;
moved = true;
}
if(moved){
if(this.avoidY){
var ay = this.avoidY;
if(y <= ay && (y+h) >= ay){
y = ay-h-5;
}
}
xy = [x, y];
this.storeXY(xy);
supr.setXY.call(this, xy);
this.sync();
}
}
},
isVisible : function(){
return this.visible;
},
// private
showAction : function(){
this.visible = true; // track visibility to prevent getStyle calls
if(this.useDisplay === true){
this.setDisplayed("");
}else if(this.lastXY){
supr.setXY.call(this, this.lastXY);
}else if(this.lastLT){
supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
}
},
// private
hideAction : function(){
this.visible = false;
if(this.useDisplay === true){
this.setDisplayed(false);
}else{
this.setLeftTop(-10000,-10000);
}
},
// overridden Element method
setVisible : function(v, a, d, c, e){
if(v){
this.showAction();
}
if(a && v){
var cb = function(){
this.sync(true);
if(c){
c();
}
}.createDelegate(this);
supr.setVisible.call(this, true, true, d, cb, e);
}else{
if(!v){
this.hideUnders(true);
}
var cb = c;
if(a){
cb = function(){
this.hideAction();
if(c){
c();
}
}.createDelegate(this);
}
supr.setVisible.call(this, v, a, d, cb, e);
if(v){
this.sync(true);
}else if(!a){
this.hideAction();
}
}
},
storeXY : function(xy){
delete this.lastLT;
this.lastXY = xy;
},
storeLeftTop : function(left, top){
delete this.lastXY;
this.lastLT = [left, top];
},
// private
beforeFx : function(){
this.beforeAction();
return Ext.Layer.superclass.beforeFx.apply(this, arguments);
},
// private
afterFx : function(){
Ext.Layer.superclass.afterFx.apply(this, arguments);
this.sync(this.isVisible());
},
// private
beforeAction : function(){
if(!this.updating && this.shadow){
this.shadow.hide();
}
},
// overridden Element method
setLeft : function(left){
this.storeLeftTop(left, this.getTop(true));
supr.setLeft.apply(this, arguments);
this.sync();
},
setTop : function(top){
this.storeLeftTop(this.getLeft(true), top);
supr.setTop.apply(this, arguments);
this.sync();
},
setLeftTop : function(left, top){
this.storeLeftTop(left, top);
supr.setLeftTop.apply(this, arguments);
this.sync();
},
setXY : function(xy, a, d, c, e){
this.fixDisplay();
this.beforeAction();
this.storeXY(xy);
var cb = this.createCB(c);
supr.setXY.call(this, xy, a, d, cb, e);
if(!a){
cb();
}
},
// private
createCB : function(c){
var el = this;
return function(){
el.constrainXY();
el.sync(true);
if(c){
c();
}
};
},
// overridden Element method
setX : function(x, a, d, c, e){
this.setXY([x, this.getY()], a, d, c, e);
},
// overridden Element method
setY : function(y, a, d, c, e){
this.setXY([this.getX(), y], a, d, c, e);
},
// overridden Element method
setSize : function(w, h, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
supr.setSize.call(this, w, h, a, d, cb, e);
if(!a){
cb();
}
},
// overridden Element method
setWidth : function(w, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
supr.setWidth.call(this, w, a, d, cb, e);
if(!a){
cb();
}
},
// overridden Element method
setHeight : function(h, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
supr.setHeight.call(this, h, a, d, cb, e);
if(!a){
cb();
}
},
// overridden Element method
setBounds : function(x, y, w, h, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
if(!a){
this.storeXY([x, y]);
supr.setXY.call(this, [x, y]);
supr.setSize.call(this, w, h, a, d, cb, e);
cb();
}else{
supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
}
return this;
},
/**
* 设置层的z-index和调整全部的阴影和垫片(shim) z-indexes。
* 层本身的z-index是会自动+2,所以它总会是在其他阴影和垫片上面(这时阴影元素会分配z-index+1,垫片的就是原本传入的z-index)。
* @param {Number} zindex 要设置的新z-index
* @return {this} The Layer
*/
setZIndex : function(zindex){
this.zindex = zindex;
this.setStyle("z-index", zindex + 2);
if(this.shadow){
this.shadow.setZIndex(zindex + 1);
}
if(this.shim){
this.shim.setStyle("z-index", zindex);
}
}
});
})(); | 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.TabPanel
* @extends Ext.util.Observable
* 一个轻量级的tab容器。
* <br><br>
* Usage:
* <pre><code>
// basic tabs 1, built from existing content
var tabs = new Ext.TabPanel("tabs1");
tabs.addTab("script", "View Script");
tabs.addTab("markup", "View Markup");
tabs.activate("script");
//更多高级的tabs, 用javascript创建
var jtabs = new Ext.TabPanel("jtabs");
jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
//设置更新管理器 UpdateManager
var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
var updater = tab2.getUpdateManager();
updater.setDefaultUrl("ajax1.htm");
tab2.on('activate', updater.refresh, updater, true);
//使用setUrl设置Ajax加载
var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
tab3.setUrl("ajax2.htm", null, true);
//使tab不可用
var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
tab4.disable();
jtabs.activate("jtabs-1");
* </code></pre>
* @constructor
* 创建一个新的TabPanel.
* @param {String/HTMLElement/Ext.Element} container 这是一个id, DOM元素 或者 Ext.Element 将被渲染的容器。
* @param {Object/Boolean} config 这是一个配置TabPanel的配置对象, 或者设置为true使得tabs渲染在下方。
*/
Ext.TabPanel = function(container, config){
/**
* The container element for this TabPanel.
* @type Ext.Element
*/
this.el = Ext.get(container, true);
if(config){
if(typeof config == "boolean"){
this.tabPosition = config ? "bottom" : "top";
}else{
Ext.apply(this, config);
}
}
if(this.tabPosition == "bottom"){
this.bodyEl = Ext.get(this.createBody(this.el.dom));
this.el.addClass("x-tabs-bottom");
}
this.stripWrap = Ext.get(this.createStrip(this.el.dom), true);
this.stripEl = Ext.get(this.createStripList(this.stripWrap.dom), true);
this.stripBody = Ext.get(this.stripWrap.dom.firstChild.firstChild, true);
if(Ext.isIE){
Ext.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
}
if(this.tabPosition != "bottom"){
/** The body element that contains {@link Ext.TabPanelItem} bodies.
* @type Ext.Element
*/
this.bodyEl = Ext.get(this.createBody(this.el.dom));
this.el.addClass("x-tabs-top");
}
this.items = [];
this.bodyEl.setStyle("position", "relative");
this.active = null;
this.activateDelegate = this.activate.createDelegate(this);
this.addEvents({
/**
* @event tabchange
* 当激活的tab改变时执行
* @param {Ext.TabPanel} this
* @param {Ext.TabPanelItem} activePanel 新激活的tab
*/
"tabchange": true,
/**
* @event beforetabchange
* Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
* @param {Ext.TabPanel} this
* @param {Object} e Set cancel to true on this object to cancel the tab change
* @param {Ext.TabPanelItem} tab The tab being changed to
*/
"beforetabchange" : true
});
Ext.EventManager.onWindowResize(this.onResize, this);
this.cpad = this.el.getPadding("lr");
this.hiddenCount = 0;
Ext.TabPanel.superclass.constructor.call(this);
};
Ext.extend(Ext.TabPanel, Ext.util.Observable, {
/*
*@cfg {String} tabPosition "top" 或者 "bottom" (默认为 "top")
*/
tabPosition : "top",
/*
*@cfg {Number} currentTabWidth tab当前的宽度 (默认为 0)
*/
currentTabWidth : 0,
/*
*@cfg {Number} minTabWidth tab的最小宽度值 (默认为 40) (当 {@link #resizeTabs} 为false时该配置被忽略)
*/
minTabWidth : 40,
/*
*@cfg {Number} maxTabWidth tab的最大宽度值 (默认为 250) (当{@link #resizeTabs} 为false时该配置被忽略)
*/
maxTabWidth : 250,
/*
*@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
*/
preferredTabWidth : 175,
/*
*@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
*/
resizeTabs : false,
/*
*@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
*/
monitorResize : true,
/**
* Creates a new {@link Ext.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
* @param {String} id The id of the div to use <b>or create</b>
* @param {String} text The text for the tab
* @param {String} content (optional) Content to put in the TabPanelItem body
* @param {Boolean} closable (optional) True to create a close icon on the tab
* @return {Ext.TabPanelItem} The created TabPanelItem
*/
addTab : function(id, text, content, closable){
var item = new Ext.TabPanelItem(this, id, text, closable);
this.addTabItem(item);
if(content){
item.setContent(content);
}
return item;
},
/**
* Returns the {@link Ext.TabPanelItem} with the specified id/index
* @param {String/Number} id The id or index of the TabPanelItem to fetch.
* @return {Ext.TabPanelItem}
*/
getTab : function(id){
return this.items[id];
},
/**
* Hides the {@link Ext.TabPanelItem} with the specified id/index
* @param {String/Number} id The id or index of the TabPanelItem to hide.
*/
hideTab : function(id){
var t = this.items[id];
if(!t.isHidden()){
t.setHidden(true);
this.hiddenCount++;
this.autoSizeTabs();
}
},
/**
* "Unhides" the {@link Ext.TabPanelItem} with the specified id/index.
* @param {String/Number} id The id or index of the TabPanelItem to unhide.
*/
unhideTab : function(id){
var t = this.items[id];
if(t.isHidden()){
t.setHidden(false);
this.hiddenCount--;
this.autoSizeTabs();
}
},
/**
* 添加一个现存的 {@link Ext.TabPanelItem}.
* @param {Ext.TabPanelItem} item 添加一个 TabPanelItem
*/
addTabItem : function(item){
this.items[item.id] = item;
this.items.push(item);
if(this.resizeTabs){
item.setWidth(this.currentTabWidth || this.preferredTabWidth);
this.autoSizeTabs();
}else{
item.autoSize();
}
},
/**
* Removes a {@link Ext.TabPanelItem}.
* @param {String/Number} id The id or index of the TabPanelItem to remove.
*/
removeTab : function(id){
var items = this.items;
var tab = items[id];
if(!tab) return;
var index = items.indexOf(tab);
if(this.active == tab && items.length > 1){
var newTab = this.getNextAvailable(index);
if(newTab)newTab.activate();
}
this.stripEl.dom.removeChild(tab.pnode.dom);
if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
this.bodyEl.dom.removeChild(tab.bodyEl.dom);
}
items.splice(index, 1);
delete this.items[tab.id];
tab.fireEvent("close", tab);
tab.purgeListeners();
this.autoSizeTabs();
},
getNextAvailable : function(start){
var items = this.items;
var index = start;
// look for a next tab that will slide over to
// replace the one being removed
while(index < items.length){
var item = items[++index];
if(item && !item.isHidden()){
return item;
}
}
// if one isn't found select the previous tab (on the left)
index = start;
while(index >= 0){
var item = items[--index];
if(item && !item.isHidden()){
return item;
}
}
return null;
},
/**
* Disables a {@link Ext.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
* @param {String/Number} id The id or index of the TabPanelItem to disable.
*/
disableTab : function(id){
var tab = this.items[id];
if(tab && this.active != tab){
tab.disable();
}
},
/**
* Enables a {@link Ext.TabPanelItem} that is disabled.
* @param {String/Number} id The id or index of the TabPanelItem to enable.
*/
enableTab : function(id){
var tab = this.items[id];
tab.enable();
},
/**
* Activates a {@link Ext.TabPanelItem}. The currently active one will be deactivated.
* @param {String/Number} id The id or index of the TabPanelItem to activate.
* @return {Ext.TabPanelItem} The TabPanelItem.
*/
activate : function(id){
var tab = this.items[id];
if(!tab){
return null;
}
if(tab == this.active || tab.disabled){
return tab;
}
var e = {};
this.fireEvent("beforetabchange", this, e, tab);
if(e.cancel !== true && !tab.disabled){
if(this.active){
this.active.hide();
}
this.active = this.items[id];
this.active.show();
this.fireEvent("tabchange", this, this.active);
}
return tab;
},
/**
* Gets the active {@link Ext.TabPanelItem}.
* @return {Ext.TabPanelItem} The active TabPanelItem or null if none are active.
*/
getActiveTab : function(){
return this.active;
},
/**
* Updates the tab body element to fit the height of the container element
* for overflow scrolling
* @param {Number} targetHeight (optional) Override the starting height from the elements height
*/
syncHeight : function(targetHeight){
var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
var bm = this.bodyEl.getMargins();
var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
this.bodyEl.setHeight(newHeight);
return newHeight;
},
onResize : function(){
if(this.monitorResize){
this.autoSizeTabs();
}
},
/**
* Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
*/
beginUpdate : function(){
this.updating = true;
},
/**
* Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
*/
endUpdate : function(){
this.updating = false;
this.autoSizeTabs();
},
/**
* Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
*/
autoSizeTabs : function(){
var count = this.items.length;
var vcount = count - this.hiddenCount;
if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
var w = Math.max(this.el.getWidth() - this.cpad, 10);
var availWidth = Math.floor(w / vcount);
var b = this.stripBody;
if(b.getWidth() > w){
var tabs = this.items;
this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
if(availWidth < this.minTabWidth){
/*if(!this.sleft){ // incomplete scrolling code
this.createScrollButtons();
}
this.showScroll();
this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
}
}else{
if(this.currentTabWidth < this.preferredTabWidth){
this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
}
}
},
/**
* Returns the number of tabs in this TabPanel.
* @return {Number}
*/
getCount : function(){
return this.items.length;
},
/**
* Resizes all the tabs to the passed width
* @param {Number} The new width
*/
setTabWidth : function(width){
this.currentTabWidth = width;
for(var i = 0, len = this.items.length; i < len; i++) {
if(!this.items[i].isHidden())this.items[i].setWidth(width);
}
},
/**
* Destroys this TabPanel
* @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
*/
destroy : function(removeEl){
Ext.EventManager.removeResizeListener(this.onResize, this);
for(var i = 0, len = this.items.length; i < len; i++){
this.items[i].purgeListeners();
}
if(removeEl === true){
this.el.update("");
this.el.remove();
}
}
});
/**
* @class Ext.TabPanelItem
* @extends Ext.util.Observable
* Represents an individual item (tab plus body) in a TabPanel.
* @param {Ext.TabPanel} tabPanel The {@link Ext.TabPanel} this TabPanelItem belongs to
* @param {String} id The id of this TabPanelItem
* @param {String} text The text for the tab of this TabPanelItem
* @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
*/
Ext.TabPanelItem = function(tabPanel, id, text, closable){
/**
* The {@link Ext.TabPanel} this TabPanelItem belongs to
* @type Ext.TabPanel
*/
this.tabPanel = tabPanel;
/**
* The id for this TabPanelItem
* @type String
*/
this.id = id;
/** @private */
this.disabled = false;
/** @private */
this.text = text;
/** @private */
this.loaded = false;
this.closable = closable;
/**
* The body element for this TabPanelItem.
* @type Ext.Element
*/
this.bodyEl = Ext.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
this.bodyEl.setVisibilityMode(Ext.Element.VISIBILITY);
this.bodyEl.setStyle("display", "block");
this.bodyEl.setStyle("zoom", "1");
this.hideAction();
var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
/** @private */
this.el = Ext.get(els.el, true);
this.inner = Ext.get(els.inner, true);
this.textEl = Ext.get(this.el.dom.firstChild.firstChild.firstChild, true);
this.pnode = Ext.get(els.el.parentNode, true);
this.el.on("mousedown", this.onTabMouseDown, this);
this.el.on("click", this.onTabClick, this);
/** @private */
if(closable){
var c = Ext.get(els.close, true);
c.dom.title = this.closeText;
c.addClassOnOver("close-over");
c.on("click", this.closeClick, this);
}
this.addEvents({
/**
* @event activate
* Fires when this tab becomes the active tab.
* @param {Ext.TabPanel} tabPanel The parent TabPanel
* @param {Ext.TabPanelItem} this
*/
"activate": true,
/**
* @event beforeclose
* Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
* @param {Ext.TabPanelItem} this
* @param {Object} e Set cancel to true on this object to cancel the close.
*/
"beforeclose": true,
/**
* @event close
* Fires when this tab is closed.
* @param {Ext.TabPanelItem} this
*/
"close": true,
/**
* @event deactivate
* Fires when this tab is no longer the active tab.
* @param {Ext.TabPanel} tabPanel The parent TabPanel
* @param {Ext.TabPanelItem} this
*/
"deactivate" : true
});
this.hidden = false;
Ext.TabPanelItem.superclass.constructor.call(this);
};
Ext.extend(Ext.TabPanelItem, Ext.util.Observable, {
purgeListeners : function(){
Ext.util.Observable.prototype.purgeListeners.call(this);
this.el.removeAllListeners();
},
/**
* Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
*/
show : function(){
this.pnode.addClass("on");
this.showAction();
if(Ext.isOpera){
this.tabPanel.stripWrap.repaint();
}
this.fireEvent("activate", this.tabPanel, this);
},
/**
* Returns true if this tab is the active tab.
* @return {Boolean}
*/
isActive : function(){
return this.tabPanel.getActiveTab() == this;
},
/**
* Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
*/
hide : function(){
this.pnode.removeClass("on");
this.hideAction();
this.fireEvent("deactivate", this.tabPanel, this);
},
hideAction : function(){
this.bodyEl.hide();
this.bodyEl.setStyle("position", "absolute");
this.bodyEl.setLeft("-20000px");
this.bodyEl.setTop("-20000px");
},
showAction : function(){
this.bodyEl.setStyle("position", "relative");
this.bodyEl.setTop("");
this.bodyEl.setLeft("");
this.bodyEl.show();
},
/**
* Set the tooltip for the tab.
* @param {String} tooltip The tab's tooltip
*/
setTooltip : function(text){
if(Ext.QuickTips && Ext.QuickTips.isEnabled()){
this.textEl.dom.qtip = text;
this.textEl.dom.removeAttribute('title');
}else{
this.textEl.dom.title = text;
}
},
onTabClick : function(e){
e.preventDefault();
this.tabPanel.activate(this.id);
},
onTabMouseDown : function(e){
e.preventDefault();
this.tabPanel.activate(this.id);
},
getWidth : function(){
return this.inner.getWidth();
},
setWidth : function(width){
var iwidth = width - this.pnode.getPadding("lr");
this.inner.setWidth(iwidth);
this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
this.pnode.setWidth(width);
},
/**
* Show or hide the tab
* @param {Boolean} hidden True to hide or false to show.
*/
setHidden : function(hidden){
this.hidden = hidden;
this.pnode.setStyle("display", hidden ? "none" : "");
},
/**
* Returns true if this tab is "hidden"
* @return {Boolean}
*/
isHidden : function(){
return this.hidden;
},
/**
* Returns the text for this tab
* @return {String}
*/
getText : function(){
return this.text;
},
autoSize : function(){
//this.el.beginMeasure();
this.textEl.setWidth(1);
this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
//this.el.endMeasure();
},
/**
* Sets the text for the tab (Note: this also sets the tooltip text)
* @param {String} text The tab's text and tooltip
*/
setText : function(text){
this.text = text;
this.textEl.update(text);
this.setTooltip(text);
if(!this.tabPanel.resizeTabs){
this.autoSize();
}
},
/**
* Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
*/
activate : function(){
this.tabPanel.activate(this.id);
},
/**
* Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
*/
disable : function(){
if(this.tabPanel.active != this){
this.disabled = true;
this.pnode.addClass("disabled");
}
},
/**
* Enables this TabPanelItem if it was previously disabled.
*/
enable : function(){
this.disabled = false;
this.pnode.removeClass("disabled");
},
/**
* Sets the content for this TabPanelItem.
* @param {String} content The content
* @param {Boolean} loadScripts true to look for and load scripts
*/
setContent : function(content, loadScripts){
this.bodyEl.update(content, loadScripts);
},
/**
* Gets the {@link Ext.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
* @return {Ext.UpdateManager} The UpdateManager
*/
getUpdateManager : function(){
return this.bodyEl.getUpdateManager();
},
/**
* Set a URL to be used to load the content for this TabPanelItem.
* @param {String/Function} url The URL to load the content from, or a function to call to get the URL
* @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Ext.UpdateManager#update} for more details. (Defaults to null)
* @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
* @return {Ext.UpdateManager} The UpdateManager
*/
setUrl : function(url, params, loadOnce){
if(this.refreshDelegate){
this.un('activate', this.refreshDelegate);
}
this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
this.on("activate", this.refreshDelegate);
return this.bodyEl.getUpdateManager();
},
/** @private */
_handleRefresh : function(url, params, loadOnce){
if(!loadOnce || !this.loaded){
var updater = this.bodyEl.getUpdateManager();
updater.update(url, params, this._setLoaded.createDelegate(this));
}
},
/**
* Forces a content refresh from the URL specified in the {@link #setUrl} method.
* Will fail silently if the setUrl method has not been called.
* This does not activate the panel, just updates its content.
*/
refresh : function(){
if(this.refreshDelegate){
this.loaded = false;
this.refreshDelegate();
}
},
/** @private */
_setLoaded : function(){
this.loaded = true;
},
/** @private */
closeClick : function(e){
var o = {};
e.stopEvent();
this.fireEvent("beforeclose", this, o);
if(o.cancel !== true){
this.tabPanel.removeTab(this.id);
}
},
/**
* The text displayed in the tooltip for the close icon.
* @type String
*/
closeText : "Close this tab"
});
/** @private */
Ext.TabPanel.prototype.createStrip = function(container){
var strip = document.createElement("div");
strip.className = "x-tabs-wrap";
container.appendChild(strip);
return strip;
};
/** @private */
Ext.TabPanel.prototype.createStripList = function(strip){
// div wrapper for retard IE
strip.innerHTML = '<div class="x-tabs-strip-wrap"><table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr></tr></tbody></table></div>';
return strip.firstChild.firstChild.firstChild.firstChild;
};
/** @private */
Ext.TabPanel.prototype.createBody = function(container){
var body = document.createElement("div");
Ext.id(body, "tab-body");
Ext.fly(body).addClass("x-tabs-body");
container.appendChild(body);
return body;
};
/** @private */
Ext.TabPanel.prototype.createItemBody = function(bodyEl, id){
var body = Ext.getDom(id);
if(!body){
body = document.createElement("div");
body.id = id;
}
Ext.fly(body).addClass("x-tabs-item-body");
bodyEl.insertBefore(body, bodyEl.firstChild);
return body;
};
/** @private */
Ext.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
var td = document.createElement("td");
stripEl.appendChild(td);
if(closable){
td.className = "x-tabs-closable";
if(!this.closeTpl){
this.closeTpl = new Ext.Template(
'<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
'<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
'<div unselectable="on" class="close-icon"> </div></em></span></a>'
);
}
var el = this.closeTpl.overwrite(td, {"text": text});
var close = el.getElementsByTagName("div")[0];
var inner = el.getElementsByTagName("em")[0];
return {"el": el, "close": close, "inner": inner};
} else {
if(!this.tabTpl){
this.tabTpl = new Ext.Template(
'<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
'<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
);
}
var el = this.tabTpl.overwrite(td, {"text": text});
var inner = el.getElementsByTagName("em")[0];
return {"el": el, "inner": inner};
}
}; | 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.BasicDialog
* @extends Ext.util.Observable
* 轻便的 Dialog 类。下面的代码展示了使用已有的 HTML 标签创建一个典型的对话框:
* <pre><code>
var dlg = new Ext.BasicDialog("my-dlg", {
height: 200,
width: 300,
minHeight: 100,
minWidth: 150,
modal: true,
proxyDrag: true,
shadow: true
});
dlg.addKeyListener(27, dlg.hide, dlg); // ESC 也能关闭对话框
dlg.addButton('OK', dlg.hide, dlg); // 可以调用保存function代替隐藏对话框
dlg.addButton('Cancel', dlg.hide, dlg);
dlg.show();
</code></pre>
<b>对话框应该为“body”元素的直系子节点。</b>
* @cfg {Boolean/DomHelper} autoCreate 值为“true”时自动创建,或者使用“DomHelper”对象创建(默认为“false”)。
* @cfg {String} title 标题栏上默认显示的文字(默认为“null”)。
* @cfg {Number} width 对话框的宽度,单位像素(也可以通过 CSS 来设置)。如果未指定则由浏览器决定。
* @cfg {Number} height 对话框的高度,单位像素(也可以通过 CSS 来设置)。如果未指定则由浏览器决定。
* @cfg {Number} x 对话框默认的顶部坐标(默认为屏幕中央)
* @cfg {Number} y 对话框默认的左边坐标(默认为屏幕中央)
* @cfg {String/Element} animateTarget 对话框打开时应用动画的 Id 或者元素(默认值为“null”,表示没有动画)。
* @cfg {Boolean} resizable 值为“false”时禁止手动调整对话框大小(默认为“true”)。
* @cfg {String} 设置显示的调整柄,详见 {@link Ext.Resizable} 中调整柄的可用值(默认为“all”)。
* @cfg {Number} minHeight 对话框高度的最小值(默认为“80”)。
* @cfg {Number} minWidth 对话框宽度的最小值(默认为“200”)。
* @cfg {Boolean} modal 值为“true”时模式显示对话框,防止用户与页面的剩余部分交互(默认为“false”)。
* @cfg {Boolean} autoScroll 值为“true”时允许对话框的主体部分里的内容溢出,并显示滚动条(默认为“false”)。
* @cfg {Boolean} closable 值为“false”时将移除标题栏右上角的关闭按钮(默认为“true”)。
* @cfg {Boolean} collapsible 值为“false”时将移除标题栏右上角的最小化按钮(默认为“true”)。
* @cfg {Boolean} constraintoviewport 值为“true”时将保持对话框限定在可视区的边界内(默认为“true”)。
* @cfg {Boolean} syncHeightBeforeShow 值为“true”时则在对话框显示前重新计算高度(默认为“false”)。
* @cfg {Boolean} draggable 值为“false”时将禁止对话框在可视区内的拖动(默认为“true”)。
* @cfg {Boolean} autoTabs 值为“true”时,所有 class 属性为“x-dlg-tab”的元素将被自动转换为 tabs(默认为“false”)。
* @cfg {String} tabTag “tab”元素的标签名称,当 autoTabs = true 时使用(默认为“div”)。
* @cfg {Boolean} proxyDrag 值为“true”时拖动对话框会显示一个轮廓,当“draggable”为“true”时使用(默认为“false”)。
* @cfg {Boolean} fixedcenter 值为“true”时将确保对话框总是在可视区的中央(默认为“false”)。
* @cfg {Boolean/String} shadow “true”或者“sides”为默认效果,“frame”为4方向阴影,“drop”为右下方阴影(默认为“false”)。
* @cfg {Number} shadowOffset 阴影显示时的偏移量,单位为像素(默认为“5”)。
* @cfg {String} buttonAlign 合法的值为:“left”、“center”和“right”(默认为“right”)。
* @cfg {Number} minButtonWidth 对话框中按钮宽度的最小值(默认为“75”)。
* @cfg {Boolean} shim 值为“true”时将创建一个“iframe”元素以免被“select”穿越(默认为“false”)。
* @constructor
* Create a new BasicDialog.
* @param {String/HTMLElement/Ext.Element} el The container element or DOM node, or its id
* @param {Object} config Configuration options
*/
Ext.BasicDialog = function(el, config){
this.el = Ext.get(el);
var dh = Ext.DomHelper;
if(!this.el && config && config.autoCreate){
if(typeof config.autoCreate == "object"){
if(!config.autoCreate.id){
config.autoCreate.id = el;
}
this.el = dh.append(document.body,
config.autoCreate, true);
}else{
this.el = dh.append(document.body,
{tag: "div", id: el, style:'visibility:hidden;'}, true);
}
}
el = this.el;
el.setDisplayed(true);
el.hide = this.hideAction;
this.id = el.id;
el.addClass("x-dlg");
Ext.apply(this, config);
this.proxy = el.createProxy("x-dlg-proxy");
this.proxy.hide = this.hideAction;
this.proxy.setOpacity(.5);
this.proxy.hide();
if(config.width){
el.setWidth(config.width);
}
if(config.height){
el.setHeight(config.height);
}
this.size = el.getSize();
if(typeof config.x != "undefined" && typeof config.y != "undefined"){
this.xy = [config.x,config.y];
}else{
this.xy = el.getCenterXY(true);
}
/** The header element @type Ext.Element */
this.header = el.child("> .x-dlg-hd");
/** The body element @type Ext.Element */
this.body = el.child("> .x-dlg-bd");
/** The footer element @type Ext.Element */
this.footer = el.child("> .x-dlg-ft");
if(!this.header){
this.header = el.createChild({tag: "div", cls:"x-dlg-hd", html: " "}, this.body ? this.body.dom : null);
}
if(!this.body){
this.body = el.createChild({tag: "div", cls:"x-dlg-bd"});
}
this.header.unselectable();
if(this.title){
this.header.update(this.title);
}
// this element allows the dialog to be focused for keyboard event
this.focusEl = el.createChild({tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1"});
this.focusEl.swallowEvent("click", true);
this.header.wrap({cls:"x-dlg-hd-right"}).wrap({cls:"x-dlg-hd-left"}, true);
// wrap the body and footer for special rendering
this.bwrap = this.body.wrap({tag: "div", cls:"x-dlg-dlg-body"});
if(this.footer){
this.bwrap.dom.appendChild(this.footer.dom);
}
this.bg = this.el.createChild({
tag: "div", cls:"x-dlg-bg",
html: '<div class="x-dlg-bg-left"><div class="x-dlg-bg-right"><div class="x-dlg-bg-center"> </div></div></div>'
});
this.centerBg = this.bg.child("div.x-dlg-bg-center");
if(this.autoScroll !== false && !this.autoTabs){
this.body.setStyle("overflow", "auto");
}
this.toolbox = this.el.createChild({cls: "x-dlg-toolbox"});
if(this.closable !== false){
this.el.addClass("x-dlg-closable");
this.close = this.toolbox.createChild({cls:"x-dlg-close"});
this.close.on("click", this.closeClick, this);
this.close.addClassOnOver("x-dlg-close-over");
}
if(this.collapsible !== false){
this.collapseBtn = this.toolbox.createChild({cls:"x-dlg-collapse"});
this.collapseBtn.on("click", this.collapseClick, this);
this.collapseBtn.addClassOnOver("x-dlg-collapse-over");
this.header.on("dblclick", this.collapseClick, this);
}
if(this.resizable !== false){
this.el.addClass("x-dlg-resizable");
this.resizer = new Ext.Resizable(el, {
minWidth: this.minWidth || 80,
minHeight:this.minHeight || 80,
handles: this.resizeHandles || "all",
pinned: true
});
this.resizer.on("beforeresize", this.beforeResize, this);
this.resizer.on("resize", this.onResize, this);
}
if(this.draggable !== false){
el.addClass("x-dlg-draggable");
if (!this.proxyDrag) {
var dd = new Ext.dd.DD(el.dom.id, "WindowDrag");
}
else {
var dd = new Ext.dd.DDProxy(el.dom.id, "WindowDrag", {dragElId: this.proxy.id});
}
dd.setHandleElId(this.header.id);
dd.endDrag = this.endMove.createDelegate(this);
dd.startDrag = this.startMove.createDelegate(this);
dd.onDrag = this.onDrag.createDelegate(this);
dd.scroll = false;
this.dd = dd;
}
if(this.modal){
this.mask = dh.append(document.body, {tag: "div", cls:"x-dlg-mask"}, true);
this.mask.enableDisplayMode("block");
this.mask.hide();
this.el.addClass("x-dlg-modal");
}
if(this.shadow){
this.shadow = new Ext.Shadow({
mode : typeof this.shadow == "string" ? this.shadow : "sides",
offset : this.shadowOffset
});
}else{
this.shadowOffset = 0;
}
if(Ext.useShims && this.shim !== false){
this.shim = this.el.createShim();
this.shim.hide = this.hideAction;
this.shim.hide();
}else{
this.shim = false;
}
if(this.autoTabs){
this.initTabs();
}
this.addEvents({
/**
* @event keydown
* 按下键盘时触发
* @param {Ext.BasicDialog} this
* @param {Ext.EventObject} e
*/
"keydown" : true,
/**
* @event move
* 用户移动对话框时触发
* @param {Ext.BasicDialog} this
* @param {Number} x 新的 X 坐标
* @param {Number} y 新的 Y 坐标
*/
"move" : true,
/**
* @event resize
* 用户调整对话框大小时触发。
* @param {Ext.BasicDialog} this
* @param {Number} width 新的宽度
* @param {Number} height 新的高度
*/
"resize" : true,
/**
* @event beforehide
* 对话框隐藏前触发。
* @param {Ext.BasicDialog} this
*/
"beforehide" : true,
/**
* @event hide
* 对话框隐藏时触发。
* @param {Ext.BasicDialog} this
*/
"hide" : true,
/**
* @event beforeshow
* 对话框展示前触发。
* @param {Ext.BasicDialog} this
*/
"beforeshow" : true,
/**
* @event show
* 对话框展示时触发。
* @param {Ext.BasicDialog} this
*/
"show" : true
});
el.on("keydown", this.onKeyDown, this);
el.on("mousedown", this.toFront, this);
Ext.EventManager.onWindowResize(this.adjustViewport, this, true);
this.el.hide();
Ext.DialogManager.register(this);
Ext.BasicDialog.superclass.constructor.call(this);
};
Ext.extend(Ext.BasicDialog, Ext.util.Observable, {
shadowOffset: Ext.isIE ? 6 : 5,
minHeight: 80,
minWidth: 200,
minButtonWidth: 75,
defaultButton: null,
buttonAlign: "right",
tabTag: 'div',
firstShow: true,
/**
* 设置对话框的标题文本。
* @param {String} text 显示的标题。
* @return {Ext.BasicDialog} this
*/
setTitle : function(text){
this.header.update(text);
return this;
},
// private
closeClick : function(){
this.hide();
},
// private
collapseClick : function(){
this[this.collapsed ? "expand" : "collapse"]();
},
/**
* 将对话框收缩到最小化状态(仅在标题栏可见时有效)。
* 相当于用户单击了收缩对话框按钮。
*/
collapse : function(){
if(!this.collapsed){
this.collapsed = true;
this.el.addClass("x-dlg-collapsed");
this.restoreHeight = this.el.getHeight();
this.resizeTo(this.el.getWidth(), this.header.getHeight());
}
},
/**
* 将对话框展开到普通状态。
* 相当于用户单击了展开对话框按钮。
*/
expand : function(){
if(this.collapsed){
this.collapsed = false;
this.el.removeClass("x-dlg-collapsed");
this.resizeTo(this.el.getWidth(), this.restoreHeight);
}
},
/**
* 重新初始化 tabs 组件,清除原有的 tabs 并返回新的。
* @return {Ext.TabPanel} tabs组件
*/
initTabs : function(){
var tabs = this.getTabs();
while(tabs.getTab(0)){
tabs.removeTab(0);
}
this.el.select(this.tabTag+'.x-dlg-tab').each(function(el){
var dom = el.dom;
tabs.addTab(Ext.id(dom), dom.title);
dom.title = "";
});
tabs.activate(0);
return tabs;
},
// private
beforeResize : function(){
this.resizer.minHeight = Math.max(this.minHeight, this.getHeaderFooterHeight(true)+40);
},
// private
onResize : function(){
this.refreshSize();
this.syncBodyHeight();
this.adjustAssets();
this.focus();
this.fireEvent("resize", this, this.size.width, this.size.height);
},
// private
onKeyDown : function(e){
if(this.isVisible()){
this.fireEvent("keydown", this, e);
}
},
/**
* 调整对话框大小。
* @param {Number} 宽度
* @param {Number} 高度
* @return {Ext.BasicDialog} this
*/
resizeTo : function(width, height){
this.el.setSize(width, height);
this.size = {width: width, height: height};
this.syncBodyHeight();
if(this.fixedcenter){
this.center();
}
if(this.isVisible()){
this.constrainXY();
this.adjustAssets();
}
this.fireEvent("resize", this, width, height);
return this;
},
/**
* 将对话框的大小调整到足以填充指定内容的大小。
* @param {Number} 宽度
* @param {Number} 高度
* @return {Ext.BasicDialog} this
*/
setContentSize : function(w, h){
h += this.getHeaderFooterHeight() + this.body.getMargins("tb");
w += this.body.getMargins("lr") + this.bwrap.getMargins("lr") + this.centerBg.getPadding("lr");
//if(!this.el.isBorderBox()){
h += this.body.getPadding("tb") + this.bwrap.getBorderWidth("tb") + this.body.getBorderWidth("tb") + this.el.getBorderWidth("tb");
w += this.body.getPadding("lr") + this.bwrap.getBorderWidth("lr") + this.body.getBorderWidth("lr") + this.bwrap.getPadding("lr") + this.el.getBorderWidth("lr");
//}
if(this.tabs){
h += this.tabs.stripWrap.getHeight() + this.tabs.bodyEl.getMargins("tb") + this.tabs.bodyEl.getPadding("tb");
w += this.tabs.bodyEl.getMargins("lr") + this.tabs.bodyEl.getPadding("lr");
}
this.resizeTo(w, h);
return this;
},
/**
* 当对话框显示的时候添加一个键盘监听器。这样将允许当对话框活动时勾住一个函数,并在按下指定的按键时执行。
* @param {Number/Array/Object} key 可以是一个 key code 、key code 数组、或者是含有下列选项的对象:{key: (number/array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
* @param {Function} fn 调用的函数
* @param {Object} scope (可选的)函数的作用域
* @return {Ext.BasicDialog} this
*/
addKeyListener : 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;
}
var handler = function(dlg, e){
if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
var k = e.getKey();
if(keyCode instanceof Array){
for(var i = 0, len = keyCode.length; i < len; i++){
if(keyCode[i] == k){
fn.call(scope || window, dlg, k, e);
return;
}
}
}else{
if(k == keyCode){
fn.call(scope || window, dlg, k, e);
}
}
}
};
this.on("keydown", handler);
return this;
},
/**
* 返回 TabPanel 组件(如果不存在则创建一个)。
* 注意:如果你只是想检查存在的 TabPanel 而不是创建,设置一个值为空的“tabs”属性。
* @return {Ext.TabPanel} tabs组件
*/
getTabs : function(){
if(!this.tabs){
this.el.addClass("x-dlg-auto-tabs");
this.body.addClass(this.tabPosition == "bottom" ? "x-tabs-bottom" : "x-tabs-top");
this.tabs = new Ext.TabPanel(this.body.dom, this.tabPosition == "bottom");
}
return this.tabs;
},
/**
* 在对话框的底部区域添加一个按钮。
* @param {String/Object} config 如果是字串则为按钮的文本,也可以是按钮设置对象或者 Ext.DomHelper 元素设置。
* @param {Function} handler 点击按钮时调用的函数。
* @param {Object} scope (可选的) 调用函数的作用域。
* @return {Ext.Button} 新的按钮
*/
addButton : function(config, handler, scope){
var dh = Ext.DomHelper;
if(!this.footer){
this.footer = dh.append(this.bwrap, {tag: "div", cls:"x-dlg-ft"}, true);
}
if(!this.btnContainer){
var tb = this.footer.createChild({
cls:"x-dlg-btns x-dlg-btns-"+this.buttonAlign,
html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
}, null, true);
this.btnContainer = tb.firstChild.firstChild.firstChild;
}
var bconfig = {
handler: handler,
scope: scope,
minWidth: this.minButtonWidth,
hideParent:true
};
if(typeof config == "string"){
bconfig.text = config;
}else{
if(config.tag){
bconfig.dhconfig = config;
}else{
Ext.apply(bconfig, config);
}
}
var btn = new Ext.Button(
this.btnContainer.appendChild(document.createElement("td")),
bconfig
);
this.syncBodyHeight();
if(!this.buttons){
/**
* 所有通过“addButton”方法添加的按钮数组
* @type Array
*/
this.buttons = [];
}
this.buttons.push(btn);
return btn;
},
/**
* 当对话框显示时将焦点设置在默认的按钮上。
* @param {Ext.BasicDialog.Button} btn 通过{@link #addButton}方法创建的按钮。
* @return {Ext.BasicDialog} this
*/
setDefaultButton : function(btn){
this.defaultButton = btn;
return this;
},
// private
getHeaderFooterHeight : function(safe){
var height = 0;
if(this.header){
height += this.header.getHeight();
}
if(this.footer){
var fm = this.footer.getMargins();
height += (this.footer.getHeight()+fm.top+fm.bottom);
}
height += this.bwrap.getPadding("tb")+this.bwrap.getBorderWidth("tb");
height += this.centerBg.getPadding("tb");
return height;
},
// private
syncBodyHeight : function(){
var bd = this.body, cb = this.centerBg, bw = this.bwrap;
var height = this.size.height - this.getHeaderFooterHeight(false);
bd.setHeight(height-bd.getMargins("tb"));
var hh = this.header.getHeight();
var h = this.size.height-hh;
cb.setHeight(h);
bw.setLeftTop(cb.getPadding("l"), hh+cb.getPadding("t"));
bw.setHeight(h-cb.getPadding("tb"));
bw.setWidth(this.el.getWidth(true)-cb.getPadding("lr"));
bd.setWidth(bw.getWidth(true));
if(this.tabs){
this.tabs.syncHeight();
if(Ext.isIE){
this.tabs.el.repaint();
}
}
},
/**
* 如果配置过 Ext.state 则恢复对话框之前的状态。
* @return {Ext.BasicDialog} this
*/
restoreState : function(){
var box = Ext.state.Manager.get(this.stateId || (this.el.id + "-state"));
if(box && box.width){
this.xy = [box.x, box.y];
this.resizeTo(box.width, box.height);
}
return this;
},
// private
beforeShow : function(){
this.expand();
if(this.fixedcenter){
this.xy = this.el.getCenterXY(true);
}
if(this.modal){
Ext.get(document.body).addClass("x-body-masked");
this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
this.mask.show();
}
this.constrainXY();
},
// private
animShow : function(){
var b = Ext.get(this.animateTarget, true).getBox();
this.proxy.setSize(b.width, b.height);
this.proxy.setLocation(b.x, b.y);
this.proxy.show();
this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height,
true, .35, this.showEl.createDelegate(this));
},
/**
* 展示对话框。
* @param {String/HTMLElement/Ext.Element} animateTarget (可选的) 重置动画的目标
* @return {Ext.BasicDialog} this
*/
show : function(animateTarget){
if (this.fireEvent("beforeshow", this) === false){
return;
}
if(this.syncHeightBeforeShow){
this.syncBodyHeight();
}else if(this.firstShow){
this.firstShow = false;
this.syncBodyHeight(); // sync the height on the first show instead of in the constructor
}
this.animateTarget = animateTarget || this.animateTarget;
if(!this.el.isVisible()){
this.beforeShow();
if(this.animateTarget){
this.animShow();
}else{
this.showEl();
}
}
return this;
},
// private
showEl : function(){
this.proxy.hide();
this.el.setXY(this.xy);
this.el.show();
this.adjustAssets(true);
this.toFront();
this.focus();
// IE peekaboo bug - fix found by Dave Fenwick
if(Ext.isIE){
this.el.repaint();
}
this.fireEvent("show", this);
},
/**
* 将焦点置于对话框上。
* 如果设置了 defaultButton ,则该按钮取得焦点,否则对话框本身取得焦点。
*/
focus : function(){
if(this.defaultButton){
this.defaultButton.focus();
}else{
this.focusEl.focus();
}
},
// private
constrainXY : function(){
if(this.constraintoviewport !== false){
if(!this.viewSize){
if(this.container){
var s = this.container.getSize();
this.viewSize = [s.width, s.height];
}else{
this.viewSize = [Ext.lib.Dom.getViewWidth(),Ext.lib.Dom.getViewHeight()];
}
}
var s = Ext.get(this.container||document).getScroll();
var x = this.xy[0], y = this.xy[1];
var w = this.size.width, h = this.size.height;
var vw = this.viewSize[0], vh = this.viewSize[1];
// only move it if it needs it
var moved = false;
// first validate right/bottom
if(x + w > vw+s.left){
x = vw - w;
moved = true;
}
if(y + h > vh+s.top){
y = vh - h;
moved = true;
}
// then make sure top/left isn't negative
if(x < s.left){
x = s.left;
moved = true;
}
if(y < s.top){
y = s.top;
moved = true;
}
if(moved){
// cache xy
this.xy = [x, y];
if(this.isVisible()){
this.el.setLocation(x, y);
this.adjustAssets();
}
}
}
},
// private
onDrag : function(){
if(!this.proxyDrag){
this.xy = this.el.getXY();
this.adjustAssets();
}
},
// private
adjustAssets : function(doShow){
var x = this.xy[0], y = this.xy[1];
var w = this.size.width, h = this.size.height;
if(doShow === true){
if(this.shadow){
this.shadow.show(this.el);
}
if(this.shim){
this.shim.show();
}
}
if(this.shadow && this.shadow.isVisible()){
this.shadow.show(this.el);
}
if(this.shim && this.shim.isVisible()){
this.shim.setBounds(x, y, w, h);
}
},
// private
adjustViewport : function(w, h){
if(!w || !h){
w = Ext.lib.Dom.getViewWidth();
h = Ext.lib.Dom.getViewHeight();
}
// cache the size
this.viewSize = [w, h];
if(this.modal && this.mask.isVisible()){
this.mask.setSize(w, h); // first make sure the mask isn't causing overflow
this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
}
if(this.isVisible()){
this.constrainXY();
}
},
/**
* 销毁对话框和所有它支持的元素(包括 tabs、 shim、 shadow、 proxy、 mask 等等。)同时也去除所有事件监听器。
* @param {Boolean} removeEl (可选的) 值为 true 时从 DOM 中删除该元素。
*/
destroy : function(removeEl){
if(this.isVisible()){
this.animateTarget = null;
this.hide();
}
Ext.EventManager.removeResizeListener(this.adjustViewport, this);
if(this.tabs){
this.tabs.destroy(removeEl);
}
Ext.destroy(
this.shim,
this.proxy,
this.resizer,
this.close,
this.mask
);
if(this.dd){
this.dd.unreg();
}
if(this.buttons){
for(var i = 0, len = this.buttons.length; i < len; i++){
this.buttons[i].destroy();
}
}
this.el.removeAllListeners();
if(removeEl === true){
this.el.update("");
this.el.remove();
}
Ext.DialogManager.unregister(this);
},
// private
startMove : function(){
if(this.proxyDrag){
this.proxy.show();
}
if(this.constraintoviewport !== false){
this.dd.constrainTo(document.body, {right: this.shadowOffset, bottom: this.shadowOffset});
}
},
// private
endMove : function(){
if(!this.proxyDrag){
Ext.dd.DD.prototype.endDrag.apply(this.dd, arguments);
}else{
Ext.dd.DDProxy.prototype.endDrag.apply(this.dd, arguments);
this.proxy.hide();
}
this.refreshSize();
this.adjustAssets();
this.focus();
this.fireEvent("move", this, this.xy[0], this.xy[1]);
},
/**
* 将对话框置于其他可见的对话框的前面。
* @return {Ext.BasicDialog} this
*/
toFront : function(){
Ext.DialogManager.bringToFront(this);
return this;
},
/**
* 将对话框置于其他可见的对话框的后面。
* @return {Ext.BasicDialog} this
*/
toBack : function(){
Ext.DialogManager.sendToBack(this);
return this;
},
/**
* 将对话框于视图居中显示。
* @return {Ext.BasicDialog} this
*/
center : function(){
var xy = this.el.getCenterXY(true);
this.moveTo(xy[0], xy[1]);
return this;
},
/**
* 将对话框的左上角移动到指定的地方。
* @param {Number} x
* @param {Number} y
* @return {Ext.BasicDialog} this
*/
moveTo : function(x, y){
this.xy = [x,y];
if(this.isVisible()){
this.el.setXY(this.xy);
this.adjustAssets();
}
return this;
},
/**
* 将对话框对齐到指定元素上。
* @param {String/HTMLElement/Ext.Element} element 要对齐的元素。
* @param {String} position 对齐到的位置(点击{@link Ext.Element#alignTo}查看详情)。
* @param {Array} offsets (可选的) 位置偏移量,形如:[x, y]
* @return {Ext.BasicDialog} this
*/
alignTo : function(element, position, offsets){
this.xy = this.el.getAlignToXY(element, position, offsets);
if(this.isVisible()){
this.el.setXY(this.xy);
this.adjustAssets();
}
return this;
},
/**
* 将元素与另一个元素绑定,并在调整窗口大小后重新对齐元素。
* @param {String/HTMLElement/Ext.Element} element 要对齐的元素。
* @param {String} position 对齐到的位置(点击{@link Ext.Element#alignTo}查看详情)。
* @param {Array} offsets (可选的) 位置偏移量,形如:[x, y]
* @param {Boolean/Number} monitorScroll (可选的) 值为 true 时监视容器的滚动并重新定位。如果为数值,将用来做为延迟缓冲量(默认为50毫秒)。
* @return {Ext.BasicDialog} this
*/
anchorTo : function(el, alignment, offsets, monitorScroll){
var action = function(){
this.alignTo(el, alignment, offsets);
};
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;
},
/**
* 当对话框可见时返回“true”。
* @return {Boolean}
*/
isVisible : function(){
return this.el.isVisible();
},
// private
animHide : function(callback){
var b = Ext.get(this.animateTarget).getBox();
this.proxy.show();
this.proxy.setBounds(this.xy[0], this.xy[1], this.size.width, this.size.height);
this.el.hide();
this.proxy.setBounds(b.x, b.y, b.width, b.height, true, .35,
this.hideEl.createDelegate(this, [callback]));
},
/**
* 隐藏对话框。
* @param {Function} callback (可选的) 对话框隐藏时调用的函数。
* @return {Ext.BasicDialog} this
*/
hide : function(callback){
if (this.fireEvent("beforehide", this) === false){
return;
}
if(this.shadow){
this.shadow.hide();
}
if(this.shim) {
this.shim.hide();
}
if(this.animateTarget){
this.animHide(callback);
}else{
this.el.hide();
this.hideEl(callback);
}
return this;
},
// private
hideEl : function(callback){
this.proxy.hide();
if(this.modal){
this.mask.hide();
Ext.get(document.body).removeClass("x-body-masked");
}
this.fireEvent("hide", this);
if(typeof callback == "function"){
callback();
}
},
// private
hideAction : function(){
this.setLeft("-10000px");
this.setTop("-10000px");
this.setStyle("visibility", "hidden");
},
// private
refreshSize : function(){
this.size = this.el.getSize();
this.xy = this.el.getXY();
Ext.state.Manager.set(this.stateId || this.el.id + "-state", this.el.getBox());
},
// private
// z-index is managed by the DialogManager and may be overwritten at any time
setZIndex : function(index){
if(this.modal){
this.mask.setStyle("z-index", index);
}
if(this.shim){
this.shim.setStyle("z-index", ++index);
}
if(this.shadow){
this.shadow.setZIndex(++index);
}
this.el.setStyle("z-index", ++index);
if(this.proxy){
this.proxy.setStyle("z-index", ++index);
}
if(this.resizer){
this.resizer.proxy.setStyle("z-index", ++index);
}
this.lastZIndex = index;
},
/**
* 返回对话框元素。
* @return {Ext.Element} 所在的对话框元素
*/
getEl : function(){
return this.el;
}
});
/**
* @class Ext.DialogManager
* Provides global access to BasicDialogs that have been created and
* support for z-indexing (layering) multiple open dialogs.
*/
Ext.DialogManager = function(){
var list = {};
var accessList = [];
var front = null;
// private
var sortDialogs = function(d1, d2){
return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
};
// private
var orderDialogs = function(){
accessList.sort(sortDialogs);
var seed = Ext.DialogManager.zseed;
for(var i = 0, len = accessList.length; i < len; i++){
var dlg = accessList[i];
if(dlg){
dlg.setZIndex(seed + (i*10));
}
}
};
return {
/**
* The starting z-index for BasicDialogs (defaults to 9000)
* @type Number The z-index value
*/
zseed : 9000,
// private
register : function(dlg){
list[dlg.id] = dlg;
accessList.push(dlg);
},
// private
unregister : function(dlg){
delete list[dlg.id];
if(!accessList.indexOf){
for(var i = 0, len = accessList.length; i < len; i++){
if(accessList[i] == dlg){
accessList.splice(i, 1);
return;
}
}
}else{
var i = accessList.indexOf(dlg);
if(i != -1){
accessList.splice(i, 1);
}
}
},
/**
* Gets a registered dialog by id
* @param {String/Object} id The id of the dialog or a dialog
* @return {Ext.BasicDialog} this
*/
get : function(id){
return typeof id == "object" ? id : list[id];
},
/**
* Brings the specified dialog to the front
* @param {String/Object} dlg The id of the dialog or a dialog
* @return {Ext.BasicDialog} this
*/
bringToFront : function(dlg){
dlg = this.get(dlg);
if(dlg != front){
front = dlg;
dlg._lastAccess = new Date().getTime();
orderDialogs();
}
return dlg;
},
/**
* Sends the specified dialog to the back
* @param {String/Object} dlg The id of the dialog or a dialog
* @return {Ext.BasicDialog} this
*/
sendToBack : function(dlg){
dlg = this.get(dlg);
dlg._lastAccess = -(new Date().getTime());
orderDialogs();
return dlg;
},
/**
* Hides all dialogs
*/
hideAll : function(){
for(var id in list){
if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
list[id].hide();
}
}
}
};
}();
/**
* @class Ext.LayoutDialog
* @extends Ext.BasicDialog
* Dialog which provides adjustments for working with a layout in a Dialog.
* Add your necessary layout config options to the dialog's config.<br>
* Example usage (including a nested layout):
* <pre><code>
if(!dialog){
dialog = new Ext.LayoutDialog("download-dlg", {
modal: true,
width:600,
height:450,
shadow:true,
minWidth:500,
minHeight:350,
autoTabs:true,
proxyDrag:true,
// layout config merges with the dialog config
center:{
tabPosition: "top",
alwaysShowTabs: true
}
});
dialog.addKeyListener(27, dialog.hide, dialog);
dialog.setDefaultButton(dialog.addButton("Close", dialog.hide, dialog));
dialog.addButton("Build It!", this.getDownload, this);
// we can even add nested layouts
var innerLayout = new Ext.BorderLayout("dl-inner", {
east: {
initialSize: 200,
autoScroll:true,
split:true
},
center: {
autoScroll:true
}
});
innerLayout.beginUpdate();
innerLayout.add("east", new Ext.ContentPanel("dl-details"));
innerLayout.add("center", new Ext.ContentPanel("selection-panel"));
innerLayout.endUpdate(true);
var layout = dialog.getLayout();
layout.beginUpdate();
layout.add("center", new Ext.ContentPanel("standard-panel",
{title: "Download the Source", fitToFrame:true}));
layout.add("center", new Ext.NestedLayoutPanel(innerLayout,
{title: "Build your own ext.js"}));
layout.getRegion("center").showPanel(sp);
layout.endUpdate();
}
</code></pre>
* @constructor
* @param {String/HTMLElement/Ext.Element} el The id of or container element
* @param {Object} config configuration options
*/
Ext.LayoutDialog = function(el, config){
config.autoTabs = false;
Ext.LayoutDialog.superclass.constructor.call(this, el, config);
this.body.setStyle({overflow:"hidden", position:"relative"});
this.layout = new Ext.BorderLayout(this.body.dom, config);
this.layout.monitorWindowResize = false;
this.el.addClass("x-dlg-auto-layout");
// fix case when center region overwrites center function
this.center = Ext.BasicDialog.prototype.center;
this.on("show", this.layout.layout, this.layout, true);
};
Ext.extend(Ext.LayoutDialog, Ext.BasicDialog, {
/**
* Ends update of the layout <strike>and resets display to none</strike>. Use standard beginUpdate/endUpdate on the layout.
* @deprecated
*/
endUpdate : function(){
this.layout.endUpdate();
},
/**
* Begins an update of the layout <strike>and sets display to block and visibility to hidden</strike>. Use standard beginUpdate/endUpdate on the layout.
* @deprecated
*/
beginUpdate : function(){
this.layout.beginUpdate();
},
/**
* Get the BorderLayout for this dialog
* @return {Ext.BorderLayout}
*/
getLayout : function(){
return this.layout;
},
showEl : function(){
Ext.LayoutDialog.superclass.showEl.apply(this, arguments);
if(Ext.isIE7){
this.layout.layout();
}
},
// private
// Use the syncHeightBeforeShow config option to control this automatically
syncBodyHeight : function(){
Ext.LayoutDialog.superclass.syncBodyHeight.call(this);
if(this.layout){this.layout.layout();}
}
}); | 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.Shadow
* 为所有元素提供投影效果的一个简易类。 注意元素必须为绝对定位,而且投影并没有垫片的效果(shimming)。
* This should be used only in simple cases --
* 这只是适用简单的场合- 如想提供更高阶的投影效果,请参阅{@link Ext.Layer}类。
* @constructor
* Create a new Shadow
* @param {Object} config 配置项对象
*/
Ext.Shadow = function(config){
Ext.apply(this, config);
if(typeof this.mode != "string"){
this.mode = this.defaultMode;
}
var o = this.offset, a = {h: 0};
var rad = Math.floor(this.offset/2);
switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows
case "drop":
a.w = 0;
a.l = a.t = o;
a.t -= 1;
if(Ext.isIE){
a.l -= this.offset + rad;
a.t -= this.offset + rad;
a.w -= rad;
a.h -= rad;
a.t += 1;
}
break;
case "sides":
a.w = (o*2);
a.l = -o;
a.t = o-1;
if(Ext.isIE){
a.l -= (this.offset - rad);
a.t -= this.offset + rad;
a.l += 1;
a.w -= (this.offset - rad)*2;
a.w -= rad + 1;
a.h -= 1;
}
break;
case "frame":
a.w = a.h = (o*2);
a.l = a.t = -o;
a.t += 1;
a.h -= 2;
if(Ext.isIE){
a.l -= (this.offset - rad);
a.t -= (this.offset - rad);
a.l += 1;
a.w -= (this.offset + rad + 1);
a.h -= (this.offset + rad);
a.h += 1;
}
break;
};
this.adjusts = a;
};
Ext.Shadow.prototype = {
/**
* @cfg {String} mode
* 投影显示的模式。有下列选项:<br />
* sides: 投影限显示在两边和底部<br />
* frame: 投影在四边均匀出现<br />
* drop: 传统的物理效果的,底部和右边。这是默认值。
*/
/**
* @cfg {String} offset
* 元素和投影之间的偏移象素值(默认为4)
*/
offset: 4,
// private
defaultMode: "drop",
/**
* 在目标元素上显示投影,
* @param {String/HTMLElement/Element} targetEl 指定要显示投影的那个元素
*/
show : function(target){
target = Ext.get(target);
if(!this.el){
this.el = Ext.Shadow.Pool.pull();
if(this.el.dom.nextSibling != target.dom){
this.el.insertBefore(target);
}
}
this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1);
if(Ext.isIE){
this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")";
}
this.realign(
target.getLeft(true),
target.getTop(true),
target.getWidth(),
target.getHeight()
);
this.el.dom.style.display = "block";
},
/**
* 返回投影是否在显示
*/
isVisible : function(){
return this.el ? true : false;
},
/**
* 当值可用时直接对称位置。
* Show方法必须至少在调用realign方法之前调用一次,以保证能够初始化。
* @param {Number} left 目标元素left位置
* @param {Number} top 目标元素top位置
* @param {Number} width 目标元素宽度
* @param {Number} height 目标元素高度
*/
realign : function(l, t, w, h){
if(!this.el){
return;
}
var a = this.adjusts, d = this.el.dom, s = d.style;
var iea = 0;
s.left = (l+a.l)+"px";
s.top = (t+a.t)+"px";
var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px";
if(s.width != sws || s.height != shs){
s.width = sws;
s.height = shs;
if(!Ext.isIE){
var cn = d.childNodes;
var sww = Math.max(0, (sw-12))+"px";
cn[0].childNodes[1].style.width = sww;
cn[1].childNodes[1].style.width = sww;
cn[2].childNodes[1].style.width = sww;
cn[1].style.height = Math.max(0, (sh-12))+"px";
}
}
},
/**
* 隐藏投影
*/
hide : function(){
if(this.el){
this.el.dom.style.display = "none";
Ext.Shadow.Pool.push(this.el);
delete this.el;
}
},
/**
* 调整该投影的z-index
* @param {Number} zindex 新z-index
*/
setZIndex : function(z){
this.zIndex = z;
if(this.el){
this.el.setStyle("z-index", z);
}
}
};
// Private utility class that manages the internal Shadow cache
Ext.Shadow.Pool = function(){
var p = [];
var markup = Ext.isIE ?
'<div class="x-ie-shadow"></div>' :
'<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';
return {
pull : function(){
var sh = p.shift();
if(!sh){
sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup));
sh.autoBoxAdjust = false;
}
return sh;
},
push : function(sh){
p.push(sh);
}
};
}(); | 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.JsonView
* @extends Ext.View
* 为了方便使用JSON+{@link Ext.UpdateManager},而创建的一个模板视图类。用法:
<pre><code>
var view = new Ext.JsonView("my-element",
'<div id="{id}">{foo} - {bar}</div>', // 自动创建模板
{ multiSelect: true, jsonRoot: "data" }
);
//是否侦听节点的单击事件?
view.on("click", function(vw, index, node, e){
alert('点中节点"' + node.id + '" 位于索引:' + index + "。");
});
// 直接加载JSON数据
view.load("foobar.php");
// JACK博客上的范例
var tpl = new Ext.Template(
'<div class="entry">' +
'<a class="entry-title" href="{link}">{title}</a>' +
"<h4>{date} by {author} | {comments} Comments</h4>{description}" +
"</div><hr />"
);
var moreView = new Ext.JsonView("entry-list", tpl, {
jsonRoot: "posts"
});
moreView.on("beforerender", this.sortEntries, this);
moreView.load({
url: "/blog/get-posts.php",
params: "allposts=true",
text: "Loading Blog Entries..."
});
</code></pre>
* @constructor
* 创建一个新的JSON视图(JSONView)
* @param {String/HTMLElement/Element} container 渲染视图的容器元素。
* @param {Template} tpl 渲染模板
* @param {Object} config 配置项对象
*/
Ext.JsonView = function(container, tpl, config){
Ext.JsonView.superclass.constructor.call(this, container, tpl, config);
var um = this.el.getUpdateManager();
um.setRenderer(this);
um.on("update", this.onLoad, this);
um.on("failure", this.onLoadException, this);
/**
* @event beforerender
* JSON数据已加载好了,view渲染之前触发。
* @param {Ext.JsonView} this
* @param {Object} data 已加载好的JSON数据
*/
/**
* @event load
* 当数据加载后触发。
* @param {Ext.JsonView} this
* @param {Object} data 已加载好的JSON数据
* @param {Object} response 原始的连接对象(从服务区响应回来的)
*/
/**
* @event loadexception
* 当加载失败时触发。
* @param {Ext.JsonView} this
* @param {Object} response 原始的连接对象(从服务区响应回来的)
*/
this.addEvents({
'beforerender' : true,
'load' : true,
'loadexception' : true
});
};
Ext.extend(Ext.JsonView, Ext.View, {
/**
* 包含数据的 JSON 对象的根属性
* @type {String}
*/
jsonRoot : "",
/**
* 刷新 view
*/
refresh : function(){
this.clearSelections();
this.el.update("");
var html = [];
var o = this.jsonData;
if(o && o.length > 0){
for(var i = 0, len = o.length; i < len; i++){
var data = this.prepareData(o[i], i, o);
html[html.length] = this.tpl.apply(data);
}
}else{
html.push(this.emptyText);
}
this.el.update(html.join(""));
this.nodes = this.el.dom.childNodes;
this.updateIndexes(0);
},
/**
* 发起一个异步的 HTTP 请求,然后得到 JSON 的响应.如不指定<i>params</i> 则使用 POST, 否则就是 GET.
* @param {Object/String/Function} 该请求的 URL, 或是可返回 URL 的函数,也可是包含下列选项的配置项对象:
<pre><code>
view.load({
url: "your-url.php",
params: {param1: "foo", param2: "bar"}, // 或是可URL编码的字符串
callback: yourFunction,
scope: yourObject, //(作用域可选)
discardUrl: false,
nocache: false,
text: "加载中...",
timeout: 30,
scripts: false
});
</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 (可选的)请求往返完成后的回调,调用时有参数(oElement, bSuccess)
* @param {Boolean} discardUrl (可选的)默认情况下你执行一次更新后,最后一次url会保存到defaultUrl。如果true的话,将不会保存。
*/
load : function(){
var um = this.el.getUpdateManager();
um.update.apply(um, arguments);
},
render : function(el, response){
this.clearSelections();
this.el.update("");
var o;
try{
o = Ext.util.JSON.decode(response.responseText);
if(this.jsonRoot){
o = eval("o." + this.jsonRoot);
}
} catch(e){
}
/**
* 当前的JSON数据或是null
*/
this.jsonData = o;
this.beforeRender();
this.refresh();
},
/**
* 获取当前JSON数据集的总记录数
* @return {Number}
*/
getCount : function(){
return this.jsonData ? this.jsonData.length : 0;
},
/**
* 指定一个或多个节点返回JSON对象
* @param {HTMLElement/Array} 节点或节点组成的数组
* @return {Object/Array} 如果传入的参数是数组的类型,返回的也是一个数组,反之
* 你得到是节点的 JSON 对象
*/
getNodeData : function(node){
if(node instanceof Array){
var data = [];
for(var i = 0, len = node.length; i < len; i++){
data.push(this.getNodeData(node[i]));
}
return data;
}
return this.jsonData[this.indexOf(node)] || null;
},
beforeRender : function(){
this.snapshot = this.jsonData;
if(this.sortInfo){
this.sort.apply(this, this.sortInfo);
}
this.fireEvent("beforerender", this, this.jsonData);
},
onLoad : function(el, o){
this.fireEvent("load", this, this.jsonData, o);
},
onLoadException : function(el, o){
this.fireEvent("loadexception", this, o);
},
/**
* 指定某个属性,进行数据筛选
* @param {String} 指定JSON对象的某个属性
* @param {String/RegExp} value 既可是属性值的字符串,也可是用来查找属性的正则表达式。
*/
filter : function(property, value){
if(this.jsonData){
var data = [];
var ss = this.snapshot;
if(typeof value == "string"){
var vlen = value.length;
if(vlen == 0){
this.clearFilter();
return;
}
value = value.toLowerCase();
for(var i = 0, len = ss.length; i < len; i++){
var o = ss[i];
if(o[property].substr(0, vlen).toLowerCase() == value){
data.push(o);
}
}
} else if(value.exec){ // regex?
for(var i = 0, len = ss.length; i < len; i++){
var o = ss[i];
if(value.test(o[property])){
data.push(o);
}
}
} else{
return;
}
this.jsonData = data;
this.refresh();
}
},
/**
* 指定一个函数,进行数据筛选。该函数会被当前数据集中的每个对象调用。
* 若函数返回true值,记录值会被保留,否则会被过滤掉,
* otherwise it is filtered.
* @param {Function} fn
* @param {Object} scope (optional) 函数的作用域(默认为JsonView)
*/
filterBy : function(fn, scope){
if(this.jsonData){
var data = [];
var ss = this.snapshot;
for(var i = 0, len = ss.length; i < len; i++){
var o = ss[i];
if(fn.call(scope || this, o)){
data.push(o);
}
}
this.jsonData = data;
this.refresh();
}
},
/**
* 清除当前的筛选
*/
clearFilter : function(){
if(this.snapshot && this.jsonData != this.snapshot){
this.jsonData = this.snapshot;
this.refresh();
}
},
/**
* 对当前的view进行数据排序并刷新
* @param {String} 要排序的那个JSON对象上的属性
* @param {String} (可选的)"升序(desc)"或"降序"(asc)
* @param {Function} 该函数负责将数据转换到可排序的值
*/
sort : function(property, dir, sortType){
this.sortInfo = Array.prototype.slice.call(arguments, 0);
if(this.jsonData){
var p = property;
var dsc = dir && dir.toLowerCase() == "desc";
var f = function(o1, o2){
var v1 = sortType ? sortType(o1[p]) : o1[p];
var v2 = sortType ? sortType(o2[p]) : o2[p];
;
if(v1 < v2){
return dsc ? +1 : -1;
} else if(v1 > v2){
return dsc ? -1 : +1;
} else{
return 0;
}
};
this.jsonData.sort(f);
this.refresh();
if(this.jsonData != this.snapshot){
this.snapshot.sort(f);
}
}
}
}); | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.