code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* 更新地址:http://jstang.cn/docs/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://jstang.cn/thread-90-1-2.html
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/*
* 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;
/**
* @class Ext.dd.DragDrop
* 对于可被拖动(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/DragDrops} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组(DragDrop[])
*/
onDragEnter: function(e, id) { /* override this */ },
/**
* onDragOver事件发生在前执行的代码。
* @method b4DragOver
* @private
*/
b4DragOver: function(e) { },
/**
* 抽象方法:在这个元素悬停在其他DD对象范围内的调用。
* @method onDragOver
* @param {Event} e mousemove事件
* @param {String/DragDrops} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组(DragDrop[])
*/
onDragOver: function(e, id) { /* override this */ },
/**
* onDragOut事件发生之前执行的代码。
* @method b4DragOut
* @private
*/
b4DragOut: function(e) { },
/**
* 抽象方法:当不再有任何悬停DD对象的时候调用。
* @method onDragOut
* @param {Event} e mousemove事件
* @param {String/DragDrops} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组(DragDrop[])
*/
onDragOut: function(e, id) { /* override this */ },
/**
* onDragDrop事件发生之前执行的代码。
* @method b4DragDrop
* @private
*/
b4DragDrop: function(e) { },
/**
* 抽象方法:该项在另外一个DD对象上落下的时候调用。
* @method onDragDrop
* @param {Event} e mouseup事件
* @param {String/DragDrops} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组(DragDrop[])
*/
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 {String} 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 {String} 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 {Array} 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 {string} sGroup 组名称
*/
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 {string} id 将会用于初始拖动的元素id
*/
setDragElId: function(id) {
this.dragElId = id;
},
/**
* 允许你指定一个关联元素下面的子元素以初始化拖动操作。
* 一个例子就是假设你有一段套着div文本和若干连接,点击正文的区域便引发拖动的操作。
* 使用这个方法来指定正文内的div元素,然后拖动操作就会从这个元素开始了。
* @method setHandleElId
* @param {string} id 将会用于初始拖动的元素id
*/
setHandleElId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
this.handleElId = id;
this.DDM.regHandle(this.id, id);
},
/**
* 允许你在关联元素之外设置一个元素作为拖动处理。
* @method setOuterHandleElId
* @param {string} 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} oDD 单击的 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);
}
};
})();
/**
* @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 {int} iPageX 当前X位置(可选的),只要为了以后不用再查询
* @param {int} 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
* @extends Ext.dd.DD
* 一种拖放的实现,把一个空白的、带边框的div插入到文档,并会伴随着鼠标指针移动。
* 当点击那一下发生,边框div会调整大小到关联html元素的尺寸大小,然后移动到关联元素的位置。
* “边框”元素的引用指的是页面上我们创建能够被DDProxy元素拖动到的地方的单个代理元素。
* @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
* @extends Ext.dd.DragDrop
* 一种拖放的实现,不能移动,但可以置下目标,对于事件回调,省略一些简单的实现也可得到相同的结果。
* 但这样降低了event listener和回调的处理成本。
* @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);
}
});
/**
* @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} oDD 拖动对象
* @param {DragDrop} oTargetDD 目标
* @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} oDD 要计算的对象
* @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 {DragDrop} 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 {int} x 原始mousedown发生的X位置
* @param {int} y 原始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 {DragDrops} dds 拖放对象之数组DragDrop[]
* 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;
},
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 {Object} el 指获取坐标的元素
* @static
*/
getPosX: function(el) {
return Ext.lib.Dom.getX(el);
},
/**
* 返回html元素的Y坐标。
* @method getPosY
* @param {Object} el 指获取坐标的元素
* @return {int} y坐标
* @deprecated 推荐使用Ext.lib.Dom.getY
* @static
*/
getPosY: function(el) {
return Ext.lib.Dom.getY(el);
},
/**
* 调换两个节点,对于IE,我们使用原生的方法。
* @method swapNode
* @param {Objbect} n1 要调换的第一个节点
* @param {Objbect} 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 {Object} 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;
}
};
}();
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.dd.DragTracker
* Ext.dd.DragTracker类
*/
Ext.dd.DragTracker = function(config){
Ext.apply(this, config);
this.addEvents(
'mousedown',
'mouseup',
'mousemove',
'dragstart',
'dragend',
'drag'
);
this.dragRegion = new Ext.lib.Region(0,0,0,0);
if(this.el){
this.initEl(this.el);
}
}
Ext.extend(Ext.dd.DragTracker, Ext.util.Observable, {
active: false,
tolerance: 5,
autoStart: false,
initEl: function(el){
this.el = Ext.get(el);
el.on('mousedown', this.onMouseDown, this,
this.delegate ? {delegate: this.delegate} : undefined);
},
destroy : function(){
this.el.un('mousedown', this.onMouseDown, this);
},
onMouseDown: function(e, target){
if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){
this.startXY = this.lastXY = e.getXY();
this.dragTarget = this.delegate ? target : this.el.dom;
if(this.preventDefault !== false){
e.preventDefault();
}
var doc = Ext.getDoc();
doc.on('mouseup', this.onMouseUp, this);
doc.on('mousemove', this.onMouseMove, this);
doc.on('selectstart', this.stopSelect, this);
if(this.autoStart){
this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this);
}
}
},
onMouseMove: function(e, target){
e.preventDefault();
var xy = e.getXY(), s = this.startXY;
this.lastXY = xy;
if(!this.active){
if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){
this.triggerStart();
}else{
return;
}
}
this.fireEvent('mousemove', this, e);
this.onDrag(e);
this.fireEvent('drag', this, e);
},
onMouseUp: function(e){
var doc = Ext.getDoc();
doc.un('mousemove', this.onMouseMove, this);
doc.un('mouseup', this.onMouseUp, this);
doc.un('selectstart', this.stopSelect, this);
e.preventDefault();
this.clearStart();
var wasActive = this.active;
this.active = false;
delete this.elRegion;
this.fireEvent('mouseup', this, e);
if(wasActive){
this.onEnd(e);
this.fireEvent('dragend', this, e);
}
},
triggerStart: function(isTimer){
this.clearStart();
this.active = true;
this.onStart(this.startXY);
this.fireEvent('dragstart', this, this.startXY);
},
clearStart : function(){
if(this.timer){
clearTimeout(this.timer);
delete this.timer;
}
},
stopSelect : function(e){
e.stopEvent();
return false;
},
onBeforeStart : function(e){
},
onStart : function(xy){
},
onDrag : function(e){
},
onEnd : function(e){
},
getDragTarget : function(){
return this.dragTarget;
},
getDragCt : function(){
return this.el;
},
getXY : function(constrain){
return constrain ?
this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY;
},
getOffset : function(constrain){
var xy = this.getXY(constrain);
var s = this.startXY;
return [s[0]-xy[0], s[1]-xy[1]];
},
constrainModes: {
'point' : function(xy){
if(!this.elRegion){
this.elRegion = this.getDragCt().getRegion();
}
var dr = this.dragRegion;
dr.left = xy[0];
dr.top = xy[1];
dr.right = xy[0];
dr.bottom = xy[1];
dr.constrainTo(this.elRegion);
return [dr.left, dr.top];
}
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.dd.DropZone
* @extends Ext.dd.DropTarget
* <p>对于多个子节点的目标,该类提供一个DD实例的容器(扮演代理角色)。This class provides a container DD instance that allows dropping on multiple child target nodes.</p>
* <p>默认地,该类需要一个可拖动的子节点,并且需在{@link Ext.dd.Registry}登记好的。By default, this class requires that child nodes accepting drop are registered with {@link Ext.dd.Registry}.
* However a simpler way to allow a DropZone to manage any number of target elements is to configure the
* DropZone with an implementation of {@link #getTargetFromEvent} which interrogates the passed
* mouse event to see if it has taken place within an element, or class of elements. This is easily done
* by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
* {@link Ext.DomQuery} selector.</p>
* <p>Once the DropZone has detected through calling getTargetFromEvent, that the mouse is over
* a drop target, that target is passed as the first parameter to {@link #onNodeEnter}, {@link #onNodeOver},
* {@link #onNodeOut}, {@link #onNodeDrop}. You may configure the instance of DropZone with implementations
* of these methods to provide application-specific behaviour for these events to update both
* application state, and UI state.</p>
* <p>For example to make a GridPanel a cooperating target with the example illustrated in
* {@link Ext.dd.DragZone DragZone}, the following technique might be used:</p><pre><code>
myGridPanel.on('render', function() {
myGridPanel.dropZone = new Ext.dd.DropZone(myGridPanel.getView().scroller, {
// If the mouse is over a grid row, return that node. This is
// provided as the "target" parameter in all "onNodeXXXX" node event handling functions
getTargetFromEvent: function(e) {
return e.getTarget(myGridPanel.getView().rowSelector);
},
// On entry into a target node, highlight that node.
onNodeEnter : function(target, dd, e, data){
Ext.fly(target).addClass('my-row-highlight-class');
},
// On exit from a target node, unhighlight that node.
onNodeOut : function(target, dd, e, data){
Ext.fly(target).removeClass('my-row-highlight-class');
},
// While over a target node, return the default drop allowed class which
// places a "tick" icon into the drag proxy.
onNodeOver : function(target, dd, e, data){
return Ext.dd.DropZone.prototype.dropAllowed;
},
// On node drop we can interrogate the target to find the underlying
// application object that is the real target of the dragged data.
// In this case, it is a Record in the GridPanel's Store.
// We can use the data set up by the DragZone's getDragData method to read
// any data we decided to attach in the DragZone's getDragData method.
onNodeDrop : function(target, dd, e, data){
var rowIndex = myGridPanel.getView().findRowIndex(target);
var r = myGridPanel.getStore().getAt(rowIndex);
Ext.Msg.alert('Drop gesture', 'Dropped Record id ' + data.draggedRecord.id +
' on Record id ' + r.id);
return true;
}
});
}
</code></pre>
* See the {@link Ext.dd.DragZone DragZone} documentation for details about building a DragZone which
* cooperates with this DropZone.
* @constructor
* @param {Mixed} 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}中查找对象,但是你亦可以根据自身的需求,重写该方法。
* Returns a custom data object associated with the DOM node that is the target of the event. By default
* this looks up the event target in the {@link Ext.dd.Registry}, although you can override this method to
* provide your own custom lookup.
* @param {Event} e 事件对象The event
* @return {Object} data 自定义数据The custom data
*/
getTargetFromEvent : function(e){
return Ext.dd.Registry.getTargetFromEvent(e);
},
/**
* 当DropZone确定有一个{@link Ext.dd.DragSource},已经进入一个已登记的落下节点(drop node)的范围内,就会调用。
* 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。
* Called when the DropZone determines that a {@link Ext.dd.DragSource} has entered a drop node
* that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
* This method has no default implementation and should be overridden to provide
* node-specific processing if necessary.
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)The custom data associated with the drop node (this is the same value returned from
* {@link #getTargetFromEvent} for this node)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
*/
onNodeEnter : function(n, dd, e, data){
},
/**
* 当DropZone确定有一个{@link Ext.dd.DragSource},已经位于一个已登记的落下节点(drop node)的上方时,就会调用。
* 默认的实现是返回this.dropAllowed。因此应该重写它以便提供合适的反馈。
* Called while the DropZone determines that a {@link Ext.dd.DragSource} is over a drop node
* that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
* The default implementation returns this.dropNotAllowed, so it should be
* overridden to provide the proper feedback.
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)The custom data associated with the drop node (this is the same value returned from
* {@link #getTargetFromEvent} for this node)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。The CSS class that communicates the drop status back to the source so that the
* underlying {@link Ext.dd.StatusProxy} can be updated
*/
onNodeOver : function(n, dd, e, data){
return this.dropAllowed;
},
/**
* 当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经离开一个已登记的落下节点(drop node)的范围内,就会调用。
* 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。
* Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dragged out of
* the drop node without dropping. This method has no default implementation and should be overridden to provide
* node-specific processing if necessary.
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)The custom data associated with the drop node (this is the same value returned from
* {@link #getTargetFromEvent} for this node)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
*/
onNodeOut : function(n, dd, e, data){
},
/**
* 当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经在一个已登记的落下节点(drop node)落下的时候,就会调用。
* 默认的方法返回false,应提供一个合适的实现来处理落下的事件,重写该方法,
* 并返回true值,说明拖放行为有效,拖动源的修复动作便不会进行。
* Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped onto
* the drop node. The default implementation returns false, so it should be overridden to provide the
* appropriate processing of the drop event and return true so that the drag source's repair action does not run.
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)The custom data associated with the drop node (this is the same value returned from
* {@link #getTargetFromEvent} for this node)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {Boolean} 有效的落下返回true否则为falseTrue if the drop was valid, else false
*/
onNodeDrop : function(n, dd, e, data){
return false;
},
/**
* 当DrapZone发现有一个{@link Ext.dd.DragSource}正处于其上方时,但是没有放下任何落下的节点时调用。
* 默认的实现是返回this.dropNotAllowed,如需提供一些合适的反馈,应重写该函数。
* Called while the DropZone determines that a {@link Ext.dd.DragSource} is being dragged over it,
* but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
* it should be overridden to provide the proper feedback if necessary.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。The CSS class that communicates the drop status back to the source so that the
* underlying {@link Ext.dd.StatusProxy} can be updated
*/
onContainerOver : function(dd, e, data){
return this.dropNotAllowed;
},
/**
* 当DrapZone确定{@link Ext.dd.DragSource}落下的动作已经执行,但是没有放下任何落下的节点时调用。
* 欲将DropZone本身也可接收落下的行为,应提供一个合适的实现来处理落下的事件,重写该方法,并返回true值,
* 说明拖放行为有效,拖动源的修复动作便不会进行。默认的实现返回false。
* Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped on it,
* but not on any of its registered drop nodes. The default implementation returns false, so it should be
* overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
* be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {Boolean} 有效的落下返回true否则为falseTrue if the drop was valid, else false
*/
onContainerDrop : function(dd, e, data){
return false;
},
/**
* 通知DropZone源已经在Zone上方的函数。
* 默认的实现返回this.dropNotAllowed,一般说只有登记的落下节点可以处理拖放操作。
* 欲将DropZone本身也可接收落下的行为,应提供一个自定义的实现,重写该方法。
* The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source is now over
* the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
* nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
* you should override this method and provide a custom implementation.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。The CSS class that communicates the drop status back to the source so that the
* underlying {@link Ext.dd.StatusProxy} can be updated
*/
notifyEnter : function(dd, e, data){
return this.dropNotAllowed;
},
/**
* 当{@link Ext.dd.DragSource}在DropZone范围内时,拖动过程中不断调用的函数。
* 拖动源进入DropZone后,进入每移动一下鼠标都会调用该方法。
* 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onNodeOver},
* 如果拖动源进入{@link #onNodeEnter},{@link #onNodeOut}这样已登记的节点,通知过程会按照需要自动进行指定的节点处理,
* 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onContainerOver}。
* The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the drop zone.
* This method will be called on every mouse movement while the drag source is over the drop zone.
* It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
* delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
* registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
* registered node, it will call {@link #onContainerOver}.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。The CSS class that communicates the drop status back to the source so that the
* underlying {@link Ext.dd.StatusProxy} can be updated
*/
notifyOver : function(dd, e, data){
var n = this.getTargetFromEvent(e);
if(!n){ // not over valid 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}进行指定的节点处理,否则的话会被忽略。
* The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source has been dragged
* out of the zone without dropping. If the drag source is currently over a registered node, the notification
* will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop target
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源地区规定格式的数据对象An object containing arbitrary data supplied by the drag zone
*/
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}。
* The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the dragged item has
* been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
* is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
* otherwise it will call {@link #onContainerDrop}.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源The drag source that was dragged over this drop zone
* @param {Event} e 事件对象The event
* @param {Object} data 由拖动源规定格式的数据对象An object containing arbitrary data supplied by the drag source
* @return {Boolean} 有效的落下返回true否则为falseTrue if the drop was valid, else 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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @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"){ // must be element?
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"){ // must be element?
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.dd.DragZone
* @extends Ext.dd.DragSource
* <p>该类继承了{@link Ext.dd.DragSource},对于多节点的源,该类提供了一个DD实理容器来代理。
* This class provides a container DD instance that allows dragging of multiple child source nodes.</p>
* <p>This class does not move the drag target nodes, but a proxy element which may contain
* any DOM structure you wish. The DOM element to show in the proxy is provided by either a
* provided implementation of {@link #getDragData}, or by registered draggables registered with {@link Ext.dd.Registry}</p>
* <p>If you wish to provide draggability for an arbitrary number of DOM nodes, each of which represent some
* application object (For example nodes in a {@link Ext.DataView DataView}) then use of this class
* is the most efficient way to "activate" those nodes.</p>
* <p>
* 默认情况下,该类要求可拖动的子节点已在{@link Ext.dd.Registry}类中全部注册。
* By default, this class requires that draggable child nodes are registered with {@link Ext.dd.Registry}.
* However a simpler way to allow a DragZone to manage any number of draggable elements is to configure
* the DragZone with an implementation of the {@link #getDragData} method which interrogates the passed
* mouse event to see if it has taken place within an element, or class of elements. This is easily done
* by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
* {@link Ext.DomQuery} selector. For example, to make the nodes of a DataView draggable, use the following
* technique. Knowledge of the use of the DataView is required:</p>
* <pre><code>
myDataView.on('render', function() {
myDataView.dragZone = new Ext.dd.DragZone(myDataView.getEl(), {
// On receipt of a mousedown event, see if it is within a DataView node.
// Return a drag data object if so.
getDragData: function(e) {
// Use the DataView's own itemSelector (a mandatory property) to
// test if the mousedown is within one of the DataView's nodes.
var sourceEl = e.getTarget(myDataView.itemSelector, 10);
// If the mousedown is within a DataView node, clone the node to produce
// a ddel element for use by the drag proxy. Also add application data
// to the returned data object.
if (sourceEl) {
d = sourceEl.cloneNode(true);
d.id = Ext.id();
return {
ddel: d,
sourceEl: sourceEl,
repairXY: Ext.fly(sourceEl).getXY(),
sourceStore: myDataView.store,
draggedRecord: v.getRecord(sourceEl)
}
}
},
// Provide coordinates for the proxy to slide back to on failed drag.
// This is the original XY coordinates of the draggable element captured
// in the getDragData method.
getRepairXY: function() {
return this.dragData.repairXY;
}
});
});</code></pre>
* See the {@link Ext.dd.DropZone DropZone} documentation for details about building a DropZone which
* cooperates with this DragZone.
* @constructor
* @param {Mixed} 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, {
/**
* This property contains the data representing the dragged object. This data is set up by the implementation
* of the {@link #getDragData} method. It must contain a <tt>ddel</tt> property, but can contain
* any other data according to the application's needs.
* @type Object
* @property dragData
*/
/**
* @cfg {Boolean} containerScroll 设为True 用来将此容器在Scrollmanager上注册,使得在拖动操作发生时可以自动卷动。
* True to register this container with the Scrollmanager
* for auto scrolling during drag operations.
*/
/**
* @cfg {String} hlColor 第二个参数:hlColor 用于在一次失败的拖动操作后调用afterRepair方法会用在此设定的颜色(默认颜色为亮蓝"c3daf9")来标识可见的拽源
* The color to use when visually highlighting the drag source in the afterRepair
* method after a failed drop (defaults to "c3daf9" - light blue)
*/
/**
* 该方法会在鼠标位于该容器内按下时触发,个中机制可参照类{@link Ext.dd.Registry},因为有效的拖动目标是以获取鼠标按下事件为前提的。<br/>
* 如果想实现自己的查找方式(如根据类名查找子对象),可以重载这个方法,但是必须确保该方法返回的对象有一个"ddel"属性(属性的值是一个HTML元素),以便函数能正常工作。<br/>
* Called when a mousedown occurs in this container. Looks in {@link Ext.dd.Registry}
* for a valid target to drag based on the mouse down. Override this method
* to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
* object has a "ddel" attribute (with an HTML Element) for other functions to work.
* @param {EventObject} e 鼠标按下事件The mouse down event
* @return {Object} 被拖拽对象The dragData
*/
getDragData : function(e){
return Ext.dd.Registry.getHandleFromEvent(e);
},
/**
* 该方法在拖拽动作开始,初始化代理元素时调用,默认情况下,它克隆了this.dragData.ddel。
* Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
* this.dragData.ddel.
* @param {Number} x 被点击的拖拽对象的X坐标The x position of the click on the dragged object
* @param {Number} y 被点击的拖拽对象的y坐标The y position of the click on the dragged object
* @return {Boolean} 该方法返回一个布尔常量,当返回true时,表示继续(保持)拖拽,返回false时,表示取消拖拽true to continue the drag, false to cancel
*/
onInitDrag : function(x, y){
this.proxy.update(this.dragData.ddel.cloneNode(true));
this.onStartDrag(x, y);
return true;
},
/**
* 该方法在修复无效的drop操作后调用。默认情况下,高亮显示this.dragData.ddel。
* Called after a repair of an invalid drop. By default, highlights 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属性
* Called before a repair of an invalid drop to get the XY to animate to. By default returns
* the XY of this.dragData.ddel
* @param {EventObject} e 鼠标松开事件The mouse up event
* @return {Array} 区域的xy位置 (例如: [100, 200])The xy location (e.g. [100, 200])
*/
getRepairXY : function(e){
return Ext.Element.fly(this.dragData.ddel).getXY();
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Tree
* @extends Ext.util.Observable
* 该对象抽象了一棵树的结构和树节点的事件上报。树包含的节点拥有大部分的DOM功能。<br />
* 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 = function(root){
this.nodeHash = {};
/**
* 该树的根节点。The root node for this tree
* @type Node
* @property root
*/
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",
/**
* @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",
/**
* @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",
/**
* @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",
/**
* @event beforeappend
* 当树中有新的子节点添加到某个节点上之前触发,返回false表示取消这个添加行动。
* 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",
/**
* @event beforeremove
* 当树中有节点移动到新的地方之前触发,返回false表示取消这个移动行动。
* 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",
/**
* @event beforemove
* 当树中有新的子节点移除到某个节点上之前触发,返回false表示取消这个移除行动。
* 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",
/**
* @event beforeinsert
* 当树中有新的子节点插入某个节点之前触发,返回false表示取消这个插入行动。
* 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"
);
Ext.data.Tree.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Tree, Ext.util.Observable, {
/**
* @cfg {String} pathSeparator 分割节点Id的标识符(默认为"/")。
* The token used to separate paths in node ids (defaults to '/').
*/
pathSeparator: "/",
// private
proxyNodeEvent : function(){
return this.fireEvent.apply(this, arguments);
},
/**
* 为这棵树返回根节点。
* Returns the root node for this tree.
* @return {Node}
*/
getRootNode : function(){
return this.root;
},
/**
* 设置这棵树的根节点。
* Sets the root node for this tree.
* @param {Node} node 节点
* @return {Node}
*/
setRootNode : function(node){
this.root = node;
node.ownerTree = this;
node.isRoot = true;
this.registerNode(node);
return node;
},
/**
* 根据ID查找节点。
* Gets a node in this tree by its id.
* @param {String} id
* @return {Node}
*/
getNodeById : function(id){
return this.nodeHash[id];
},
// private
registerNode : function(node){
this.nodeHash[node.id] = node;
},
// private
unregisterNode : function(node){
delete this.nodeHash[node.id];
},
toString : function(){
return "[Tree"+(this.id?" "+this.id:"")+"]";
}
});
/**
* @class Ext.data.Node
* @extends Ext.util.Observable
* @cfg {Boolean} leaf true表示该节点是树叶节点没有子节点。
* true if this node is a leaf and does not have children
* @cfg {String} id 该节点的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 = function(attributes){
/**
* 节点属性。你可以在此添加任意的自定义的属性。
* The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
* @type Object
* @property attributes
*/
this.attributes = attributes || {};
this.leaf = this.attributes.leaf;
/**
* 节点ID。The node id.
* @type String
* @property id
*/
this.id = this.attributes.id;
if(!this.id){
this.id = Ext.id(null, "xnode-");
this.attributes.id = this.id;
}
/**
* 此节点的所有子节点。
* All child nodes of this node.
* @type Array
* @property childNodes
*/
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
* @property parentNode
*/
this.parentNode = null;
/**
* 该节点下面最前一个子节点(直属的),null的话就表示这是没有子节点的。
* The first direct child node of this node, or null if this node has no child nodes.
* @type Node
* @property firstChild
*/
this.firstChild = null;
/**
* 该节点下面最后一个子节点(直属的),null的话就表示这是没有子节点的。
* The last direct child node of this node, or null if this node has no child nodes.
* @type Node
* @property lastChild
*/
this.lastChild = null;
/**
* 该节点前面一个节点,同级的,null的话就表示这没有侧边节点。
* The node immediately preceding this node in the tree, or null if there is no sibling node.
* @type Node
* @property previousSibling
*/
this.previousSibling = null;
/**
* 该节点后面一个节点,同级的,null的话就表示这没有侧边节点。
* The node immediately following this node in the tree, or null if there is no sibling node.
* @type Node
* @property nextSibling
*/
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" : 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" : 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" : 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" : true,
/**
* @event beforeappend
* 当有新的子节点被添加时触发,返回false就取消添加。
* 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" : true,
/**
* @event beforeremove
* 当有子节点被移出的时候触发,返回false就取消移出。
* 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" : true,
/**
* @event beforemove
* 当该节点移动到树下面的另外一个新位置的时候触发。返回false就取消移动。
* 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" : true,
/**
* @event beforeinsert
* 当有新的节点插入时触发,返回false就取消插入。
* 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" : true
});
this.listeners = this.attributes.listeners;
Ext.data.Node.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Node, Ext.util.Observable, {
// private
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;
},
/**
* 若节点是叶子节点的话返回true。
* Returns true if this node is a leaf
* @return {Boolean}
*/
isLeaf : function(){
return this.leaf === true;
},
// private
setFirstChild : function(node){
this.firstChild = node;
},
//private
setLastChild : function(node){
this.lastChild = node;
},
/**
* 如果这个节点是其父节点下面的最后一个节点的话返回true。
* Returns true if this node is the last child of its parent
* @return {Boolean}
*/
isLast : function(){
return (!this.parentNode ? true : this.parentNode.lastChild == this);
},
/**
* 如果这个节点是其父节点下面的第一个节点的话返回true。
* Returns true if this node is the first child of its parent
* @return {Boolean}
*/
isFirst : function(){
return (!this.parentNode ? true : this.parentNode.firstChild == this);
},
/**
* 如果有子节点返回true。
* Returns true if this node has one or more child nodes, else false.
* @return {Boolean}
*/
hasChildNodes : function(){
return !this.isLeaf() && this.childNodes.length > 0;
},
/**
* 如果该节点有一个或多个的子节点,或其节点<tt>可展开的</tt>属性是明确制定为true的话返回true。
* Returns true if this node has one or more child nodes, or if the <tt>expandable</tt>
* node attribute is explicitly specified as true (see {@link #attributes}), otherwise returns false.
* @return {Boolean}
*/
isExpandable : function(){
return this.attributes.expandable || this.hasChildNodes();
},
/**
* 在该节点里面最后的位置上插入节点,可以多个。
* 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} 如果是单个节点,加入后返回true,如果是数组返回null。The appended node if single append, or null if an array was passed
*/
appendChild : function(node){
var multi = false;
if(Ext.isArray(node)){
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
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
*/
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 要插入的节点。he node to insert
* @param {Node} refNode 前面插入的节点(如果为null表示节点是追加的)。The node to insert before (if null the node is appended)
* @return {Node} 插入的节点。The inserted 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
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;
},
/**
* 从父节点上移除子节点。
* Removes this node from its parent
* @return {Node} this
*/
remove : function(){
this.parentNode.removeChild(this);
return this;
},
/**
* 指定索引,在自节点中查找匹配索引的节点。
* Returns the child node at the specified index.
* @param {Number} index
* @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
*/
replaceChild : function(newChild, oldChild){
var s = oldChild ? oldChild.nextSibling : null;
this.removeChild(oldChild);
this.insertBefore(newChild, s);
return oldChild;
},
/**
* 返回某个子节点的索引。
* Returns the index of a child node
* @param {Node} node 节点
* @return {Number} 节点的索引或是-1表示找不到。The index of the node or -1 if it was not found
*/
indexOf : function(child){
return this.childNodes.indexOf(child);
},
/**
* 返回节点所在的树对象。
* Returns the tree this node is in.
* @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;
},
/**
* 返回该节点的深度(根节点的深度是0)。
* Returns depth of this node (the root node has a depth of 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 is a 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);
}
}
},
/**
* 改变该节点的id
* Changes the id of this node.
* @param {String} id 节点的新id。The new id for the node.
*/
setId: function(id){
if(id !== this.id){
var t = this.ownerTree;
if(t){
t.unregisterNode(this);
}
this.id = id;
if(t){
t.registerNode(this);
}
this.onIdChange(id);
}
},
// private
onIdChange: Ext.emptyFn,
/**
* 返回该节点的路径,以方便控制这个节点展开或选择。
* Returns the path for this node. The path can be used to expand or select this node programmatically.
* @param {String} attr(可选的)路径采用的属性(默认为节点的id)。 (optional) The attr to use for the path (defaults to the node's id)
* @return {String} 路径。The path
*/
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)节点,上报过程中对每个节点执行指定的函数。
* 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。
* 函数的参数可经由args指定或当前节点,如果函数在某一个层次上返回false,上升将会停止。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)
*/
bubble : function(fn, scope, args){
var p = this;
while(p){
if(fn.apply(scope || p, args || [p]) === false){
break;
}
p = p.parentNode;
}
},
/**
* 从该节点开始逐层下报(Bubbles up)节点,上报过程中对每个节点执行指定的函数。
* 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。
* 函数的参数可经由args指定或当前节点,如果函数在某一个层次上返回false,下升到那个分支的位置将会停止。
* 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)
*/
cascade : function(fn, scope, args){
if(fn.apply(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);
}
}
},
/**
* 遍历该节点下的子节点,枚举过程中对每个节点执行指定的函数。函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。
* 函数的参数可经由args指定或当前节点,如果函数走到某处地方返回false,遍历将会停止。
* 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)
*/
eachChild : function(fn, scope, args){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(fn.apply(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} 已找到的子节点或null表示找不到。The found child or null if none was found
*/
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;
},
/**
* 通过自定义的函数查找子节点,找到第一个合适的就返回。要求的条件是函数返回true。
* 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} 找到的子元素或null就代表没找到。The found child or null if none was found
*/
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)
*/
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);
}
}
}
},
/**
* 返回true表示为该节点是送入节点的祖先节点(无论在哪那一级的)。
* Returns true if this node is an ancestor (at any point) of the passed node.
* @param {Node} node 节点
* @return {Boolean}
*/
contains : function(node){
return node.isAncestor(this);
},
/**
* 返回true表示为送入的节点是该的祖先节点(无论在哪那一级的)。
* Returns true if the passed node is an ancestor (at any point) of this node.
* @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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.DataProxy
* @extends Ext.util.Observable
* <p>
* 一个抽象的基类,只提供获取未格式化的原始数据。<br />
* This class is an abstract base class for implementations which provide retrieval of unformatted data objects.
* </p>
* <p>
* DataProxy的实现通常用于连接Ext.data.DataReader的实现(以适当的类型去解析数据对象)来一同协作,向一{@link Ext.data.Store}提供{@link Ext.data.Records}块。<br />
* 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}.
* </p>
* 自定义子类的实现必须符合{@link Ext.data.HttpProxy#load}方法那般的实现。<br />
* Custom implementations must implement the load method as described in {@link Ext.data.HttpProxy#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
* @param {Object} params 送入{@link #load}函数的参数对象。The params object passed to the {@link #load} function
*/
'beforeload',
/**
* @event load
* 当load方法的回调执行后触发。
* Fires before the load method's callback is called.
* @param {Object} this DataProxy
* @param {Object} o 数据对象。The data object
* @param {Object} arg 送入{@link #load}函数的回调参数对象。The callback's arg object passed to the {@link #load} function
*/
'load'
);
Ext.data.DataProxy.superclass.constructor.call(this);
};
Ext.extend(Ext.data.DataProxy, Ext.util.Observable); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Store
* @extends Ext.util.Observable
* Store类封装了一个客户端的{@link Ext.data.Record Record}对象的缓存,
* 为诸如{@link Ext.grid.GridPanel GridPanel}、{@link Ext.form.ComboBox ComboBox}和{@link Ext.DataView DataView}等的小部件提供了数据的入口。<br />
* The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
* objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
* the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}<br>
*
* <p>
* Store对象使用一个{@link Ext.data.DataProxy DataProxy}的实现来访问数据对象,该Proxy对象在{@link #proxy configured}定义。
* 不过你可以调用{@link #loadData}直接地把数据对象传入你的数据。<br />
* A Store object uses its {@link #proxy configured} implementation of {@link Ext.data.DataProxy DataProxy}
* to access a data object unless you call {@link #loadData} directly and pass in your data.</p>
*
* <p>Store没有储存关于Proxy返回数据格式的信息。<br />
* A Store object has no knowledge of the format of the data returned by the Proxy.</p>
*
* <p>
* 在{@link Ext.data.DataReader DataReader}实现的帮助下,从该类提供的数据对象来创建{@link Ext.data.Record Record}实例。
* 你可在{@link #reader configured}指定这个DataReader对象。这些records都被缓存的并且通过访问器函数可利用到。<br />
* A Store object uses its {@link #reader configured} implementation of {@link Ext.data.DataReader DataReader}
* to create {@link Ext.data.Record Record} instances from the data object. These Records
* are cached and made available through accessor functions.</p>
* @constructor 创建新的Store对象。Creates a new Store.
* @param {Object} config 一配置对象,包含了Store用来访问数据,及读数据至Records的对象。A config object containing the objects needed for the Store to access data,
* and read the data into Records.
*/
Ext.data.Store = function(config){
this.data = new Ext.util.MixedCollection(false);
this.data.getKey = function(o){
return o.id;
};
/**
* 每次HTTP请求都会携带的参数,就保存在这个对象身上。
* An object containing properties which are used as parameters on any HTTP request.
* @type Object
* @property baseParams
*/
this.baseParams = {};
/**
* <p>
* 当进行服务端分页的时候,加载分页数据所必须的分页参数是什么和排序参数是什么。
* 默认下是这样的:<br />
* An object containing properties which specify the names of the paging and
* sorting parameters passed to remote servers when loading blocks of data. By default, this
* object takes the following form:</p><pre><code>
{
start : "start", // 指定哪一行开始的参数是什么。The parameter name which specifies the start row
limit : "limit", // 指定读取的行数的参数是什么。The parameter name which specifies number of rows to return
sort : "sort", // 指定哪一列进行排序的参数是什名。The parameter name which specifies the column to sort on
dir : "dir" // 指定哪一个方向排序的参数时什么。The parameter name which specifies the sort direction
}
</code></pre>
* <p>
* 服务端就必须清楚这些参数名称是作何种用途的。
* 如果有不同的参数名称,在配置的时候覆盖对象的值便可。<br />
* The server must produce the requested data block upon receipt of these parameter names.
* If different parameter names are required, this property can be overriden using a configuration
* property.</p>
* 绑定在这个Grid的{@link Ext.PagingToolbar PagingToolbar}就使用这些配置来分页。请求中将会使用到。<br />
* A {@link Ext.PagingToolbar PagingToolbar} bound to this grid uses this property to determine
* the parameter names to use in its requests.
* @type Object
* @property paramNames
*/
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.url && !this.proxy){
this.proxy = new Ext.data.HttpProxy({url: this.url});
}
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
* 当有批量操作的时候,也就是数据发生改动的时候触发(如进行了排序、过滤的操作)。
* 使用该Store应该的UI应该有所响应,如刷新其视图。<br />
* Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
* widget that is using this Store as a Record cache should refresh its view.
* @param {Store} this Ext.data.Store
*/
'datachanged',
/**
* @event metachange
* 当Store的Reader对象有提供新的元数据(也就是新字段)时触发。当前只对JsonReaders有效。
* Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
* @param {Store} this Ext.data.Store
* @param {Object} meta JSON格式的元数据。The JSON metadata
*/
'metachange',
/**
* @event add
* 当有Record添加到Store里面后触发。
* Fires when Records have been added to the Store
* @param {Store} this Ext.data.Store
* @param {Ext.data.Record} records 加入的Record数组(Ext.data.Record[])。The array of Records added
* @param {Number} index 添加Record的索引。The index at which the record(s) were added
*/
'add',
/**
* @event remove
* 当Store中的Record被移除后触发。
* Fires when a Record has been removed from the Store
* @param {Store} this
* @param {Ext.data.Record} record 那个被移出的RecordThe Record that was removed
* @param {Number} index 移出Record的索引。The index at which the record was removed
*/
'remove',
/**
* @event update
* 当有Record改动时触发。
* Fires when a Record has been updated
* @param {Store} this
* @param {Ext.data.Record} 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>
*/
'update',
/**
* @event clear
* 当数据缓存被清除的时候触发。
* Fires when the data cache has been cleared.
* @param {Store} this
*/
'clear',
/**
* @event beforeload
* 当请求新的数据对象之前触发。如果beforeload返回false表示load的操作被取消。
* 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 所指定的laoding操作(请参阅{@link #load}了解更多)。The loading options that were specified (see {@link #load} for details)
*/
'beforeload',
/**
* @event load
* 当一笔新的Record加载完毕后触发。
* Fires after a new set of Records has been loaded.
* @param {Store} this
* @param {Ext.data.Record} records 加载好的Record(Ext.data.Record[])。The Records that were loaded
* @param {Object} options 所指定的laoding操作(请参阅{@link #load}了解更多)。The loading options that were specified (see {@link #load} for details)
*/
'load',
/**
* @event loadexception
* 当Proxy加载过程中有异常时触发。连同Proxy“loadexception”的事件一起触发。
* Fires if an exception occurs in the Proxy during loading.
* Called with the signature of the Proxy's "loadexception" event.
*/
'loadexception'
);
if(this.proxy){
this.relayEvents(this.proxy, ["loadexception"]);
}
this.sortToggle = {};
if(this.sortField){
this.setDefaultSort(this.sortField, this.sortDir);
}else if(this.sortInfo){
this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
}
Ext.data.Store.superclass.constructor.call(this);
if(this.storeId || this.id){
Ext.StoreMgr.register(this);
}
if(this.inlineData){
this.loadData(this.inlineData);
delete this.inlineData;
}else if(this.autoLoad){
this.load.defer(10, this, [
typeof this.autoLoad == 'object' ?
this.autoLoad : undefined]);
}
};
Ext.extend(Ext.data.Store, Ext.util.Observable, {
/**
* @cfg {String} storeId 如果有值传入,该ID用于在StoreMgr登记时用。
* storeId If passed, the id to use to register with the StoreMgr
*/
/**
* @cfg {String} url 如果有值传入,会为该URL创建一个HttpProxy对象。
* url If passed, an HttpProxy is created for the passed URL
*/
/**
* @cfg {Boolean/Object} autoLoad 如果有值传入,那么store的load会自动调用,发生在autoLoaded对象创建之后。
* autoLoad If passed, this store's load method is automatically called after creation with the autoLoad object
*/
/**
* @cfg {Ext.data.DataProxy} proxy Proxy对象,用于访问数据对象。
* proxy The Proxy object which provides access to a data object.
*/
/**
* @cfg {Array} data 表示store初始化后,要加载的内联数据。
* data Inline data to be loaded when the store is initialized.
*/
/**
* @cfg {Ext.data.DataReader} reader 处理数据对象的DataReader会返回一个Ext.data.Record对象的数组。其中的<em>id</em>属性会是一个缓冲了的键。
* reader The DataReader 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 {Object} baseParams 每次HTTP请求都会带上这个参数,本来它是一个对象的形式,请求时会转化为参数的字符串。
* baseParams An object containing properties which are to be sent as parameters
* on any HTTP request
*/
/**
* @cfg {Object} sortInfo 如何排序的对象,格式如下:{field: "fieldName", direction: "ASC|DESC"}。排序方向的大小写敏感的。
* sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"} to
* specify the sort order in the request of a remote Store's {@link #load} operation. Note that for
* local sorting, the direction property is case-sensitive.
*/
/**
* @cfg {boolean} remoteSort True表示在proxy配合下,要求服务器提供一个更新版本的数据对象以便排序,反之就是在Record缓存中排序(默认是false)。
* 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).
* <p>如果开启远程排序,那么点击头部时就会使当前页面向服务器请求排序,会有以下的参数:
* If remote sorting is specified, then clicking on a column header causes the
* current page to be requested from the server with the addition of the following
* two parameters:
* <div class="mdetail-params"><ul>
* <li><b>sort</b> : String<p class="sub-desc">要排序的字段字符串(即在Record对象内的字段定义)
* The name (as specified in
* the Record's Field definition) of the field to sort on.</p></li>
* <li><b>dir</b> : String<p class="sub-desc">排序的方向,“ASC”或“DESC”(一定要大写)
* The direction of the sort, "ASC" or "DESC" (case-sensitive).</p></li>
* </ul></div></p>
*/
remoteSort : false,
/**
* @cfg {boolean} pruneModifiedRecords True表示为,每次Store加载后,清除所有修改过的记录信息;record被移除时也会这样(默认为false)。
* pruneModifiedRecords True to clear all modified record information each time the store is
* loaded or when a record is removed. (defaults to false).
*/
pruneModifiedRecords : false,
/**
* 保存了上次load方法执行时,发出去的参数是什么。参阅{@link #load}了解这些是什么的参数。
* 加载当前的Record缓存的时候,清楚用了哪些的参数有时是非常有用的。
* Contains the last options object used as the parameter to the load method. See {@link #load}
* for the details of what this may contain. This may be useful for accessing any params which
* were used to load the current Record cache.
* @type Object
* @property lastOptions
*/
lastOptions : null,
destroy : function(){
if(this.id){
Ext.StoreMgr.unregister(this);
}
this.data = null;
this.purgeListeners();
},
/**
* 往Store对象添加Records,并触发{@link #add}事件。
* Add Records to the Store and fires the {@link #add} event.
* @param {Ext.data.Record} records 准备加入到缓存的Ext.data.Record对象数组(Ext.data.Record[])。
* An Array of Ext.data.Record objects to add to the cache.
*/
add : function(records){
records = [].concat(records);
if(records.length < 1){
return;
}
for(var i = 0, len = records.length; i < len; i++){
records[i].join(this);
}
var index = this.data.length;
this.data.addAll(records);
if(this.snapshot){
this.snapshot.addAll(records);
}
this.fireEvent("add", this, records, index);
},
/**
* (只限本地排序) 传入一个Record,按照队列(以固定的排序顺序)插入到Store对象中。
* (Local sort only) Inserts the passed Record into the Store at the index where it
* should go based on the current sort information.
* @param {Ext.data.Record} record
*/
addSorted : function(record){
var index = this.findInsertIndex(record);
this.insert(index, record);
},
/**
* 从Store中移除一Record对象,并触发{@link #remove}移除事件。
* Remove a Record from the Store and fires the {@link #remove} event.
* @param {Ext.data.Record} record 被从缓存中移除的Ext.data.Record对象
* record The Ext.data.Record object to remove from the cache.
*/
remove : function(record){
var index = this.data.indexOf(record);
this.data.removeAt(index);
if(this.pruneModifiedRecords){
this.modified.remove(record);
}
if(this.snapshot){
this.snapshot.remove(record);
}
this.fireEvent("remove", this, record, index);
},
/**
* 根据指定的索引移除Store中的某个Record。
* 触发{@link #remove}事件。
* Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
* @param {Number} index 要被移除的Record索引。The index of the record to remove.
*/
removeAt : function(index){
this.remove(this.getAt(index));
},
/**
* 从Store中清空所有Record对象,并触发{@link #clear}事件。
* Remove all Records from the Store and fires the {@link #clear} event.
*/
removeAll : function(){
this.data.clear();
if(this.snapshot){
this.snapshot.clear();
}
if(this.pruneModifiedRecords){
this.modified = [];
}
this.fireEvent("clear", this);
},
/**
* 触发添加事件时插入records到指定的store位置
* Inserts Records into the Store at the given index and fires the {@link #add} event.
* @param {Number} index 传入的Records插入的开始位置
* index The start index at which to insert the passed Records.
* @param {Ext.data.Record} records 加入到缓存中的Ext.data.Record对象(Ext.data.Record[])。
* records An Array of Ext.data.Record objects to add to the cache.
*/
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 要找寻的Ext.data.Record
* record The Ext.data.Record object to find.
* @return {Number} 被传入的Record的索引,如果未找到返回-1
* The index of the passed Record. Returns -1 if not found.
*/
indexOf : function(record){
return this.data.indexOf(record);
},
/**
* 传入一个id,根据id查询缓存里的Record,返回其索引。
* Get the index within the cache of the Record with the passed id.
* @param {String} id 要找到Record的id
* id The id of the Record to find.
* @return {Number} 被找到的Record的索引,如果未找到返回-1
* The index of the Record. Returns -1 if not found.
*/
indexOfId : function(id){
return this.data.indexOfKey(id);
},
/**
* 根据指定的id找到Record。
* Get the Record with the specified id.
* @param {String} id 要找的Record的id
* The id of the Record to find.
* @return {Ext.data.Record} 返回匹配id的Record,如果未找到则返回undefined
* The Record with the passed id. Returns undefined if not found.
*/
getById : function(id){
return this.data.key(id);
},
/**
* 根据指定的索引找到Record。
* Get the Record at the specified index.
* @param {Number} index 要找的Record的索引
* The index of the Record to find.
* @return {Ext.data.Record} 返回匹配索引的Record,如果未找到则返回undefined
* The Record at the passed index. Returns undefined if not found.
*/
getAt : function(index){
return this.data.itemAt(index);
},
/**
* 查找指定范围里的Records。
* Returns a range of Records between specified indices.
* @param {Number} startIndex (可选项)开始索引 (默认为 0)
* startIndex (optional) The starting index (defaults to 0)
* @param {Number} endIndex (可选项)结束的索引 (默认是Store中最后一个Record的索引)
* endIndex (optional) The ending index (defaults to the last Record in the Store)
* @return {Ext.data.Record[]} 返回一个Record数组
* An array of Records
*/
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;
},
/**
* 采用配置好的Reader格式去加载Record缓存,具体请求的任务由配置好的Proxy对象完成。
* Loads the Record cache from the configured Proxy using the configured Reader.
* <p>
* 如果使用服务器分页,那么必须指定在options.params中<tt>start</tt>和<tt>limit</tt>两个参数。
* start参数表明了从记录集(dataset)的哪一个位置开始读取,limit是读取多少笔的记录。Proxy负责送出参数。If using remote paging, then the first load call must specify the <tt>start</tt>
* and <tt>limit</tt> 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>
* <p><b>
* 由于采用了异步加载,因此该方法执行完毕后,数据不是按照load()方法下一个语句的顺序可以获取得到的。
* 应该登记一个回调函数,或者“load”的事件,登记一个处理函数。
* 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.</b></p>
* @param {Object} options 传入以下属性的对象,传入的对象会影响加载的选项:An object containing properties which control loading options:<ul>
* <li><b>params</b> :Object<p class="sub-desc">送出的HTTP参数,格式是JS对象。
* An object containing properties to pass as HTTP parameters to a remote data source.</p></li>
* <li><b>callback</b> : Function<p class="sub-desc">回调函数,这个函数会有以下的参数传入: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></p></li>
* <li><b>scope</b> : Object<p class="sub-desc">回调函数的作用域(默认为Store对象)。
* Scope with which to call the callback (defaults to the Store object)</p></li>
* <li><b>add</b> : Boolean<p class="sub-desc">表示到底是追加数据,还是替换数据。
* Indicator to append loaded records rather than replace the current cache.</p></li>
* </ul>
* @return {Boolean} 是否执行了load(受beforeload的影响,参见源码)。Whether the load fired (if beforeload failed).
*/
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);
return true;
} else {
return false;
}
},
/**
*
* <p>依据上一次的load操作的参数的Reader制订的格式,再一次向Proxy对象要求施以加载(Reload)Record缓存的操作。
* Reloads the Record cache from the configured Proxy using the configured Reader and
* the options from the last load operation performed.</p>
* <p><b>
* 由于采用了异步加载,因此该方法执行完毕后,数据不是按照load()方法下一个语句的顺序可以获取得到的。
* 应该登记一个回调函数,或者“load”的事件,登记一个处理函数。
* 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.</b></p>
* @param {Object} options (可选的)该对象包含的属性会覆盖上次load操作的参数。参阅{@link #load}了解详细内容(默认为null,即就是复用上次的选项参数)。
* (optional) An object containing loading options 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.
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);
}
},
/**
* 从传入的数据块中装载数据,并触发{@link #load}事件。传入的数据格式是Reader必须能够读取理解的,Reader是在构造器中配置好的。
* Loads data from a passed data block and fires the {@link #load} event. A Reader which understands the format of the data
* must have been configured in the constructor.
* @param {Object} data 要被转化为Records的数据块。数据类型会是由这个Reader的配置所决定的,并且符合Reader对象的readRecord参数的要求。
* 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} add (可选的)True表示为是在缓存中追加新的Records而不是进行替换。
* (Optional) True to add the new Records rather than replace the existing cache.
* <b>切记Store中的Record是按照{@link Ext.data.Record#id id}记录的,所以新加的Records如果id一样的话就会<i>替换</i>Stroe里面原有的,新的就会追加。
* Remember that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records with ids which are already present in
* the Store will <i>replace</i> existing Records. Records with new, unique ids will be added.</b>
*/
loadData : function(o, append){
var r = this.reader.readRecords(o);
this.loadRecords(r, {add: append}, true);
},
/**
* 获取缓存记录的总数。
* Gets the number of cached records.
* <p>如果使用了分页,那么这就是当前分页的总数,而不是全部记录的总数。
* 要获取记录总数应使用{@link #getTotalCount}方法,才能从Reader身上获取正确的全部记录数。
* 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 {@link #getTotalCount} function returns
* the dataset size.</p>
* @return {Number} Store缓存中记录总数
* The number of Records in the Store's cache.
*/
getCount : function(){
return this.data.length || 0;
},
/**
* 获取作为服务端返回的数据集中记录的总数。
* Gets the total number of records in the dataset as returned by the server.
* <p>如果分页,该值必须声明存在才能成功分页。Reader对象处理数据对象该值不能或缺。
* 对于远程数据而言,这是有服务器查询的结果。
* If using paging, for this to be accurate, the data object used by the Reader must contain
* the dataset size. For remote data sources, this is provided by a query on the server.</p>
* @return {Number} 数据对象由Proxy传给Reader对象,这个数据对象包含Record记录的总数
* The number of Records as specified in the data object passed to the Reader
* by the Proxy
* <p><b>如果是在本地更新Store的内容,那么该值是不会发生变化的。
* This value is not updated when changing the contents of the Store locally.</b></p>
*/
getTotalCount : function(){
return this.totalLength || 0;
},
/**
* 以对象的形式返回当前排序的状态。
* Returns an object describing the current sort state of this Store.
* @return {Object} 当前排序的状态:它是一个对象,有以下两个属性:
* The sort state of the Store. An object with two properties:<ul>
* <li><b>field : String<p class="sub-desc">一个是排序字段
* The name of the field by which the Records are sorted.</p></li>
* <li><b>direction : String<p class="sub-desc">一个是排序方向,"ASC"或"DESC"
* The sort order, "ASC" or "DESC" (case-sensitive).</p></li>
* </ul>
*/
getSortState : function(){
return this.sortInfo;
},
// private
applySort : function(){
if(this.sortInfo && !this.remoteSort){
var s = this.sortInfo, f = s.field;
this.sortData(f, s.direction);
}
},
// private
sortData : function(f, direction){
direction = direction || 'ASC';
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(direction, fn);
if(this.snapshot && this.snapshot != this.data){
this.snapshot.sort(direction, fn);
}
},
/**
* 设置默认的列排序,以便下次load操作时使用
* 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 (可选的) 排序顺序,“ASC”或“DESC”(默认为“ASC”)
* (optional) The sort order, "ASC" or "DESC" (case-sensitive, defaults to "ASC")
*/
setDefaultSort : function(field, dir){
dir = dir ? dir.toUpperCase() : "ASC";
this.sortInfo = {field: field, direction: dir};
this.sortToggle[field] = dir;
},
/**
* 对记录排序。
* 如果使用远程排序,排序是在服务端中进行的,缓存就会重新加载;如果使用本地排序,缓存就会内部排序。
* 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) 排序方向,“ASC”或“DESC”(大小写敏感的,默认为“ASC”)。The sort order, "ASC" or "DESC" (case-sensitive, defaults to "ASC")
*/
sort : function(fieldName, dir){
var f = this.fields.get(fieldName);
if(!f){
return false;
}
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;
}
}
var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
var si = (this.sortInfo) ? this.sortInfo : null;
this.sortToggle[f.name] = dir;
this.sortInfo = {field: f.name, direction: dir};
if(!this.remoteSort){
this.applySort();
this.fireEvent("datachanged", this);
}else{
if (!this.load(this.lastOptions)) {
if (st) {
this.sortToggle[f.name] = st;
}
if (si) {
this.sortInfo = si;
}
}
}
},
/**
* 对缓存中每个记录调用特点的函数。
* Calls the specified function for each of the Records in the cache.
* @param {Function} fn 要调用的函数。Record对象将是第一个参数。如果返回
* The function to call. The Record is passed as the first parameter.
* Returning <tt>false</tt> aborts and exits the iteration.
* @param {Object} scope 函数的作用域(默认为Record对象)(可选的)
* (optional) The scope in which to call the function (defaults to the Record).
*/
each : function(fn, scope){
this.data.each(fn, scope);
},
/**
* 距离上次提交之后,把所有修改过的、变化的记录收集起来。
* 通过加载(load)的操作来持久化这些修改的记录。(例如在分页期间)
* Gets all records modified since the last commit. Modified records are persisted across load operations
* (e.g., during paging).
* @return {Ext.data.Record[]} 包含了显注修改的Record数组.
* An array of Records containing outstanding modifications.
*/
getModifiedRecords : function(){
return this.modified;
},
// private
createFilterFn : function(property, value, anyMatch, caseSensitive){
if(Ext.isEmpty(value, false)){
return false;
}
value = this.data.createValueMatcher(value, anyMatch, caseSensitive);
return function(r){
return value.test(r.data[property]);
};
},
/**
* 统计每个记录<i>属性</i>值的个数。可设置区间。
* 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 计算的记录开始索引(默认为0)。start The record index to start at (defaults to 0)
* @param {Number} end 计算的记录结尾索引(默认为length - 1,从零开始算)。The last record index to include (defaults to length - 1)
* @return {Number} 总数 The sum
*
*/
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 既可以是字段开头的字符串,也可以是针对该字段的正则表达式
* value Either a string that the field should begin with, or a RegExp to test against the field.
* @param {Boolean} anyMatch (可选的)True表示不一定要开头的,当中包含的亦可
* (optional) True to match any part not just the beginning
* @param {Boolean} caseSensitive (可选的)True表示大小写敏感
* (optional) True for case sensitive comparison
*/
filter : function(property, value, anyMatch, caseSensitive){
var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
return fn ? this.filterBy(fn) : this.clearFilter();
},
/**
* 由外部函数进行筛选。Store里面的每个记录都经过这个函数内部使用。
* 如果函数返回<tt>true</tt>的话,就引入(included)到匹配的结果集中,否则就会被过滤掉。
* Filter by a function. The specified function will be called for each
* Record in this Store. If the function returns <tt>true</tt> the Record is included,
* otherwise it is filtered out.
* @param {Function} fn 要执行的函数。它会被传入以下的参数:
* The function to be called. It will be passed the following parameters:<ul>
* <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
* 对象用来测试过滤结果的。访问字段值就用{@link Ext.data.Record#get}方法。
* to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
* <li><b>id</b> : Object<p class="sub-desc">所传入的Record的ID
* The ID of the Record passed.</p></li>
* </ul>
* @param {Object} scope (可选的)函数作用域(默认为this)。
* (optional) The scope of the function (defaults to this)
*/
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 begin with, or a RegExp to test against the field.
* @param {Boolean} anyMatch (可选的)True表示不一定要开头的,当中包含的亦可
* (optional) True to match any part not just the beginning
* @param {Boolean} caseSensitive (可选的)True表示大小写敏感
* (optional) True for case sensitive comparison
* @return {MixedCollection} 返回一个Ext.util.MixedCollection实例,包含了匹配的记录
* Returns an Ext.util.MixedCollection of the matched records
*/
query : function(property, value, anyMatch, caseSensitive){
var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
return fn ? this.queryBy(fn) : this.data.clone();
},
/**
* 由外部函数进行该Store缓存记录的筛选。Store里面的每个记录都经过这个函数内部使用。
* 如果函数返回<tt>true</tt>的话,就引入(included)到匹配的结果集中。
* Query the cached records in this Store using a filtering function. The specified function
* will be called with each record in this Store. If the function returns <tt>true</tt> the record is
* included in the results.
* @param {Function} fn 要执行的函数。它会被传入以下的参数:
* The function to be called. It will be passed the following parameters:<ul>
* <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
* 对象用来测试过滤结果的。访问字段值就用{@link Ext.data.Record#get}方法。
* to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
* <li><b>id</b> : Object<p class="sub-desc">所传入的Record的ID
* The ID of the Record passed.</p></li>
* </ul>
* @param {Object} scope (可选的)函数作用域(默认为this)
* (optional) The scope of the function (defaults to this)
* @return {MixedCollection} 返回一个Ext.util.MixedCollection实例,包含了匹配的记录
* Returns an Ext.util.MixedCollection of the matched records
**/
queryBy : function(fn, scope){
var data = this.snapshot || this.data;
return data.filterBy(fn, scope||this);
},
/**
* 由指定的属性、值来查询记录,返回的是记录的索引值。只考虑第一次匹配的结果。
* Finds the index of the first matching record in this store by a specific property/value.
* @param {String} property 你查询对象的属性
* A property on your objects
* @param {String/RegExp} value 既可以是字段开头的字符串,也可以是针对该字段的正则表达式
* Either a string that the property value
* should begin with, or a RegExp to test against the property.
* @param {Number} startIndex (可选的) 查询的开始索引
* (optional) The index to start searching at
* @param {Boolean} anyMatch (可选的)True表示不一定要开头的,当中包含的亦可
* (optional) True to match any part of the string, not just the beginning
* @param {Boolean} caseSensitive (可选的)True表示大小写敏感
* (optional) True for case sensitive comparison
* @return {Number} 匹配的索引或-1 The matched index or -1
*/
find : function(property, value, start, anyMatch, caseSensitive){
var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
return fn ? this.data.findIndexBy(fn, null, start) : -1;
},
/**
* 由外部函数从某个索引开始进行筛选。只考虑第一次匹配的结果。
* 如果函数返回<tt>true</tt>的话,就被认为是一个匹配的结果。
* Find the index of the first matching Record in this Store by a function.
* If the function returns <tt>true</tt> it is considered a match.
* @param {Function} fn 要执行的函数。它会被传入以下的参数:The function to be called. It will be passed the following parameters:<ul>
* <li><b>record</b> : Ext.data.Record<p class="sub-desc">{@link Ext.data.Record record}
* 对象用来测试过滤结果的。访问字段值就用{@link Ext.data.Record#get}方法。The {@link Ext.data.Record record}
* to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
* <li><b>id</b> : Object<p class="sub-desc">所传入的Record的IDThe ID of the Record passed.</p></li>
* </ul>
* @param {Object} scope (可选的) 函数作用域(默认为this)(optional) The scope of the function (defaults to this)
* @param {Number} startIndex (可选的) 查询的开始索引(optional) The index to start searching at
* @return {Number} 匹配的索引或-1The matched index or -1
*/
findBy : function(fn, scope, start){
return this.data.findIndexBy(fn, scope, start);
},
/**
* 从这个Store身上收集由dataIndex指定的惟一的值。
* Collects unique values for a particular dataIndex from this store.
* @param {String} dataIndex 要收集的属性The property to collect
* @param {Boolean} allowNull (可选的) 送入true表示允许null、undefined或空白字符串这些无意义的值(optional) Pass true to allow null, undefined or empty string values
* @param {Boolean} bypassFilter (可选的)送入true表示收集所有记录,哪怕是被经过筛选的记录(optional) Pass true to collect from all records, even ones which are filtered
* @return {Array} 惟一的值所构成的数组An array of the unique values
**/
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;
},
/**
* 恢复到Record缓存的视图,这是没有经过筛选的Record。
* Revert to a view of the Record cache with no filtering applied.
* @param {Boolean} suppressEvent 如果设置为true,该筛选器会低调地清空,而不会通知监听器If true the filter is cleared silently without notifying listeners
*/
clearFilter : function(suppressEvent){
if(this.isFiltered()){
this.data = this.snapshot;
delete this.snapshot;
if(suppressEvent !== true){
this.fireEvent("datachanged", this);
}
}
},
/**
* 返回true表明这个store当前是在筛选的。
* Returns true if this store is currently filtered
* @return {Boolean}
*/
isFiltered : function(){
return this.snapshot && this.snapshot != this.data;
},
// 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);
},
/**
* 提交全部有变化的Record集。在实际处理这些更新的编码中,
* 应该登记Store的“update”事件,事件的处理函数中的第三个参数就是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.
*/
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();
}
},
// private
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);
},
// private
findInsertIndex : function(record){
this.suspendEvents();
var data = this.data.clone();
this.data.add(record);
this.applySort();
var index = this.data.indexOf(record);
this.data = data;
this.resumeEvents();
return index;
},
setBaseParam : function (name, value){
this.baseParams = this.baseParams || {};
this.baseParams[name] = value;
}
});
Ext.reg('store', Ext.data.Store); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Field
* <p>
* 该类封装了{@link Ext.data.Record#create}所传入字段定义对象的信息。<br />
* This class encpasulates the field definition information specified in the field definition objects
* passed to {@link Ext.data.Record#create}.
* </p>
* <p>
* 开发者一般不需要实例化该类。方法执行过程中创建该实例,并且在Record构造器的<b>原型prototype中</b>的{@link Ext.data.Record#fields fields}属性就是该实例。<br />
* Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
* and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
*/
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
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(Ext.isDate(v)){
return v;
}
if(dateFormat){
if(dateFormat == "timestamp"){
return new Date(v*1000);
}
if(dateFormat == "time"){
return new Date(parseInt(v, 10));
}
return Date.parseDate(v, dateFormat);
}
var parsed = Date.parse(v);
return parsed ? new Date(parsed) : null;
};
break;
}
this.convert = cv;
}
};
Ext.data.Field.prototype = {
/**
* @cfg {String} name
* 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}
*/
/**
* @cfg {String} type
* (Optional) The data type for conversion to displayable value. Possible values are
* <ul><li>auto (Default, implies no conversion)</li>
* <li>string</li>
* <li>int</li>
* <li>float</li>
* <li>boolean</li>
* <li>date</li></ul>
*/
/**
* @cfg {Function} convert
* (Optional) A function which converts the value provided by the Reader into an object that will be stored
* in the Record. It is passed the following parameters:<ul>
* <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader.</div></li>
* <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
* Depending on Reader type, this could be an Array, an object, or an XML element.</div></li>
* </ul>
*/
/**
* @cfg {String} dateFormat
* (Optional) A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
* value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
* javascript millisecond timestamp.
*/
dateFormat: null,
/**
* @cfg {Mixed} defaultValue
* (Optional) The default value used <b>when a Record is being created by a
* {@link Ext.data.Reader Reader}</b> when the item referenced by the <b><tt>mapping</tt></b> does not exist in the data object
* (i.e. undefined). (defaults to "")
*/
defaultValue: "",
/**
* @cfg {String} mapping
* (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.
*/
mapping: null,
/**
* @cfg {Function} sortType
* (Optional) A function which converts a Field's value to a comparable value in order to ensure correct
* sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}
*/
sortType : null,
/**
* @cfg {String} sortDir
* (Optional) Initial direction to sort. "ASC" or "DESC"
*/
sortDir : "ASC"
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.DirectProxy
* @extends Ext.data.DataProxy
*/
Ext.data.DirectProxy = function(config){
Ext.apply(this, config);
if(typeof this.paramOrder == 'string'){
this.paramOrder = this.paramOrder.split(/[\s,|]/);
}
Ext.data.DirectProxy.superclass.constructor.call(this, config);
};
Ext.extend(Ext.data.DirectProxy, Ext.data.DataProxy, {
/**
* @cfg {Array/String} paramOrder
* 默认为<tt>undefined</tt>。服务端处理执行的参数顺序列表。
* 指定一定的顺序的话服务端将甄别处理,可以(1)字符串的数组,或(2)空格、逗号、分号划分的字符串。例如以下的字符都可被处理:
* <br />
* Defaults to <tt>undefined</tt>. A list of params to be executed
* server side. Specify the params in the order in which they must be executed on the server-side
* as either (1) an Array of String values, or (2) a String of params delimited by either whitespace,
* comma, or pipe. For example,
* any of the following would be acceptable:<pre><code>
paramOrder: ['param1','param2','param3']
paramOrder: 'param1 param2 param3'
paramOrder: 'param1,param2,param3'
paramOrder: 'param1|param2|param'
</code></pre>
*/
paramOrder: undefined,
/**
* @cfg {Boolean} paramsAsHash
* 以一个Hash结果发送参数(默认为<tt>true</tt>)。有了<tt>{@link #paramOrder}</tt>这项那此项无效。<br />
* Send parameters as a collection of named arguments (defaults to <tt>true</tt>). Providing a
* <tt>{@link #paramOrder}</tt> nullifies this configuration.
*/
paramsAsHash: true,
/**
* @cfg {Function} directFn
* 当发起一个请求的时候执行的函数。directFn是另外一个简单的方案,适用于在未完整实现CRUD Api的Store的时候,定义一个API的配置参数。<br />
* Function to call when executing a request. directFn is a simple alternative to defining the api configuration-parameter
* for Store's which will not implement a full CRUD api.
*/
directFn : undefined,
/**
* {@link Ext.data.DataProxy#doRequest}的DirectProxy实现。
* DirectProxy implementation of {@link Ext.data.DataProxy#doRequest}
* @param {String} action CRUD操作的类型。The crud action type (create, read, update, destroy)
* @param {Ext.data.Record/Ext.data.Record[]} rs 动作操作后,rs变为null。If action is load, rs will be null
* @param {Object} params 表明HTTP参数的参数对象,请求到远程服务器上。An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader Reader的作用是转换数据对象为标准的{@link Ext.data.DataProxy#doRequest}块。The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback
* <div class="sub-desc"><p>请求完毕后的执行的函数。A function to be called after the request.
* 这个<tt>回调函数</tt>就有以下的参数:The <tt>callback</tt> is passed the following arguments:<ul>
* <li><tt>r</tt> : Ext.data.Record[] Ext.data.Records数据块。The block of Ext.data.Records.</li>
* <li><tt>options</tt>: 该次动作请求的参数对象。Options object from the action request</li>
* <li><tt>success</tt>:是否XHR通讯成功? Boolean success indicator</li></ul></p></div>
* @param {Object} scope 回调函数的作用域(即<code>this</code>引用)。默认为浏览器的window对象。The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
* @param {Object} arg 送入到回调函数的第二个参数,可选的。An optional argument which is passed to the callback as its second parameter.
* @protected
*/
doRequest : function(action, rs, params, reader, callback, scope, options) {
var args = [],
directFn = this.api[action] || this.directFn;
switch (action) {
case Ext.data.Api.actions.create:
args.push(params.jsonData); // <-- create(Hash)
break;
case Ext.data.Api.actions.read:
// If the method has no parameters, ignore the paramOrder/paramsAsHash.
if(directFn.directCfg.method.len > 0){
if(this.paramOrder){
for(var i = 0, len = this.paramOrder.length; i < len; i++){
args.push(params[this.paramOrder[i]]);
}
}else if(this.paramsAsHash){
args.push(params);
}
}
break;
case Ext.data.Api.actions.update:
args.push(params.jsonData); // <-- update(Hash/Hash[])
break;
case Ext.data.Api.actions.destroy:
args.push(params.jsonData); // <-- destroy(Int/Int[])
break;
}
var trans = {
params : params || {},
request: {
callback : callback,
scope : scope,
arg : options
},
reader: reader
};
args.push(this.createCallback(action, rs, trans), this);
directFn.apply(window, args);
},
// private
createCallback : function(action, rs, trans) {
return function(result, res) {
if (!res.status) {
// @deprecated fire loadexception
if (action === Ext.data.Api.actions.read) {
this.fireEvent("loadexception", this, trans, res, null);
}
this.fireEvent('exception', this, 'remote', action, trans, res, null);
trans.request.callback.call(trans.request.scope, null, trans.request.arg, false);
return;
}
if (action === Ext.data.Api.actions.read) {
this.onRead(action, trans, result, res);
} else {
this.onWrite(action, trans, result, res, rs);
}
};
},
/**
* 读操作的回调函数。
* Callback for read actions
* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
* @param {Object} trans 请求的事务对象。The request transaction object
* @param {Object} result 返回的数据对象。Data object picked out of the server-response.
* @param {Object} res 服务端响应。The server response
* @protected
*/
onRead : function(action, trans, result, res) {
var records;
try {
records = trans.reader.readRecords(result);
}
catch (ex) {
// @deprecated: Fire old loadexception for backwards-compat.
this.fireEvent("loadexception", this, trans, res, ex);
this.fireEvent('exception', this, 'response', action, trans, res, ex);
trans.request.callback.call(trans.request.scope, null, trans.request.arg, false);
return;
}
this.fireEvent("load", this, res, trans.request.arg);
trans.request.callback.call(trans.request.scope, records, trans.request.arg, true);
},
/**
* 写操作的回调函数。
* Callback for write actions
* @param {String} action [{@link Ext.data.Api#actions create|read|update|destroy}]
* @param {Object} trans 请求的事务对象。The request transaction object
* @param {Object} result 返回的数据对象。Data object picked out of the server-response.
* @param {Object} res 服务端响应。The server response
* @param {Ext.data.Record/[Ext.data.Record]} rs 执行动作相关的Store结果集。The Store resultset associated with the action.
* @protected
*/
onWrite : function(action, trans, result, res, rs) {
var data = trans.reader.extractData(result);
this.fireEvent("write", this, action, data, res, rs, trans.request.arg);
trans.request.callback.call(trans.request.scope, data, res, true);
}
});
| JavaScript |
/*!
* Ext JS Library 3.0.0
* Copyright(c) 2006-2009 Ext JS, LLC
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.data.XmlStore
* @extends Ext.data.Store
* <p>
* 一个轻型的辅助类,好让处理XML类型的{@link Ext.data.Store}起来更加轻松。XmlStore可通过{@link Ext.data.XmlReader}自动配置。
* <br />
* Small helper class to make creating {@link Ext.data.Store}s from XML data easier.
* A XmlStore will be automatically configured with a {@link Ext.data.XmlReader}.</p>
* <p>如是这样地配置一个Store:<br />
* A store configuration would be something like:<pre><code>
var store = new Ext.data.XmlStore({
// store configs
autoDestroy: true,
storeId: 'myStore',
url: 'sheldon.xml', // 会自动转为HttpProxy的代理。automatically configures a HttpProxy
// reader configs
record: 'Item', // 每条记录都有Item标签。records will have an "Item" tag
idPath: 'ASIN',
totalRecords: '@TotalResults'
fields: [
// 设置与xml文档映射的字段。最紧要的事mapping项,其他的就次要。
// set up the fields mapping into the xml doc
// The first needs mapping, the others are very basic
{name: 'Author', mapping: 'ItemAttributes > Author'},
'Title', 'Manufacturer', 'ProductGroup'
]
});
* </code></pre></p>
* <p>经过配置后,这样的xml会演变成为store对象:<br />
* This store is configured to consume a returned object of the form:<pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15">
<Items>
<Request>
<IsValid>True</IsValid>
<ItemSearchRequest>
<Author>Sidney Sheldon</Author>
<SearchIndex>Books</SearchIndex>
</ItemSearchRequest>
</Request>
<TotalResults>203</TotalResults>
<TotalPages>21</TotalPages>
<Item>
<ASIN>0446355453</ASIN>
<DetailPageURL>
http://www.amazon.com/
</DetailPageURL>
<ItemAttributes>
<Author>Sidney Sheldon</Author>
<Manufacturer>Warner Books</Manufacturer>
<ProductGroup>Book</ProductGroup>
<Title>Master of the Game</Title>
</ItemAttributes>
</Item>
</Items>
</ItemSearchResponse>
* </code></pre>
* “对象字面化”的形式也可以用于{@link #data}的配置项。<br />
* An object literal of this form could also be used as the {@link #data} config option.</p>
* <p>
* <b>注意:</b>尽管还没有列出,该类可接收来自<b>{@link Ext.data.XmlReader XmlReader}</b>所有的配置项。<br />
* <b>Note:</b> Although not listed here, this class accepts all of the configuration options of
* <b>{@link Ext.data.XmlReader XmlReader}</b>.</p>
* @constructor
* @param {Object} config
* @xtype xmlstore
*/
Ext.data.XmlStore = Ext.extend(Ext.data.Store, {
/**
* @cfg {Ext.data.DataReader} reader @hide
*/
constructor: function(config){
Ext.data.XmlStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new Ext.data.XmlReader(config)
}));
}
});
Ext.reg('xmlstore', Ext.data.XmlStore); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.XmlWriter
* @extends Ext.data.DataWriter
* DataWriter的子类相对于远程CRUD操作而言,这是一个在前端的初始化部分,负责写入单个或多个的{@link Ext.data.Record}对象。通过XML的格式。
* 如果默认的XML Scheam不太合适,可让XmlWriter采用{@link Ext.XTemplate}的实例制作一份XML文档的模版,使得你自己可定义XML Scheam,灵活性较大。请参阅{@link #tpl}配置项。<br />
* DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action via XML.
* XmlWriter uses an instance of {@link Ext.XTemplate} for maximum flexibility in defining your own custom XML schema if the default schema is not appropriate for your needs.
* See the {@link #tpl} configuration-property.
*/
Ext.data.XmlWriter = function(params) {
Ext.data.XmlWriter.superclass.constructor.apply(this, arguments);
// compile the XTemplate for rendering XML documents.
this.tpl = (typeof(this.tpl) === 'string') ? new Ext.XTemplate(this.tpl).compile() : this.tpl.compile();
};
Ext.extend(Ext.data.XmlWriter, Ext.data.DataWriter, {
/**
* @cfg {String} documentRoot [xrequest] (Optional) The name of the XML document root-node. <b>Note:</b>
* this parameter is required </b>only when</b> sending extra {@link Ext.data.Store#baseParams baseParams} to the server
* during a write-request -- if no baseParams are set, the {@link Ext.data.XmlReader#record} meta-property can
* suffice as the XML document root-node for write-actions involving just a <b>single record</b>. For requests
* involving <b>multiple</b> records and <b>NO</b> baseParams, the {@link Ext.data.XmlWriter#root} property can
* act as the XML document root.
*/
documentRoot: 'xrequest',
/**
* @cfg {Boolean} forceDocumentRoot [false] Set to <tt>true</tt> to force XML documents having a root-node as defined
* by {@link #documentRoot}, even with no baseParams defined.
*/
forceDocumentRoot: false,
/**
* @cfg {String} root [records] The name of the containing element which will contain the nodes of an write-action involving <b>multiple</b> records. Each
* xml-record written to the server will be wrapped in an element named after {@link Ext.data.XmlReader#record} property.
* eg:
<code><pre>
<?xml version="1.0" encoding="UTF-8"?>
<user><first>Barney</first></user>
</code></pre>
* However, when <b>multiple</b> records are written in a batch-operation, these records must be wrapped in a containing
* Element.
* eg:
<code><pre>
<?xml version="1.0" encoding="UTF-8"?>
<records>
<first>Barney</first></user>
<records><first>Barney</first></user>
</records>
</code></pre>
* Defaults to <tt>records</tt>. Do not confuse the nature of this property with that of {@link #documentRoot}
*/
root: 'records',
/**
* @cfg {String} xmlVersion [1.0] The <tt>version</tt> written to header of xml documents.
<code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
*/
xmlVersion : '1.0',
/**
* @cfg {String} xmlEncoding [ISO-8859-15] The <tt>encoding</tt> written to header of xml documents.
<code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
*/
xmlEncoding: 'ISO-8859-15',
/**
* @cfg {String/Ext.XTemplate} tpl The XML template used to render {@link Ext.data.Api#actions write-actions} to your server.
* <p>One can easily provide his/her own custom {@link Ext.XTemplate#constructor template-definition} if the default does not suffice.</p>
* <p>Defaults to:</p>
<code><pre>
<?xml version="{version}" encoding="{encoding}"?>
<tpl if="documentRoot"><{documentRoot}>
<tpl for="baseParams">
<tpl for=".">
<{name}>{value}</{name}>
</tpl>
</tpl>
<tpl if="records.length > 1"><{root}>',
<tpl for="records">
<{parent.record}>
<tpl for=".">
<{name}>{value}</{name}>
</tpl>
</{parent.record}>
</tpl>
<tpl if="records.length > 1"></{root}></tpl>
<tpl if="documentRoot"></{documentRoot}></tpl>
</pre></code>
* <p>Templates will be called with the following API</p>
* <ul>
* <li>{String} version [1.0] The xml version.</li>
* <li>{String} encoding [ISO-8859-15] The xml encoding.</li>
* <li>{String/false} documentRoot The XML document root-node name or <tt>false</tt> if not required. See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
* <li>{String} record The meta-data parameter defined on your {@link Ext.data.XmlReader#record} configuration represents the name of the xml-tag containing each record.</li>
* <li>{String} root The meta-data parameter defined by {@link Ext.data.XmlWriter#root} configuration-parameter. Represents the name of the xml root-tag when sending <b>multiple</b> records to the server.</li>
* <li>{Array} records The records being sent to the server, ie: the subject of the write-action being performed. The records parameter will be always be an array, even when only a single record is being acted upon.
* Each item within the records array will contain an array of field objects having the following properties:
* <ul>
* <li>{String} name The field-name of the record as defined by your {@link Ext.data.Record#create Ext.data.Record definition}. The "mapping" property will be used, otherwise it will match the "name" property. Use this parameter to define the XML tag-name of the property.</li>
* <li>{Mixed} value The record value of the field enclosed within XML tags specified by name property above.</li>
* </ul></li>
* <li>{Array} baseParams. The baseParams as defined upon {@link Ext.data.Store#baseParams}. Note that the baseParams have been converted into an array of [{name : "foo", value: "bar"}, ...] pairs in the same manner as the <b>records</b> parameter above. See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
* </ul>
*/
// Break up encoding here in case it's being included by some kind of page that will parse it (eg. PHP)
tpl: '<tpl for="."><' + '?xml version="{version}" encoding="{encoding}"?' + '><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}</tpl></tpl></tpl><tpl if="records.length>1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length>1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',
/**
* XmlWriter implementation of the final stage of a write action.
* @param {Object} params Transport-proxy's (eg: {@link Ext.Ajax#request}) params-object to write-to.
* @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
* @param {Object/Object[]} data Data-object representing the compiled Store-recordset.
*/
render : function(params, baseParams, data) {
baseParams = this.toArray(baseParams);
params.xmlData = this.tpl.applyTemplate({
version: this.xmlVersion,
encoding: this.xmlEncoding,
documentRoot: (baseParams.length > 0 || this.forceDocumentRoot === true) ? this.documentRoot : false,
record: this.meta.record,
root: this.root,
baseParams: baseParams,
records: (Ext.isArray(data[0])) ? data : [data]
});
},
/**
* createRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Array} Array of <tt>name:value</tt> pairs for attributes of the {@link Ext.data.Record}. See {@link Ext.data.DataWriter#toHash}.
*/
createRecord : function(rec) {
return this.toArray(this.toHash(rec));
},
/**
* updateRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Array} Array of {name:value} pairs for attributes of the {@link Ext.data.Record}. See {@link Ext.data.DataWriter#toHash}.
*/
updateRecord : function(rec) {
return this.toArray(this.toHash(rec));
},
/**
* destroyRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Array} Array containing a attribute-object (name/value pair) representing the {@link Ext.data.DataReader#idProperty idProperty}.
*/
destroyRecord : function(rec) {
var data = {};
data[this.meta.idProperty] = rec.id;
return this.toArray(data);
}
});
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.MemoryProxy
* @extends Ext.data.DataProxy
* 一个Ext.data.DataProxy的实现类,当其load方法调用时就是用送入Reader来读取那个在构造器中传入的数据。<br />
* 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 用这个数据对象来构造Ext.data.Records块。<br />The data object which the Reader uses to construct a block of 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, {
/**
* @event loadexception
* 在加载数据期间有异常发生时触发该事件。注意该事件是与{@link Ext.data.Store}对象联动的,所以你只监听其中一个事件就可以的了。
* Fires if an exception occurs in the Proxy during data loading. Note that this event is also relayed
* through {@link Ext.data.Store}, so you can listen for it directly on any Store instance.
* @param {Object} this 此DataProxy对象。
* @param {Object} arg 传入{@link #load}函数的回调参数对象。The callback's arg object passed to the {@link #load} function
* @param {Object} null 使用MemoryProxy的这就一直是null。This parameter does not apply and will always be null for MemoryProxy
* @param {Error} e 如果Reader不能读取数据就抛出一个JavaScript Error对象。The JavaScript Error object caught if the configured Reader could not read the data
*/
/**
* 根据数据源加载数据(本例中是客户端内存中的数据对象,透过构造器传入的),由指定的Ext.data.DataReader实例来解析这个Ext.data.Records块,并由指定的回调来处理这个块。
* 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 这个参数对MemoryProxy类不起作用。This parameter is not used by the MemoryProxy class.
* @param {Ext.data.DataReader} reader 能转换数据为Ext.data.Records块的Reader对象。The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback 会送入Ext.data.records块的函数。函数一定会传入:The function into which to pass the block of Ext.data.records.
* The function must be passed <ul>
* <li>Record对象。The Record block object</li>
* <li>从load函数那里来的参数"arg"。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.
*/
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.DirectStore
* @extends Ext.data.Store
* <p>
* 一个小型的辅助类,用来创建配搭了{@link Ext.data.DirectProxy}与{@link Ext.data.JsonReader}两者的{@link Ext.data.Store}更为轻松,
* 使得沟通{@link Ext.Direct}服务端供应器{@link Ext.direct.Provider Provider}更也来得更为畅顺。
* 要创建另外的proxy/reader组合,就创建一个单纯的{@link Ext.data.Store}来配置。
* <br />
* Small helper class to create an {@link Ext.data.Store} configured with an
* {@link Ext.data.DirectProxy} and {@link Ext.data.JsonReader} to make interacting
* with an {@link Ext.Direct} Server-side {@link Ext.direct.Provider Provider} easier.
* To create a different proxy/reader combination create a basic {@link Ext.data.Store}
* configured as needed.</p>
*
* <p>
* <b>注意:</b>尽管还没有列出,该类继承了以下类所有的配置项:<br />
* <b>*Note:</b> Although they are not listed, this class inherits all of the config options of:</p>
* <div><ul class="mdetail-params">
* <li><b>{@link Ext.data.Store Store}</b></li>
* <div class="sub-desc"><ul class="mdetail-params">
*
* </ul></div>
* <li><b>{@link Ext.data.JsonReader JsonReader}</b></li>
* <div class="sub-desc"><ul class="mdetail-params">
* <li><tt><b>{@link Ext.data.JsonReader#root root}</b></tt></li>
* <li><tt><b>{@link Ext.data.JsonReader#idProperty idProperty}</b></tt></li>
* <li><tt><b>{@link Ext.data.JsonReader#totalProperty totalProperty}</b></tt></li>
* </ul></div>
*
* <li><b>{@link Ext.data.DirectProxy DirectProxy}</b></li>
* <div class="sub-desc"><ul class="mdetail-params">
* <li><tt><b>{@link Ext.data.DirectProxy#directFn directFn}</b></tt></li>
* <li><tt><b>{@link Ext.data.DirectProxy#paramOrder paramOrder}</b></tt></li>
* <li><tt><b>{@link Ext.data.DirectProxy#paramsAsHash paramsAsHash}</b></tt></li>
* </ul></div>
* </ul></div>
*
* @xtype directstore
*
* @constructor
* @param {Object} config
*/
Ext.data.DirectStore = function(c){
// each transaction upon a singe record will generatie a distinct Direct transaction since Direct queues them into one Ajax request.
c.batchTransactions = false;
Ext.data.DirectStore.superclass.constructor.call(this, Ext.apply(c, {
proxy: (typeof(c.proxy) == 'undefined') ? new Ext.data.DirectProxy(Ext.copyTo({}, c, 'paramOrder,paramsAsHash,directFn,api')) : c.proxy,
reader: (typeof(c.reader) == 'undefined' && typeof(c.fields) == 'object') ? new Ext.data.JsonReader(Ext.copyTo({}, c, 'totalProperty,root,idProperty'), c.fields) : c.reader
}));
};
Ext.extend(Ext.data.DirectStore, Ext.data.Store, {});
Ext.reg('directstore', Ext.data.DirectStore);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.XmlReader
* @extends Ext.data.DataReader
* Data reader类接受一个XML文档响应后,创建一个由{@link Ext.data.Record}对象组成的数组,数组内的每个对象都是{@link Ext.data.Record}构造器负责映射(mappings)的结果。<br />
* Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
* based on mappings in a provided {@link Ext.data.Record} constructor.<br><br>
* <p>
* <em>
* 注意:为了浏览器能成功解析返回来的XML document对象,HHTP Response的content-type头必须被设成text/xml。<br />
* 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" or "application/xml".</em>
* <p>
* Example code:
* <pre><code>
var Employee = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // 如果名称相同就不需要"mapping"属性的啦"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" // 该属性是指定每一个行对象中究竟哪一个是记录的ID字段(可选的)。The element within the row that provides an ID for the record (optional)
}, Employee);
</code></pre>
* <p>
* 将形成这种形式的XML文件:
* This would consume an XML file like this:
* <pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<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 记录集的总数的DomQuery查询路径。如果是需要分页的话该属性就必须指定。
* 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 指明一个DomQuery查询路径,指定包含所有行对象的信息。
* The DomQuery path to the repeated element which contains record information.
* @cfg {String} success 指明一个DomQuery查询路径用于定位表单的success属性。The DomQuery path to the success attribute used by forms.
* @cfg {String} idPath 指明一个DomQuery查询路径,用于获取每一个行对象中究竟哪一个是记录的ID字段。The DomQuery path relative from the record element to the element that contains
* a record identifier value.
* @constructor 创建XmlReader对象。Create a new XmlReader.
* @param {Object} meta 元数据配置参数。Metadata configuration options
* @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由
* {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。
* Either an Array of field definition objects as passed to
* {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
*/
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, {
/**
* 从远端服务器取得数据后,仅供DataProxy对象所使用的方法。
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response 包含可被解析的XML文档数据在<tt>responseXML</tt>属性中的XHR的对象。The XHR object which contains the parsed XML document. The response is expected
* to contain a property called <tt>responseXML</tt> which refers to an XML document object.
* @return {Object} records 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存块。A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
read : function(response){
var doc = response.responseXML;
if(!doc) {
throw {message: "XmlReader.read: XML Document not available"};
}
return this.readRecords(doc);
},
/**
* 由一个XML文档产生一个包含Ext.data.Records的对象块。
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} doc 一个可被解析的XML文档。A parsed XML document.
* @return {Object} records 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存块。A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
readRecords : function(doc){
/**
* 异步通信完毕和读取之后,保留原始XML文档数据以便将来由必要的用途。
* After any data loads/reads, the raw XML Document is available for further custom processing.
* @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.idPath || 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, n);
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Record
* @extends Object
* <p>
* Record类不但封装了Record的<em>相关定义</em>信息,还封装了{@link Ext.data.Store}里面所使用的Recrod对象的值信息,
* 并且方便任何透过{@link Ext.data.Store}来访问Records缓存之信息的代码。<br />
* 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.</p>
* <p> * 静态方法{@link #create}可接受一个参数来生成一个属于该类的构造器,这个参数就是字段定义的数组。
* 只当{@link Ext.data.Reader}处理未格式化的数据对象时,才会创建Record的实例。<br />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.</p>
* <p>注意同一时间内一个{@link Ext.data.Store Store}只能携带一个Record类的实例。
* 要复制出另外一份的数据,就要使用{@link #copy}方法创建Record对象的副本,然后把新实例插入到另外的Store中去。<br />Note that an instance of a Record class may only belong to one {@link Ext.data.Store Store} at a time.
* In order to copy data from one Store to another, use the {@link #copy} method to create an exact
* copy of the Record, and insert the new instance into the other Store.</p>
* <p>当要序列化数据提供至服务器方面的时候,要注意Record的一些私_有属性,还有其所在的Store,反过来说,Store的引用便是一份Record的引用。
* 也就是说,{@link Ext.util.JSON.encode}不一定会对Record对象编码。这样,就用{@link data}和{@link id}属性。<br />When serializing a Record for submission to the server, be aware that it contains many private
* properties, and also a reference to its owning Store which in turn holds references to its Records.
* This means that a whole Record may not be encoded using {@link Ext.util.JSON.encode}. Instead, use the
* <code>{@link #data}</code> and <code>{@link #id}</code> properties.</p>
* Record对象经构造器产生后,拥有Ext.data.Record的一切方法,如下列。
* Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.
* @constructor 该构建器不能被用来创建Record对象。取而代之的,是用{@link #create}方法生成的构建器。参数都是相同的。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 对象数组,提供了每一个Record实例所需的字段属性定义。An object, the properties of which provide values for the new Record's fields.
* @param {Object} id (可选的)记录的id,它应当是独一无二的。{@link Ext.data.Store}会用这个id表示来标识记录里面的Record对象,如不指定就生成一个。
* (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 = function(data, id){
this.id = (id || id === 0) ? id : ++Ext.data.Record.AUTO_ID;
this.data = data;
};
/**
* 生成一个构造函数,该函数能产生符合规定的Record对象。
* Generate a constructor for a specific Record layout.
* @param {Array} o 数组。各个字段的定义,包括字段名、数据类型(可选的)、映射项(用于在{@link Ext.data.Reader}的数据对象中提取真实的数据)。
* 每一个字段的定义对象可包含以下的属性:
* 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<div class="sub-desc">
* Record对象所引用的字段名称。通常是一标识作它者引用,
* 例如,在列定义中,该值会作为{@link Ext.grid.ColumnModel}的<em>dataIndex</em>属性。
* 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}</div></li>
*
* <li><b>mapping</b> : String<div class="sub-desc">
* (可选的) 如果使用的是{@link Ext.data.Reader},这是一个Reader能够获取数据对象的数组值创建到Record对象下面的对应的映射项;
* 如果使用的是{@link Ext.data.JsonReader},那么这是一个javascript表达式的字符串,
* 能够获取数据的引用到Record对象的下面;
* 如果使用的是{@link Ext.data.XmlReader},这是一个{@link Ext.DomQuery}路径,
* 能够获取数据元素的引用到Record对象的下面;
* 如果映射名与字段名都是相同的,那么映射名可以省略。
* (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.</div></li>
*
*
* <li><b>type</b> : String<div class="sub-desc">
* (可选的) 指明数据类型,转化为可显示的值。有效值是:
* (Optional) The data type for conversion to displayable value. Possible values are
* <ul><li>auto (auto是默认的,不声明就用auto。不作转换)(Default, implies no conversion)</li>
* <li>string</li>
* <li>int</li>
* <li>float</li>
* <li>boolean</li>
* <li>date</li></ul></div></li>
*
* <li><b>dateFormat</b> : String<div class="sub-desc"></div></li>
* <li><b>defaultValue</b> : Mixed<div class="sub-desc">(可选的)默认值。<b>
* 当经过{@link Ext.data.Reader Reader}创建Record时会使用该值;</b> 当<b><tt>mapping</tt></b>的引用项不存在的时候,典型的情况为undefined时候会使用该值(默认为'')
*
*
*
* <li><b>sortType</b> : Function<div class="sub-desc">(可选的) {@link Ext.data.SortTypes}的成语。(Optional) A function which converts a Field's value to a comparable value
* in order to ensure correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}.</div></li>
* <li><b>sortDir</b> : String<div class="sub-desc">(可选的) 初始化的排序方向,“ASC”或“DESC”。(Optional) Initial direction to sort. "ASC" or "DESC"</div></li>
* <li><b>convert</b> : Function<div class="sub-desc">(可选的) 由Reader提供的用于转换值的函数,将值变为Record下面的对象。它会送入以下的参数:
* (Optional) A function which converts the value provided by the Reader into an object that will be stored in the Record. It is passed the following parameters:<ul>
*
* <li><b>v</b> : Mixed<div class="sub-desc">数据值,和Reader读取的一样。The data value as read by the Reader.</div></li>
* <li><b>rec</b> : Mixed<div class="sub-desc">包含行的数据对象,和Reader读取的一样。
* 这可以是数组,对象,XML元素对象,这取决于Reader对象的类型。
* The data object containing the row as read by the Reader.
* Depending on Reader type, this could be an Array, an object, or an XML element.</div></li>
* </ul></div></li>
*
* <li><b>dateFormat</b> : String<div class="sub-desc">(可选的) 字符串格式的{@link Date#parseDate Date.parseDate}函数,
* 或“timestamp”表示Reader读取UNIX格式的timestamp,或“time”是Reader读取的是javascript毫秒的timestamp。
* (Optional) A format string for the {@link Date#parseDate Date.parseDate} function,
* or "timestamp" if the value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
* javascript millisecond timestamp.</div></li>
*
* <li><b>defaultValue</b> : Mixed<div class="sub-desc">(可选的)默认值。
* <b>当经过{@link Ext.data.Reader Reader}创建Record时会使用该值;</b> 当<b><tt>mapping</tt></b>的引用项不存在的时候,典型的情况为undefined时候会使用该值(默认为'')。
* (Optional) The default value used <b>when a Record is being created by a
* {@link Ext.data.Reader Reader}</b> when the item referenced by the <b><tt>mapping</tt></b> does not exist in the data object
* (i.e. undefined). (defaults to "")</div></li>
*
* </ul>
* 透过create方法会返回一个构造器的函数,这样就可以用来创建一个一个Record对象了。
* 数据对象(在第一个参数上)一定要有一个属性,是名为<b>names</b>的属性,以说明是什么字段。
* The constructor generated by this method may be used to create new Record instances. The data object must contain properties
* named after the field <b>names</b>.
* <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>
* <p>简单地说,除了 <tt>name</tt>属性是必须的外,其他属性是可以不要的,因此,你只要传入一个字符串就可满足最低条件了,因为它就代表字段名称。
* In the simplest case, if no properties other than <tt>name</tt> are required, a field definition
* may consist of just a field name string.</p>
* @method create
* @return {function} 根据定义创建新Records的构造器。A constructor which is used to create new Records according
* to the definition.
* @static
*/
Ext.data.Record.create = function(o){
var f = Ext.extend(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 = {
/**
* <p><b>
* Record定义的<u>prototype</u>保存了该属性。
* This property is stored in the Record definition's <u>prototype</u></b></p>
* 为该Record服务的{@link Ext.data.Field Field},存储在一个MixedCollection对象中。只读的。
* A MixedCollection containing the defined {@link Ext.data.Field Field}s for this Record. Read-only.
* @property fields
* @type Ext.util.MixedCollection
*/
/**
* Record的数据对象。Record定义中的所有字段名就表示该对象属性身上的名称。
* 注意除非你指定了一个字段的名称为"id"在Record定义中,否则这<b>不会</b>包含一个<tt>id</tt>属性。
* An object hash representing the data for this Record. Every field name in the Record definition
* is represented by a property of that name in this object. Note that unless you specified a field
* with name "id" in the Record definition, this will <b>not</b> contain an <tt>id</tt> property.
* @property data
* @type {Object}
*/
/**
* 惟一的ID,在Record创建时分派此值。
* The unique ID of the Record as specified at construction time.
* @property id
* @type {Object}
*/
/**
* 只读。true表示为Record有修改。
* Readonly flag - true if this Record has been modified.
* @type Boolean
*/
dirty : false,
editing : false,
error: null,
/**
* 该对象保存了所有修改过的字段的原始值数据(键和值key and Value)。
* 如果没有字段被修改的话,该值是null。
* This object contains a key and value storing the original values of all modified fields or is null if no fields have been modified.
* @property modified
* @type {Object}
*/
modified: null,
// private
join : function(store){
/**
* 该Record所属的{@link Ext.data.Store}对象。
* The {@link Ext.data.Store} to which this Record belongs.
* @property store
* @type {Ext.data.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.
*/
set : function(name, value){
if(String(this.data[name]) == String(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){
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.
*/
get : function(name){
return this.data[name];
},
/**
* 开始进入编辑。编辑期间,没有与所在的store任何关联的事件。
* Begin an edit. While in edit mode, no events are relayed to the containing store.
*/
beginEdit : function(){
this.editing = true;
this.modified = this.modified || {};
},
/**
* 取消所有已修改过的数据。
* Cancels all changes made in the current edit operation.
*/
cancelEdit : function(){
this.editing = false;
delete this.modified;
},
/**
* 结束编辑。如数据有变动,则会通知所在的store。
* End an edit. If any data was modified, the containing store is notified.
*/
endEdit : function(){
this.editing = false;
if(this.dirty && this.store){
this.store.afterEdit(this);
}
},
/**
* @param {Boolean} silent
* 这个方法通常给Record对象所在的那个{@link Ext.data.Store}对象调用。
* 创建Record、或上一次提交的操作都会使得Record对象执行reject撤销方法。
* 原始值会变化为已修改的值。
* 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>
* 要根据提交(commit)操作而传达的通知,开发人员应该登记{@link Ext.data.Store#update}事件来编码来执行特定的撤销操作
* Developers should subscribe to the {@link Ext.data.Store#update} event to have their code notified
* of reject operations.</p>
* @param {Boolean} silent (可选的)True表示不通知自身的store对象有所改变(默认为false)。(optional) True to skip notification of the owning store of the change (defaults to false)
*/
reject : function(silent){
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 && silent !== true){
this.store.afterReject(this);
}
},
/**
* 这个方法通常给Record对象所在的那个{@link Ext.data.Store}对象调用。
* 创建Record、或上一次提交的操作都会使得Record对象执行commit提交方法。
* 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>
* 要根据提交(commit)操作而传达的通知,开发人员应该登记{@link Ext.data.Store#update}事件来编码来执行特定的更新操作。</p>
* Developers should subscribe to the {@link Ext.data.Store#update} event to have their code notified
* of commit operations.
* </p>
* @param {Boolean} silent (可选的)True表示不通知自身的store对象有所改变(默认为false)。(optional) True to skip notification of the owning store of the change (defaults to false)
*/
commit : function(silent){
this.dirty = false;
delete this.modified;
this.editing = false;
if(this.store && silent !== true){
this.store.afterCommit(this);
}
},
/**
* 该对象被创建或提交之后,用来获取字段的哈希值(hash)。
* Gets a hash of only the fields that have been modified since this Record was created or commited.
* @return Object
*/
getChanges : function(){
var m = this.modified, cs = {};
for(var n in m){
if(m.hasOwnProperty(n)){
cs[n] = this.data[n];
}
}
return cs;
},
// private
hasError : function(){
return this.error != null;
},
// private
clearError : function(){
this.error = null;
},
/**
* 创建记录的副本。
* Creates a copy of this Record.
* @param {String} id (可选的)创建新的ID如果你不想在ID上也雷同。(optional) A new Record id if you don't want to use this Record's id
* @return {Record}
*/
copy : function(newId) {
return new this.constructor(Ext.apply({}, this.data), newId || this.id);
},
/**
* 如果传入的字段是修改过的(load或上一次提交)就返回true。
* Returns true if the field passed has been modified since the load or last commit.
* @param {String} fieldName
* @return {Boolean}
*/
isModified : function(fieldName){
return !!(this.modified && this.modified.hasOwnProperty(fieldName));
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见http://ajaxjs.com 或者 http://jstang.cn
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Api
* @extends Object
* 为了确保开发者的DataProxy API使用无误,我们定义了Ext.data.Api单例管理这些数据的API。
* 除了创、见、变、灭的这四种CRUD操作进行了定义之外,还分别将这些操作映射到了RESTful的HTTP方法:GET、POST、PUT和DELETE。<br />
* Ext.data.Api is a singleton designed to manage the data API including methods
* for validating a developer's DataProxy API. Defines variables for CRUD actions
* create, read, update and destroy in addition to a mapping of RESTful HTTP methods
* GET, POST, PUT and DELETE to CRUD actions.
* @singleton
*/
Ext.data.Api = (function() {
// private validActions.
// validActions就是反转Ext.data.Api.actions的哈希表hash,即value变为是key。
// 本单例的一些方法(如getActions、getVerb)以<code>for (var verb in this.actions)</code>遍历这些actions,
// 所以为了效率更快的话,访问过hash的会保存成为缓存,某些方法首先会检查hash命中匹配的值。
// 需要注意的是,此hash运作过程中不断的读写、修改,因此我们不能够预定义这个hash。
// validActions is essentially an inverted hash of Ext.data.Api.actions, where value becomes the key.
// Some methods in this singleton (e.g.: getActions, getVerb)
// will loop through actions with the code <code>for (var verb in this.actions)</code>
// For efficiency, some methods will first check this hash for a match.
// Those methods which do acces validActions will cache their result here.
// We cannot pre-define this hash since the developer may over-ride the actions at runtime.
var validActions = {};
return {
/**
* 定义远程动作所关联的本地动作:
* Defined actions corresponding to remote actions:
* <pre><code>
actions: {
create : 'create', // 表示位于服务端创建记录所执行的创建动作。Text representing the remote-action to create records on server.
read : 'read', // 表示位于服务端读取、加载数据所执行的创建动作。Text representing the remote-action to read/load data from server.
update : 'update', // 表示位于服务端更新记录所执行的创建动作。Text representing the remote-action to update records on server.
destroy : 'destroy' // 表示位于服务端消除记录所执行的创建动作。Text representing the remote-action to destroy records on server.
}
* </code></pre>
* @property actions
* @type Object
*/
actions : {
create : 'create',
read : 'read',
update : 'update',
destroy : 'destroy'
},
/**
* 将HTTP方法与关联的动作定义在一起的{CRUD action}:{HTTP method}的结对,将用于{@link Ext.data.DataProxy#restful RESTful proxies}的时候。
* 默认为:
* Defined {CRUD action}:{HTTP method} pairs to associate HTTP methods with the
* corresponding actions for {@link Ext.data.DataProxy#restful RESTful proxies}.
* Defaults to:
* <pre><code>
restActions : {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE'
},
* </code></pre>
*/
restActions : {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE'
},
/**
* 若传入的动作名称,在常量<code>{@link #actions}</code>中已经是有的就返回true.<br />
* Returns true if supplied action-name is a valid API action defined in <code>{@link #actions}</code> constants
* @param {String/String[]} action CRUD操作字符串,也可以是CRUD操作的数组。多次操作的时候传入数组的话会更快。List of available CRUD actions. Pass in list when executing multiple times for efficiency.
* @return {Boolean}
*/
isAction : function(action) {
return (Ext.data.Api.actions[action]) ? true : false;
},
/**
* 返回实际的CRUD操作键值,根据传入的动作名称辨认出实际的"create", "read", "update"或"destroy"操作类型。
* 一般来说该方法是内置使用的,不会直接地调用它。 Ext.data.Api.actions的key/value结对是相同无异的,但是也不一定的说。
* 有需要的话,开发者可允许覆盖约定的名称。不过,框架内部依据KEY来调用方法的,因此就需要某种方式取得"create"、"read"、"update"和"destroy" 关键字才可以。
* 如果发现KEYS已被缓存在validActions中,那么该就会直接从缓存中返回。<br />
* Returns the actual CRUD action KEY "create", "read", "update" or "destroy" from the supplied action-name. This method is used internally and shouldn't generally
* need to be used directly. The key/value pair of Ext.data.Api.actions will often be identical but this is not necessarily true.
* A developer can override this naming
* convention if desired. However, the framework internally calls methods based upon the KEY so a way of retreiving the the words "create", "read", "update" and "destroy" is
* required. This method will cache discovered KEYS into the private validActions hash.
* @param {String} name The runtime name of the action.
* @return {String||null} returns the action-key, or verb of the user-action or null if invalid.
* @nodoc
*/
getVerb : function(name) {
if (validActions[name]) {
return validActions[name]; // <-- found in cache. return immediately.
}
for (var verb in this.actions) {
if (this.actions[verb] === name) {
validActions[name] = verb;
break;
}
}
return (validActions[name] !== undefined) ? validActions[name] : null;
},
/**
* 如果传入的API是有效的,就返回true;这样的话,同时检查到预定义没有的动作,就会传入到数组中,最后返回(错误的动作)。<br />
* Returns true if the supplied API is valid; that is, check that all keys match defined actions
* otherwise returns an array of mistakes.
* @return {String[]||true}
*/
isValid : function(api){
var invalid = [];
var crud = this.actions; // <-- cache a copy of the actions.
for (var action in api) {
if (!(action in crud)) {
invalid.push(action);
}
}
return (!invalid.length) ? true : invalid;
},
/**
* 在传入的proxy在一个原来唯一的proxy地址的时候,并没有其他API动作染指的时候,返回true。
* 当决定是否插入“xaction”的HTTP参数到某个Ajax请求的时候,这个问题就显得重要了。
* 一般来说该方法是内置使用的,不会直接地调用它。<br />
* Returns true if the supplied verb upon the supplied proxy points to a unique url
* in that none of the other api-actions
* point to the same url. The question is important for deciding whether to insert the "xaction" HTTP parameter within an
* Ajax request. This method is used internally and shouldn't generally need to be called directly.
* @param {Ext.data.DataProxy} proxy
* @param {String} verb
* @return {Boolean}
*/
hasUniqueUrl : function(proxy, verb) {
var url = (proxy.api[verb]) ? proxy.api[verb].url : null;
var unique = true;
for (var action in proxy.api) {
if ((unique = (action === verb) ? true : (proxy.api[action].url != url) ? true : false) === false) {
break;
}
}
return unique;
},
/**
* 该方法由<tt>{@link Ext.data.DataProxy DataProxy}</tt>内部使用,一般不宜直接使用。
* 内部定义时,每个DataProxy API的动作可以是String或者是Object。
* 当定义为Object的时候,就可以为其中的CRUD操作精确指定是哪一种HTTP方法(GET、POST…)。
* 该方法会初始化传入的API,将每一项的操作转换为Object的形式。如果你传入的API没有设定HTTP方法的话,那么“method”所指定的配置项就是默认的方法。
* 如果连method的配置项都没有指定的话,那么就是POST了。<br />
* This method is used internally by <tt>{@link Ext.data.DataProxy DataProxy}</tt> and should not generally need to be used directly.
* Each action of a DataProxy api can be initially defined as either a String or an Object.
* When specified as an object,
* one can explicitly define the HTTP method (GET|POST) to use for each CRUD action.
* This method will prepare the supplied API, setting
* each action to the Object form. If your API-actions do not explicitly define the HTTP method, the "method" configuration-parameter will
* be used. If the method configuration parameter is not specified, POST will be used.
<pre><code>
new Ext.data.HttpProxy({
method: "POST", // 没有指定时默认的HTTP方法。<-- default HTTP method when not specified.
api: {
create: 'create.php',
load: 'read.php',
save: 'save.php',
destroy: 'destroy.php'
}
});
// 可选地,也可以对象形式定义。Alternatively, one can use the object-form to specify the API
new Ext.data.HttpProxy({
api: {
load: {url: 'read.php', method: 'GET'},
create: 'create.php',
destroy: 'destroy.php',
save: 'update.php'
}
});
</code></pre>
*
* @param {Ext.data.DataProxy} proxy
*/
prepare : function(proxy) {
if (!proxy.api) {
proxy.api = {}; // <-- No api? create a blank one.
}
for (var verb in this.actions) {
var action = this.actions[verb];
proxy.api[action] = proxy.api[action] || proxy.url || proxy.directFn;
if (typeof(proxy.api[action]) == 'string') {
proxy.api[action] = {
url: proxy.api[action]
};
}
}
},
/**
* 初始化Proxy,让其成为RESTful的。可根据{@link #restActions}的值定义每个API动作的HTTP方法(GET, POST, PUT, DELETE的任意一种)。<br />
* Prepares a supplied Proxy to be RESTful. Sets the HTTP method for each api-action to be one of
* GET, POST, PUT, DELETE according to the defined {@link #restActions}.
* @param {Ext.data.DataProxy} proxy
*/
restify : function(proxy) {
proxy.restful = true;
for (var verb in this.restActions) {
proxy.api[this.actions[verb]].method = this.restActions[verb];
}
}
};
})();
/**
* @class Ext.data.Api.Error
* @extends Ext.Error
*
* Error class for Ext.data.Api errors
*/
Ext.data.Api.Error = Ext.extend(Ext.Error, {
constructor : function(message, arg) {
this.arg = arg;
Ext.Error.call(this, message);
},
name: 'Ext.data.Api'
});
Ext.apply(Ext.data.Api.Error.prototype, {
lang: {
'action-url-undefined': 'No fallback url defined for this action. When defining a DataProxy api, please be sure to define an url for each CRUD action in Ext.data.Api.actions or define a default url in addition to your api-configuration.',
'invalid': 'received an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions',
'invalid-url': 'Invalid url. Please review your proxy configuration.',
'execute': 'Attempted to execute an unknown action. Valid API actions are defined in Ext.data.Api.actions"'
}
});
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.StoreMgr
* @extends Ext.util.MixedCollection
* store组管理器。这是全局的、并且是缺省的。<br />
* The default global group of stores.
* @singleton
*/
Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), {
/**
* @cfg {Object} listeners @hide
*/
/**
* 登记更多的Store对象到StoreMgr。一般情况下你不需要手动加入。任何透过{@link Ext.data.Store#storeId}初始化的Store都会自动登记。
* Registers one or more Stores with the StoreMgr. You do not normally need to register stores
* manually. Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered.
* @param {Ext.data.Store} store1 Store实例。A Store instance
* @param {Ext.data.Store} store2 (可选的)Store实例2。(optional)
* @param {Ext.data.Store} etc... (可选的)Store实例x……。(optional)
*/
register : function(){
for(var i = 0, s; s = arguments[i]; i++){
this.add(s);
}
},
/**
* 注销一个或多个Stores。
* Unregisters one or more Stores with the StoreMgr
* @param {String/Object} id1 Store的id或是Store对象The id of the Store, or a Store instance
* @param {String/Object} id2 (可选的)Store实例2。(optional)
* @param {String/Object} etc... (可选的)Store实例x……。(optional)
*/
unregister : function(){
for(var i = 0, s; s = arguments[i]; i++){
this.remove(this.lookup(s));
}
},
/**
* 由id返回一个已登记的Store。
* Gets a registered Store by id
* @param {String/Object} id Store的id或是Store对象。The id of the Store, or a Store instance
* @return {Ext.data.Store}
*/
lookup : function(id){
return typeof id == "object" ? (id.events ? id : Ext.create(id, 'store')) : this.get(id);
},
// getKey implementation for MixedCollection
getKey : function(o){
return o.storeId || o.id;
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.SortTypes
* @singleton
* 定义一些缺省的比较函数,供排序时使用。<br />
* Defines the default sorting (casting?) comparison functions used when sorting data.
*/
Ext.data.SortTypes = {
/**
* 默认的排序即什么也不做。
* Default sort that does nothing
* @param {Mixed} s 将被转换的值将被转换的值。The value being converted
* @return {Mixed} 用来比较的值所比较的值。The comparison value
*/
none : function(s){
return s;
},
/**
* 用来去掉标签的规则表达式。
* The regular expression used to strip tags
* @type {RegExp}
* @property stripTagsRE
*/
stripTagsRE : /<\/?[^>]+>/gi,
/**
* 去掉所有html标签来基于纯文本排序。
* Strips all HTML tags to sort on text only
* @param {Mixed} s 将被转换的值将被转换的值。The value being converted
* @return {String} 用来比较的值所比较的值。The comparison value
*/
asText : function(s){
return String(s).replace(this.stripTagsRE, "");
},
/**
* 去掉所有html标签来基于无大小写区别的文本的排序。
* Strips all HTML tags to sort on text only - Case insensitive
* @param {Mixed} s 将被转换的值。The value being converted
* @return {String} 所比较的值所比较的值。The comparison value
*/
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
*/
asUCString : function(s) {
return String(s).toUpperCase();
},
/**
* 对日期排序。
* Date sorting
* @param {Mixed} s 将被转换的值。The value being converted
* @return {Number} 所比较的值。The comparison value
*/
asDate : function(s) {
if(!s){
return 0;
}
if(Ext.isDate(s)){
return s.getTime();
}
return Date.parse(String(s));
},
/**
* 浮点数的排序。
* Float sorting
* @param {Mixed} s 将被转换的值。The value being converted
* @return {Float} 所比较的值。The comparison value
*/
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
*/
asInt : function(s) {
var val = parseInt(String(s).replace(/,/g, ""));
if(isNaN(val)) val = 0;
return val;
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.JsonStore
* @extends Ext.data.Store
* 使得从远程JSON数据创建stores更为方便的简单辅助类。
* JsonStore合成了{@link Ext.data.HttpProxy}与{@link Ext.data.JsonReader}两者。
* 如果你需要其他类型的proxy或reader组合,那么你要创建以{@link Ext.data.Store}为基类的配置。<br />
* Small helper class to make creating Stores for remotely-loaded JSON data easier. JsonStore is pre-configured
* with a built-in {@link Ext.data.HttpProxy} and {@link Ext.data.JsonReader}. If you require some other proxy/reader
* combination then you'll have to create a basic {@link Ext.data.Store} configured as needed.<br/>
<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>
* 形成这种形式的对象: This would consume a returned object of the form:
<pre><code>
{
images: [
{name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
{name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
]
}
</code></pre>
*
* <b></b>
* @cfg {String} url
* @cfg {Object} data
* @cfg {Array} fields 这种形式的数据(对象实字,object literal)会作用在{@link #data}配置项上。<br />
* An object literal of this form could also be used as the {@link #data} config option.
* <b>注意:尽管未有列出,该类继承了Store对象、JsonReader对象的所有的配置项。<br />
* Note: Although they are not listed, this class inherits all of the config options of Store,
* JsonReader.</b>
*
* @cfg {String} url HttpProxy对象的URL地址。可以从这里指定,也可以从{@link #data}配置中指定。不能缺少。
* The URL from which to load data through an HttpProxy. Either this option, or the {@link #data} option must be specified.
*
* @cfg {Object} data 能够被该对象所属的JsonReader解析的数据对象。可以从这里指定,也可以从{@link #url}配置中指定。不能缺少。
* A data object readable by this object's JsonReader. Either this option, or the {@link #url} option must be specified.
*
* @cfg {Array} fields 既可以是字段的定义对象组成的数组,会作为{@link Ext.data.Record#create}方法的参数用途,也可以是一个{@link Ext.data.Record Record}构造器,来给{@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。
* Either an Array of field definition objects as passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record} constructor created using {@link Ext.data.Record#create}.<br>
* <p>
* 这个配置项是用于创建{@link Ext.data.JsonReader#JsonReader JsonReader}构造器中的<tt>recordType</tt>,它是隐式调用,还创建了供Store使用的{@link Ext.data.Record Record definition}。
* This config is used to create the <tt>recordType</tt> parameter to the {@link Ext.data.JsonReader#JsonReader JsonReader}
* constructor that is implicitly called, and creates the {@link Ext.data.Record Record definition} used by the Store.
* @constructor
* @param {Object} config
*/
Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
constructor: function(config){
Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new Ext.data.JsonReader(config)
}));
}
/**
* @cfg {Ext.data.DataReader} reader @hide
*/
/**
* @cfg {Ext.data.DataProxy} proxy @hide
*/
});
Ext.reg('jsonstore', Ext.data.JsonStore); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Connection
* @extends Ext.util.Observable
* <p>
* 此类封装了一个页面到当前域的连接,以响应(来自配置文件中的url或请求时指定的url)请求。<br />
* 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.</p>
*
* <p>
* 通过该类产生的请求都是异步的,并且会立刻返回,这样紧跟其后的{@link #request}调用将得不到数据
* 可以使用在request配置项一个<a href="#request-option-success" ext:member="request-option-success" ext:cls="Ext.data.Connection">回调函数</a>,
* 或{@link #requestcomplete 事件侦听器}来处理返回来的数据。<br />
* 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 <a href="#request-option-success" ext:member="request-option-success" ext:cls="Ext.data.Connection">success callback</a>
* in the request options object,or an {@link #requestcomplete event listener}.</p>
*
* <p>
* response对象是通过iframe的document的innerTHML作为responseText属性,如果存在,
* 该iframe的xml document作为responseXML属性。<br />
* <h3>File Uploads</h3><a href="#request-option-isUpload" ext:member="request-option-isUpload" ext:cls="Ext.data.Connection">File uploads</a> are not performed using normal "Ajax" techniques,
* that is they are <b>not</b> performed using XMLHttpRequests.
* Instead the form is submitted in the standard manner with the DOM <tt><form></tt> element temporarily modified to
* have its <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
* to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
* but removed after the return data has been gathered.</p>
*
* <p>
* 注意:如果你正在上传文件,你将得不到一个正常的响应对象送回到你的回调或事件处理函数中,原因是上传利用iframe来处理的。
* 这意味着一个有效的xml或html document必须被返回,如果需要json数据,这次意味着它将放到。<br />
* The server response is parsed by the browser to create the document for the IFRAME.
* If the server is using JSON to send the return object, then the
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
*
* <p>
* Characters which are significant to an HTML parser must be sent as HTML entities, so encode
* "<" as "&lt;", "&" as "&amp;" etc.</p>
*
* <p>
* 响应结果取自document对象,这里利用了一个xmlhttpRequest对象的<tt>responseText</tt>属性来暂时存储响应结果,目的是利用其事件处理器和回调的机制完成所需的任务。<br />
* The response text is retrieved from the document, and a fake XMLHttpRequest object
* is created containing a <tt>responseText</tt> property in order to conform to the
* requirements of event handlers and callbacks.</p>
*
* <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
* and some server technologies (notably JEE) may require some custom processing in order to
* retrieve parameter names and parameter values from the packet content.</p>
* @constructor
* @param {Object} config 配置对象。a configuration object.
*/
Ext.data.Connection = function(config){
Ext.apply(this, config);
this.addEvents(
/**
* @event beforerequest
* 任何Ajax请求发送之前触发。
* Fires before a network request is made to retrieve a data object.
* @param {Connection} conn This Connection object.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
"beforerequest",
/**
* @event requestcomplete
* 任何Ajax成功请求后触发。
* Fires if the request was successfully completed.
* @param {Connection} conn This Connection object.
* @param {Object} response The XHR object containing the response data.
* See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
* for details.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
"requestcomplete",
/**
* @event requestexception
* 服务端返回一个错误的HTTP状态码时触发。
* Fires if an error HTTP status was returned from the server.
* See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
* for details of HTTP status codes.
* @param {Connection} conn This Connection object.
* @param {Object} response The XHR object containing the response data.
* See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
* for details.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
"requestexception"
);
Ext.data.Connection.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Connection, Ext.util.Observable, {
/**
* @cfg {String} url (可选项)被用来向服务发起请求默认的url(默认值为undefined)。
* (Optional) The default URL to be used for requests to the server. (defaults to undefined)
*/
/**
* @cfg {Object} extraParams (可选项)一个包含属性值的对象,这些属性在该Connection发起的每次请求中作为外部参数(默认值为undefined)。
* (Optional) An object containing properties which are used as
* extra parameters to each request made by this object. (defaults to undefined)
*/
/**
* @cfg {Object} defaultHeaders (可选项)一个包含请求头信息的对象,此请求头被附加在该Connection对象的每次请求中(默认值为undefined)。
* (Optional) An object containing request headers which are added
* to each request made by this object. (defaults to undefined)
*/
/**
* @cfg {String} method (可选项)请求时使用的默认的http方法(默认为undefined;如果存在参数但没有设值,则值为post,否则为get)。
* (Optional) The default HTTP method to be used for requests.
* (defaults to undefined; if not set, but {@link #request} params are present, POST will be used;
* otherwise, GET will be used.)
*/
/**
* @cfg {Number} timeout (可选项)一次请求超时的毫秒数(默认为30秒钟)。
* (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
*/
timeout : 30000,
/**
* @cfg {Boolean} autoAbort (可选项)该request是否应当中断挂起的请求(默认值为false)。
* (Optional) Whether this request should abort any pending requests. (defaults to false)
* @type Boolean
*/
autoAbort:false,
/**
* @cfg {Boolean} disableCaching (可选项)设置为true就会添加一个独一无二的cache-buster参数来获取请求(默认值为true)。
* (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
* @type Boolean
*/
disableCaching: true,
/**
* @cfg {String} disableCachingParam (可选项)(Optional) Change the parameter which is sent went disabling caching
* through a cache buster. Defaults to '_dc'
* @type String
*/
disableCachingParam: '_dc',
/**
* <p>
* 向远程服务器发送一http请求。
* Sends an HTTP request to a remote server.</p>
* <p>
* <b>Important:</b> Ajax server requests are asynchronous, and this call will
* return before the response has been received. Process any returned data
* in a callback function.</p>
* <p>
* 要正确指定回调函数的作用域,应适用<tt>scope</tt>选项。
* To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
* @param {Object} options 包含如下属性的一对象:An object which may contain the following properties:<ul>
* <li><b>url</b> : String/Function (Optional)<div class="sub-desc">
* (可选项)发送请求的url,默认为配置的url。
* 若为函数类型那么其作用域将由配置项<tt>scope</tt>所指定。默认为配置好的URL。
* The URL to which to send the request, or a function to call which returns a URL string. The scope of the
* function is specified by the <tt>scope</tt> option. Defaults to configured URL.</div></li>
*
* <li><b>params</b> : Object/String/Function (可选项)(Optional)<div class="sub-desc">
* 一包含属性的对象(这些属性被用作request的参数)或一个编码后的url字串或一个能调用其中任一一属性的函数。
* 若为函数类型那么其作用域将由配置项<tt>scope</tt>所指定。
* An object containing properties which are used as parameters to the
* request, a url encoded string or a function to call to get either. The scope of the function
* is specified by the <tt>scope</tt> option.</div></li>
*
* <li><b>method</b> : String (可选项)(Optional)<div class="sub-desc">
* 该请求所用的http方面,默认值为配置的方法,或者当没有方法被配置时,如果没有发送参数时用get,有参数时用post。
* The HTTP method to use for the request. Defaults to the configured method, or if no method was configured,
* "GET" if no parameters are being sent, and "POST" if parameters are being sent. Note that
* the method name is case-sensitive and should be all caps.</div></li>
*
* <li><b>callback</b> : Function (可选项)(Optional)<div class="sub-desc">
* 该方法被调用时附上返回的http response对象。不管成功还是失败,该回调函数都将被调用,该函数中传入了如下参数:
* The function to be called upon receipt of the HTTP response. The callback is
* called regardless of success or failure and is passed the following
* parameters:<ul>
* <li><b>options</b> : Object<div class="sub-desc">>请求所调用的参数。The parameter to the request call.</div></li>
* <li><b>success</b> : Boolean<div class="sub-desc">请求成功则为true。True if the request succeeded.</div></li>
* <li><b>response</b> : Object<div class="sub-desc">包含了返回数据的xhr对象。The XMLHttpRequest object containing the response data.
* See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
* accessing elements of the response.</div></li>
* </ul></div></li>
* <li><a id="request-option-success"></a><b>success</b>: Function (可选项)(Optional)<div class="sub-desc">
* 该函数被调用取决于请求是否成功。该回调函数被传入如下参数:
* The function to be called upon success of the request. The callback is passed the following
* parameters:<ul>
* <li><b>response</b> : Object<div class="sub-desc">包含数据的xhr对象。The XMLHttpRequest object containing the response data.</div></li>
* <li><b>options</b> : Object<div class="sub-desc">请求所调用的参数。The parameter to the request call.</div></li>
* </ul></div></li>
* <li><b>failure</b> : Function (可选项)(Optional)<div class="sub-desc">
* 该函数被调用取决于请求失败。该回调函数被传入如下参数:
* The function to be called upon failure of the request. The callback is passed the following parameters:<ul>
*
* <li><b>response</b> : Object<div class="sub-desc">
* 包含数据的xhr对象。
* The XMLHttpRequest object containing the response data.</div></li>
*
* <li><b>options</b> : Object<div class="sub-desc">
* 请求所调用的参数。
* The parameter to the request call.</div></li>
* </ul></div></li>
*
* <li><b>scope</b> : Object (可选项)(Optional)<div class="sub-desc">
* 回调函数的作用域:回调函数"this"对象指针。默认值为浏览器窗口。
* The scope in which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were
* specified as functions from which to draw values, then this also serves as the scope for those function calls.
* Defaults to the browser window.</div></li>
*
* <li><b>form</b> : Element/HTMLElement/String (可选项)(Optional)<div class="sub-desc">
* 用来压入参数的一个<tt><form></tt>元素或<tt><form></tt>的标识。
* The <tt><form></tt> Element or the id of the <tt><form></tt> to pull parameters from.</div></li>
*
* <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (可选项)(Optional)<div class="sub-desc"><b>
* 如果该form对象是上传form,为true(通常情况下会自动探测)。
* Only meaningful when used with the <tt>form</tt> option</b>.
* <p>True if the form object is a file upload (will be set automatically if the form was
* configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
* <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
* performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
* DOM <tt><form></tt> element temporarily modified to have its
* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
* to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
* but removed after the return data has been gathered.</p>
* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
* server is using JSON to send the return object, then the
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
* is created containing a <tt>responseText</tt> property in order to conform to the
* requirements of event handlers and callbacks.</p>
* <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
* and some server technologies (notably JEE) may require some custom processing in order to
* retrieve parameter names and parameter values from the packet content.</p>
* </div></li>
*
* <li><b>headers</b> : Object (可选项)(Optional)<div class="sub-desc">为请求所加的请求头。
* Request headers to set for the request.</div></li>
*
* <li><b>xmlData</b> : Object (可选项)(Optional)<div class="sub-desc">
* 用于发送的xml document。注意:它将会被用来在发送数据中代替参数任务参数将会被追加在url中。
* XML document to use for the post. Note: This will be used instead of params for the post
* data. Any params will be appended to the URL.</div></li>
*
* <li>
* <b>jsonData</b> : Object/String (可选项)(Optional)<div class="sub-desc">
*
* JSON data to use as the post. Note: This will be used instead of params for the post
* data. Any params will be appended to the URL.</div>
* </li>
*
* <li>
* <b>disableCaching</b> : Boolean (可选项)(Optional)<div class="sub-desc">
* 设置为True,则添加一个独一无二的cache-buster参数来获取请求。
* True to add a unique cache-buster param to GET requests.</div>
* </li>
*
* </ul></p>
* <p>The options object may also contain any other property which might be needed to perform
* postprocessing in a callback because it is passed to callback functions.</p>
* @return {Number} transactionId The id of the server transaction. This may be used
* to cancel the request.
*/
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(p);
}
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 : o.timeout || this.timeout
};
var method = o.method||this.method||((p || o.xmlData || o.jsonData) ? "POST" : "GET");
if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
var dcp = o.disableCachingParam || this.disableCachingParam;
url += (url.indexOf('?') != -1 ? '&' : '?') + dcp + '=' + (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' || o.xmlData || o.jsonData) && p){
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。True if there is an outstanding request.
*/
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
*/
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){
var fc = doc.body.firstChild;
if(fc && String(fc.tagName).toLowerCase() == 'textarea'){ // json response wrapped in textarea
r.responseText = fc.value;
}else{
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]);
if(!this.debugUploads){
setTimeout(function(){Ext.removeNode(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++){
Ext.removeNode(hiddens[i]);
}
}
}
});
/**
* @class Ext.Ajax
* @extends Ext.data.Connection
* Ext.Ajax类继承了Ext.data.Connection,为Ajax的请求提供了最大灵活性的操作方式。示例代码:
* Global Ajax request class. Provides a simple way to make Ajax requests with maximum flexibility. Example usage:
* <pre><code>
// 简单的请求 Basic request
Ext.Ajax.request({
url: 'foo.php',
success: someFn,
failure: otherFn,
headers: {
'my-header': 'foo'
},
params: { foo: 'bar' }
});
// 简单的Ajax式的表单提交。Simple ajax form submission
Ext.Ajax.request({
form: 'some-form',
params: 'foo=bar'
});
// 规定每次请求的头部都有这样的字段。Default headers to pass in every request
Ext.Ajax.defaultHeaders = {
'Powered-By': 'Ext'
};
// 规定每次请求的头部都有这样的事件!Global Ajax events can be handled on every request!
Ext.Ajax.on('beforerequest', this.showSpinner, this);
</code></pre>
* @singleton
*/
Ext.Ajax = new Ext.data.Connection({
/**
* @cfg {String} url @hide
*/
/**
* @cfg {Object} extraParams 外部参数 @hide
*/
/**
* @cfg {Object} defaultHeaders 默认请求头 @hide
*/
/**
* @cfg {String} method 请求的方法 (可选项)(Optional) @hide
*/
/**
* @cfg {Number} timeout 超时时间 (可选项)(Optional) @hide
*/
/**
* @cfg {Boolean} autoAbort 自动中断 (可选项)(Optional) @hide
*/
/**
* @cfg {Boolean} disableCaching (Optional) 不启用缓存 (可选项)@hide
*/
/**
* @property disableCaching 设置为true使得增加一cache-buster参数来获取请求(默认为true)。
* True to add a unique cache-buster param to GET requests. (defaults to true)
* @type Boolean
*/
/**
* @property url 默认的被用来向服务器发起请求的url(默认为 undefined)。
* The default URL to be used for requests to the server. (defaults to undefined)
* @type String
*/
/**
* @property extraParams 外部参数,一个包含属性的对象(这些属性在该Connection发起的每次请求中作为外部参数)。
* An object containing properties which are used as extra parameters to each request made by this object. (defaults to undefined)
* @type Object
*/
/**
* @property defaultHeaders 默认的请求头,一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中)。
* An object containing request headers which are added to each request made by this object. (defaults to undefined)
* @type Object
*/
/**
* @property method 请求的方法,请求时使用的默认的http方法(默认为undefined;如果存在参数但没有设值,则值为post,否则为get)。
* The default HTTP method to be used for requests. Note that this is case-sensitive and should be all caps (defaults
* to undefined; if not set but parms are present will use "POST," otherwise "GET.")
* @type String
*/
/**
* @property timeout 超时时间,请求的超时豪秒数(默认为30秒)。
* The timeout in milliseconds to be used for requests. (defaults to 30000)
* @type Number
*/
/**
* @property autoAbort 自动中断。该request是否应当中断挂起的请求(默认值为false)。
* Whether a new request should abort any pending requests. (defaults to false)
* @type Boolean
*/
autoAbort : false,
/**
* 序列化传入的form为编码后的url字符串。
* Serialize the passed form into a url encoded string
* @param {String/HTMLElement} form
* @return {String}
*/
serializeForm : function(form){
return Ext.lib.Ajax.serializeForm(form);
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.JsonReader
* @extends Ext.data.DataReader
* Data reader类接受一个JSON响应结果后,创建一个由{@link Ext.data.Record}对象组成的数组,数组内的每个对象都是{@link Ext.data.Record}构造器负责映射(mappings)的结果。<br />
* Data reader class to create an Array of {@link Ext.data.Record} objects from a JSON response
* based on mappings in a provided {@link Ext.data.Record} constructor.<br>
* <p>
* 示例代码:Example code:
* <pre><code>
var Employee = Ext.data.Record.create([
{name: 'firstname'}, // 映射了Record的"firstname" 字段为行对象的同名键名称 map the Record's "firstname" field to the row object's key of the same name
{name: 'job', mapping: 'occupation'} // 映射了"job"字段为行对象的"occupation"键 map the Record's "job" field to the row object's "occupation" key
]);
var myReader = new Ext.data.JsonReader(
{ // metadata元数据属性,有以下的属性:The metadata property, with configuration options:
totalProperty: "results", // 该属性是指定记录集的总数(可选的)the property which contains the total dataset size (optional)
root: "rows", // 该属性是指定包含所有行对象的数组the property which contains an Array of row objects
idProperty: "id" // 该属性是指定每一个行对象中究竟哪一个是记录的ID字段(可选的)the property within each row object that provides an ID for the record (optional)
},
Employee // {@link Ext.data.Record}构造器是提供JSON对象的映射。{@link Ext.data.Record} constructor that provides mapping for JSON object
);
</code></pre>
* <p>形成这种形式的JSON对象:<br />This would consume a JSON data object of the form:</p><pre><code>
{
results: 2, // 对应Reader对象total属性。的Reader's configured totalProperty
rows: [ // 对应Reader对象root属性。Reader's configured root
{ id: 1, firstname: 'Bill', occupation: 'Gardener' }, // 一行对象 a row object
{ id: 2, firstname: 'Ben' , occupation: 'Horticulturalist' } // 另外的行对象 another row object
]
}
</code></pre>
* <p><b><u>使用metaData自动配置。 <br />Automatic configuration using metaData</u></b>
* <p>
* 随时都可以改变JsonReader的元数据,只要在数据对象中放置一个<b><tt>metaData</tt></b>的属性。
* 一旦将该属性对象检测出来,就会触发Reader所使用的{@link Ext.data.Store Store}对象身上的{@link Ext.data.Store#metachange metachange}事件。
* Metachange事件的处理函数在重新进行配置之时会处理<b><tt>metaData</tt></b>属性。
* 注意重新配置Store有可能会引发不存在的Fields或Records变为无效。<br />
* It is possible to change a JsonReader's metadata at any time by including a <b><tt>metaData</tt></b>
* property in the JSON data object.
* If the JSON data object has a <b><tt>metaData</tt></b> property, a
* {@link Ext.data.Store Store} object using this Reader will reconfigure itself to use the newly provided
* field definition and fire its {@link Ext.data.Store#metachange metachange} event.
* The metachange event
* handler may interrogate the <b><tt>metaData</tt></b> property to perform any configuration required.
* Note that reconfiguring a Store potentially invalidates objects which may refer to Fields or Records
* which no longer exist.</p>
*
* <p>
* JSON数据对象其中包含的<b><tt>metaData</tt></b>属性有:
* The <b><tt>metaData</tt></b> property in the JSON data object may contain:</p>
*
* <div class="mdetail-params"><ul>
* <li>
* 任何为该类服务的配置选项。<br />
* any of the configuration options for this class</li>
*
* <li>
* <b><tt>{@link Ext.data.Record#fields fields}</tt></b>的属性,会给JsonReader用作{@link Ext.data.Record#create data 产生Record方法}的参数,以便配置所产生的Records布局。<br />
* a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which the JsonReader will
* use as an argument to the {@link Ext.data.Record#create data Record create method} in order to
* configure the layout of the Records it will produce.</li>
*
* <li>
* JsonReader设置{@link Ext.data.Store}的{@link Ext.data.Store#sortInfo sortInfo}属性所使用的b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b>。
* a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property which the JsonReader will
* use to set the {@link Ext.data.Store}'s {@link Ext.data.Store#sortInfo sortInfo} property</li>
* <li>
* 任何需要的用户自定义属性。<br />
* any user-defined properties needed</li>
* </ul></div>
*
* <p>
* 要创建无须好像上一例那样配置的Record构造器的JsonReader对象,你可以采取这样的机制:<br />
* To use this facility to send the same data as the example above (without having to code the creation
* of the Record constructor), you would create the JsonReader like this:</p>
* <pre><code>
var myReader = new Ext.data.JsonReader();
</code></pre>
* <p>
* 可由数据库返回reader所需的配置信息,叫做metaData属性,只需要在第一次请求的时候返回便可,而且metaData属性可以实际数据并列放在一起:<br />
* The first data packet from the server would configure the reader by containing a
* <b><tt>metaData</tt></b> property <b>and</b> the data. For example, the JSON data object might take
* the form:</p>
<pre><code>
{
metaData: {
idProperty: 'id',
root: 'rows',
totalProperty: 'results',
fields: [
{name: 'name'},
{name: 'job', mapping: 'occupation'}
],
sortInfo: {field: 'name', direction:'ASC'}, // used by store to set its sortInfo
foo: 'bar' // custom property
},
results: 2,
rows: [
{ 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
{ 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' }
]
}
</code></pre>
* @cfg {String} totalProperty 记录集的总数的属性名称。如果是需要分页的话该属性就必须指定。
* Name of the property 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} 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} idProperty 指定每一个行对象中究竟哪一个是记录的ID字段(可选的)。
* Name of the property within a row object that contains a record identifier value.
* @constructor 创建一个新的JsonReader对象。Create a new JsonReader
* @param {Object} meta 元数据配置参数。Metadata configuration options.
* @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由{@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。
* Either an Array of field definition objects as passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record} constructor 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, {
/**
* 送入到构造器的JsonReader的元数据,或由数据包携带的<b><tt>metaData</tt></b>属性。
* This JsonReader's metadata as passed to the constructor, or as passed in
* the last data packet's <b><tt>metaData</tt></b> property.
* @type Mixed
* @property meta
*/
/**
* 从远端服务器取得数据后,仅供DataProxy对象所使用的方法。
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response 包含JSON的数据在responseText属性的XHR的对象。The XHR object which contains the JSON data in its responseText.
* @return {Object} data 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存。A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
read : function(response){
var json = response.responseText;
var o = eval("("+json+")");
if(!o) {
throw {message: "JsonReader.read: Json object not found"};
}
return this.readRecords(o);
},
// private function a store will implement
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;
};
}(),
/**
* 由一个JSON对象产生一个包含Ext.data.Records的对象块。
* Create a data block containing Ext.data.Records from a JSON object.
* @param {Object} o 该对象包含以下属性:root指定包含所有行对象的数组;totalProperty制定了记录集的总数的属性名称(可选的)。
* 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} 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存。data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
readRecords : function(o){
/**
* 异步通信完毕后,保留原始JSON数据以便将来有必要的用途。如果没有数据加载,那么会抛出一个load异常,该属性为undefined。
* After any data loads, the raw JSON data is available for further custom processing. If no data is
* loaded or there is a load exception this property will be undefined.
* @type Object
*/
this.jsonData = o;
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);
}
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
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 || s.idProperty) {
var g = this.getJsonAccessor(s.id || s.idProperty);
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, n);
}
var record = new Record(values, id);
record.json = n;
records[i] = record;
}
return {
success : success,
records : records,
totalRecords : totalRecords
};
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.JsonWriter
* @extends Ext.data.DataWriter
* 这个DataWriter的子类相对于远程CRUD操作而言,这是一个在前端的初始化部分,负责写入单个或多个的{@link Ext.data.Record}对象。<br />
* DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action.
*/
Ext.data.JsonWriter = function(config) {
Ext.data.JsonWriter.superclass.constructor.call(this, config);
// careful to respect "returnJson", renamed to "encode"
// TODO: remove after Ext-3.0.1 release
if (this.returnJson != undefined) {
this.encode = this.returnJson;
}
}
Ext.extend(Ext.data.JsonWriter, Ext.data.DataWriter, {
/**
* @cfg {Boolean} returnJson <b>Deprecated, will be removed in Ext-3.0.1</b>. Use {@link Ext.data.JsonWriter#encode} instead.
*/
returnJson : undefined,
/**
* @cfg {Boolean} encode
* <tt>true</tt>表示对{@link Ext.data.DataWriter#toHash 哈希数据}进行{@link Ext.util.JSON#encode 编码}。
* 默认为<tt>true</tt>。当使用{@link Ext.data.DirectProxy}的时候,不同于Ext.Direct.JsonProvider有自己的JSON编码,所以该配置项要设置为<tt>false</tt>。
* 此外,如果你使用的是{@link Ext.data.HttpProxy},设置该项为<tt>false</tt>就会使得HttpProxy采用 {@link Ext.Ajax#request}配置参数的<b>jsonData</b>传输数据,而非<b>params</b>。
* 当使用{@link Ext.data.Store#restful}的Store,一些服务端框架就会认为数据从jsonData的通道经过。如果采用这样的机制的话,应该让底层的连接对象完成编码的工作(如Ext.Ajax),把<b>encode: 设为<tt>false</tt></b>。
* <br />
* <tt>true</tt> to {@link Ext.util.JSON#encode encode} the
* {@link Ext.data.DataWriter#toHash hashed data}. Defaults to <tt>true</tt>. When using
* {@link Ext.data.DirectProxy}, set this to <tt>false</tt> since Ext.Direct.JsonProvider will perform
* its own json-encoding. In addition, if you're using {@link Ext.data.HttpProxy}, setting to <tt>false</tt>
* will cause HttpProxy to transmit data using the <b>jsonData</b> configuration-params of {@link Ext.Ajax#request}
* instead of <b>params</b>. When using a {@link Ext.data.Store#restful} Store, some serverside frameworks are
* tuned to expect data through the jsonData mechanism. In those cases, one will want to set <b>encode: <tt>false</tt></b>, as in
* let the lower-level connection object (eg: Ext.Ajax) do the encoding.
*/
encode : true,
/**
* 写事件的最后动作。将写入的数据对象添加到参数。
* Final action of a write event. Apply the written data-object to params.
* @param {Object} params 要写入的参数对象。http params object to write-to.
* @param {Object} baseParams Store定义的那个{@link Ext.data.Store#baseParams},该参数必须由{@link Ext.data.JsonWriter}或{@link Ext.data.XmlWriter}进行编码。baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
* @param {Object/Object[]} data 由Store推演过来的数据对象。Data-object representing compiled Store-recordset.
*/
render : function(params, baseParams, data) {
if (this.encode === true) {
// Encode here now.
Ext.apply(params, baseParams);
params[this.meta.root] = Ext.encode(data);
} else {
// defer encoding for some other layer, probably in {@link Ext.Ajax#request}. Place everything into "jsonData" key.
var jdata = Ext.apply({}, baseParams);
jdata[this.meta.root] = data;
params.jsonData = jdata;
}
},
/**
* Implements abstract Ext.data.DataWriter#createRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Object}
*/
createRecord : function(rec) {
return this.toHash(rec);
},
/**
* Implements abstract Ext.data.DataWriter#updateRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Object}
*/
updateRecord : function(rec) {
return this.toHash(rec);
},
/**
* Implements abstract Ext.data.DataWriter#destroyRecord
* @protected
* @param {Ext.data.Record} rec
* @return {Object}
*/
destroyRecord : function(rec) {
return rec.id;
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.ArrayStore
* @extends Ext.data.Store
* 小型的辅助类使得数组转化为Store更来得容易。<br />
* Small helper class to make creating Stores from Array data easier.
* @cfg {Number} id 记录id的索引数组,留空为自动生成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.ArrayStore = Ext.extend(Ext.data.Store, {
constructor: function(config){
Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
reader: new Ext.data.ArrayReader(config)
}));
},
loadData : function(data, append){
if(this.expandData === true){
var r = [];
for(var i = 0, len = data.length; i < len; i++){
r[r.length] = [data[i]];
}
data = r;
}
Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
}
});
Ext.reg('arraystore', Ext.data.ArrayStore);
// backwards compat
Ext.data.SimpleStore = Ext.data.ArrayStore;
Ext.reg('simplestore', Ext.data.SimpleStore); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.ArrayReader
* @extends Ext.data.JsonReader
* <p>
* Data reader透过一个数组而转化成为{@link Ext.data.Record}对象所组成的数组,数组内的每个元素就代表一行数据。
* 字段定义中,通过使用下标来把字段抽取到Record对象,属性<em>mapping</em>用于指定下标,如果不指定就按照定义的先后顺序。<br />
* Data reader class to create an Array of {@link 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>
* 示例代码:
* Example code:.
* <pre><code>
var Employee = Ext.data.Record.create([
{name: 'name', mapping: 1}, // 属性<em>mapping</em>用于指定下标 // "mapping" only needed if an "id" field is present which
{name: 'occupation', mapping: 2} // 如果不指定就按照定义的先后顺序 // precludes using the ordinal position as the index.
]);
var myReader = new Ext.data.ArrayReader({
id: 0 // 提供数组的下标位置存放记录的ID(可选的) // The subscript within row Array that provides an ID for the Record (optional)
}, Employee);
</code></pre>
* <p>
* 形成这种形式的数组:This would consume an Array like this:
* <pre><code>
[ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
</code></pre>
* @cfg {String} id (可选的)提供数组的下标位置存放记录的ID。(optional)The subscript within row Array that provides an ID for the Record
* @constructor 创建一个ArrayReader对象。Create a new ArrayReader
* @param {Object} meta 元数据配置参数。Metadata configuration options.
* @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由
* {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。
* Either an Array of field definition objects as specified to {@link Ext.data.Record#create},
* or a {@link Ext.data.Record Record} constructor created using {@link Ext.data.Record#create}.
*/
Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
/**
* 由一个数组产生一个包含Ext.data.Records的对象块。
* Create a data block containing Ext.data.Records from an Array.
* @param {Object} o 包含行对象的数组,就是记录集。An Array of row objects which represents the dataset.
* @return {Object} 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存。data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
readRecords : function(o){
this.arrayData = o;
var s = this.meta;
var sid = s ? (s.idIndex || s.id) : null;
var recordType = this.recordType, fields = recordType.prototype.fields;
var records = [];
if(!this.getRoot){
this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
if(s.totalProperty) {
this.getTotal = this.getJsonAccessor(s.totalProperty);
}
}
var root = this.getRoot(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, n);
values[f.name] = v;
}
var record = new recordType(values, id);
record.json = n;
records[records.length] = record;
}
var totalRecords = records.length;
if(s.totalProperty){
var v = parseInt(this.getTotal(o), 10);
if(!isNaN(v)){
totalRecords = v;
}
}
return {
records : records,
totalRecords : totalRecords
};
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.DataReader
* 用于读取结构化数据(来自数据源)然后转换为{@link Ext.data.Record}对象集合和元数据{@link Ext.data.Store}这二者合成的对象。
* 这个类应用于被扩展而最好不要直接使用。要了解当前的实现,可参阅{@link Ext.data.ArrayReader},{@link Ext.data.JsonReader}以及{@link Ext.data.XmlReader}。
* <br />
* Abstract base class for reading structured data from a data source and converting
* it into an object containing {@link Ext.data.Record} objects and metadata for use
* by an {@link Ext.data.Store}. This class is intended to be extended and should not
* be created directly. For existing implementations, see {@link Ext.data.ArrayReader},
* {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.
* @constructor 创建DataReader对象。Create a new DataReader
* @param {Object} meta Metadata 配置选项的元数据(由实现指定的)。configuration options (implementation-specific)
* @param {Object} recordType 既可以是字段的定义对象组成的数组,可以是一个由{@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。
* Either an Array of field definition objects as specified
* in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
* using {@link Ext.data.Record#create}.
*/
Ext.data.DataReader = function(meta, recordType){
/**
* 透过构造器参数传入到此DataReader的配置信息。<br />
* This DataReader's configured metadata as passed to the constructor.
* @type Mixed
* @property meta
*/
this.meta = meta;
this.recordType = Ext.isArray(recordType) ?
Ext.data.Record.create(recordType) : recordType;
};
Ext.data.DataReader.prototype = {
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.GroupingStore
* @extends Ext.data.Store
* 一个特殊的Store实现,提供由字段中提取某一个来划分记录的功能。
* GroupingStore通常和{@link Ext.grid.GroupingView}一起用,来证明为分组GridPanel划分data model。<br />
* A specialized store implementation that provides for grouping records by one of the available fields. This
* is usually used in conjunction with an {@link Ext.grid.GroupingView} to proved the data model for
* a grouped GridPanel.
* @constructor 创建一个新的GroupingStore对象。Creates a new GroupingStore.
* @param {Object} config 一配置对象,包含了Store用来访问数据,及读数据至Records的对象。 A config object containing the objects needed for the Store to access data,
* and read the data into Records.
*/
Ext.data.GroupingStore = Ext.extend(Ext.data.Store, {
/**
* @cfg {String} groupField
* Store中哪一个字段的数据是要排序的(默认为"")。
* The field name by which to sort the store's data (defaults to '').
*/
/**
* @cfg {Boolean} remoteGroup
* True表示让服务端进行排序,false就表示本地排序(默认为false)
* 如果是本地的排序,那么数据会立即发生变化。
* 如果是远程的, 那么这仅仅是一个辅助类,它会向服务器发出“groupBy”的参数。
* True if the grouping should apply on the server side, false if it is local only (defaults to false). If the
* grouping is local, it can be applied immediately to the data. If it is remote, then it will simply act as a
* helper, automatically sending the grouping field name as the 'groupBy' param with each XHR call.
*/
remoteGroup : false,
/**
* @cfg {Boolean} groupOnSort
* True表示为当分组操作发起时,在分组字段上进行数据排序,false表示为只根据当前排序的信息来排序(默认为false)。
* True to sort the data on the grouping field when a grouping operation occurs, false to sort based on the
* existing sort info (defaults to false).
*/
groupOnSort:false,
/**
* 清除当前的组,并使用默认排序来刷新数据。
* Clears any existing grouping and refreshes the data using the default sort.
*/
clearGrouping : function(){
this.groupField = false;
if(this.remoteGroup){
if(this.baseParams){
delete this.baseParams.groupBy;
}
this.reload();
}else{
this.applySort();
this.fireEvent('datachanged', this);
}
},
/**
* 对特定的字段进行分组。
* Groups the data by the specified field.
* @param {String} field field中哪一个字段的数据是要排序的名称。The field name by which to sort the store's data
* @param {Boolean} forceRegroup (可选的)True表示为强制必须刷新组,即使传入的组与当前在分组的字段同名;false表示跳过同名字段的分组(默认为false)。 (optional)True to force the group to be refreshed even if the field passed
* in is the same as the current grouping field, false to skip grouping on the same field (defaults to false)
*/
groupBy : function(field, forceRegroup){
if(this.groupField == field && !forceRegroup){
return; // already grouped by this field
}
this.groupField = field;
if(this.remoteGroup){
if(!this.baseParams){
this.baseParams = {};
}
this.baseParams['groupBy'] = field;
}
if(this.groupOnSort){
this.sort(field);
return;
}
if(this.remoteGroup){
this.reload();
}else{
var si = this.sortInfo || {};
if(si.field != field){
this.applySort();
}else{
this.sortData(field);
}
this.fireEvent('datachanged', this);
}
},
// private
applySort : function(){
Ext.data.GroupingStore.superclass.applySort.call(this);
if(!this.groupOnSort && !this.remoteGroup){
var gs = this.getGroupState();
if(gs && gs != this.sortInfo.field){
this.sortData(this.groupField);
}
}
},
// private
applyGrouping : function(alwaysFireChange){
if(this.groupField !== false){
this.groupBy(this.groupField, true);
return true;
}else{
if(alwaysFireChange === true){
this.fireEvent('datachanged', this);
}
return false;
}
},
// private
getGroupState : function(){
return this.groupOnSort && this.groupField !== false ?
(this.sortInfo ? this.sortInfo.field : undefined) : this.groupField;
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.DataWriter
* <p>
* Ext.data.DataWriter提供了增、删、改、查的实现让Ext.data.Store与服务端框架密切通讯。
* Writer控制了Store了自动管理AJAX的请求,让其成为Store CRUD操作的管道。
* <br />
* Ext.data.DataWriter facilitates create, update, and destroy actions between
* an Ext.data.Store and a server-side framework. A Writer enabled Store will
* automatically manage the Ajax requests to perform CRUD actions on a Store.</p>
* <p>
* Ext.data.DataWriter是一个抽象类,一般用于让来被继承。例如{@link Ext.data.JsonWriter}。
* <br />
* Ext.data.DataWriter is an abstract base class which is intended to be extended
* and should not be created directly. For existing implementations, see
* {@link Ext.data.JsonWriter}.</p>
* <p>创建一个Writer很简单:Creating a writer is simple:</p>
* <pre><code>
var writer = new Ext.data.JsonWriter();
* </code></pre>
* <p>通过proxy对象激活Store对象来控制writer,也就是配置一个<code>url</code>:<br />The proxy for a writer enabled store can be configured with a simple <code>url</code>:</p>
* <pre><code>
// Create a standard HttpProxy instance.
var proxy = new Ext.data.HttpProxy({
url: 'app.php/users'
});
* </code></pre>
* <p>
* 对于更细颗粒的控制,proxy也可配置成为 <code>api</code>:
* For finer grained control, the proxy may also be configured with an <code>api</code>:</p>
* <pre><code>
// Use the api specification 用API指定
var proxy = new Ext.data.HttpProxy({
api: {
read : 'app.php/users/read',
create : 'app.php/users/create',
update : 'app.php/users/update',
destroy : 'app.php/users/destroy'
}
});
* </code></pre>
* <p>创建Writer控制的Store的:Creating a Writer enabled store:</p>
* <pre><code>
var store = new Ext.data.Store({
proxy: proxy,
reader: reader,
writer: writer
});
* </code></pre>
* @constructor 创建一个新的DataWriter。Create a new DataWriter
* @param {Object} meta 配置选项的元数据(由实现指定)Metadata configuration options (implementation-specific)
* @param {Object} recordType {@link Ext.data.Record#create}规定的对象数组,或是用{@link Ext.data.Record#create}生成的{@link Ext.data.Record}对象。Either an Array of field definition objects as specified
* in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
* using {@link Ext.data.Record#create}.
*/
Ext.data.DataWriter = function(config){
/**
* This DataWriter's configured metadata as passed to the constructor.
* @type Mixed
* @property meta
*/
Ext.apply(this, config);
};
Ext.data.DataWriter.prototype = {
/**
* @cfg {Boolean} writeAllFields
* 默认是<tt>false</tt>。设为<tt>true</tt>的话,就表示让DataWriter返回所有那个记录的所有字段,不仅仅是修改的那些字段。<br />
* <tt>true</tt>就是记录那些修改的字段而已。<br />
* <tt>false</tt> by default. Set <tt>true</tt> to have DataWriter return ALL fields of a modified
* record -- not just those that changed.
* <tt>false</tt> to have DataWriter only request modified fields from a record.
*/
writeAllFields : false,
/**
* @cfg {Boolean} listful
* 默认是<tt>false</tt>。设为<tt>true</tt>的话,就表示DataWriter写入HTTP参数的时候总是一数组,即使单个记录也如是。<br />
* <tt>false</tt> by default. Set <tt>true</tt> to have the DataWriter <b>always</b> write HTTP params as a list,
* even when acting upon a single record.
*/
listful : false, // <-- listful is actually not used internally here in DataWriter. @see Ext.data.Store#execute.
/**
* 服务端写操作的前期写数据。只需要有DataWriter#update、DataWriter#create、DataWriter#destroy的proxy就可以囊括“写”的操作。<br />
* Writes data in preparation for server-write action. Simply proxies to DataWriter#update, DataWriter#create
* DataWriter#destroy.
* @param {String} action [CREATE|UPDATE|DESTROY]
* @param {Object} params 写入的hash参数。The params-hash to write-to
* @param {Record/Record[]} rs 要写的数据。The recordset write.
*/
write : function(action, params, rs) {
this.render(action, rs, params, this[action](rs));
},
/**
* 抽象的方法,应该由DataWriter的子类提供,扩展子类时重写该方法就可以使用参数“data”和“params”。
* 送抵的数据对象会依据用户在DataReader配置的元数据信息产生真正的渲染数据。<br />
* abstract method meant to be overridden by all DataWriter extensions. It's the extension's job to apply the "data" to the "params".
* The data-object provided to render is populated with data according to the meta-info defined in the user's DataReader config,
* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
* @param {Record[]} rs Store数据集。Store recordset
* @param {Object} params 发送到服务器的HTTP参数。Http params to be sent to server.
* @param {Object} data 依据DataReader元数据产生的数据对象。data object populated according to DataReader meta-data.
*/
render : Ext.emptyFn,
/**
* update
* @param {Object} p 应用于结果的hash参数。Params-hash to apply result to.
* @param {Record/Record[]} rs 写入的记录。Record(s) to write
* @private
*/
update : function(rs) {
var params = {};
if (Ext.isArray(rs)) {
var data = [],
ids = [];
Ext.each(rs, function(val){
ids.push(val.id);
data.push(this.updateRecord(val));
}, this);
params[this.meta.idProperty] = ids;
params[this.meta.root] = data;
}
else if (rs instanceof Ext.data.Record) {
params[this.meta.idProperty] = rs.id;
params[this.meta.root] = this.updateRecord(rs);
}
return params;
},
/**
* @cfg {Function} saveRecord 抽象的方法,应该由子类提供,如{@link Ext.data.JsonWriter#saveRecord JsonWriter.saveRecord}。Abstract method that should be implemented in all subclasses
* (e.g.: {@link Ext.data.JsonWriter#saveRecord JsonWriter.saveRecord}
*/
updateRecord : Ext.emptyFn,
/**
* create
* @param {Object} p 应用于结果的hash参数。Params-hash to apply result to.
* @param {Record/Record[]} rs 写入的记录。Record(s) to write
* @private
*/
create : function(rs) {
var params = {};
if (Ext.isArray(rs)) {
var data = [];
Ext.each(rs, function(val){
data.push(this.createRecord(val));
}, this);
params[this.meta.root] = data;
}
else if (rs instanceof Ext.data.Record) {
params[this.meta.root] = this.createRecord(rs);
}
return params;
},
/**
* @cfg {Function} createRecord 抽象的方法,应该由子类提供,如{@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord}。Abstract method that should be implemented in all subclasses
* (e.g.: {@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord})
*/
createRecord : Ext.emptyFn,
/**
* destroy
* @param {Object} p 应用于结果的hash参数。Params-hash to apply result to.
* @param {Record/Record[]} rs 写入的记录。Record(s) to write
* @private
*/
destroy : function(rs) {
var params = {};
if (Ext.isArray(rs)) {
var data = [],
ids = [];
Ext.each(rs, function(val){
data.push(this.destroyRecord(val));
}, this);
params[this.meta.root] = data;
} else if (rs instanceof Ext.data.Record) {
params[this.meta.root] = this.destroyRecord(rs);
}
return params;
},
/**
* @cfg {Function} destroyRecord 抽象的方法,应该由子类提供,如{@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord}。Abstract method that should be implemented in all subclasses
* (e.g.: {@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord})
*/
destroyRecord : Ext.emptyFn,
/**
* 转换Recod为hash。Converts a Record to a hash
* @param {Record} record 记录
* @private
*/
toHash : function(rec) {
var map = rec.fields.map,
data = {},
raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
m;
Ext.iterate(raw, function(prop, value){
if((m = map[prop])){
data[m.mapping ? m.mapping : m.name] = value;
}
});
data[this.meta.idProperty] = rec.id;
return data;
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见http://ajaxjs.com 或者 http://jstang.cn
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.Response
* 框架内使用的通用类,用于规范一般的响应处理。<br />
* A generic response class to normalize response-handling internally to the framework.
*/
Ext.data.Response = function(params) {
Ext.apply(this, params);
};
Ext.data.Response.prototype = {
/**
* @cfg {String} action {@link Ext.data.Api#actions}
*/
action: undefined,
/**
* @cfg {Boolean} success
*/
success : undefined,
/**
* @cfg {String} message
*/
message : undefined,
/**
* @cfg {Array/Object} data
*/
data: undefined,
/**
* @cfg {Object} raw 由服务端代码生成的最原始响应内容。The raw response returned from server-code
*/
raw: undefined,
/**
* @cfg {Ext.data.Record/Ext.data.Record[]} records 相关的请求动作。related to the Request action
*/
records: undefined
};
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.HttpProxy
* @extends Ext.data.DataProxy
* 一个{@link Ext.data.DataProxy}所实现的子类,能从{@link Ext.data.Connection Connection}(针对某个URL地址)对象读取数据。<br />
* An implementation of {@link Ext.data.DataProxy} that reads a data object from a {@link Ext.data.Connection Connection} object
* configured to reference a certain URL.
* @constructor
* @param {Object} conn 一个{@link Ext.data.Connection}对象,或像{@link Ext.Ajax#request}那样的配置项。
* 如果是配置项,那么就会创建一个为这次请求服务的{@link Ext.Ajax}单件对象。
* An implementation of {@link Ext.data.DataProxy} that reads a data object from a {@link Ext.data.Connection Connection} object
* configured to reference a certain URL.<br>
* <b>注意这个类不能脱离本页面的范围进行跨域(Cross Domain)获取数据。
* Note that this class cannot be used to retrieve data from a domain other than the domain
* from which the running page was served.</b><br>
* 要进行跨域获取数据,请使用{@link Ext.data.ScriptTagProxy ScriptTagProxy}。
* For cross-domain access to remote data, use a {@link Ext.data.ScriptTagProxy ScriptTagProxy}.
* <br>
* 为了浏览器能成功解析返回来的XML document对象,HTTP Response的content-type 头必须被设成为text/xml。
* 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 一个{@link Ext.data.Connection}对象,或者{@link Ext.Ajax#request}选项参数。<br />
* an {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.
* <p>
* 注意如果该HttpProxy正在使用的是{@link Ext.data.Store Store},那么Store的{@link #load}调用将会覆盖全部指定的<tt>callback</tt>与<tt>params</tt>选项。
* 这样,在Store的{@link Ext.data.Store#events events}那里就可以改变参数,或处理加载事件。
* 在实例化的时候就会使用了Store的{@link Ext.data.Store#baseParams baseParams}。<br />
* Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the Store's call to
* {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt> options. In this
* case, use the Store's {@link Ext.data.Store#events events} to modify parameters, or react to loading events.
* The Store's {@link Ext.data.Store#baseParams baseParams} may also be used to pass parameters known at
* instantiation time.
* </p>
* <p>如果传入一个选项参数,那么就即会使用{@link Ext.Ajax}这个单例对象进行网络通讯。If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make the request.</p>
*/
Ext.data.HttpProxy = function(conn){
Ext.data.HttpProxy.superclass.constructor.call(this);
/**
* 向服务器端方面负责发起请求的Connection对象(或者是{@link Ext.Ajax#request}参数对象)。
* 当请求数据的方式改变时该对象的这个属性也会应因应改变。
* The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy uses to make requests to the server.
* Properties of this object may be changed dynamically to change the way data is requested.
* @type Connection
* @property conn
*/
this.conn = conn;
this.useAjax = !conn || !conn.events;
/**
* @event loadexception
* 当数据加载的时候如有错误发生触发该事件。发生该事件归咎于两种原因:
* Fires if an exception occurs in the Proxy during data loading. This event can be fired for one of two reasons:
* <ul><li><b>load方法返回success: false。The load call returned success: false.</b>
* 这表示服务端逻辑返回错误的状态信号,没有可用的数据。这样该事件将会触发而第四个参数(读错误)将是null。
* This means the server logic returned a failure
* status and there is no data to read. In this case, this event will be raised and the
* fourth parameter (read error) will be null.</li>
* <li><b>虽然load方法成功了,但reader不能够读取响应的数据。The load succeeded but the reader could not read the response.</b>
* 这表示服务端是返回了数据,但解析数据时有问题,已配置好的Reader就抛出异常。这样会触发该事件并将捕获的异常放在该事件的第四个参数中。
* 注意该事件依赖了{@link Ext.data.Store},所以你也可以直接在任意一个Store实例上侦听事件。
* This means the server returned data, but the configured Reader threw an error while reading the data. In this case, this event will be
* raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>
* Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly
* on any Store instance.
* @param {Object} this
* @param {Object} options 指定的加载选项(请参阅{@link #load})。The loading options that were specified (see {@link #load} for details)
* @param {Object} response 包含响应数据的XMLHttpRequest对象。The XMLHttpRequest object containing the response data
* @param {Error} e 已准备好的Reader无法读取数据的情况下,捕获的JavaScript Error对象。
* 如果load调用返回success: false的话,该参数为null。
* The JavaScript Error object caught if the configured Reader could not read the data.
* If the load call returned success: false, this parameter will be null.
*/
};
Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {
/**
* 返回这个Proxy所调用的{@link Ext.data.Connection}。
* Return the {@link Ext.data.Connection} object being used by this Proxy.
* @return {Connection} {Connection} Connection对象。该对象可以被用来订阅事件,而且比DataProxy事件更细微的颗粒度。
* The Connection object. This object may be used to subscribe to events on
* a finer-grained basis than the DataProxy events.
*/
getConnection : function(){
return this.useAjax ? Ext.Ajax : this.conn;
},
/**
* 根据指定的URL位置加载数据(透过一个配置好的{@link Ext.data.Connection})。
* 由指定的{@link Ext.data.DataReader}实例来解析这个Ext.data.Records块,并由指定的回调来处理这个块。
* 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 一个对象,其属性用于向远端服务器作HTTP请求时所用的参数。An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader 能转换数据为Ext.data.Records块的Reader对象。The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback 会送入Ext.data.records块的函数。函数一定会传入:The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>Record对象。The Record block object</li>
* <li>从load函数那里来的参数"arg"。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.
*/
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.data.ScriptTagProxy
* @extends Ext.data.DataProxy
* 一个{@link Ext.data.DataProxy}所实现的子类,能从一个与本页不同的域的URL地址上读取数据对象。<br />
* 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>
* <p>
* <b>注意如果你从与一个本页所在域不同的地方获取数据的话,应该使用这个类,而非HttpProxy。<br />
* 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 HttpProxy.</b><br>
* </p>
* 服务端返回的必须是JSON格式的数据,这是因为ScriptTagProxy是把返回的数据放在一个<script>标签中保存的。<br />
* The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript
* source code because it is used as the source inside a <script> tag.<br>
* <p>为了浏览器能够自动处理返回的数据,服务器应该在打包数据对象的同时,指定一个回调函数的函数名称,这个名称从ScriptTagProxy发出的参数送出。
* 下面是一个Java中的Servlet例子,可适应ScriptTagProxy或者HttpProxy的情况,取决于是否有callback的参数送入:<br />
* 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>
* <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(");");
}
</code></pre>
*
* @constructor
* @param {Object} config 配置项对象 A configuration object.
*/
Ext.data.ScriptTagProxy = function(config){
Ext.data.ScriptTagProxy.superclass.constructor.call(this);
Ext.apply(this, config);
this.head = document.getElementsByTagName("head")[0];
/**
* @event loadexception
* 当数据加载的时候如有错误发生触发该事件。发生该事件归咎于两种原因:
* Fires if an exception occurs in the Proxy during data loading. This event can be fired for one of two reasons:
* <ul><li><b>load方法返回success: false。The load call returned success: false.</b>
* 这表示服务端逻辑返回错误的状态信号,没有可用的数据。这样该事件将会触发而第四个参数(读错误)将是null。
* This means the server logic returned a failure
* status and there is no data to read. In this case, this event will be raised and the
* fourth parameter (read error) will be null.</li>
* <li><b>虽然load方法成功了,但reader不能够读取响应的数据。The load succeeded but the reader could not read the response.</b>
* 这表示服务端是返回了数据,但解析数据时有问题,已配置好的Reader就抛出异常。这样会触发该事件并将捕获的异常放在该事件的第四个参数中。
* 注意该事件依赖了{@link Ext.data.Store},所以你也可以直接在任意一个Store实例上侦听事件。
* This means the server returned data, but the configured Reader threw an error while reading the data. In this case, this event will be
* raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>
* Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly
* on any Store instance.
* @param {Object} this
* @param {Object} options 指定的加载选项(请参阅{@link #load})。The loading options that were specified (see {@link #load} for details)
* @param {Object} response 包含响应数据的XMLHttpRequest对象。The XMLHttpRequest object containing the response data
* @param {Error} e 已准备好的Reader无法读取数据的情况下,捕获的JavaScript Error对象。
* 如果load调用返回success: false的话,该参数为null。
* The JavaScript Error object caught if the configured Reader could not read the data.
* If the load call returned success: false, this parameter will be null.
*/
};
Ext.data.ScriptTagProxy.TRANS_ID = 1000;
Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
/**
* @cfg {String} url 请求数据对象的URL地址。
* The URL from which to request the data object.
*/
/**
* @cfg {Number} timeout (optional) 响应的超时限制。默认为30秒。
* The number of milliseconds to wait for a response. Defaults to 30 seconds.
*/
timeout : 30000,
/**
* @cfg {String} callbackParam (Optional) (可选的)这个值会作为参数传到服务端方面。默认是“callback”。
* 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>得到返回的数据后,客户端方面会执行callbackParam指定名称的函数,因此这个值必须要让服务端进行处理。这个函数将有一个唯一的参数,就是数据对象本身。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.
*/
callbackParam : "callback",
/**
* @cfg {Boolean} nocache (optional) (可选的)默认值为true,在请求中添加一个独一无二的参数来禁用缓存。
* Defaults to true. Disable caching by adding a unique parameter name to the request.
*/
nocache : true,
/**
* 根据指定的URL位置加载数据。
* 由指定的Ext.data.DataReader实例来解析这个Ext.data.Records块,并由指定的回调来处理这个块。
* 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 一个对象,其属性用于向远端服务器作HTTP请求时所用的参数。
* An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader 能转换数据为Ext.data.Records块的Reader对象。
* The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback 会送入Ext.data.records块的函数。函数一定会传入这些参数:
* The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>Record对象 The Record block object</li>
* <li>从load函数那里来的参数"arg"。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.
*/
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Window
* @extends Ext.Panel
* <p>
* 一种专用于程序中的"视窗"(window)的特殊面板。Window默认下是可拖动的{@link #draggable}、浮动的窗体。
* 窗体可以最大化到整个视图、恢复原来的大小,还可以最小化{@link #minimize}。<br />
* A specialized panel intended for use as an application window. Windows are floated, {@link #resizable}, and
* {@link #draggable} by default. Windows can be maximized to fill the viewport, restored to their prior size, and can be {@link #minimize}d.
* </p>
* <p>
* Windows既可关联到{@link Ext.WindowGroup}或籍由{@link Ext.WindowManager}来管理,
* 提供分组(grouping),活动(activation),置前/置后(to front/back)或其它应用程序特定的功能。<br />
* Windows can also be linked to a {@link Ext.WindowGroup} or managed by the {@link Ext.WindowMgr} to provide
* grouping, activation, to front, to back and other application-specific behavior.</p>
* <p>
* 缺省状态下,窗体都渲染到document.body。
* 要强制{@link #constrain}窗体以某个元素为依托就要使用{@link Ext.Component#renderTo renderTo}方法。<br />
* By default, Windows will be rendered to document.body. To {@link #constrain} a Window to another element
* specify {@link Ext.Component#renderTo renderTo}.</p>
* @constructor
* @param {Object} config 配置项对象。The config object
*/
Ext.Window = Ext.extend(Ext.Panel, {
/**
* @cfg {Number} x
* 设置当窗体初次显示的时候,距离左方边缘的X坐标。默认为在窗体其容器元素{@link Ext.Element Element}的居中位置(窗体渲染的元素)。
* The X position of the left edge of the window on initial showing. Defaults to centering the Window within
* the width of the Window's container {@link Ext.Element Element} (The Element that the Window is rendered to).
*/
/**
* @cfg {Number} y
* 设置当窗体初次显示的时候,距离左方边缘的Y坐标。默认为在窗体其容器元素{@link Ext.Element Element}的居中位置(窗体渲染的元素)。
* The Y position of the top edge of the window on initial showing. Defaults to centering the Window within
* the height of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
*/
/**
* @cfg {Boolean} modal
* True 表示为当window显示时对其后面的一切内容进行遮罩,false表示为限制对其它UI元素的语法(默认为 false)。
* True to make the window modal and mask everything behind it when displayed, false to display it without
* restricting access to other UI elements (defaults to false).
*/
/**
* @cfg {String/Element} animateTarget
* 当指定一个id或元素,window打开时会与元素之间产生动画效果(缺省为null即没有动画效果)。
* Id or element from which the window should animate while opening (defaults to null with no animation).
*/
/**
* @cfg {String} resizeHandles
* 一个有效的 {@link Ext.Resizable}手柄的配置字符串(默认为 'all')。只当 resizable = true时有效.
* A valid {@link Ext.Resizable}handles config string (defaults to 'all'). Only applies when resizable = true.
*/
/**
* @cfg {Ext.WindowGroup} manager
* 管理该window的WindowGroup引用(默认为 {@link Ext.WindowMgr})。
* A reference to the WindowGroup that should manage this window (defaults to {@link Ext.WindowMgr}).
*/
/**
* @cfg {String/Number/Button} defaultButton
* 按钮的id/index或按钮实例,当window接收到焦点此按钮也会得到焦点。
* The id / index of a button or a button instance to focus when this window received the focus.
*/
/**
* @cfg {Function} onEsc
* 允许重写该句柄以替代escape键的内建控制句柄。默认的动作句柄是关闭window(执行 {@link #closeAction}所指的动作)。
* 若按下escape键不关闭window,可指定此项为{@link Ext#emptyFn})。
* Allows override of the built-in processing for the escape key. Default action
* is to close the Window (performing whatever action is specified in {@link #closeAction}.
* To prevent the Window closing when the escape key is pressed, specify this as
* Ext.emptyFn (See {@link Ext#emptyFn}).
*/
/**
* @cfg {Boolean} collapsed
* True表示为渲染window就是关闭着的,false就表示展开地渲染(默认为false)。
* True to render the window collapsed, false to render it expanded (defaults to false). Note that if
* {@link #expandOnShow} is true (the default) it will override the <tt>collapsed</tt> config and the window
* will always be expanded when shown.
*/
/**
* @cfg {Boolean} maximized
* True表示显示窗体时就已最大化的状态显示(默认为false)。
* True to initially display the window in a maximized state. (Defaults to false).
*/
/**
* @cfg {String} baseCls
* 作用在面板元素上的CSS样式类(默认为 'x-window')。
* The base CSS class to apply to this panel's element (defaults to 'x-window').
*/
baseCls : 'x-window',
/**
* @cfg {Boolean} resizable
* True 表示为允许用户从window的四边和四角改变window的大小(默认为 true)。
* True to allow user resizing at each edge and corner of the window, false to disable resizing (defaults to true).
*/
resizable : true,
/**
* @cfg {Boolean} draggable
* True 表示为window可被拖动,false表示禁止拖动(默认为true)。
* 注意:默认下window会在视图中居中显示(因为可拖动),所以如果禁止可拖动的话意味着window生成之后应用一定代码定义(如 myWindow.setPosition(100, 100);)。
* True to allow the window to be dragged by the header bar, false to disable dragging (defaults to true). Note
* that by default the window will be centered in the viewport, so if dragging is disabled the window may need
* to be positioned programmatically after render (e.g., myWindow.setPosition(100, 100);).
*/
draggable : true,
/**
* @cfg {Boolean} closable
* <p>True 表示为显示'close'的工具按钮可让用户关闭window,false表示为隐藏按钮,并不允许关闭window(默认为 true)。
* True to display the 'close' tool button and allow the user to close the window, false to
* hide the button and disallow closing the window (default to true).</p>
* <p>默认状态下,当那个窗体是拥有焦点的,用户按下关闭按钮或ESC键,{@link #close}方法就会调用。
* 这表示窗体会彻底被<i>摧毁</i>而且无法在重用。
* By default, when close is requested by either clicking the close button in the header
* or pressing ESC when the Window has focus, the {@link #close} method will be called. This
* will <i>destroy</i> the Window and its content meaning that it may not be reused.</p>
* <p>要使得窗体只是<i>隐藏</i>的话,就设置{@link #closeAction}为'hide',这样便可以重用窗体。
* To make closing a Window <i>hide</i> the Window so that it may be reused, set
* {@link #closeAction} to 'hide'.
*/
closable : true,
/**
* @cfg {Boolean} constrain
* True表示为将window约束在视图中显示,false表示为允许window在视图之外的地方显示(默认为false)。
* 可选地设置{@link #constrainHeader}使得头部只被约束。
* True to constrain the window within its containing element, false to allow it to fall outside of its
* containing element. By default the window will be rendered to document.body. To render and constrain the
* window within another element specify {@link #renderTo}.
* (defaults to false). Optionally the header only can be constrained using {@link #constrainHeader}.
*/
constrain : false,
/**
* @cfg {Boolean} constrainHeader
* True表示为将window header约束在视图中显示,
* false表示为允许header在视图之外的地方显示(默认为false)。可选地设置{@link #constrain}使得整个窗体可被约束。
* True to constrain the window header within its containing element (allowing the window body to fall outside
* of its containing element) or false to allow the header to fall outside its containing element (defaults to
* false). Optionally the entire window can be constrained using {@link #constrain}.
*/
constrainHeader : false,
/**
* @cfg {Boolean} plain
* True表示为渲染window body的背景为透明的背景,这样看来window body与边框元素(framing elements)融为一体,
* false表示为加入浅色的背景,使得在视觉上body元素与外围边框清晰地分辨出来(默认为false)。
* True to render the window body with a transparent background so that it will blend into the framing
* elements, false to add a lighter background color to visually highlight the body element and separate it
* more distinctly from the surrounding frame (defaults to false).
*/
plain : false,
/**
* @cfg {Boolean} minimizable
* True表示为显示“最小化minimize”的工具按钮,允许用户最小化window,false表示隐藏按钮,禁止window最小化的功能(默认为false)。
* 注意最小化window是实现具体特定的(implementation-specific),该按钮不提供最小化window的实现,所以必须提供一个最小化的事件来制定最小化的行为,这样该项才有用的。
* True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button
* and disallow minimizing the window (defaults to false). Note that this button provides no implementation --
* the behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a
* custom minimize behavior implemented for this option to be useful.
*/
minimizable : false,
/**
* @cfg {Boolean} maximizable
* True表示为显示“最大化maximize”的工具按钮,允许用户最大化window(默认为false)。
* 注意当window最大化时,这个工具按钮会自动变为“restore”按钮。
* 同时相应的行为也变成内建复原(restore)行为,即window可回变之前的尺寸。
* True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button
* and disallow maximizing the window (defaults to false). Note that when a window is maximized, the tool button
* will automatically change to a 'restore' button with the appropriate behavior already built-in that will
* restore the window to its previous size.
*/
maximizable : false,
/**
* @cfg {Number} minHeight
* window高度的最小值,单位为象素(缺省为 100)。只当 resizable 为 true时有效。
* The minimum height in pixels allowed for this window (defaults to 100). Only applies when resizable = true.
*/
minHeight : 100,
/**
* @cfg {Number} minWidth
* window宽度的最小值,单位为象素(缺省为 200)。只当 resizable 为 true时有效。
* The minimum width in pixels allowed for this window (defaults to 200). Only applies when resizable = true.
*/
minWidth : 200,
/**
* @cfg {Boolean} expandOnShow
* True 表示为window显示时总是展开window,false则表示为按照打开时的状态显示(有可能是闭合的{@link #collapsed})(默认为 true)。
* True to always expand the window when it is displayed, false to keep it in its current state (which may be
* {@link #collapsed}) when displayed (defaults to true).
*/
expandOnShow : true,
/**
* @cfg {String} closeAction
* 当关闭按钮被点击时执行的动作。“close”缺省的动作是从DOM树中移除window并彻底加以销毁。
* “hide”是另外一个有效的选项,只是在视觉上通过偏移到零下(negative)的区域的手法来隐藏,这样使得window可通过{@link #show} 的方法再显示.
* The action to take when the close button is clicked. The default action is 'close' which will actually remove
* the window from the DOM and destroy it. The other valid option is 'hide' which will simply hide the window
* by setting visibility to hidden and applying negative offsets, keeping the window available to be redisplayed
* via the {@link #show} method.
*/
closeAction : 'close',
// inherited docs, same default
collapsible : false,
// private
initHidden : true,
/**
* @cfg {Boolean} monitorResize @hide
* This is automatically managed based on the value of constrain and constrainToHeader
*/
monitorResize : true,
// The following configs are set to provide the basic functionality of a window.
// Changing them would require additional code to handle correctly and should
// usually only be done in subclasses that can provide custom behavior. Changing them
// may have unexpected or undesirable results.
/** @cfg {String} elements @hide */
elements : 'header,body',
/** @cfg {Boolean} frame @hide */
frame : true,
/** @cfg {Boolean} floating @hide */
floating : true,
// private
initComponent : function(){
Ext.Window.superclass.initComponent.call(this);
this.addEvents(
/**
* @event activate
* 当通过{@link setActive}的方法视觉上激活window后触发的事件。
* Fires after the window has been visually activated via {@link setActive}.
* @param {Ext.Window} this
*/
/**
* @event deactivate
* 当通过{@link setActive}的方法视觉上使window不活动后触发的事件。
* Fires after the window has been visually deactivated via {@link setActive}.
* @param {Ext.Window} this
*/
/**
* @event resize
* 调整window大小后触发。
* Fires after the window has been resized.
* @param {Ext.Window} this
* @param {Number} width window的新宽度 The window's new width
* @param {Number} height window的新高度 The window's new height
*/
'resize',
/**
* @event maximize
* 当window完成最大化后触发。
* Fires after the window has been maximized.
* @param {Ext.Window} this
*/
'maximize',
/**
* @event minimize
* 当window完成最小化后触发。
* Fires after the window has been minimized.
* @param {Ext.Window} this
*/
'minimize',
/**
* @event restore
* 当window复原到原始的尺寸大小时触发。
* Fires after the window has been restored to its original size after being maximized.
* @param {Ext.Window} this
*/
'restore'
);
},
// private
getState : function(){
return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox());
},
// private
onRender : function(ct, position){
Ext.Window.superclass.onRender.call(this, ct, position);
if(this.plain){
this.el.addClass('x-window-plain');
}
// this element allows the Window to be focused for keyboard events
this.focusEl = this.el.createChild({
tag: "a", href:"#", cls:"x-dlg-focus",
tabIndex:"-1", html: " "});
this.focusEl.swallowEvent('click', true);
this.proxy = this.el.createProxy("x-window-proxy");
this.proxy.enableDisplayMode('block');
if(this.modal){
this.mask = this.container.createChild({cls:"ext-el-mask"}, this.el.dom);
this.mask.enableDisplayMode("block");
this.mask.hide();
this.mon(this.mask, 'click', this.focus, this);
}
this.initTools();
},
// private
initEvents : function(){
Ext.Window.superclass.initEvents.call(this);
if(this.animateTarget){
this.setAnimateTarget(this.animateTarget);
}
if(this.resizable){
this.resizer = new Ext.Resizable(this.el, {
minWidth: this.minWidth,
minHeight:this.minHeight,
handles: this.resizeHandles || "all",
pinned: true,
resizeElement : this.resizerAction
});
this.resizer.window = this;
this.mon(this.resizer, 'beforeresize', this.beforeResize, this);
}
if(this.draggable){
this.header.addClass("x-window-draggable");
}
this.mon(this.el, 'mousedown', this.toFront, this);
this.manager = this.manager || Ext.WindowMgr;
this.manager.register(this);
this.hidden = true;
if(this.maximized){
this.maximized = false;
this.maximize();
}
if(this.closable){
var km = this.getKeyMap();
km.on(27, this.onEsc, this);
km.disable();
}
},
initDraggable : function(){
/**
* 如果窗体的配置项{@link #draggable}被打开,那么该属性就是一个{@link Ext.dd.DD}的实例,包含了拖动窗体的DOM元素信息。
* If this Window is configured {@link #draggable}, this property will contain
* an instance of {@link Ext.dd.DD} which handles dragging the Window's DOM Element.
* @type Ext.dd.DD
* @property dd
*/
this.dd = new Ext.Window.DD(this);
},
// private
onEsc : function(){
this[this.closeAction]();
},
// private
beforeDestroy : function(){
if (this.rendered){
this.hide();
if(this.doAnchor){
Ext.EventManager.removeResizeListener(this.doAnchor, this);
Ext.EventManager.un(window, 'scroll', this.doAnchor, this);
}
Ext.destroy(
this.focusEl,
this.resizer,
this.dd,
this.proxy,
this.mask
);
}
Ext.Window.superclass.beforeDestroy.call(this);
},
// private
onDestroy : function(){
if(this.manager){
this.manager.unregister(this);
}
Ext.Window.superclass.onDestroy.call(this);
},
// private
initTools : function(){
if(this.minimizable){
this.addTool({
id: 'minimize',
handler: this.minimize.createDelegate(this, [])
});
}
if(this.maximizable){
this.addTool({
id: 'maximize',
handler: this.maximize.createDelegate(this, [])
});
this.addTool({
id: 'restore',
handler: this.restore.createDelegate(this, []),
hidden:true
});
this.mon(this.header, 'dblclick', this.toggleMaximize, this);
}
if(this.closable){
this.addTool({
id: 'close',
handler: this[this.closeAction].createDelegate(this, [])
});
}
},
// private
resizerAction : function(){
var box = this.proxy.getBox();
this.proxy.hide();
this.window.handleResize(box);
return box;
},
// private
beforeResize : function(){
this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); // 40 is a magic minimum content size?
this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40);
this.resizeBox = this.el.getBox();
},
// private
updateHandles : function(){
if(Ext.isIE && this.resizer){
this.resizer.syncHandleHeight();
this.el.repaint();
}
},
// private
handleResize : function(box){
var rz = this.resizeBox;
if(rz.x != box.x || rz.y != box.y){
this.updateBox(box);
}else{
this.setSize(box);
}
this.focus();
this.updateHandles();
this.saveState();
if(this.layout){
this.doLayout();
}
this.fireEvent("resize", this, box.width, box.height);
},
/**
* 焦点这个window。若有defaultButton,它就会顺便也接送到一个焦点,否则是window本身接收到焦点。
* Focuses the window. If a defaultButton is set, it will receive focus, otherwise the
* window itself will receive focus.
*/
focus : function(){
var f = this.focusEl, db = this.defaultButton, t = typeof db;
if(t != 'undefined'){
if(t == 'number' && this.fbar){
f = this.fbar.items.get(db);
}else if(t == 'string'){
f = Ext.getCmp(db);
}else{
f = db;
}
}
f = f || this.focusEl;
f.focus.defer(10, f);
},
/**
* 设置window目标动画元素,当window打开是产生动画效果。
* Sets the target element from which the window should animate while opening.
* @param {String/Element} el 目标元素或 id。The target element or id
*/
setAnimateTarget : function(el){
el = Ext.get(el);
this.animateTarget = el;
},
// private
beforeShow : function(){
delete this.el.lastXY;
delete this.el.lastLT;
if(this.x === undefined || this.y === undefined){
var xy = this.el.getAlignToXY(this.container, 'c-c');
var pos = this.el.translatePoints(xy[0], xy[1]);
this.x = this.x === undefined? pos.left : this.x;
this.y = this.y === undefined? pos.top : this.y;
}
this.el.setLeftTop(this.x, this.y);
if(this.expandOnShow){
this.expand(false);
}
if(this.modal){
Ext.getBody().addClass("x-body-masked");
this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
this.mask.show();
}
},
/**
* 显示window、或者会先进行渲染、或者会设为活动、又或者会从隐藏变为置顶显示。
* Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden.
* @param {String/Element} animateTarget (可选的) window产生动画的那个目标元素或id (默认为null即没有动画).animateTarget (optional) The target element or id from which the window should
* animate while opening (defaults to null with no animation)
* @param {Function} callback (可选的) 窗体显示之后执行的回调函数。(optional) A callback function to call after the window is displayed
* @param {Object} scope (optional) (可选的) window显示后执行的回调函数.The scope in which to execute the callback
* @return {Ext.Window} this
*/
show : function(animateTarget, cb, scope){
if(!this.rendered){
this.render(Ext.getBody());
}
if(this.hidden === false){
this.toFront();
return this;
}
if(this.fireEvent("beforeshow", this) === false){
return this;
}
if(cb){
this.on('show', cb, scope, {single:true});
}
this.hidden = false;
if(animateTarget !== undefined){
this.setAnimateTarget(animateTarget);
}
this.beforeShow();
if(this.animateTarget){
this.animShow();
}else{
this.afterShow();
}
return this;
},
// private
afterShow : function(){
this.proxy.hide();
this.el.setStyle('display', 'block');
this.el.show();
if(this.maximized){
this.fitContainer();
}
if(Ext.isMac && Ext.isGecko){ // work around stupid FF 2.0/Mac scroll bar bug
this.cascade(this.setAutoScroll);
}
if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){
Ext.EventManager.onWindowResize(this.onWindowResize, this);
}
this.doConstrain();
if(this.layout){
this.doLayout();
}
if(this.keyMap){
this.keyMap.enable();
}
this.toFront();
this.updateHandles();
this.fireEvent("show", this);
},
// private
animShow : function(){
this.proxy.show();
this.proxy.setBox(this.animateTarget.getBox());
this.proxy.setOpacity(0);
var b = this.getBox(false);
b.callback = this.afterShow;
b.scope = this;
b.duration = .25;
b.easing = 'easeNone';
b.opacity = .5;
b.block = true;
this.el.setStyle('display', 'none');
this.proxy.shift(b);
},
/**
* 隐藏window,设其为不可视并偏移到零下的区域。
* Hides the window, setting it to invisible and applying negative offsets.
* @param {String/Element} animateTarget (可选的)window产生动画的那个目标元素或id(默认为null即没有动画)。(optional) The target element or id to which the window should
* animate while hiding (defaults to null with no animation)
* @param {Function} callback (可选的)window显示后执行的回调函数。(optional) A callback function to call after the window is hidden
* @param {Object} scope (可选的)回调函数的作用域。(optional)The scope in which to execute the callback
* @return {Ext.Window} this
*/
hide : function(animateTarget, cb, scope){
if(this.hidden || this.fireEvent("beforehide", this) === false){
return this;
}
if(cb){
this.on('hide', cb, scope, {single:true});
}
this.hidden = true;
if(animateTarget !== undefined){
this.setAnimateTarget(animateTarget);
}
if(this.modal){
this.mask.hide();
Ext.getBody().removeClass("x-body-masked");
}
if(this.animateTarget){
this.animHide();
}else{
this.el.hide();
this.afterHide();
}
return this;
},
// private
afterHide : function(){
this.proxy.hide();
if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){
Ext.EventManager.removeResizeListener(this.onWindowResize, this);
}
if(this.keyMap){
this.keyMap.disable();
}
this.fireEvent("hide", this);
},
// private
animHide : function(){
this.proxy.setOpacity(.5);
this.proxy.show();
var tb = this.getBox(false);
this.proxy.setBox(tb);
this.el.hide();
var b = this.animateTarget.getBox();
b.callback = this.afterHide;
b.scope = this;
b.duration = .25;
b.easing = 'easeNone';
b.block = true;
b.opacity = 0;
this.proxy.shift(b);
},
// private
onWindowResize : function(){
if(this.maximized){
this.fitContainer();
}
if(this.modal){
this.mask.setSize('100%', '100%');
var force = this.mask.dom.offsetHeight;
this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
}
this.doConstrain();
},
// private
doConstrain : function(){
if(this.constrain || this.constrainHeader){
var offsets;
if(this.constrain){
offsets = {
right:this.el.shadowOffset,
left:this.el.shadowOffset,
bottom:this.el.shadowOffset
};
}else {
var s = this.getSize();
offsets = {
right:-(s.width - 100),
bottom:-(s.height - 25)
};
}
var xy = this.el.getConstrainToXY(this.container, true, offsets);
if(xy){
this.setPosition(xy[0], xy[1]);
}
}
},
// private - used for dragging
ghost : function(cls){
var ghost = this.createGhost(cls);
var box = this.getBox(true);
ghost.setLeftTop(box.x, box.y);
ghost.setWidth(box.width);
this.el.hide();
this.activeGhost = ghost;
return ghost;
},
// private
unghost : function(show, matchPosition){
if(show !== false){
this.el.show();
this.focus();
if(Ext.isMac && Ext.isGecko){ // work around stupid FF 2.0/Mac scroll bar bug
this.cascade(this.setAutoScroll);
}
}
if(matchPosition !== false){
this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true));
}
this.activeGhost.hide();
this.activeGhost.remove();
delete this.activeGhost;
},
/**
* window最小化方法的载体(Placeholder)。默认下,该方法简单地触发最小化事件{@link #minimize},因为最小化的行为是应用程序特定的,要实现自定义的最小化行为,应提供一个最小化事件处理函数或重写该方法。
* Placeholder method for minimizing the window. By default, this method simply fires the {@link #minimize} event
* since the behavior of minimizing a window is application-specific. To implement custom minimize behavior,
* either the minimize event can be handled or this method can be overridden.
* @return {Ext.Window} this
*/
minimize : function(){
this.fireEvent('minimize', this);
return this;
},
/**
* 关闭window,在DOM中移除并摧毁window对象。在关闭动作发生之前触发beforeclose事件,如返回false则取消close动作。
* Closes the window, removes it from the DOM and destroys the window object. The beforeclose event is fired
* before the close happens and will cancel the close action if it returns false.
*/
close : function(){
if(this.fireEvent("beforeclose", this) !== false){
this.hide(null, function(){
this.fireEvent('close', this);
this.destroy();
}, this);
}
},
/**
* 自适应window尺寸到其当前的容器,并将'最大化'按钮换成'复原'按钮。
* Fits the window within its current container and automatically replaces the 'maximize' tool button with
* the 'restore' tool button.
* @return {Ext.Window} this
*/
maximize : function(){
if(!this.maximized){
this.expand(false);
this.restoreSize = this.getSize();
this.restorePos = this.getPosition(true);
if (this.maximizable){
this.tools.maximize.hide();
this.tools.restore.show();
}
this.maximized = true;
this.el.disableShadow();
if(this.dd){
this.dd.lock();
}
if(this.collapsible){
this.tools.toggle.hide();
}
this.el.addClass('x-window-maximized');
this.container.addClass('x-window-maximized-ct');
this.setPosition(0, 0);
this.fitContainer();
this.fireEvent('maximize', this);
}
return this;
},
/**
* 把已最大化window复原到原始的尺寸,并将“复原”按钮换成“最大化”按钮。
* Restores a maximized window back to its original size and position prior to being maximized and also replaces
* the 'restore' tool button with the 'maximize' tool button.
* @return {Ext.Window} this
*/
restore : function(){
if(this.maximized){
this.el.removeClass('x-window-maximized');
this.tools.restore.hide();
this.tools.maximize.show();
this.setPosition(this.restorePos[0], this.restorePos[1]);
this.setSize(this.restoreSize.width, this.restoreSize.height);
delete this.restorePos;
delete this.restoreSize;
this.maximized = false;
this.el.enableShadow(true);
if(this.dd){
this.dd.unlock();
}
if(this.collapsible){
this.tools.toggle.show();
}
this.container.removeClass('x-window-maximized-ct');
this.doConstrain();
this.fireEvent('restore', this);
}
return this;
},
/**
* 根据当前window的最大化状态轮换{@link #maximize}和{@link #restore}的快捷方法。
* A shortcut method for toggling between {@link #maximize} and {@link #restore} based on the current maximized state of the window.
* @return {Ext.Window} this
*/
toggleMaximize : function(){
return this[this.maximized ? 'restore' : 'maximize']();
},
// private
fitContainer : function(){
var vs = this.container.getViewSize();
this.setSize(vs.width, vs.height);
},
// private
// z-index is managed by the WindowManager and may be overwritten at any time
setZIndex : function(index){
if(this.modal){
this.mask.setStyle("z-index", index);
}
this.el.setZIndex(++index);
index += 5;
if(this.resizer){
this.resizer.proxy.setStyle("z-index", ++index);
}
this.lastZIndex = index;
},
/**
* 对齐window到特定的元素。
* Aligns the window to the specified element
* @param {Mixed} element 要对齐的元素。 The element to align to.
* @param {String} position 对齐的位置(参阅{@link Ext.Element#alignTo}个中细节)。 The position to align to (see {@link Ext.Element#alignTo} for more details).
* @param {Array} offsets (可选的)偏移位置 [x, y]。(optional)Offset the positioning by [x, y]
* @return {Ext.Window} this
*/
alignTo : function(element, position, offsets){
var xy = this.el.getAlignToXY(element, position, offsets);
this.setPagePosition(xy[0], xy[1]);
return this;
},
/**
* 当window大小变化时或滚动时,固定此window到另外一个元素和重新对齐。
* Anchors this window to another element and realigns it when the window is resized or scrolled.
* @param {Mixed} element 对齐的元素。The element to align to.
* @param {String} position 对齐的位置(参阅{@link Ext.Element#alignTo}细节)。The position to align to (see {@link Ext.Element#alignTo} for more details)
* @param {Array} offsets (可选的)偏移位置 [x, y]。(optional)Offset the positioning by [x, y]
* @param {Boolean/Number} monitorScroll (可选的) true表示为随着body的变化而重新定位,如果此参数是一个数字,那么将用于缓冲的延时(默认为50ms)。(optional) true to monitor body scroll and reposition. If this parameter
* is a number, it is used as the buffer delay (defaults to 50ms).
* @return {Ext.Window} this
*/
anchorTo : function(el, alignment, offsets, monitorScroll){
if(this.doAnchor){
Ext.EventManager.removeResizeListener(this.doAnchor, this);
Ext.EventManager.un(window, 'scroll', this.doAnchor, this);
}
this.doAnchor = function(){
this.alignTo(el, alignment, offsets);
};
Ext.EventManager.onWindowResize(this.doAnchor, this);
var tm = typeof monitorScroll;
if(tm != 'undefined'){
Ext.EventManager.on(window, 'scroll', this.doAnchor, this,
{buffer: tm == 'number' ? monitorScroll : 50});
}
this.doAnchor();
return this;
},
/**
* 使用window先于其它window显示。
* Brings this window to the front of any other visible windows
* @return {Ext.Window} this
*/
toFront : function(e){
if(this.manager.bringToFront(this)){
if(!e || !e.getTarget().focus){
this.focus();
}
}
return this;
},
/**
* 激活此window并出现投影效果、或“反激活”并隐藏投影效果,此方法会触发相应的激活/反激活事件。
* Makes this the active window by showing its shadow, or deactivates it by hiding its shadow. This method also
* fires the {@link #activate} or {@link #deactivate} event depending on which action occurred.
* @param {Boolean} active True表示为激活window(默认为 false)。True to activate the window, false to deactivate it (defaults to false)
*/
setActive : function(active){
if(active){
if(!this.maximized){
this.el.enableShadow(true);
}
this.fireEvent('activate', this);
}else{
this.el.disableShadow();
this.fireEvent('deactivate', this);
}
},
/**
* 让这个window居后显示(设其 z-index 稍低)。
* Sends this window to the back of (lower z-index than) any other visible windows
* @return {Ext.Window} this
*/
toBack : function(){
this.manager.sendToBack(this);
return this;
},
/**
* 使window在视图居中。
* Centers this window in the viewport
* @return {Ext.Window} this
*/
center : function(){
var xy = this.el.getAlignToXY(this.container, 'c-c');
this.setPagePosition(xy[0], xy[1]);
return this;
}
/**
* @cfg {Boolean} autoWidth @hide
*/
});
Ext.reg('window', Ext.Window);
// private - custom Window DD implementation
Ext.Window.DD = function(win){
this.win = win;
Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-'+win.id);
this.setHandleElId(win.header.id);
this.scroll = false;
};
Ext.extend(Ext.Window.DD, Ext.dd.DD, {
moveOnly:true,
headerOffsets:[100, 25],
startDrag : function(){
var w = this.win;
this.proxy = w.ghost();
if(w.constrain !== false){
var so = w.el.shadowOffset;
this.constrainTo(w.container, {right: so, left: so, bottom: so});
}else if(w.constrainHeader !== false){
var s = this.proxy.getSize();
this.constrainTo(w.container, {right: -(s.width-this.headerOffsets[0]), bottom: -(s.height-this.headerOffsets[1])});
}
},
b4Drag : Ext.emptyFn,
onDrag : function(e){
this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY());
},
endDrag : function(e){
this.win.unghost();
this.win.saveState();
}
});
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.Item
* @extends Ext.menu.BaseItem
* 所有与菜单功能相关的(如:子菜单)以及非静态显示的菜单项的基类。Item 类继承了 {@link Ext.menu.BaseItem}
* 类的基本功能,并添加了菜单所特有的动作和点击事件的处理方法<br />
* @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)如果icon指定了{@link #iconCls}就不应存在
*/
/**
* @cfg {String} iconCls 定义了背景图的CSS样式类,用于该项的图标显示。(默认为 '')
* 如果iconCls指定了{@link #icon}就不应存在
*/
/**
* @cfg {String} text 此项显示的文本 (默认为 '').
*/
/**
* @cfg {String} href 要使用的那个连接的href属性 (默认为 '#').
*/
/**
* @cfg {String} hrefTarget 要使用的那个连接的target属性 (defaults to '').
*/
/**
* @cfg {String} itemCls The 菜单项使用的默认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.itemText||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.doAutoSize();
}
},
/**
* 把CSS样式类得效果应用在items的图标元素上
* @param {String} cls The CSS class to apply
*/
setIconClass : function(cls){
var oldCls = this.iconCls;
this.iconCls = cls;
if(this.rendered){
this.el.child('img.x-menu-item-icon').replaceClass(oldCls, this.iconCls);
}
},
//private
beforeDestroy: function(){
if (this.menu){
this.menu.destroy();
}
Ext.menu.Item.superclass.beforeDestroy.call(this);
},
// 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();
}
}); }
},
// private
deferHide : function(){
delete this.hideTimer;
this.menu.hide();
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.ColorMenu
* @extends Ext.menu.Menu
* 一个包含 {@link Ext.menu.ColorItem} 组件的菜单(提供了基本的颜色选择器)。<br />
* @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, {
//private
beforeDestroy: function(){
this.palette.destroy();
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.DateItem
* @extends Ext.menu.Adapter
* 一个通过封装 {@link Ext.DatPicker} 组件而成的菜单项。<br />
* @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');
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @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 {String} text 此项所显示的文本(默认为'')
*/
/**
* @cfg {Boolean} hideOnClick 值为 True 时该项被点击后隐藏包含的菜单(默认为 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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.MenuMgr
* 提供一个页面中所有菜单项的公共注册表,以便于能够很容易地通过ID来访问这些菜单对象。
* @singleton
*/
Ext.menu.MenuMgr = function(){
var menus, active, groups = {}, attached = false, lastShow = new Date();
// private - called when first menu is created
function init(){
menus = {};
active = new Ext.util.MixedCollection();
Ext.getDoc().addKeyListener(27, function(){
if(active.length > 0){
hideAll();
}
});
}
// private
function hideAll(){
if(active && 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.getDoc().un("mousedown", onMouseDown);
attached = false;
}
}
// private
function onShow(m){
var last = active.last();
lastShow = new Date();
active.add(m);
if(!attached){
Ext.getDoc().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 {
/**
* 隐藏所有当前可见的菜单
*/
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 如果值为字符串形式的菜单ID,则返回存在的对象引用。如果是 Menu 类的配置选项对象,则被用来生成并返回一个新的 Menu 实例。
* @return {Ext.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);
}
},
getCheckedItem : function(groupId){
var g = groups[groupId];
if(g){
for(var i = 0, l = g.length; i < l; i++){
if(g[i].checked){
return g[i];
}
}
}
return null;
},
setCheckedItem : function(groupId, itemId){
var g = groups[groupId];
if(g){
for(var i = 0, l = g.length; i < l; i++){
if(g[i].id == itemId){
g[i].setChecked(true);
}
}
}
return null;
}
};
}();
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.CheckItem
* @extends Ext.menu.Item
* 添加一个默认为多选框的菜单选项,也可以是单选框组中的一个组员。<br />
* @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" ,
/**
* @event checkchange
* checked 属性被设置后触发
* @param {Ext.menu.CheckItem} this
* @param {Boolean} checked 被设置的 checked 属性值
*/
"checkchange"
);
/**
* 为checkchange事件准备的函数。
* 缺省下这个函数是不存在的,如实例有提供这个函数那么将登记到checkchange事件中,一触发该事件就会执行这个函数。
* @param {Ext.menu.CheckItem} this
* @param {Boolean} checked 是否选中
* @method checkHandler
*/
if(this.checkHandler){
this.on('checkchange', this.checkHandler, this.scope);
}
Ext.menu.MenuMgr.registerCheckable(this);
};
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);
}
if(this.checked){
this.checked = false;
this.setChecked(true, true);
}
},
// private
destroy : function(){
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.Menu
* @extends Ext.util.Observable
* 一个菜单对象。它是所有你添加的菜单项的容器。Menu 类也可以当作是你根据其他组件生成的菜单的基类(例如:{@link Ext.menu.DateMenu})。
* @constructor
* 创建一个 Menu 对象
* @param {Object} config 配置选项对象
*/
Ext.menu.Menu = function(config){
if(config instanceof Array){
config = {items:config};
}
Ext.apply(this, config);
this.id = this.id || Ext.id();
this.addEvents(
/**
* @event beforeshow
* 在该菜单显示之前触发
* @param {Ext.menu.Menu} this
*/
'beforeshow',
/**
* @event beforehide
* 在该菜单隐藏之前触发
* @param {Ext.menu.Menu} this
*/
'beforehide',
/**
* @event show
* 在该菜单显示之后触发
* @param {Ext.menu.Menu} this
*/
'show',
/**
* @event hide
* 在该菜单隐藏之后触发
* @param {Ext.menu.Menu} this
*/
'hide',
/**
* @event click
* 当点击该菜单时触发(或者当该菜单处于活动状态且回车键被按下时触发)
* @param {Ext.menu.Menu} this
* @param {Ext.menu.Item} menuItem 被点击的 Item 对象
* @param {Ext.EventObject} e
*/
'click',
/**
* @event mouseover
* 当鼠标经过该菜单时触发
* @param {Ext.menu.Menu} this
* @param {Ext.EventObject} e
* @param {Ext.menu.Item} menuItem 被点击的 Item 对象
*/
'mouseover',
/**
* @event mouseout
* 当鼠标离开该菜单时触发
* @param {Ext.menu.Menu} this
* @param {Ext.EventObject} e
* @param {Ext.menu.Item} menuItem 被点击的 Item 对象
*/
'mouseout',
/**
* @event itemclick
* 当该菜单所包含的菜单项被点击时触发
* @param {Ext.menu.BaseItem} baseItem 被点击的 BaseItem 对象
* @param {Ext.EventObject} e
*/
'mouseout',
/**
* @event itemclick
* 当此菜单的子菜单被点击时触发。
* @param {Ext.menu.BaseItem} baseItem 单击的BaseItem
* @param {Ext.EventObject} e
*/
'itemclick'
);
Ext.menu.MenuMgr.register(this);
Ext.menu.Menu.superclass.constructor.call(this);
var mis = this.items;
this.items = new Ext.util.MixedCollection(false, Ext.Container.prototype.getComponentId);
if(mis){
this.add.apply(this, mis);
}
};
Ext.extend(Ext.menu.Menu, Ext.util.Observable, {
/**
* @cfg {Object} defaults
* 作用到全体item的配置项对象,无论是通过{@link #items}定义的抑或是{@link #add}方法加入的。
* 默认配置项可以是任意数量的name/value组合,只要是能够被菜单使用的项就可以。
*/
/**
* @cfg {Mixed} items
* 添加到菜单的Item,类型为Array。参阅 {@link #add}了解有效的类型。
*/
/**
* @cfg {Number} minWidth 以象素为单位设置的菜单最小宽度值(默认为 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,
createEl : function(){
return new Ext.Layer({
cls: "x-menu",
shadow:this.shadow,
constrain: false,
parentEl: this.parentEl || document.body,
zIndex:this.zIndex || 15000
});
},
// private
render : function(){
if(this.el){
return;
}
var el = this.el = this.createEl();
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.doAutoSize();
},
// private
doAutoSize : 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.el){
if(!this.awTask){
this.awTask = new Ext.util.DelayedTask(this.doAutoSize, 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 {Mixed} 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()){
if(this.fireEvent("beforehide", this) !== false){
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 类支持的菜单项,或者可以被转换为菜单项的对象。
* 满足下列任一条件即可:
* <ul>
* <li>任何基于 {@link Ext.menu.Item} 的菜单项对象</li>
* <li>可以被转换为菜单项的 HTML 元素对象</li>
* <li>可以被创建为一个菜单项对象的菜单项配置选项对象</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!' });
// 通过不同的方法一次添加一组菜单项。
// 最后被添加的菜单项才会被返回。
var item = menu.add(
menuItem, // 添加一个已经定义过的菜单项
'Dynamic Item', // 添加一个 TextItem 对象
'-', // 添加一个分隔栏
{ text: 'Config Item' } // 由配置选项对象生成的菜单项
);
</code></pre>
* @param {Mixed} args 一个或多个菜单项,菜单项配置选项或其他可以被转换为菜单项的对象
* @return {Ext.menu.Item} 被添加的菜单项,或者多个被添加的菜单项中的最后一个
*/
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?
Ext.applyIf(el, this.defaults);
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} 被添加的菜单项
*/
addSeparator : function(){
return this.addItem(new Ext.menu.Separator());
},
/**
* 添加一个 {@link Ext.Element} 对象到菜单
* @param {Mixed} el 被添加的元素或者 DOM 节点,或者它的ID
* @return {Ext.menu.Item} 被添加的菜单项
*/
addElement : function(el){
return this.addItem(new Ext.menu.BaseItem(el));
},
/**
* 添加一个已经存在的基于 {@link Ext.menu.Item} 的对象到菜单
* @param {Ext.menu.Item} item 被添加的菜单项
* @return {Ext.menu.Item} 被添加的菜单项
*/
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} 被添加的菜单项
*/
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.Item} 对象并添加到菜单
* @param {String} text 菜单项中显示的文本
* @return {Ext.menu.Item} 被添加的菜单项
*/
addText : function(text){
return this.addItem(new Ext.menu.TextItem(text));
},
/**
* 在指定的位置插入一个已经存在的基于 {@link Ext.menu.Item} 的对象到菜单
* @param {Number} index 要插入的对象在菜单中菜单项列表的位置的索引值
* @param {Ext.menu.Item} item 要添加的菜单项
* @return {Ext.menu.Item} 被添加的菜单项
*/
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 要删除的菜单项
*/
remove : function(item){
this.items.removeKey(item);
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.DateMenu
* @extends Ext.menu.Menu
* 一个包含 {@link Ext.menu.DateItem} 组件的菜单(提供了日期选择器)。<br />
* @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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.BaseItem
* @extends Ext.Component
* 菜单组件中包含的所有选项的基类。BaseItem 提供默认的渲染、活动状态管理和由菜单组件共享的基本配置。<br />
* @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',
/**
* @event activate
* 当该选项被激活时触发
* @param {Ext.menu.BaseItem} this
*/
'activate',
/**
* @event deactivate
* 当该选项被释放里触发
* @param {Ext.menu.BaseItem} this
*/
'deactivate'
);
if(this.handler){
this.on("click", this.handler, this.scope);
}
};
Ext.extend(Ext.menu.BaseItem, Ext.Component, {
/**
* @cfg {Function} handler
* 用来处理该选项单击事件的函数(默认为 undefined)
*/
/**
* @cfg {Object} scope
* 句柄函数内的作用域会被调用
*/
/**
* @cfg {Boolean} canActivate 值为 True 时该选项能够在可见的情况下被激活
*/
canActivate : false,
/**
* @cfg {String} activeClass 当该选项成为激活状态时所使用的CSS样式类(默认为 "x-menu-item-active")
*/
activeClass : "x-menu-item-active",
/**
* @cfg {Boolean} hideOnClick 值为 True 时该选项单击后隐藏所包含的菜单(默认为 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);
},
/**
* 为该项设置单击事件的句柄(相当于传入一个{@link #handler}配置项属性)
* 如果该句柄以登记,那么先会把它卸掉。
* @param {Function} handler 单击时所执行的函数
* @param {Object} scope 句柄所在的作用域
*/
setHandler : function(handler, scope){
if(this.handler){
this.un("click", this.handler, this.scope);
}
this.on("click", this.handler = handler, this.scope = scope);
},
// 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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.ColorItem
* @extends Ext.menu.Adapter
* 一个通过封装 {@link Ext.ColorPalette} 组件而成的菜单项。<br />
* @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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.menu.Adapter
* @extends Ext.menu.BaseItem
* 一个公共的基类,用来使原本无菜单的组件能够被菜单选项封装起来并被添加到菜单中去。
* 它提供了菜单组件所必须的基本的渲染、活动管理和启用/禁用逻辑功能。<br />
* @constructor
* 创建一个 Adapter 对象
* @param {Ext.Component} component 渲染到菜单的那个组件
* @param {Object} config 配置选项对象
*/
Ext.menu.Adapter = function(component, config){
Ext.menu.Adapter.superclass.constructor.call(this, config);
this.component = Ext.ComponentMgr.create(component, 'textfield');
};
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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @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 时该项被点击后隐藏包含的菜单(默认为 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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Container
* @extends Ext.BoxComponent
* <p>
* {@link Ext.BoxComponent}的子类,用于承载其它任何组件,容器负责一些基础性的行为,也就是装载子项、添加、插入和移除子项。
* 根据容纳子项的不同,所产生的可视效果,需委托任意布局类{@link #layout}中的一种来指点特定的布局逻辑(layout logic)。
* 此类被于继承而且一般情况下不应通过关键字new来直接实例化。<br />
* Base class for any {@link Ext.BoxComponent} that can contain other Components. The most commonly
* used Container classes are {@link Ext.Panel}, {@link Ext.Window} and {@link Ext.TabPanel}, but you can
* create a lightweight Container to be encapsulated by an HTML element that is created to your
* specifications at render time by using the {@link Ext.Component#autoEl autoEl} config option
* which takes the form of a {@link Ext.DomHelper DomHelper} specification, or tag name. If you do not need
* the capabilities offered by the above mentioned classes, for instance when creating embedded
* {@link Ext.layout.ColumnLayout column} layouts inside FormPanels, then this is a useful technique.</p>
* <p>The code below illustrates both how to explicitly <i>create</i> a Container, and how to implicitly
* create one using the <b><tt>'container'</tt></b> xtype:<pre><code>
var embeddedColumns = new Ext.Container({
autoEl: 'div', // 默认的设置。This is the default
layout: 'column',
defaults: {
xtype: 'container',
autoEl: 'div', // 默认的设置。This is the default.
layout: 'form',
columnWidth: 0.5,
style: {
padding: '10px'
}
},
// 下面两项都成为Ext.Containers,都是对<DIV>元素的封装。
// The two items below will be Ext.Containers, each encapsulated by a <DIV> element.
items: [{
items: {
xtype: 'datefield',
name: 'startDate',
fieldLabel: 'Start date'
}
}, {
items: {
xtype: 'datefield',
name: 'endDate',
fieldLabel: 'End date'
}
}]
});</code></pre></p>
* 容器负责处理容纳子项的基本行为,命名式加入、插入和移除等任务。进行可视化子项的渲染任务,其制定的布局逻辑是委托任意一个{@link #layout}类来完成的。<br />
* Containers handle the basic behavior of containing items, namely adding, inserting and removing them.
* The specific layout logic required to visually render contained items is delegated to any one of the different
* {@link #layout} classes available.</p>
* <p>
* 无论是通过配置项{@link #items}说明容器的子项,还是动态地加入容器,都要考虑何如安排这些子元素的,并是否处于Ext内建的布局规程下的大小调节控制。<br />
* When either specifying child {@link #items} of a Container, or dynamically adding components to a Container,
* remember to consider how you wish the Container to arrange those child elements, and whether those child elements
* need to be sized using one of Ext's built-in layout schemes.</p>
* <p>
* 默认下,容器使用{@link Ext.layout.ContainerLayout ContainerLayout}规程。
* 该布局规程充其量只会负责渲染子组件,将容器中的内容一个接着一个来渲染,并没有提供任何大小调节的功能。
* 出于该原因,有时在使用GridPanel或TreePanel的时候,误用了某种风格的布局规程便会有不正确的效果。
* 如果容器用着还是ContainerLayout规程,这即意味着调节父容器大小,子容器也是熟视无睹的。<br />
* By default, Containers use the {@link Ext.layout.ContainerLayout ContainerLayout} scheme. This simply renders
* child components, appending them one after the other inside the Container, and does not apply any sizing at all.
* This is a common source of confusion when widgets like GridPanels or TreePanels are added to Containers for
* which no layout has been specified. If a Container is left to use the ContainerLayout scheme, none of its child
* components will be resized, or changed in any way when the Container is resized.</p>
* <p>
*
* A very common example of this is where a developer will attempt to add a GridPanel to a TabPanel by wrapping
* the GridPanel <i>inside</i> a wrapping Panel and add that wrapping Panel to the TabPanel. This misses the point that
* Ext's inheritance means that a GridPanel <b>is</b> a Component which can be added unadorned into a Container. If
* that wrapping Panel has no layout configuration, then the GridPanel will not be sized as expected.<p>
* <p>Below is an example of adding a newly created GridPanel to a TabPanel. A TabPanel uses {@link Ext.layout.CardLayout}
* as its layout manager which means all its child items are sized to fit exactly into its client area. The following
* code requires prior knowledge of how to create GridPanels. See {@link Ext.grid.GridPanel}, {@link Ext.data.Store}
* and {@link Ext.data.JsonReader} as well as the grid examples in the Ext installation's <tt>examples/grid</tt>
* directory.</p><pre><code>
// 创建一个GridPanel。Create the GridPanel.
myGrid = new Ext.grid.GridPanel({
store: myStore,
columns: myColumnModel,
title: 'Results',
});
myTabPanel.add(myGrid);
myTabPanel.setActiveTab(myGrid);
</code></pre>
*/
Ext.Container = Ext.extend(Ext.BoxComponent, {
/** @cfg {Boolean} monitorResize
* Ture表示为自动监视window resize的事件,以处理接下来一切的事情,包括对视见区(viewport)当前大小的感知,一般情况该值由{@link #layout}调控,而无须手动设置。True to automatically monitor window resize events to handle anything that is sensitive to the current size
* of the viewport. This value is typically managed by the chosen {@link #layout} and should not need to be set manually.
*/
/**
* @cfg {String} layout
* 此容器所使用的布局类型。如不指定,则使用缺省的{@link Ext.layout.ContainerLayout}类型。
* 当中有效的值可以是:accordion、anchor、border、cavd、column、fit、form和table。
* 针对所选择布局类型,可指定{@link #layoutConfig}进一步配置。
* The layout type to be used in this container. If not specified, a default {@link Ext.layout.ContainerLayout}
* will be created and used. Specific config values for the chosen layout type can be specified using
* {@link #layoutConfig}. Valid values are:<ul class="mdetail-params">
* <li>absolute</li>
* <li>accordion</li>
* <li>anchor</li>
* <li>border</li>
* <li>card</li>
* <li>column</li>
* <li>fit</li>
* <li>form</li>
* <li>table</li></ul>
*/
/**
* @cfg {Object} layoutConfig
* 选定好layout布局后,其相应的配置属性就在这个对象上进行设置。
* (即与{@link #layout}配置联合使用)有关不同类型布局有效的完整配置信息,参阅对应的布局类:
* This is a config object containing properties specific to the chosen layout (to be used in conjunction with
* the {@link #layout} config value). For complete details regarding the valid config options for each layout
* type, see the layout class corresponding to the type specified:<ul class="mdetail-params">
* <li>{@link Ext.layout.Absolute}</li>
* <li>{@link Ext.layout.Accordion}</li>
* <li>{@link Ext.layout.AnchorLayout}</li>
* <li>{@link Ext.layout.BorderLayout}</li>
* <li>{@link Ext.layout.CardLayout}</li>
* <li>{@link Ext.layout.ColumnLayout}</li>
* <li>{@link Ext.layout.FitLayout}</li>
* <li>{@link Ext.layout.FormLayout}</li>
* <li>{@link Ext.layout.TableLayout}</li></ul>
*/
/**
* @cfg {Boolean/Number} bufferResize
* 当设置为true(100毫秒)或输入一个毫秒数,为此容器所分配的布局会缓冲其计算的频率和缓冲组件的重新布局。
* 如容器包含大量的子组件或这样重型容器,在频繁进行高开销的布局时,该项尤为有用。
* When set to true (100 milliseconds) or a number of milliseconds, the layout assigned for this container will buffer
* the frequency it calculates and does a re-layout of components. This is useful for heavy containers or containers
* with a large quantity of sub-components for which frequent layout calls would be expensive.
*/
/**
* @cfg {String/Number} activeItem
* 组件id的字符串,或组件的索引,用于在容器布局渲染时候的设置为活动。例如,activeItem: 'item-1'或activeItem: 0
* index 0 = 容器集合中的第一项)。只有某些风格的布局可设置activeItem(如{@link Ext.layout.Accordion}、{@link Ext.layout.CardLayout}和
* {@link Ext.layout.FitLayout}),以在某个时刻中显示一项内容。相关内容请参阅{@link Ext.layout.ContainerLayout#activeItem}。
* A string component id or the numeric index of the component that should be initially activated within the
* container's layout on render. For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first
* item in the container's collection). activeItem only applies to layout styles that can display
* items one at a time (like {@link Ext.layout.Accordion}, {@link Ext.layout.CardLayout} and
* {@link Ext.layout.FitLayout}). Related to {@link Ext.layout.ContainerLayout#activeItem}.
*/
/**
* @cfg {Mixed} items
* 一个单独项,或子组件组成的数组,加入到此容器中。
* 每一项的对象类型是基于{@link Ext.Component}的<br><br>
* 你可传入一个组件的配置对象即是lazy-rendering的做法,这样做的好处是组件不会立即渲染,减低直接构建组件对象带来的开销。
* 要发挥"lazy instantiation延时初始化"的特性,应对组件所属的登记类型的{@link Ext.Component#xtype}属性进行配置。<br><br>
* 要了解所有可用的xtyps,可参阅{@link Ext.Component}。如传入的单独一个项,应直接传入一个对象的引用(
* 如items: {...})。多个项应以数组的类型传入(如items: [{...}, {...}])。
* A single item, or an array of child Components to be added to this container.
* Each item can be any type of object based on {@link Ext.Component}.<br><br>
* Component config objects may also be specified in order to avoid the overhead
* of constructing a real Component object if lazy rendering might mean that the
* added Component will not be rendered immediately. To take advantage of this
* "lazy instantiation", set the {@link Ext.Component#xtype} config property to
* the registered type of the Component wanted.<br><br>
* For a list of all available xtypes, see {@link Ext.Component}.
* If a single item is being passed, it should be passed directly as an object
* reference (e.g., items: {...}). Multiple items should be passed as an array
* of objects (e.g., items: [{...}, {...}]).
*/
/**
* @cfg {Object} defaults
* 应用在全体组件上的配置项对象,无论组件是由{@link #items}指定,抑或是通过{@link #add}、{@link #insert}的方法加入,都可支持。
* 缺省的配置可以是任意多个容器能识别的“名称/值”,
* 假设要自动为每一个{@link Ext.Panel}项设置padding内补丁,你可以传入defaults: {bodyStyle:'padding:15px'}。
* A config object that will be applied to all components added to this container either via the {@link #items}
* config or via the {@link #add} or {@link #insert} methods. The defaults config can contain any number of
* name/value property pairs to be added to each item, and should be valid for the types of items
* being added to the container. For example, to automatically apply padding to the body of each of a set of
* contained {@link Ext.Panel} items, you could pass: defaults: {bodyStyle:'padding:15px'}.
*/
/** @cfg {Boolean} autoDestroy
* 若为true容器会自动销毁容器下面全部的组件,否则的话必须手动执行销毁过程(默认为true)。
* If true the container will automatically destroy any contained component that is removed from it, else
* destruction must be handled manually (defaults to true).
*/
autoDestroy: true,
/** @cfg {Boolean} hideBorders
* True表示为隐藏容器下每个组件的边框,false表示保留组件现有的边框设置(默认为false)。
* True to hide the borders of each contained component, false to defer to the component's existing
* border settings (defaults to false).
*/
/** @cfg {String} defaultType
* <p>容器的默认类型,用于在{@link Ext.ComponentMgr}中表示它的对象。(默认为'panel')The default {@link Ext.Component xtype} of child Components to create in this Container when
* a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>
* <p>Defaults to 'panel'.</p>
*/
defaultType: 'panel',
// private
initComponent : function(){
Ext.Container.superclass.initComponent.call(this);
this.addEvents(
/**
* @event afterlayout
* 由关联的布局管理器(layout manager)分配好容器上的组件后触发 Fires when the components in this container are arranged by the associated layout manager.
* @param {Ext.Container} this
* @param {ContainerLayout} layout 此容器的ContainerLayout实现。 The ContainerLayout implementation for this container
*/
'afterlayout',
/**
* @event beforeadd
* {@link Ext.Component}要加入或要插入到容器之前触发的事件 Fires before any {@link Ext.Component} is added or inserted into the container.
* A handler can return false to cancel the add.
* @param {Ext.Container} this
* @param {Ext.Component} component 要添加的组件 The component being added
* @param {Number} index 组件将会加入到容器items集合中的那个索引。 The index at which the component will be added to the container's items collection
*/
'beforeadd',
/**
* @event beforeremove
* 任何从该容器身上移除{@link Ext.Component}之前触发的事件。若句柄返回false则取消移除。 Fires before any {@link Ext.Component} is removed from the container. A handler can return
* false to cancel the remove.
* @param {Ext.Container} this
* @param {Ext.Component} component 要被移除的组件 The component being removed
*/
'beforeremove',
/**
* @event add
* @bubbles
* {@link Ext.Component}加入或插入到容器成功后触发的事件 Fires after any {@link Ext.Component} is added or inserted into the container.
* @param {Ext.Container} this
* @param {Ext.Component} component 已添加的组件 The component that was added
* @param {Number} index 组件加入到容器items集合中的索引。 The index at which the component was added to the container's items collection
*/
'add',
/**
* @event remove
* @bubbles
* 任何从该容器身上移除{@link Ext.Component}成功后触发的事件。 Fires after any {@link Ext.Component} is removed from the container.
* @param {Ext.Container} this
* @param {Ext.Component} component 被移除的组件对象 The component that was removed
*/
'remove'
);
this.enableBubble(['add', 'remove']);
/**
* 此容器的组件集合,类型为{@link Ext.util.MixedCollection}。
* The collection of components in this container as a {@link Ext.util.MixedCollection}
* @type MixedCollection
* @property items
*/
var items = this.items;
if(items){
delete this.items;
if(Ext.isArray(items) && items.length > 0){
this.add.apply(this, items);
}else{
this.add(items);
}
}
},
// private
initItems : function(){
if(!this.items){
this.items = new Ext.util.MixedCollection(false, this.getComponentId);
this.getLayout(); // initialize the layout
}
},
// private
setLayout : function(layout){
if(this.layout && this.layout != layout){
this.layout.setContainer(null);
}
this.initItems();
this.layout = layout;
layout.setContainer(this);
},
// private
render : function(){
Ext.Container.superclass.render.apply(this, arguments);
if(this.layout){
if(typeof this.layout == 'object' && !this.layout.layout){
this.layoutConfig = this.layout;
this.layout = this.layoutConfig.type;
}
if(typeof this.layout == 'string'){
this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);
}
this.setLayout(this.layout);
if(this.activeItem !== undefined){
var item = this.activeItem;
delete this.activeItem;
this.layout.setActiveItem(item);
return;
}
}
if(!this.ownerCt){
this.doLayout();
}
if(this.monitorResize === true){
Ext.EventManager.onWindowResize(this.doLayout, this, [false]);
}
},
/**
* <p>Returns the Element to be used to contain the child Components of this Container.</p>
* <p>An implementation is provided which returns the Container's {@link #getEl Element}, but
* if there is a more complex structure to a Container, this may be overridden to return
* the element into which the {@link #layout layout} renders child Components.</p>
* @return {Ext.Element} The Element to render child Components into.
*/
getLayoutTarget : function(){
return this.el;
},
// private - used as the key lookup function for the items collection
getComponentId : function(comp){
return comp.itemId || comp.id;
},
/**
* <p>
* 把{@link Ext.Component 组件}加入到此容器。
* 在加入之前触发{@link #beforeadd}事件和加入完毕后触发{@link #add}事件。
* 如果在容器已渲染后执行add方法(译注,如没渲染,即是属于lazy rending状态,自由地调用add方法是无所谓的),
* 你或许需要调用{@link #doLayout}的方法,刷新视图。
* 而多个子组件加入到布局,你只需执行一次这个方法。
* Adds a {@link Ext.Component Component} to this Container. Fires the {@link #beforeadd} event before
* adding, then fires the {@link #add} event after the component has been added.</p>
* <p>
* You will never call the render method of a child Component when using a Container.
* Child Components are rendered by this Container's {@link #layout} manager when
* this Container is first rendered.</p>
*
* <p>
* Certain layout managers allow dynamic addition of child components. Those that do
* include {@link Ext.layout.CardLayout}, {@link Ext.layout.AnchorLayout},
* {@link Ext.layout.FormLayout}, {@link Ext.layout.TableLayout}.</p>
*
* <p>
* If the Container is already rendered when add is called, you may need to call
* {@link #doLayout} to refresh the view which causes any unrendered child Components
* to be rendered. This is required so that you can add multiple child components if needed
* while only refreshing the layout once.</p>
*
* <p>
* When creating complex UIs, it is important to remember that sizing and positioning
* of child items is the responsibility of the Container's {@link #layout} manager. If
* you expect child items to be sized in response to user interactions, you must
* specify a layout manager which creates and manages the type of layout you have in mind.</p>
*
* <p><b>
* Omitting the {@link #layout} config means that a basic layout manager is
* used which does nothing but render child components sequentially into the Container.
* No sizing or positioning will be performed in this situation.</b></p>
* @param {Ext.Component/Object} component 欲加入的组件。The Component to add.<br><br>
* Ext采用延时渲染(lazy-rendering),加入的组件只有到了需要显示的时候才会被渲染出来。<br><br>
* 你可传入一个组件的配置对象即是lazy-rendering的做法,这样做的好处是组件不会立即渲染,减低直接构建组件对象带来的开销。<br><br>
* 要了解所有可用的xtyps,可参阅{@link Ext.Component}。
* 要发挥"lazy instantiation延时初始化"的特性,应对组件所属的登记类型的{@link Ext.Component#xtype}属性进行配置。
* Ext uses lazy rendering, and will only render the added Component should
* it become necessary, that is: when the Container is layed out either on first render
* or in response to a {@link #doLayout} call.<br><br>
* A Component config object may be passed instead of an instantiated Component object.
* The type of Component created from a config object is determined by the {@link Ext.Component#xtype xtype}
* config property. If no xtype is configured, the Container's {@link #defaultType}
* is used.<br><br>
* 对于全部可用xtype列表可参阅{@link Ext.Component}。
* For a list of all available xtypes, see {@link Ext.Component}.
* @param {Ext.Component/Object} component2
* @param {Ext.Component/Object} etc
* @return {Ext.Component} component 包含容器缺省配置值的组件(或配置项对象)。The Component (or config object) that was
* added with the Container's default config values applied.
* <p>example:</p><pre><code>
var myNewGrid = new Ext.grid.GridPanel({
store: myStore,
colModel: myColModel
});
myTabPanel.add(myNewGrid);
myTabPanel.setActiveTab(myNewGrid);
</code></pre>
*/
add : function(comp){
this.initItems();
var a = arguments, len = a.length;
if(len > 1){
for(var i = 0; i < len; i++) {
Ext.Container.prototype.add.call(this, a[i]);
}
return;
}
var c = this.lookupComponent(this.applyDefaults(comp));
var pos = this.items.length;
if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){
this.items.add(c);
c.ownerCt = this;
this.fireEvent('add', this, c, pos);
}
return c;
},
/**
* 把插件(Component)插入到容器指定的位置(按索引)。
* 执行插入之前触发{@link #beforeadd}事件,插入完毕触发{@link #add}事件。
* Inserts a Component into this Container at a specified index. Fires the
* {@link #beforeadd} event before inserting, then fires the {@link #add} event after the
* Component has been inserted.
* @param {Number} index 组件插入到容器collection集合的索引。The index at which the Component will be inserted
* into the Container's items collection
* @param {Ext.Component} component 欲加入的组件。The child Component to insert.<br><br>
* Ext采用延时渲染(lazy-rendering),加入的组件只有到了需要显示的时候才会被渲染出来。<br><br>
* 你可传入一个组件的配置对象即是lazy-rendering,这样做的好处是组件不会立即渲染
* 减低直接构建组件对象带来的开销。<br><br>
* 要了解所有可用的xtyps,可参阅{@link Ext.Component}。
* 要发挥“lazy instantiation延时初始化”的特性,应对组件所属的登记类型的{@link Ext.Component#xtype}属性进行配置。
* Ext uses lazy rendering, and will only render the inserted Component should
* it become necessary.<br><br>
* A Component config object may be passed in order to avoid the overhead of
* constructing a real Component object if lazy rendering might mean that the
* inserted Component will not be rendered immediately. To take advantage of
* this "lazy instantiation", set the {@link Ext.Component#xtype} config
* property to the registered type of the Component wanted.<br><br>
* For a list of all available xtypes, see {@link Ext.Component}.
* @return {Ext.Component} component 包含容器缺省配置值的组件(或配置项对象)。The Component (or config object) that was
* inserted with the Container's default config values applied.
*/
insert : function(index, comp){
this.initItems();
var a = arguments, len = a.length;
if(len > 2){
for(var i = len-1; i >= 1; --i) {
this.insert(index, a[i]);
}
return;
}
var c = this.lookupComponent(this.applyDefaults(comp));
if(c.ownerCt == this && this.items.indexOf(c) < index){
--index;
}
if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){
this.items.insert(index, c);
c.ownerCt = this;
this.fireEvent('add', this, c, index);
}
return c;
},
// private
applyDefaults : function(c){
if(this.defaults){
if(typeof c == 'string'){
c = Ext.ComponentMgr.get(c);
Ext.apply(c, this.defaults);
}else if(!c.events){
Ext.applyIf(c, this.defaults);
}else{
Ext.apply(c, this.defaults);
}
}
return c;
},
// private
onBeforeAdd : function(item){
if(item.ownerCt){
item.ownerCt.remove(item, false);
}
if(this.hideBorders === true){
item.border = (item.border === true);
}
},
/**
* 从此容器中移除某个组件。执行之前触发{@link #beforeremove}事件,移除完毕后触发{@link #remove}事件。
* Removes a component from this container. Fires the {@link #beforeremove} event before removing, then fires
* the {@link #remove} event after the component has been removed.
* @param {Component/String} component 组件的引用或其id。The component reference or id to remove.
* @param {Boolean} autoDestroy (可选的)True表示为自动执行组件{@link Ext.Component#destroy} 的函数。(optional)True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
* Defaults to the value of this Container's {@link #autoDestroy} config.
* @return {Ext.Component} component 被移除的Component对象。The Component that was removed.
*/
remove : function(comp, autoDestroy){
this.initItems();
var c = this.getComponent(comp);
if(c && this.fireEvent('beforeremove', this, c) !== false){
this.items.remove(c);
delete c.ownerCt;
if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){
c.destroy();
}
if(this.layout && this.layout.activeItem == c){
delete this.layout.activeItem;
}
this.fireEvent('remove', this, c);
}
return c;
},
/**
* 从此容器中移除某个组件。
* Removes all components from this container.
* @param {Boolean} autoDestroy (可选的) True表示为自动执行组件{@link Ext.Component#destroy} 的函数。(optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
* Defaults to the value of this Container's {@link #autoDestroy} config.
* @return {Array} 被销毁的组件数组。Array of the destroyed components
*/
removeAll: function(autoDestroy){
this.initItems();
var item, items = [];
while((item = this.items.last())){
items.unshift(this.remove(item, autoDestroy));
}
return items;
},
/**
* 由id或索引直接返回容器的子组件。
* Gets a direct child Component by id, or by index.
* @param {String/Number} comp 子组件的id或index。 id or index of child Component to return.
* @return Ext.Component
*/
getComponent : function(comp){
if(typeof comp == 'object'){
return comp;
}
return this.items.get(comp);
},
// private
lookupComponent : function(comp){
if(typeof comp == 'string'){
return Ext.ComponentMgr.get(comp);
}else if(!comp.events){
return this.createComponent(comp);
}
return comp;
},
// private
createComponent : function(config){
return Ext.create(config, this.defaultType);
},
/**
* 重新计算容器的布局尺寸。当有新组件加入到已渲染容器或改变子组件的大小/位置之后,就需要执行此函数。
* Force this container's layout to be recalculated. A call to this function is required after adding a new component
* to an already rendered container, or possibly after changing sizing/position properties of child components.
* @param {Boolean} shallow (可选的)True表示只是计算该组件的布局,而子组件则有需要才自动计算(默认为false每个子容器就调用doLayout)。
* (optional) True to only calc the layout of this component, and let child components auto
* calc layouts as required (defaults to false, which calls doLayout recursively for each subcontainer)
* @return {Ext.Container} this
*/
doLayout : function(shallow){
if(this.rendered && this.layout){
this.layout.layout();
}
if(shallow !== false && this.items){
var cs = this.items.items;
for(var i = 0, len = cs.length; i < len; i++) {
var c = cs[i];
if(c.doLayout){
c.doLayout();
}
}
}
return this;
},
/**
* 返回容器在使用的布局。如没设置,会创建默认的{@link Ext.layout.ContainerLayout}作为容器的布局。
* Returns the layout currently in use by the container. If the container does not currently have a layout
* set, a default {@link Ext.layout.ContainerLayout} will be created and set as the container's layout.
* @return {ContainerLayout} layout 容器的布局。The container's layout
*/
getLayout : function(){
if(!this.layout){
var layout = new Ext.layout.ContainerLayout(this.layoutConfig);
this.setLayout(layout);
}
return this.layout;
},
// private
beforeDestroy : function(){
if(this.items){
Ext.destroy.apply(Ext, this.items.items);
}
if(this.monitorResize){
Ext.EventManager.removeResizeListener(this.doLayout, this);
}
if (this.layout && this.layout.destroy) {
this.layout.destroy();
}
Ext.Container.superclass.beforeDestroy.call(this);
},
/**
* 逐层上报(Bubbles up)组件/容器,上报过程中对组件执行指定的函数。
* 函数的作用域(<i>this</i>)既可是参数传入或是当前组件(默认)函数的参数可经由args指定或当前组件提供,
* 如果函数在某一个层次上返回false,上升将会停止。
* Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of
* function call will be the scope provided or the current component. The arguments to the function
* will be the args provided or the current component. 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 component)
* @return {Ext.Container} this
*/
bubble : function(fn, scope, args){
var p = this;
while(p){
if(fn.apply(scope || p, args || [p]) === false){
break;
}
p = p.ownerCt;
}
return this;
},
/**
* 逐层下报(Cascades down)组件/容器(从它开始),下报过程中对组件执行指定的函数。
* 函数的作用域(<i>this</i>)既可是参数传入或是当前组件(默认)函数的参数可经由args指定或当前组件提供,
* 如果函数在某一个层次上返回false,下降将会停止。
* Cascades down the component/container heirarchy from this component (called first), calling the specified function with
* each component. The scope (<i>this</i>) of
* function call will be the scope provided or the current component. The arguments to the function
* will be the args provided or the current component. 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 component)
* @return {Ext.Container} this
*/
cascade : function(fn, scope, args){
if(fn.apply(scope || this, args || [this]) !== false){
if(this.items){
var cs = this.items.items;
for(var i = 0, len = cs.length; i < len; i++){
if(cs[i].cascade){
cs[i].cascade(fn, scope, args);
}else{
fn.apply(scope || cs[i], args || [cs[i]]);
}
}
}
}
return this;
},
/**
* 在此容器之下由id查找任意层次的组件。
* Find a component under this container at any level by id
* @param {String} id
* @return Ext.Component
*/
findById : function(id){
var m, ct = this;
this.cascade(function(c){
if(ct != c && c.id === id){
m = c;
return false;
}
});
return m || null;
},
/**
* 根据xtype或class查找该容器下任意层次中某个组件。
* Find a component under this container at any level by xtype or class
* @param {String/Class} xtype 组件的xtype字符串,或直接就是组件的类本身。
* The xtype string for a component, or the class of the component directly
* @param {Boolean} shallow (可选的)False表示xtype可兼容组件的父类(这里缺省的),或true就表示xtype压根就是这个组件,没有继承上的泛指。
* (optional) False to check whether this Component is descended from the xtype (this is
* the default), or true to check whether this Component is directly of the specified xtype.
* @return {Array} Ext.Components数组。Array of Ext.Components
*/
findByType : function(xtype, shallow){
return this.findBy(function(c){
return c.isXType(xtype, shallow);
});
},
/**
* 在此容器之下由属性作搜索依据查找组件。
* Find a component under this container at any level by property
* @param {String} prop
* @param {String} value
* @return {Array} Array of Ext.Components 数组
*/
find : function(prop, value){
return this.findBy(function(c){
return c[prop] === value;
});
},
/**
* 在此容器之下由自定义的函数作搜索依据查找组件。
* 如函数返回true返回组件的结果。传入的函数会有(component, this container)的参数。
* Find a component under this container at any level by a custom function. If the passed function returns
* true, the component will be included in the results. The passed function is called with the arguments (component, this container).
* @param {Function} fcn
* @param {Object} scope (optional)(可选的)
* @return {Array} Ext.Component数组。Array of Ext.Components
*/
findBy : function(fn, scope){
var m = [], ct = this;
this.cascade(function(c){
if(ct != c && fn.call(scope || c, c, ct) === true){
m.push(c);
}
});
return m;
},
/**
*返回该容器下辖的某个组件(是items.get(key)的简写方式)。
* Get a component contained by this container (alias for items.get(key))
* @param {String/Number} key 组件的索引或id。The index or id of the component
* @return {Ext.Component} Ext.Component
*/
get : function(key){
return this.items.get(key);
}
});
Ext.Container.LAYOUTS = {};
Ext.reg('container', Ext.Container); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.DatePicker
* @extends Ext.Component
* 简单的日期选择类。
* Simple date picker class.
* @constructor 创建一个DatePicker对象。Create a new DatePicker
* @param {Object} config 配置选项对象。The config object
*/
Ext.DatePicker = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {String} todayText 显示在选择当前日期的按钮上的文本(默认为 "Today")。
* The text to display on the button that selects the current date (defaults to "Today")
*/
todayText : "Today",
/**
* @cfg {String} okText 显示在 ok 按钮上的文本。
* The text to display on the ok button
*/
okText : " OK ", //   用来给用户更多的点击空间 to give the user extra clicking room
/**
* @cfg {String} cancelText 显示在 cancel 按钮上的文本。
* The text to display on the cancel button
*/
cancelText : "Cancel",
/**
* @cfg {String} todayTip 选择当前日期的按钮的快捷提示(默认为"{current date} (Spacebar)")。
* The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
*/
todayTip : "{0} (Spacebar)",
/**
* @cfg {String} minText minDate 效验失败时显示的错误文本(默认为"This date is before the minimum date")。
* The error text to display if the minDate validation fails (defaults to "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")。
* The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
*/
maxText : "This date is after the maximum date",
/**
* @cfg {String} format 默认的日期格式化字串,可以被覆写以实现本地化支持。格式化字串必须为{@link Date#parseDate}中记载的有效格式(默认为 'm/d/y')。
* 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').
*/
format : "m/d/y",
/**
* @cfg {String} disabledDaysText 当选中禁用星期时显示的错误文本(默认为"")。
* The tooltip to display when the date falls on a disabled day (defaults to "Disabled")
*/
disabledDaysText : "Disabled",
/**
* @cfg {String} disabledDatesText 当选中禁用日期时显示的错误文本(默认为 "")。
* The tooltip text to display when the date falls on a disabled date (defaults to "Disabled")
*/
disabledDatesText : "Disabled",
/**
* @cfg {Array} monthNames
* 出于本地化的支持,决定那些可被覆盖的,这是由月份字符串组成的数组(默认为Date.monthNames)。
* An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
*/
monthNames : Date.monthNames,
/**
* @cfg {Array} dayNames
* 星期名称数组,可以被覆写以实现本地化支持(默认为 Date.dayNames)。
* An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
*/
dayNames : Date.dayNames,
/**
* @cfg {String} nextText
* 下个月按钮的快捷提示(默认为 'Next Month (Control+Right)')。
* The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
*/
nextText: 'Next Month (Control+Right)',
/**
* @cfg {String} prevText
* 上个月按钮的快捷提示(默认为 'Previous Month (Control+Left)')。
* The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
*/
prevText: 'Previous Month (Control+Left)',
/**
* @cfg {String} monthYearText
* 月份选择器的快捷提示(默认为 'Choose a month (Control+Up/Down to move years)')。
* The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
*/
monthYearText: 'Choose a month (Control+Up/Down to move years)',
/**
* @cfg {Number} startDay
* 每周第一天的索引数,以 0 起始。(默认为 0,表示每周的第一天为周日)。
* Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
*/
startDay : 0,
/**
* @cfg {Boolean} showToday
* False表示隐藏在底部区域的Today按钮,也禁止键盘选取当日的日期(默认为true)。
* False to hide the footer area containing the Today button and disable the keyboard handler for spacebar
* that selects the current date (defaults to true).
*/
showToday : true,
/**
* @cfg {Date} minDate
* 允许的最小日期(JavaScript 日期对象,默认为 null)。
* Minimum allowable date (JavaScript date object, defaults to null)
*/
/**
* @cfg {Date} maxDate
* 允许的最大日期(JavaScript 日期对象,默认为 null)。
* Maximum allowable date (JavaScript date object, defaults to null)
*/
/**
* @cfg {Array} disabledDays
* 一个禁用星期数组,以 0 起始。例如:[0, 6] 表示禁用周日和周六(默认为 null)。
* An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
*/
/**
* @cfg {RegExp} disabledDatesRE
* 一个用来表示禁用日期的 JavaScript 正则表达式(默认为 null)。
* JavaScript regular expression used to disable a pattern of dates (defaults to null). The {@link #disabledDates}
* config will generate this regex internally, but if you specify disabledDatesRE it will take precedence over the
* disabledDates value.
*/
/**
* @cfg {Array} disabledDates
* 不能选取的日期列表,用字符串表示。这些字符串可以是正则表达式的字符串,因此是非常强大的。若干例子:
* An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
* expression so they are very powerful. Some examples:
* <ul>
* <li>["03/08/2003", "09/16/2003"]就是声明禁用这些日期。</li>
* <li>["03/08", "09/16"] 这样会每年的这些日子都被禁用。would disable those days for every year</li>
* <li>["^03/08"] 自该日子开始(使用短year格式时有用).would only match the beginning (useful if you are using short years)</li>
* <li>["03/../2006"]2006年的三月内每一日都禁用。would disable every day in March 2006</li>
* <li>["^03"]每逢三月都禁止。would disable every day in every March</li>
* </ul>
* 注意数组内的每一个日期的格式,都必须符合{@link #format}格式的要求。如遇到日期格式有“.”的,就要转义以符合正则的要求,如["03\\.08\\.03"]。
* Note that the format of the dates included in the array should exactly match the {@link #format} config.
* 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"].
*/
// private
initComponent : function(){
Ext.DatePicker.superclass.initComponent.call(this);
this.value = this.value ?
this.value.clearTime() : new Date().clearTime();
this.addEvents(
/**
* @event select
* 选中日期时触发。
* Fires when a date is selected
* @param {DatePicker} this
* @param {Date} date 选中的日期。The selected date
*/
'select'
);
if(this.handler){
this.on("select", this.handler, this.scope || this);
}
this.initDisabledDays();
},
// private
initDisabledDays : function(){
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 + ")");
}
},
/**
* 替换现有的不可选取日期,并刷新DatePicker。
* Replaces any existing disabled dates with new values and refreshes the DatePicker.
* @param {Array/RegExp} disabledDates 日期的字符串组成的数组,或禁止日期的JavaScript正则表达式。参阅{@link #disabledDays}配置项。An array of date strings (see the {@link #disabledDates} config
* for details on supported values), or a JavaScript regular expression used to disable a pattern of dates.
*/
setDisabledDates : function(dd){
if(Ext.isArray(dd)){
this.disabledDates = dd;
this.disabledDatesRE = null;
}else{
this.disabledDatesRE = dd;
}
this.initDisabledDays();
this.update(this.value, true);
},
/**
* 替换现有的不可选取日子(index式,0-6),并刷新DatePicker。
* Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
* @param {Array} disabledDays 禁止日期的数组。参阅{@link #disabledDays}配置项。An array of disabled day indexes. See the {@link #disabledDays} config
* for details on supported values.
*/
setDisabledDays : function(dd){
this.disabledDays = dd;
this.update(this.value, true);
},
/**
* 替换现有的{@link #minDate}值,并刷新DatePicker。
* Replaces any existing {@link #minDate} with the new value and refreshes the DatePicker.
* @param {Date} value 允许选择的最早日期。The minimum date that can be selected
*/
setMinDate : function(dt){
this.minDate = dt;
this.update(this.value, true);
},
/**
* 替换现有的{@link #maxDate}值,并刷新DatePicker。
* Replaces any existing {@link #maxDate} with the new value and refreshes the DatePicker.
* @param {Date} value 允许选择的最迟日期。The maximum date that can be selected
*/
setMaxDate : function(dt){
this.maxDate = dt;
this.update(this.value, true);
},
/**
* 获取当前日期字段中选中的值。
* Sets the value of the date field
* @param {Date} value 选中的日期。The date to set
*/
setValue : function(value){
var old = this.value;
this.value = value.clearTime(true);
if(this.el){
this.update(this.value);
}
},
/**
* 获取当前已选中的日期值。
* Gets the current selected value of the date field
* @return {Date} 日期。The selected 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.push('</tr></tbody></table></td></tr>',
this.showToday ? '<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.mon(this.eventEl, "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.mon(this.eventEl, "click", this.handleDateClick, this, {delegate: "a.x-date-date"});
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({
text: " ",
tooltip: this.monthYearText,
renderTo: this.el.child("td.x-date-middle", true)
});
this.mon(this.mbtn, 'click', this.showMonthPicker, this);
this.mbtn.el.child('em').addClass("x-btn-arrow");
if(this.showToday){
this.todayKeyListener = this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this);
var today = (new Date()).dateFormat(this.format);
this.todayBtn = new Ext.Button({
renderTo: 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);
},
// private
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.mon(this.monthPicker, 'click', this.onMonthClick, this);
this.mon(this.dblclick, 'click', 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);
}
});
}
},
// private
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});
},
// private
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');
}
},
// private
updateMPMonth : function(sm){
this.mpMonths.each(function(m, a, i){
m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
});
},
// private
selectMPMonth: function(m){
},
// private
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')){
var d = new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate());
if(d.getMonth() != this.mpSelMonth){
// "fix" the JS rolling date conversion if needed
d = new Date(this.mpSelYear, this.mpSelMonth, 1).getLastDateOfMonth();
}
this.update(d);
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);
}
},
// private
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();
}
},
// private
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(){
if(this.todayBtn && !this.todayBtn.disabled){
this.setValue(new Date().clearTime());
this.fireEvent("select", this, this.value);
}
},
// private
update : function(date, forceRefresh){
var vd = this.activeDate;
this.activeDate = date;
if(!forceRefresh && 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;
if(this.showToday){
var td = new Date().clearTime();
var disable = (td < min || td > max ||
(ddMatch && format && ddMatch.test(td.dateFormat(format))) ||
(ddays && ddays.indexOf(td.getDay()) != -1));
this.todayBtn.setDisabled(disable);
this.todayKeyListener[disable ? 'disable' : 'enable']();
}
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++){
var 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]);
}
}
},
// private
beforeDestroy : function() {
if(this.rendered){
Ext.destroy(
this.leftClickRpt,
this.rightClickRpt,
this.monthPicker,
this.eventEl,
this.mbtn,
this.todayBtn
);
}
}
/**
* @cfg {String} autoEl @hide
*/
});
Ext.reg('datepicker', Ext.DatePicker); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.ProgressBar
* @extends Ext.BoxComponent
* <p>
* 可更新进度条的组件。进度条支持两种不同的模式:手动的和自动的。<br />
* An updateable progress bar component. The progress bar supports two different modes: manual and automatic.</p>
* <p>
* 手动模式下,进度条的显示、更新(通过{@link #updateProgress})和清除这些任务便需要你代码的去完成。
* 此方法最适用于可实现预测点的操作显示进度条。<br />
* In manual mode, you are responsible for showing, updating (via {@link #updateProgress}) and clearing the
* progress bar as needed from your own code. This method is most appropriate when you want to show progress
* throughout an operation that has predictable points of interest at which you can update the control.</p>
* <p>
* 自动模式下,你只需要调用{@link #wait}并让进度条不停地运行下去,然后直到操作完成后停止进度条。另外一种用法是你让进度条显示一定的时间(wait方法),wait一定时间后停止显示进度。
* 自动模式最适用于已知时间的操作或不需要标识实际进度的异步操作。<br />
* In automatic mode, you simply call {@link #wait} and let the progress bar run indefinitely, only clearing it
* once the operation is complete. You can optionally have the progress bar wait for a specific amount of time
* and then clear itself. Automatic mode is most appropriate for timed operations or asynchronous operations in
* which you have no need for indicating intermediate progress.</p>
* @cfg {Float} value 0到1区间的浮点数(例如:.5,默认为0)。A floating point value between 0 and 1 (e.g., .5, defaults to 0)
* @cfg {String} text 进度条提示的文本(默认为'')。The progress bar text (defaults to '')
* @cfg {Mixed} textEl 负责进度条渲染的那个元素(默认为进度条内部文本元素)。The element to render the progress text to (defaults to the progress
* bar's internal text element)
* @cfg {String} id 进度条元素的Id(默认为自动生成的id)。The progress bar element's id (defaults to an auto-generated id)
*/
Ext.ProgressBar = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {String} baseCls
* 进度条外层元素所使用的CSS样式类基类(默认为'x-progress')。
* The base CSS class to apply to the progress bar's wrapper element (defaults to 'x-progress')
*/
baseCls : 'x-progress',
/**
* @cfg {Boolean} animate
* True表示为变化过程中将有动画效果(默认为false)。
* True to animate the progress bar during transitions (defaults to false)
*/
animate : false,
// private
waitTimer : null,
// private
initComponent : function(){
Ext.ProgressBar.superclass.initComponent.call(this);
this.addEvents(
/**
* @event update
* 每一次更新就触发该事件。
* Fires after each update interval
* @param {Ext.ProgressBar} this
* @param {Number} v 当前进度条的值。The current progress value
* @param {String} text 当前进度条的提示文字。The current progress text
*/
"update"
);
},
// private
onRender : function(ct, position){
var tpl = new Ext.Template(
'<div class="{cls}-wrap">',
'<div class="{cls}-inner">',
'<div class="{cls}-bar">',
'<div class="{cls}-text">',
'<div> </div>',
'</div>',
'</div>',
'<div class="{cls}-text {cls}-text-back">',
'<div> </div>',
'</div>',
'</div>',
'</div>'
);
this.el = position
? tpl.insertBefore(position, {cls: this.baseCls}, true)
: tpl.append(ct, {cls: this.baseCls}, true);
if(this.id){
this.el.dom.id = this.id;
}
var inner = this.el.dom.firstChild;
this.progressBar = Ext.get(inner.firstChild);
if(this.textEl){
//use an external text el
this.textEl = Ext.get(this.textEl);
delete this.textTopEl;
}else{
//setup our internal layered text els
this.textTopEl = Ext.get(this.progressBar.dom.firstChild);
var textBackEl = Ext.get(inner.childNodes[1]);
this.textTopEl.setStyle("z-index", 99).addClass('x-hidden');
this.textEl = new Ext.CompositeElement([this.textTopEl.dom.firstChild, textBackEl.dom.firstChild]);
this.textEl.setWidth(inner.offsetWidth);
}
this.progressBar.setHeight(inner.offsetHeight);
},
// private
afterRender : function(){
Ext.ProgressBar.superclass.afterRender.call(this);
if(this.value){
this.updateProgress(this.value, this.text);
}else{
this.updateText(this.text);
}
},
/**
* 更新进度条的刻度值,也可以更新提示文本。如果文本的参数没传入,那么当前的文本将不会有变化。
* 要取消当前文本,传入''。注意即使进度条的值溢出(大于1),也不会自动复位,这样你就要确定进度是何时完成然后调用{@link #reset}停止或隐藏控件。
* Updates the progress bar value, and optionally its text. If the text argument is not specified,
* any existing text value will be unchanged. To blank out existing text, pass ''. Note that even
* if the progress bar value exceeds 1, it will never automatically reset -- you are responsible for
* determining when the progress is complete and calling {@link #reset} to clear and/or hide the control.
* @param {Float} value (可选的)介乎0与1之间浮点数(如.5,默认为零)。(optional) A floating point value between 0 and 1 (e.g., .5, defaults to 0)
* @param {String} text (可选的)显示在进度条提示文本元素的字符串(默认为'')。(optional) The string to display in the progress text element (defaults to '')
* @param {Boolean} animate (可选的)True表示为变化过程中将有动画效果(默认为false)。如果不制定值那就使用默认当前类所使用着的。(optional) Whether to animate the transition of the progress bar. If this value is
* not specified, the default for the class is used (default to false)
* @return {Ext.ProgressBar} this
*/
updateProgress : function(value, text, animate){
this.value = value || 0;
if(text){
this.updateText(text);
}
if(this.rendered){
var w = Math.floor(value*this.el.dom.firstChild.offsetWidth);
this.progressBar.setWidth(w, animate === true || (animate !== false && this.animate));
if(this.textTopEl){
//textTopEl should be the same width as the bar so overflow will clip as the bar moves
this.textTopEl.removeClass('x-hidden').setWidth(w);
}
}
this.fireEvent('update', this, value, text);
return this;
},
/**
* 初始化一个自动更新的进度条。
* 如果有duration的参数传入,那么代表进度条会运行到一定的时间后停止(自动调用reset方法),并若然有指定一个回调函数,也会执行。
* 如果duration的参数不传入,那么进度条将会不停地运行下去,这样你就要调用{@link #reset}的方法停止他。wait方法可接受以下属性的配置对象:
* Initiates an auto-updating progress bar. A duration can be specified, in which case the progress
* bar will automatically reset after a fixed amount of time and optionally call a callback function
* if specified. If no duration is passed in, then the progress bar will run indefinitely and must
* be manually cleared by calling {@link #reset}. The wait method accepts a config object with
* the following properties:
* <pre>
Property Type Description
属性 类型 内容
---------- ------------ ----------------------------------------------------------------------
duration Number 进度条运作时间的长度,单位是毫秒,跑完后执行自身的复位方法(默认为undefined,即不断地运行除非执行reset方法结束)The length of time in milliseconds that the progress bar should
run before resetting itself (defaults to undefined, in which case it
will run indefinitely until reset is called)
interval Number 每次更新的间隔周期(默认为1000毫秒)The length of time in milliseconds between each progress update
(defaults to 1000 ms)
animate Boolean Whether to animate the transition of the progress bar. If this value is
not specified, the default for the class is used.
increment Number 进度条每次更新的幅度大小(默认为10)。如果进度条达到最后,那么它会回到原点。The number of progress update segments to display within the progress
bar (defaults to 10). If the bar reaches the end and is still
updating, it will automatically wrap back to the beginning.
text String Optional text to display in the progress bar element (defaults to '').
fn Function 当进度条完成自动更新后执行的回调函数。该函数没有参数。如不指定duration该项自动忽略,这样进度条只能写代码结束更新A callback function to execute after the progress bar finishes auto-
updating. The function will be called with no arguments. This function
will be ignored if duration is not specified since in that case the
progress bar can only be stopped programmatically, so any required function
should be called by the same code after it resets the progress bar.
scope Object 回调函数的作用域(只当duration与fn两项都传入时有效)The scope that is passed to the callback function (only applies when
duration and fn are both passed).
</pre>
*
* 用法举例: Example usage:
* <pre><code>
var p = new Ext.ProgressBar({
renderTo: 'my-el'
});
//等待五秒,然后更新状态元素(进度条会自动复位) Wait for 5 seconds, then update the status el (progress bar will auto-reset)
p.wait({
interval: 100, //非常快地移动! bar will move fast!
duration: 5000,
increment: 15,
text: 'Updating...',
scope: this,
fn: function(){
Ext.fly('status').update(完成了!'Done!');
}
});
//一种情况是,不停的更新直到有手工的操作控制结束。 Or update indefinitely until some async action completes, then reset manually
p.wait();
myAction.on('complete', function(){
p.reset();
Ext.fly('status').update('Done!');
});
</code></pre>
* @param {Object} config (optional)(可选的)配置项对象 Configuration options
* @return {Ext.ProgressBar} this
*/
wait : function(o){
if(!this.waitTimer){
var scope = this;
o = o || {};
this.updateText(o.text);
this.waitTimer = Ext.TaskMgr.start({
run: function(i){
var inc = o.increment || 10;
this.updateProgress(((((i+inc)%inc)+1)*(100/inc))*.01, null, o.animate);
},
interval: o.interval || 1000,
duration: o.duration,
onStop: function(){
if(o.fn){
o.fn.apply(o.scope || this);
}
this.reset();
},
scope: scope
});
}
return this;
},
/**
* 返回进度条当前是否在{@link #wait}的操作中。
* Returns true if the progress bar is currently in a {@link #wait} operation
* @return {Boolean} True表示在等待,false反之。True if waiting, else false
*/
isWaiting : function(){
return this.waitTimer != null;
},
/**
* 更新进度条的提示文本。如传入text参数,textEl会更新其内容,否则进度条本身会显示已更新的文本。
* Updates the progress bar text. If specified, textEl will be updated, otherwise the progress
* bar itself will display the updated text.
* @param {String} text (可选的)显示的字符串(默认为'')。(optional)The string to display in the progress text element (defaults to '')
* @return {Ext.ProgressBar} this
*/
updateText : function(text){
this.text = text || ' ';
if(this.rendered){
this.textEl.update(this.text);
}
return this;
},
/**
* 按照进度条当前的{@link #value},同步接度条的内宽,与外组件宽度自适应。
* 如果进度条是自适应某个部件的,那么该方法会自动调用,但若此进度条渲染为自动的宽度,那么该方法会根据别的resize来酌情调用。
* Synchronizes the inner bar width to the proper proportion of the total componet width based
* on the current progress {@link #value}. This will be called automatically when the ProgressBar
* is resized by a layout, but if it is rendered auto width, this method can be called from
* another resize handler to sync the ProgressBar if necessary.
*/
syncProgressBar : function(){
if(this.value){
this.updateProgress(this.value, this.text);
}
return this;
},
/**
* 设置进度条的尺寸大小。
* Sets the size of the progress bar.
* @param {Number} width 新宽度(像素)。The new width in pixels
* @param {Number} height 新高度(像素)。The new height in pixels
* @return {Ext.ProgressBar} this
*/
setSize : function(w, h){
Ext.ProgressBar.superclass.setSize.call(this, w, h);
if(this.textTopEl){
var inner = this.el.dom.firstChild;
this.textEl.setSize(inner.offsetWidth, inner.offsetHeight);
}
this.syncProgressBar();
return this;
},
/**
* 将进度条的刻度复位为零,并将提示文本设置为空白字符串。
* 如果hide=true,那么进度条会被隐藏(根据在内部的{@link #hideMode}属性)。
* Resets the progress bar value to 0 and text to empty string. If hide = true, the progress
* bar will also be hidden (using the {@link #hideMode} property internally).
* @param {Boolean} hide (可选的)True表示隐藏进度条(默认为false)。(optional) True to hide the progress bar (defaults to false)
* @return {Ext.ProgressBar} this
*/
reset : function(hide){
this.updateProgress(0);
if(this.textTopEl){
this.textTopEl.addClass('x-hidden');
}
if(this.waitTimer){
this.waitTimer.onStop = null; //prevent recursion
Ext.TaskMgr.stop(this.waitTimer);
this.waitTimer = null;
}
if(hide === true){
this.hide();
}
return this;
}
});
Ext.reg('progress', Ext.ProgressBar); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.ComponentMgr
* <p>为页面上全体的组件(特指{@link Ext.Component}的子类)以便能够可通过组件的id方便地去访问,(参见{@link Ext.getCmp}方法)。<br />
* Provides a registry of all Components (instances of {@link Ext.Component} or any subclass
* thereof) on a page so that they can be easily accessed by component id (see {@link #get}, or
* the convenience method {@link Ext#getCmp Ext.getCmp}).</p>
* <p>
* 此对象对组件的<i>类classes</i>提供索引检索的功能,这个索引应是如{@link Ext.Component#xtype}般的易记标识码。
* 对于由大量复合配置对象构成的Ext页面,使用<tt>xtype</tt>能避免不必要子组件实例化。<br />
* This object also provides a registry of available Component <i>classes</i>
* indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}.
* The <tt>xtype</tt> provides a way to avoid instantiating child Components
* when creating a full, nested config object for a complete Ext page.</p>
* <p>
* 只要xtype正确声明好,就可利用<i>配置项对象(config object)</i>表示一个子组件。
* 这样如遇到组件真是需要显示的时候,与之适合的类型(xtype)就会匹配对应的组件类,达到延时实例化(lazy instantiation)。<br />
* A child Component may be specified simply as a <i>config object</i>
* as long as the correct xtype is specified so that if and when the Component
* needs rendering, the correct type can be looked up for lazy instantiation.</p>
* <p>
* 全部的xtype列表可参阅{@link Ext.Component}。<br />
* For a list of all available xtypes, see {@link Ext.Component}.</p>
* @singleton
*/
Ext.ComponentMgr = function(){
var all = new Ext.util.MixedCollection();
var types = {};
var ptypes = {};
return {
/**
* 注册一个组件。
* Registers a component.
* @param {Ext.Component} c 组件对象。The component
*/
register : function(c){
all.add(c);
},
/**
* 撤消登记一个组件。
* Unregisters a component.
* @param {Ext.Component} c 组件对象。The component
*/
unregister : function(c){
all.remove(c);
},
/**
* 由id返回组件。
* Returns a component by id
* @param {String} id 组件的id。The component id
* @return Ext.Component
*/
get : function(id){
return all.get(id);
},
/**
* 当指定组件被加入到ComponentMgr时调用的函数。
* Registers a function that will be called when a specified component is added to ComponentMgr
* @param {String} id 组件Id。The component id
* @param {Function} fn 回调函数。The callback function
* @param {Object} scope 回调的作用域。The scope of the callback
*/
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);
}
});
},
/**
* 为组件缓存所使用的MixedCollection。可在这个MixedCollection中加入相应的事件,监视增加或移除的情况。只读的。
* The MixedCollection used internally for the component cache. An example usage may be subscribing to
* events on the MixedCollection to monitor addition or removal. Read-only.
* @type MixedCollection
* @property all
*/
all : all,
/**
* <p>
* 输入新的{@link Ext.Component#xtype},登记一个新组件的构造器。
* Registers a new Component constructor, keyed by a new
* {@link Ext.Component#xtype}.</p>
* <p>使用该方法登记{@link Ext.Component}的子类以便当指定子组件的xtype时即可延时加载(lazy instantiation)。
* 请参阅{@link Ext.Container#items}。
* Use this method to register new subclasses of {@link Ext.Component} so
* that lazy instantiation may be used when specifying child Components.
* see {@link Ext.Container#items}</p>
* @param {String} xtype 组件类的标识字符串。The mnemonic string by which the Component class
* may be looked up.
* @param {Constructor} cls 新的组件类。The new Component class.
*/
registerType : function(xtype, cls){
types[xtype] = cls;
cls.xtype = xtype;
},
/**
* 告诉需要哪个组建的{@link Ext.component#xtype xtype},添加适合的配置项对象,就创建新的Component,实际上返回这个类的实例。
* Creates a new Component from the specified config object using the
* config object's {@link Ext.component#xtype xtype} to determine the class to instantiate.
* @param {Object} config 你打算创建组件的配置项对象。A configuration object for the Component you wish to create.
* @param {Constructor} defaultType 如果第一个参数不包含组件的xtype就在第二个参数中指定,作为默认的组件类型。(如果第一个参数已经有的话这个参数就可选吧)。The constructor to provide the default Component type if
* the config object does not contain an xtype. (Optional if the config contains an xtype).
* @return {Ext.Component} 刚实例化的组件。The newly instantiated Component.
*/
create : function(config, defaultType){
return config.render ? config : new types[config.xtype || defaultType](config);
},
registerPlugin : function(ptype, cls){
ptypes[ptype] = cls;
cls.ptype = ptype;
},
createPlugin : function(config, defaultType){
return new ptypes[config.ptype || defaultType](config);
}
};
}();
/**
* Shorthand for {@link Ext.ComponentMgr#registerType}
* @param {String} xtype The mnemonic string by which the Component class
* may be looked up.
* @param {Constructor} cls The new Component class.
* @member Ext
* @method reg
*/
Ext.reg = Ext.ComponentMgr.registerType; // this will be called a lot internally, shorthand to keep the bytes down
Ext.preg = Ext.ComponentMgr.registerPlugin;
Ext.create = Ext.ComponentMgr.create;
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Button
* @extends Ext.BoxComponent
* 简单的按钮类。
* Simple Button class
* @cfg {String} text 按钮文本。The button text to be used as innerHTML (html tags are accepted)
* @cfg {String} icon 背景图片路径(默认是采用css的background-image来设置图片,所以如果你需要混合了图片和文字的图片按钮请使用cls类"x-btn-text-icon")。The path to an image to display in the button (the image will be set as the background-image
* CSS property of the button by default, so if you want a mixed icon/text button, set cls:"x-btn-text-icon")
* @cfg {Function} handler 按钮单击事件触发函数 (可取代单击的事件)。 A function called when the button is clicked (can be used instead of click event)
* @cfg {Object} scope 按钮单击事件触发函数的作用域。The scope of the handler
* @cfg {Number} minWidth 按钮最小宽度(常用于定义一组按钮的标准宽度)。The minimum width for this button (used to give a set of buttons a common width)
* @cfg {String/Object} tooltip 按钮鼠标划过时的提示语类似title - 可以是字符串QuickTips配置项对象。The tooltip for the button - can be a string to be used as innerHTML (html tags are accepted) or QuickTips config object
* @cfg {Boolean} hidden 是否隐藏(默认为false)。True to start hidden (defaults to false)
* @cfg {Boolean} disabled True 是否失效(默认为false)。True to start disabled (defaults to false)
* @cfg {Boolean} pressed 是否为按下状态(仅当enableToggle = true时)。True to start pressed (only if enableToggle = true)
* @cfg {String} toggleGroup 是否属于按钮组(组里只有一个按钮可以为按下状态,仅当enableToggle = true时)。The group this toggle button is a member of (only 1 per group can be pressed)
* @cfg {Boolean/Object} repeat 触发函数是否可以重复触发。 默认为false,也可以为{@link Ext.util.ClickRepeater}的参数对象。
* while the mouse is down.True to repeat fire the click event while the mouse is down. This can also be
an {@link Ext.util.ClickRepeater} config object (defaults to false).
* @constructor 创建新的按钮。Create a new button
* @param {Object} config 参数对象。The config object
*/
Ext.Button = Ext.extend(Ext.BoxComponent, {
/**
* Read-only. 如果按钮是隐藏的。
* True if this button is hidden
* @type Boolean
*/
hidden : false,
/**
* Read-only. 如果按钮是失效的。
* True if this button is disabled
* @type Boolean
*/
disabled : false,
/**
* Read-only. 如果按钮是按下状态(仅当enableToggle = true时)。
* True if this button is pressed (only if enableToggle = true)
* @type Boolean
* @property pressed
*/
pressed : false,
/**
* 按钮所在的{@link Ext.Panel}。(默认为undefined,当按钮加入到容器后自动设置该属性)。只读的。
* The Button's owner {@link Ext.Panel} (defaults to undefined, and is set automatically when
* the Button is added to a container). Read-only.
* @type Ext.Panel
* @property ownerCt
*/
/**
* @cfg {Number} tabIndex 按钮的DOM焦点序号即tab键时候得到焦点的序号(默认为undefined)。
* Set a DOM tabIndex for this button (defaults to undefined)
*/
/**
* @cfg {Boolean} allowDepress
* False表示不允许按钮“固定按下的状态”,(默认为undefined)。当{@link #enableToggle}激活时,该项才有效。
* False to not allow a pressed Button to be depressed (defaults to undefined). Only valid when {@link #enableToggle} is true.
*/
/**
* @cfg {Boolean} enableToggle
* True 是否在 pressed/not pressed 这两个状态间切换 (默认为false)。
* True to enable pressed/not pressed toggling (defaults to false)
*/
enableToggle: false,
/**
* @cfg {Function} toggleHandler
* 当{@link #enableToggle}激活时,该项才有效。这是点击的处理函数。会送入两个参数:
* Function called when a Button with {@link #enableToggle} set to true is clicked. Two arguments are passed:<ul class="mdetail-params">
* <li><b>button</b> : Ext.Button<div class="sub-desc">Button对象。this Button object</div></li>
* <li><b>state</b> : Boolean<div class="sub-desc">按钮的已发生的状态,true表示按了。The next state if the Button, true means pressed.</div></li>
* </ul>
*/
/**
* @cfg {Mixed} menu
* 标准menu属性 可设置为menu的引用 或者menu的id 或者menu的参数对象 (默认为undefined)。
* Standard menu attribute consisting of a reference to a menu object, a menu id or a menu config blob (defaults to undefined).
*/
/**
* @cfg {String} menuAlign
* 菜单的对齐方式(参阅{@link Ext.Element#alignTo}以了解个中细节,默认为'tl-bl?')。
* 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
* 用来指定背景图片的样式类。
* A css class which sets a background image to be used as the icon for this button
*/
/**
* @cfg {String} type
* 按钮的三种类型(submit、reset、button),默认为'button'。
* submit, reset or button - defaults to 'button'
*/
type : 'button',
// private
menuClassTarget: 'tr:nth(2)',
/**
* @cfg {String} clickEvent handler 处理函数触发事件(默认是单击)。
* The type of event to map to the button's event handler (defaults to 'click')
*/
clickEvent : 'click',
/**
* @cfg {Boolean} handleMouseEvents 是否启用mouseover,mouseout与mousedown鼠标事件(默认为true)。
* False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
*/
handleMouseEvents : true,
/**
* @cfg {String} tooltipType
* tooltip 的显示方式 既可是'qtip'(默认),也可是设置title属性的“标题”。
* The type of tooltip to use. Either "qtip" (default) for QuickTips or "title" for title attribute.
*/
tooltipType : 'qtip',
/**
* @cfg {String} buttonSelector
* <p>
* (可选的)
* 分辨DOM结构其中的激活、可点击元素的{@link Ext.DomQuery DomQuery}。
* (Optional) A {@link Ext.DomQuery DomQuery} selector which is used to extract the active, clickable element from the
* DOM structure created.</p>
* <p>
* 当定义了{@link #template},你必须保证该选择符的结果限于一个可以获得焦点的元素。
* When a custom {@link #template} is used, you must ensure that this selector results in the selection of
* a focussable element.</p>
* <p>
* 默认为<b><tt>"button:first-child"</tt></b>。
* Defaults to <b><tt>"button:first-child"</tt></b>.</p>
*/
buttonSelector : "button:first-child",
/**
* @cfg {String} scale
* <p>
* (可选的)元素的大小。可允许有这三种的值:
* (Optional) The size of the Button. Three values are allowed:</p>
* <ul class="mdetail-params">
* <li>"small"<div class="sub-desc">按钮元素是16px的高度。Results in the button element being 16px high.</div></li>
* <li>"medium"<div class="sub-desc">按钮元素是24px的高度。Results in the button element being 24px high.</div></li>
* <li>"large"<div class="sub-desc">按钮元素是32px的高度。Results in the button element being 32px high.</div></li>
* </ul>
* <p>
* 默认为<b><tt>"small"</tt></b>。
* Defaults to <b><tt>"small"</tt></b>.</p>
*/
scale: 'small',
/**
* @cfg {String} iconAlign
* <p>(可选的)渲染图标的按钮方向。可允许有这四种的值:
* (Optional)The side of the Button box to render the icon. Four values are allowed:</p>
* <ul class="mdetail-params">
* <li>"top"<div class="sub-desc"></div></li>
* <li>"right"<div class="sub-desc"></div></li>
* <li>"bottom"<div class="sub-desc"></div></li>
* <li>"left"<div class="sub-desc"></div></li>
* </ul>
* <p>
* 默认为<b><tt>"left"</tt></b>。
* Defaults to <b><tt>"left"</tt></b>.</p>
*/
iconAlign : 'left',
/**
* @cfg {String} arrowAlign
* <p>(可选的)渲染图标的箭头方向,如果有关联{@link #menu}的话。可允许有这两种的值:
* (Optional) The side of the Button box to render the arrow if the button has an associated {@link #menu}.
* Two values are allowed:</p>
* <ul class="mdetail-params">
* <li>"right"<div class="sub-desc"></div></li>
* <li>"bottom"<div class="sub-desc"></div></li>
* </ul>
* <p>Defaults to <b><tt>"right"</tt></b>.</p>
*/
arrowAlign : 'right',
/**
* @cfg {Ext.Template} template
* (可选配置) 如果设置了可用来生成按钮的主要元素。第一个占位符为按钮文本.修改这个属性要主意相关参数不能缺失。
* (Optional)A {@link Ext.Template Template} used to create the Button's DOM structure.
* Instances, or subclasses which need a different DOM structure may provide a different
* template layout in conjunction with an implementation of {@link #getTemplateArgs}.
* @type Ext.Template
* @property template
*/
/**
* @cfg {String} cls
* 为按钮主元素设置一个CSS样式。
* A CSS class string to apply to the button's main element.
*/
initComponent : function(){
Ext.Button.superclass.initComponent.call(this);
this.addEvents(
/**
* @event click
* 单击触发事件。
* Fires when this button is clicked
* @param {Button} this
* @param {EventObject} e 单击的事件对象。The click event
*/
"click",
/**
* @event toggle
* 按钮按下状态切换触发事件(仅当enableToggle = true时)。
* Fires when the "pressed" state of this button changes (only if enableToggle = true)
* @param {Button} this
* @param {Boolean} pressed
*/
"toggle",
/**
* @event mouseover
* 鼠标居上触发事件。
* Fires when the mouse hovers over the button
* @param {Button} this
* @param {Event} e 事件对象。The event object
*/
'mouseover',
/**
* @event mouseout
* 鼠标离开事件。
* Fires when the mouse exits the button
* @param {Button} this
* @param {Event} e 事件对象。The event object
*/
'mouseout',
/**
* @event menushow
* 有menu的时候 menu显示触发事件。
* If this button has a menu, this event fires when it is shown
* @param {Button} this
* @param {Menu} menu
*/
'menushow',
/**
* @event menuhide
* 有menu的时候 menu隐藏触发事件。
* If this button has a menu, this event fires when it is hidden
* @param {Button} this
* @param {Menu} menu
*/
'menuhide',
/**
* @event menutriggerover
* 有menu的时候 menu焦点转移到菜单项时触发事件。
* If this button has a menu, this event fires when the mouse enters the menu triggering element
* @param {Button} this
* @param {Menu} menu
* @param {EventObject} e 事件对象
*/
'menutriggerover',
/**
* @event menutriggerout
* 有menu的时候 menu焦点离开菜单项时触发事件。
* If this button has a menu, this event fires when the mouse leaves the menu triggering element
* @param {Button} this
* @param {Menu} menu
* @param {EventObject} e 事件对象
*/
'menutriggerout'
);
if(this.menu){
this.menu = Ext.menu.MenuMgr.get(this.menu);
}
if(typeof this.toggleGroup === 'string'){
this.enableToggle = true;
}
},
/**
* <p>
* 这个方法返回一个提供可替换参数的对象,供{@link #template Template}所使用以创建按钮的DOM结构。
* {@link #template Template}This method returns an object which provides substitution parameters for the {@link #template Template} used
* to create this Button's DOM structure.</p>
* <p>
* 实例或子类如果在模板上面有变化的话,可提供一个新的该方法之实现,以适应新模板创建不同的DOM结构。
* Instances or subclasses which use a different Template to create a different DOM structure may need to provide their
* own implementation of this method.</p>
* <p>
* 默认的实现就返回包含以下元素的数组:
* The default implementation which provides data for the default {@link #template} returns an Array containing the
* following items:</p><div class="mdetail-params"><ul>
* <li>按钮的文本{@link #text}。The Button's {@link #text}</li>
* <li><button>的类型{@link #type}。The <button>'s {@link #type}</li>
* <li><button> {@link #btnEl element}按钮元素的{@link iconCls}。The {@link iconCls} applied to the <button> {@link #btnEl element}</li>
* <li>The {@link #cls} applied to the Button's main {@link #getEl Element}</li>
* <li>控制Button的{@link #scale}与{@link #iconAlign icon alignment}的CSS样式名称。A CSS class name controlling the Button's {@link #scale} and {@link #iconAlign icon alignment}</li>
* <li>若已设{@link #menu}给Button所设的CSS样式名称。A CSS class name which applies an arrow to the Button if configured with a {@link #menu}</li>
* </ul></div>
* @return {Object} 模板的替换数据。Substitution data for a Template.
*/
getTemplateArgs : function(){
var cls = (this.cls || '');
cls += this.iconCls ? (this.text ? ' x-btn-text-icon' : ' x-btn-icon') : ' x-btn-noicon';
if(this.pressed){
cls += ' x-btn-pressed';
}
return [this.text || ' ', this.type, this.iconCls || '', cls, 'x-btn-' + this.scale + ' x-btn-icon-' + this.scale + '-' + this.iconAlign, this.getMenuClass()];
},
// protected
getMenuClass : function(){
return this.menu ? (this.arrowAlign != 'bottom' ? 'x-btn-arrow' : 'x-btn-arrow-bottom') : '';
},
// private
onRender : function(ct, position){
if(!this.template){
if(!Ext.Button.buttonTemplate){
// hideous table template
Ext.Button.buttonTemplate = new Ext.Template(
'<table cellspacing="0" class="x-btn {3}"><tbody class="{4}">',
'<tr><td class="x-btn-tl"><i> </i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i> </i></td></tr>',
'<tr><td class="x-btn-ml"><i> </i></td><td class="x-btn-mc"><em class="{5}" unselectable="on"><button class="x-btn-text {2}" type="{1}">{0}</button></em></td><td class="x-btn-mr"><i> </i></td></tr>',
'<tr><td class="x-btn-bl"><i> </i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i> </i></td></tr>',
"</tbody></table>");
Ext.Button.buttonTemplate.compile();
}
this.template = Ext.Button.buttonTemplate;
}
var btn, targs = this.getTemplateArgs();
if(position){
btn = this.template.insertBefore(position, targs, true);
}else{
btn = this.template.append(ct, targs, true);
}
/**
* 一个对Button可点击元素的封装。默认下这是<tt><button></tt>元素的引用。只读的。
* An {@link Ext.Element Element} encapsulating the Button's clickable element. By default,
* this references a <tt><button></tt> element. Read only.
* @type Ext.Element
* @property btnEl
*/
var btnEl = this.btnEl = btn.child(this.buttonSelector);
this.mon(btnEl, 'focus', this.onFocus, this);
this.mon(btnEl, 'blur', this.onBlur, this);
this.initButtonEl(btn, btnEl);
Ext.ButtonToggleMgr.register(this);
},
// private
initButtonEl : function(btn, btnEl){
this.el = btn;
if(this.id){
this.el.dom.id = this.el.id = this.id;
}
if(this.icon){
btnEl.setStyle('background-image', 'url(' +this.icon +')');
}
if(this.tabIndex !== undefined){
btnEl.dom.tabIndex = this.tabIndex;
}
if(this.tooltip){
this.setTooltip(this.tooltip);
}
if(this.handleMouseEvents){
this.mon(btn, 'mouseover', this.onMouseOver, this);
this.mon(btn, 'mousedown', this.onMouseDown, this);
// new functionality for monitoring on the document level
//this.mon(btn, "mouseout", this.onMouseOut, this);
}
if(this.menu){
this.mon(this.menu, 'show', this.onMenuShow, this);
this.mon(this.menu, 'hide', this.onMenuHide, this);
}
if(this.repeat){
var repeater = new Ext.util.ClickRepeater(btn,
typeof this.repeat == "object" ? this.repeat : {}
);
this.mon(repeater, 'click', this.onClick, this);
}
this.mon(btn, this.clickEvent, this.onClick, this);
},
// private
afterRender : function(){
Ext.Button.superclass.afterRender.call(this);
if(Ext.isIE6){
this.doAutoWidth.defer(1, this);
}else{
this.doAutoWidth();
}
},
/**
* 替换按钮针对背景图片的css类。连动替换按钮参数对象中的该属性。
* Sets the CSS class that provides a background image to use as the button's icon. This method also changes
* the value of the {@link iconCls} config internally.
* @param {String} cls 图标的CSS样式类。The CSS class providing the icon image
* @return {Ext.Button} this
*/
setIconClass : function(cls){
if(this.el){
this.btnEl.replaceClass(this.iconCls, cls);
}
this.iconCls = cls;
return this;
},
/**
* 设置该按钮的tooltip动态提示。
* Sets the tooltip for this Button.
* @param {String/Object} tooltip. This may be:<div class="mdesc-details"><ul>
* <li><b>String</b> : 用于在Tooltip显示的文本,由于分配到innerHTML属性因此可以是HTML标签的。A string to be used as innerHTML (html tags are accepted) to show in a tooltip</li>
* <li><b>Object</b> : {@link Ext.QuickTips#register}的配置对象。A configuration object for {@link Ext.QuickTips#register}.</li>
* </ul></div>
* @return {Ext.Button} this
*/
setTooltip : function(tooltip){
if(Ext.isObject(tooltip)){
Ext.QuickTips.register(Ext.apply({
target: this.btnEl.id
}, tooltip));
} else {
this.btnEl.dom[this.tooltipType] = tooltip;
}
return this;
},
// private
beforeDestroy: function(){
if(this.rendered){
if(this.btnEl){
if(typeof this.tooltip == 'object'){
Ext.QuickTips.unregister(this.btnEl);
}
}
}
Ext.destroy(this.menu);
},
// private
onDestroy : function(){
if(this.rendered){
Ext.ButtonToggleMgr.unregister(this);
}
},
// private
doAutoWidth : function(){
if(this.el && this.text && typeof this.width == 'undefined'){
this.el.setWidth("auto");
if(Ext.isIE7 && Ext.isStrict){
var ib = this.btnEl;
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.el.getWidth() < this.minWidth){
this.el.setWidth(this.minWidth);
}
}
}
},
/**
* 增加按钮事件句柄触发函数的方法。
* Assigns this Button's click handler
* @param {Function} handler 当按钮按下执行的函数。The function to call when the button is clicked
* @param {Object} scope (可选的)传入参数的作用域。(optional) Scope for the function passed in
* @return {Ext.Button} this
*/
setHandler : function(handler, scope){
this.handler = handler;
this.scope = scope;
return this;
},
/**
* 设置按钮文本。
* Sets this Button's text
* @param {String} text 按钮的文字。The button text
* @return {Ext.Button} this
*/
setText : function(text){
this.text = text;
if(this.el){
this.el.child("td.x-btn-mc " + this.buttonSelector).update(text);
}
this.doAutoWidth();
return this;
},
/**
* 获取按钮的文字。
* Gets the text for this Button
* @return {String} 按钮的文字。The button text
*/
getText : function(){
return this.text;
},
/**
* 如果有传入state的参数,就按照state的参数设置否则当前的state就会轮换。
* If a state it passed, it becomes the pressed state otherwise the current state is toggled.
* @param {Boolean} state (可选的)指定特定的状态。(optional) Force a particular state
* @param {Boolean} supressEvent (可选的)表示为调用该方法时不触发事件。(optional) True to stop events being fired when calling this method.
* @return {Ext.Button} this
*/
toggle : function(state, suppressEvent){
state = state === undefined ? !this.pressed : !!state;
if(state != this.pressed){
this.el[state ? 'addClass' : 'removeClass']("x-btn-pressed");
this.pressed = state;
if(!suppressEvent){
this.fireEvent("toggle", this, state);
if(this.toggleHandler){
this.toggleHandler.call(this.scope || this, this, state);
}
}
}
return this;
},
/**
* 使按钮获取焦点。
* Focus the button
*/
focus : function(){
this.btnEl.focus();
},
// private
onDisable : function(){
this.onDisableChange(true);
},
// private
onEnable : function(){
this.onDisableChange(false);
},
onDisableChange : function(disabled){
if(this.el){
if(!Ext.isIE6 || !this.text){
this.el[disabled ? 'addClass' : 'removeClass'](this.disabledClass);
}
this.el.dom.disabled = disabled;
}
this.disabled = disabled;
},
/**
* 显示按钮附带的菜单(如果有的话)。
* Show this button's menu (if it has one)
*/
showMenu : function(){
if(this.menu){
this.menu.show(this.el, this.menuAlign);
}
return this;
},
/**
* 隐藏按钮附带的菜单(如果有的话)。
* Hide this button's menu (if it has one)
*/
hideMenu : function(){
if(this.menu){
this.menu.hide();
}
return this;
},
/**
* 若按钮附有菜单并且是显示着的就返回true。
* eturns true if the button has a menu and it is visible
* @return {Boolean}
*/
hasVisibleMenu : function(){
return this.menu && this.menu.isVisible();
},
// private
onClick : function(e){
if(e){
e.preventDefault();
}
if(e.button != 0){
return;
}
if(!this.disabled){
if(this.enableToggle && (this.allowDepress !== false || !this.pressed)){
this.toggle();
}
if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){
this.showMenu();
}
this.fireEvent("click", this, e);
if(this.handler){
//this.el.removeClass("x-btn-over");
this.handler.call(this.scope || this, this, e);
}
}
},
// private
isMenuTriggerOver : function(e, internal){
return this.menu && !internal;
},
// private
isMenuTriggerOut : function(e, internal){
return this.menu && !internal;
},
// private
onMouseOver : function(e){
if(!this.disabled){
var internal = e.within(this.el, true);
if(!internal){
this.el.addClass("x-btn-over");
if(!this.monitoringMouseOver){
Ext.getDoc().on('mouseover', this.monitorMouseOver, this);
this.monitoringMouseOver = true;
}
this.fireEvent('mouseover', this, e);
}
if(this.isMenuTriggerOver(e, internal)){
this.fireEvent('menutriggerover', this, this.menu, e);
}
}
},
// private
monitorMouseOver : function(e){
if(e.target != this.el.dom && !e.within(this.el)){
if(this.monitoringMouseOver){
Ext.getDoc().un('mouseover', this.monitorMouseOver, this);
this.monitoringMouseOver = false;
}
this.onMouseOut(e);
}
},
// private
onMouseOut : function(e){
var internal = e.within(this.el) && e.target != this.el.dom;
this.el.removeClass("x-btn-over");
this.fireEvent('mouseout', this, e);
if(this.isMenuTriggerOut(e, internal)){
this.fireEvent('menutriggerout', this, this.menu, 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
getClickEl : function(e, isUp){
return this.el;
},
// private
onMouseDown : function(e){
if(!this.disabled && e.button == 0){
this.getClickEl(e).addClass("x-btn-click");
Ext.getDoc().on('mouseup', this.onMouseUp, this);
}
},
// private
onMouseUp : function(e){
if(e.button == 0){
this.getClickEl(e, true).removeClass("x-btn-click");
Ext.getDoc().un('mouseup', this.onMouseUp, this);
}
},
// private
onMenuShow : function(e){
this.ignoreNextClick = 0;
this.el.addClass("x-btn-menu-active");
this.fireEvent('menushow', this, this.menu);
},
// private
onMenuHide : function(e){
this.el.removeClass("x-btn-menu-active");
this.ignoreNextClick = this.restoreClick.defer(250, this);
this.fireEvent('menuhide', this, this.menu);
},
// private
restoreClick : function(){
this.ignoreNextClick = 0;
}
/**
* @cfg {String} autoEl @hide
*/
});
Ext.reg('button', Ext.Button);
// Button的辅助类,是私有的。Private utility class used by Button
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);
}
},
/**
* 在已按下的组中返回这些按钮。没有就null。
* Gets the pressed button in the passed group or null
* @param {String} group
* @return Button
*/
getPressed : function(group){
var g = groups[group];
if(g){
for(var i = 0, len = g.length; i < len; i++){
if(g[i].pressed === true){
return g[i];
}
}
}
return null;
}
};
}(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.BoxComponent
* @extends Ext.Component
* <p>
* 任何使用矩形容器的作可视化组件{@link Ext.Component}的基类,该类的模型提供了自适应高度、宽度调节的功能,具备大小调节和定位的能力。
* 所有的容器类{@link Ext.Container}都应从BoxComponent继承,从而让参与每个布局的嵌套容器都会紧密地联系在一起工作。<br />
* Base class for any {@link Ext.Component} that is to be sized as a box, using width and height.
* BoxComponent provides automatic box model adjustments for sizing and positioning and will work correctly
* within the Component rendering model. All {@link Ext.Container} Container classes should subclass
* BoxComponent so that they will work consistently when nested within other Ext layout containers.</p>
* <p>
* 要让任意的HTML元素演变为所谓的组件概念中的一种,用BoxComponent就可以了,它可以使现有的元素,也可以是将来渲染之时要创建的元素。
* 另外,一般来说,布局中的许多Component组件就是<b>Box</b>Component,使得具备高、宽可控的特性。<br />
* A BoxComponent may be created as a custom Component which encapsulates any HTML element, either a pre-existing
* element, or one that is created to your specifications at render time. Usually, to participate in layouts,
* a Component will need to be a <b>Box</b>Component in order to have its width and height managed.</p>
* <p>
* 要打算让一个现成有的元素为BoxComponent服务,使用<b>el</b>的配置选项,指定是哪个一个元素。 <br />
* To use a pre-existing element as a BoxComponent, configure it so that you preset the <b>el</b> property to the
* element to reference:<pre><code>
var pageHeader = new Ext.BoxComponent({
el: 'my-header-div'
});</code></pre>
*
* 然后就可以使用{@link Ext.Container#add added}来加入{@link Ext.Container Container}对象为子元素。</p>
* <p>
* 要打算在BoxComponent渲染之时自动创建一个HTML元素作为其容器元素,使用{@link Ext.Component#autoEl autoEl}的配置选项。
* 该配置项的内容就是一个{@link Ext.DomHelper DomHelper}的特定项:<br />
* To create a BoxComponent based around a HTML element to be created at render time, use the
* {@link Ext.Component#autoEl autoEl} config option which takes the form of a
* {@link Ext.DomHelper DomHelper} specification:<pre><code>
var myImage = new Ext.BoxComponent({
autoEl: {
tag: 'img',
src: '/images/my-image.jpg'
}
});</code></pre></p>
* @constructor
* @param {Ext.Element/String/Object} config 配置选项。The configuration options.
*/
Ext.BoxComponent = Ext.extend(Ext.Component, {
/**
* @cfg {Number} x
* 如果该组件是在一个定位的组件之中,可通过该属性返回组件的x本地(左边)坐标。
* The local x (left) coordinate for this component if contained within a positioning container.
*/
/**
* @cfg {Number} y
* 如果该组件是在一个定位的组件之中,可通过该属性返回组件的y本地(顶部)坐标。
* The local y (top) coordinate for this component if contained within a positioning container.
*/
/**
* @cfg {Number} pageX
* 如果该组件是在一个定位的组件之中,可通过该属性返回组件的x页面坐标。
* The page level x coordinate for this component if contained within a positioning container.
*/
/**
* @cfg {Number} pageY
* 如果该组件是在一个定位的组件之中,可通过该属性返回组件的y页面坐标。
* The page level y coordinate for this component if contained within a positioning container.
*/
/**
* @cfg {Number} height
* 此组件的高度(单位象素)(缺省为auto)。
* The height of this component in pixels (defaults to auto).
*/
/**
* @cfg {Number} width
* 此组件的宽度(单位象素)(缺省为auto)。
* The width of this component in pixels (defaults to auto).
*/
/**
* @cfg {Boolean} autoHeight
* True表示为使用height:'auto',false表示为使用固定高度(缺省为false)。
* <b>注意:</b>尽管许多组件都会继承该配置选项,但是不是全部的'auto' height都有效。
* autoHeight:true的设定表示会依照元素内容自适应大小,Ext就不会过问高度的问题。
* True to use height:'auto', false to use fixed height (defaults to false). <b>Note</b>: Although many components
* inherit this config option, not all will function as expected with a height of 'auto'. Setting autoHeight:true
* means that the browser will manage height based on the element's contents, and that Ext will not manage it at all.
*/
/**
* @cfg {Boolean} autoWidth
* True表示为使用width:'auto',false表示为使用固定宽度(缺省为false)。
* <b>注意:</b>尽管许多组件都会继承该配置选项,但是不是全部的'auto' width都有效。
* autoWidth:true的设定表示会依照元素内容自适应大小,Ext就不会过问宽度的问题。
* True to use width:'auto', false to use fixed width (defaults to false). <b>Note</b>: Although many components
* inherit this config option, not all will function as expected with a width of 'auto'. Setting autoWidth:true
* means that the browser will manage width based on the element's contents, and that Ext will not manage it at all.
*/
/* // private internal config
* {Boolean} deferHeight
* True表示为根据外置的组件延时计算高度,false表示允许该组件自行设置高度(缺省为false)。
* True to defer height calculations to an external component, false to allow this component to set its own height (defaults to false).
*/
// private
initComponent : function(){
Ext.BoxComponent.superclass.initComponent.call(this);
this.addEvents(
/**
* @event resize
* 当组件调节过大小后触发。
* Fires after the component is resized.
* @param {Ext.Component} this
* @param {Number} adjWidth 矩形调整过后的宽度。The box-adjusted width that was set
* @param {Number} adjHeight 矩形调整过后的高度。The box-adjusted height that was set
* @param {Number} rawWidth 原来设定的宽度。The width that was originally specified
* @param {Number} rawHeight 原来设定的高度。The height that was originally specified
*/
'resize',
/**
* @event move
* 当组件被移动过之后触发。
* Fires after the component is moved.
* @param {Ext.Component} this
* @param {Number} x 新x位置。The new x position
* @param {Number} y 新y位置。The new y position
*/
'move'
);
},
// 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}。
* Sets the width and height of the component. This method fires the {@link #resize} event. This method can accept
* either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
* @param {Number/Object} width 要设置的宽度,或一个size对象,格式是{width, height}。The new width to set, or a size object in the format {width, height}
* @param {Number} height 要设置的高度(如第一参数是size对象的那第二个参数经不需要了)。The new height to set (not required if a size object is passed as the first arg)
* @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.cacheSizes !== false && 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;
},
/**
* 设置组件的宽度。此方法会触发{@link #resize}事件。
* Sets the width of the component. This method fires the {@link #resize} event.
* @param {Number} width 要设置的新宽度。The new width to set
* @return {Ext.BoxComponent} this
*/
setWidth : function(width){
return this.setSize(width);
},
/**
* 设置组件的高度。此方法会触发{@link #resize}事件。
* Sets the height of the component. This method fires the {@link #resize} event.
* @param {Number} height 要设置的新高度。The new height to set
* @return {Ext.BoxComponent} this
*/
setHeight : function(height){
return this.setSize(undefined, height);
},
/**
* 返回当前组件所属元素的大小。
* Gets the current size of the component's underlying element.
* @return {Object} 包含元素大小的对象,格式为{width: (元素宽度), height:(元素高度)} An object containing the element's size {width: (element width), height: (element height)}
*/
getSize : function(){
return this.getResizeEl().getSize();
},
/**
* 返回当前组件所在的HTML元素的宽度。
* Gets the current width of the component's underlying element.
* @return {Number}
*/
getWidth : function(){
return this.getResizeEl().getWidth();
},
/**
* 返回当前组件所在的HTML元素的高度。
* Gets the current height of the component's underlying element.
* @return {Number}
*/
getHeight : function(){
return this.getResizeEl().getHeight();
},
/**
* 返回当前组件所在元素的尺寸大小,包括其外补丁(margin)占据的空白位置。
* Gets the current size of the component's underlying element, including space taken by its margins.
* @return {Object} 包含元素大小的对象。{width: (元素宽度 + 左/右边距), height: (元素高度 + 上/下边距)} An object containing the element's size {width: (element width + left/right margins), height: (element height + top/bottom margins)}
*/
getOuterSize : function(){
var el = this.getResizeEl();
return {width: el.getWidth() + el.getMargins('lr'),
height: el.getHeight() + el.getMargins('tb')};
},
/**
* 对组件所在元素当前的XY位置查询。
* Gets the current XY position of the component's underlying element.
* @param {Boolean} local (可选的)如为真返回的是元素的left和top而非XY(默认为false)。(optional)If true the element's left and top are returned instead of page XY (defaults to false)
* @return {Array} 元素的XY位置(如[100, 200])。The XY position of the element (e.g., [100, 200])
*/
getPosition : function(local){
var el = this.getPositionEl();
if(local === true){
return [el.getLeft(true), el.getTop(true)];
}
return this.xy || el.getXY();
},
/**
* 返回对组件所在元素的测量矩形大小。
* Gets the current box measurements of the component's underlying element.
* @param {Boolean} local (可选的) 如为真返回的是元素的left和top而非XY(默认为false)。(optional) If true the element's left and top are returned instead of page XY (defaults to false)
* @return {Object} box格式为{x, y, width, height}的对象(矩形)。 An object in the format {x, y, width, height}
*/
getBox : function(local){
var pos = this.getPosition(local);
var s = this.getSize();
s.x = pos[0];
s.y = pos[1];
return s;
},
/**
* 对组件所在元素的测量矩形大小,然后根据此值设置组件的大小。
* Sets the current box measurements of the component's underlying element.
* @param {Object} box 格式为{x, y, width, height}的对象。An object in the format {x, y, width, height}
* @return {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}。此方法触发{@link #move}事件。
* Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}.
* This method fires the {@link #move} event.
* @param {Number} left 新left。The new left
* @param {Number} top 新top。The new top
* @return {Ext.BoxComponent} this
*/
setPosition : function(x, y){
if(x && typeof x[1] == 'number'){
y = x[1];
x = x[0];
}
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}。此方法触发{@link #move}事件。
* Sets the page XY position of the component. To set the left and top instead, use {@link #setPosition}.
* This method fires the {@link #move} event.
* @param {Number} x 新x位置。The new x position
* @param {Number} y 新y位置。The new y position
* @return {Ext.BoxComponent} this
*/
setPagePosition : function(x, y){
if(x && typeof x[1] == 'number'){
y = x[1];
x = x[0];
}
this.pageX = x;
this.pageY = y;
if(!this.boxReady){
return;
}
if(x === undefined || y === undefined){ // cannot translate undefined points
return;
}
var p = this.getPositionEl().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);
}else if(this.pageX || this.pageY){
this.setPagePosition(this.pageX, this.pageY);
}
},
/**
* 强制重新计算组件的大小尺寸,这个尺寸是基于所属元素当前的高度和宽度。
* Force the component's size to recalculate based on the underlying element's current height and width.
* @return {Ext.BoxComponent} this
*/
syncSize : function(){
delete this.lastSize;
this.setSize(this.autoWidth ? undefined : this.getResizeEl().getWidth(), this.autoHeight ? undefined : this.getResizeEl().getHeight());
return this;
},
/* // protected
* 组件大小调节过后调用的函数,这是个空函数,可由一个子类来实现,执行一些调节大小过后的自定义逻辑。 Called after the component is resized, this method is empty by default but can be implemented by any
* subclass that needs to perform custom logic after a resize occurs.
* @param {Number} adjWidth 矩形调整过后的宽度 The box-adjusted width that was set
* @param {Number} adjHeight 矩形调整过后的高度 The box-adjusted height that was set
* @param {Number} rawWidth 原本设定的宽度 The width that was originally specified
* @param {Number} rawHeight 原本设定的高度 The height that was originally specified
*/
onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
},
/* // protected
* 组件移动过后调用的函数,这是个空函数,可由一个子类来实现,执行一些移动过后的自定义逻辑。 Called after the component is moved, this method is empty by default but can be implemented by any
* subclass that needs to perform custom logic after a move occurs.
* @param {Number} x 新X值 The new x position
* @param {Number} y 新y值 The new y position
*/
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};
}
});
Ext.reg('box', Ext.BoxComponent);
Ext.Spacer = Ext.extend(Ext.BoxComponent, {
autoEl:'div'
});
Ext.reg('spacer', Ext.Spacer); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.WindowGroup
* 此对象代表一组{@link Ext.Window}的实例并提供z-order的管理和window激活的行为。<br />
* An object that represents a group of {@link Ext.Window} instances and provides z-order management
* and window activation behavior.
* @constructor
*/
Ext.WindowGroup = function(){
var list = {};
var accessList = [];
var front = null;
// private
var sortWindows = function(d1, d2){
return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
};
// private
var orderWindows = function(){
var a = accessList, len = a.length;
if(len > 0){
a.sort(sortWindows);
var seed = a[0].manager.zseed;
for(var i = 0; i < len; i++){
var win = a[i];
if(win && !win.hidden){
win.setZIndex(seed + (i*10));
}
}
}
activateLast();
};
// private
var setActiveWin = function(win){
if(win != front){
if(front){
front.setActive(false);
}
front = win;
if(win){
win.setActive(true);
}
}
};
// private
var activateLast = function(){
for(var i = accessList.length-1; i >=0; --i) {
if(!accessList[i].hidden){
setActiveWin(accessList[i]);
return;
}
}
// none to activate
setActiveWin(null);
};
return {
/**
* windows的初始z-idnex(缺省为9000)。
* The starting z-index for windows (defaults to 9000)
* @type Number z-index的值。The z-index value
*/
zseed : 9000,
// private
register : function(win){
list[win.id] = win;
accessList.push(win);
win.on('hide', activateLast);
},
// private
unregister : function(win){
delete list[win.id];
win.un('hide', activateLast);
accessList.remove(win);
},
/**
* 返回指定id的window。
* Gets a registered window by id.
* @param {String/Object} id window的id或{@link Ext.Window}实例。The id of the window or a {@link Ext.Window} instance
* @return {Ext.Window}
*/
get : function(id){
return typeof id == "object" ? id : list[id];
},
/**
* 将指定的window居于其它活动的window前面。
* Brings the specified window to the front of any other active windows.
* @param {String/Object} win window的id或{@link Ext.Window}实例。The id of the window or a {@link Ext.Window} instance
* @return {Boolean} True表示为对话框成功居前,else则本身已是在前面。True if the dialog was brought to the front, else false
* if it was already in front
*/
bringToFront : function(win){
win = this.get(win);
if(win != front){
win._lastAccess = new Date().getTime();
orderWindows();
return true;
}
return false;
},
/**
* 将指定的window居于其它活动的window后面。
* Sends the specified window to the back of other active windows.
* @param {String/Object} win window的id或{@link Ext.Window}实例。The id of the window or a {@link Ext.Window} instance
* @return {Ext.Window} The window
*/
sendToBack : function(win){
win = this.get(win);
win._lastAccess = -(new Date().getTime());
orderWindows();
return win;
},
/**
* 隐藏组内的所有的window。
* Hides all windows in the group.
*/
hideAll : function(){
for(var id in list){
if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
list[id].hide();
}
}
},
/**
* 返回组内的当前活动的window。
* Gets the currently-active window in the group.
* @return {Ext.Window} 活动的window。The active window
*/
getActive : function(){
return front;
},
/**
* 传入一个制定的搜索函数到该方法内,返回组内的零个或多个windows。
* 函数一般会接收{@link Ext.Window}的引用作为其唯一的函数,若window符合搜索的标准及返回true,否则应返回false。
* Returns zero or more windows in the group using the custom search function passed to this method.
* The function should accept a single {@link Ext.Window} reference as its only argument and should
* return true if the window matches the search criteria, otherwise it should return false.
* @param {Function} fn 搜索函数。The search function
* @param {Object} scope (可选的)执行函数的作用域(若不指定便是window会传入)。(optional) The scope in which to execute the function (defaults to the window
* that gets passed to the function if not specified)
* @return {Array} 零个或多个匹配的window。An array of zero or more matching windows
*/
getBy : function(fn, scope){
var r = [];
for(var i = accessList.length-1; i >=0; --i) {
var win = accessList[i];
if(fn.call(scope||win, win) !== false){
r.push(win);
}
}
return r;
},
/**
* 在组内的每一个window上执行指定的函数,传入window自身作为唯一的参数。若函数返回false即停止迭代。
* Executes the specified function once for every window in the group, passing each
* window as the only parameter. Returning false from the function will stop the iteration.
* @param {Function} fn 每一项都会执行的函数。The function to execute for each item
* @param {Object} scope (可选的)执行函数的作用域。(optional) The scope in which to execute the function
*/
each : function(fn, scope){
for(var id in list){
if(list[id] && typeof list[id] != "function"){
if(fn.call(scope || list[id], list[id]) === false){
return;
}
}
}
}
};
};
/**
* @class Ext.WindowMgr
* @extends Ext.WindowGroup
* 自动创建的window组管理器,全局的。要创建其他的组管理器,提供z-order的堆,实例化{@link Ext.WindowGroup}对象便可。
* The default global window group that is available automatically. To have more than one group of windows
* with separate z-order stacks, create additional instances of {@link Ext.WindowGroup} as needed.
* @singleton
*/
Ext.WindowMgr = new Ext.WindowGroup(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Editor
* @extends Ext.Component
* 一个基础性的字段编辑器,它负责完成按需显示方面的工作,还有隐藏控制、某些内建的调节大小工作及事件处理函数的逻辑。
* A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
* @constructor 建立一个新的编辑器。Create a new Editor
* @param {Object} config 配置项对象。The config object
*/
Ext.Editor = function(field, config){
if(field.field){
this.field = Ext.create(field.field, 'textfield');
config = Ext.apply({}, field); // 复制对象那么不影响原始的值 copy so we don't disturb original config
delete config.field;
}else{
this.field = field;
}
Ext.Editor.superclass.constructor.call(this, config);
};
Ext.extend(Ext.Editor, Ext.Component, {
/**
* @cfg {Ext.form.Field} field
* Field字段对象(或祖先)或field的配置项对象。
* The Field object (or descendant) or config object for field
*/
/**
* @cfg {Boolean/String} autoSize
* True表示为编辑器的大小尺寸自适应到所属的字段,设置“width”表示单单适应宽度,设置“height”表示单单适应高度(默认为fasle)。
* True for the editor to automatically adopt the size of the element being edited, "width" to adopt the width only,
* or "height" to adopt the height only (defaults to false)
*/
/**
* @cfg {Boolean} revertInvalid
* True表示为当用户完成编辑但字段验证失败后,自动恢复原始值,然后取消这次编辑(默认为true)。
* True to automatically revert the field value and cancel the edit when the user completes an edit and the field
* validation fails (defaults to true)
*/
/**
* @cfg {Boolean} ignoreNoChange
* True表示为如果用户完成一次编辑但值没有改变时,中止这次编辑的操作(不保存,不触发事件)(默认为false)。
* 只对字符类型的值有效,其它编辑的数据类型将会被忽略。
* True to skip the edit completion process (no save, no events fired) if the user completes an edit and
* the value has not changed (defaults to false). Applies only to string values - edits for other data types
* will never be ignored.
*/
/**
* @cfg {Boolean} hideEl
* False表示为当编辑器显示时,保持绑定的元素可见(默认为true)。
* False to keep the bound element visible while the editor is displayed (defaults to true)
*/
/**
* @cfg {Mixed} value 所属字段的日期值(默认为"")。
* The data value of the underlying field (defaults to "")
*/
value : "",
/**
* @cfg {String} alignment 对齐的位置(参见{@link Ext.Element#alignTo}了解详细,默认为"c-c?")。
* The position to align to (see {@link Ext.Element#alignTo} for more details, defaults to "c-c?").
*/
alignment: "c-c?",
/**
* @cfg {Boolean/String} shadow 属性为"sides"是四边都是向上阴影,"frame"表示四边外发光,"drop"表示从右下角开始投影(默认为"frame")。
* "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop" for bottom-right shadow (defaults to "frame")
*/
shadow : "frame",
/**
* @cfg {Boolean} constrain 表示为约束编辑器到视图。
* True to constrain the editor to the viewport
*/
constrain : false,
/**
* @cfg {Boolean} swallowKeys 处理keydown/keypress事件使得不会上报(propagate),(默认为true)。
* Handle the keydown/keypress events so they don't propagate (defaults to true)
*/
swallowKeys : true,
/**
* @cfg {Boolean} completeOnEnter True表示为回车按下之后就完成编辑(默认为false)。
* True to complete the edit when the enter key is pressed (defaults to false)
*/
completeOnEnter : false,
/**
* @cfg {Boolean} cancelOnEsc True表示为escape键按下之后便取消编辑(默认为false)。
* True to cancel the edit when the escape key is pressed (defaults to false)
*/
cancelOnEsc : false,
/**
* @cfg {Boolean} updateEl True表示为当更新完成之后同时更新绑定元素的innerHTML(默认为false)。
* True to update the innerHTML of the bound element when the update completes (defaults to false)
*/
updateEl : false,
initComponent : function(){
Ext.Editor.superclass.initComponent.call(this);
this.addEvents(
/**
* @event beforestartedit
* 编辑器开始初始化,但在修改值之前触发。若事件句柄返回false则取消整个编辑事件。
* Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
* false from the handler of this event.
* @param {Editor} this
* @param {Ext.Element} boundEl 编辑器绑定的所属元素。The underlying element bound to this editor
* @param {Mixed} value 正被设置的值。The field value being set
*/
"beforestartedit",
/**
* @event startedit
* 当编辑器显示时触发。
* Fires when this editor is displayed
* @param {Ext.Element} boundEl 编辑器绑定的所属元素。The underlying element bound to this editor
* @param {Mixed} value 原始字段。The starting field value
*/
"startedit",
/**
* @event beforecomplete
* 修改已提交到字段,但修改未真正反映在所属的字段上之前触发。
* 若事件句柄返回false则取消整个编辑事件。
* 注意如果值没有变动的话并且ignoreNoChange = true的情况下,
* 编辑依然会结束但因为没有真正的编辑所以不会触发事件。
* Fires after a change has been made to the field, but before the change is reflected in the underlying
* field. Saving the change to the field can be canceled by returning false from the handler of this event.
* Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
* event will not fire since no edit actually occurred.
* @param {Editor} this
* @param {Mixed} value 当前字段的值。The current field value
* @param {Mixed} startValue 原始字段的值。The original field value
*/
"beforecomplete",
/**
* @event complete
* 当编辑完成过后,任何的改变写入到所属字段时触发。
* Fires after editing is complete and any changed value has been written to the underlying field.
* @param {Editor} this
* @param {Mixed} value 当前字段的值。The current field value
* @param {Mixed} startValue 原始字段的值。The original field value
*/
"complete",
/**
* @event canceledit
* 当编辑器取消后和编辑器复位之后触发。
* Fires after editing has been canceled and the editor's value has been reset.
* @param {Editor} this
* @param {Mixed} value 用户被取消的值。The user-entered field value that was discarded
* @param {Mixed} startValue 原始值。The original field value that was set back into the editor after cancel
*/
"canceledit",
/**
* @event specialkey
* 用于导航的任意键被按下触发(arrows、tab、enter、esc等等)。
* 你可检查{@link Ext.EventObject#getKey}以确定哪个键被按了。
* 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.
* @param {Ext.form.Field} this
* @param {Ext.EventObject} e 事件对象。The event object
*/
"specialkey"
);
},
// private
onRender : function(ct, position){
this.el = new Ext.Layer({
shadow: this.shadow,
cls: "x-editor",
parentEl : ct,
shim : this.shim,
shadowOffset: this.shadowOffset || 4,
id: this.id,
constrain: this.constrain
});
if(this.zIndex){
this.el.setZIndex(this.zIndex);
}
this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden");
if(this.field.msgTarget != 'title'){
this.field.msgTarget = 'qtip';
}
this.field.inEditor = true;
this.field.render(this.el);
if(Ext.isGecko){
this.field.el.dom.setAttribute('autocomplete', 'off');
}
this.mon(this.field, "specialkey", this.onSpecialKey, this);
if(this.swallowKeys){
this.field.el.swallowEvent(['keydown','keypress']);
}
this.field.show();
this.mon(this.field, "blur", this.onBlur, this);
if(this.field.grow){
this.mon(this.field, "autosize", this.el.sync, this.el, {delay:1});
}
},
// private
onSpecialKey : function(field, e){
var key = e.getKey();
if(this.completeOnEnter && key == e.ENTER){
e.stopEvent();
this.completeEdit();
}else if(this.cancelOnEsc && key == e.ESC){
this.cancelEdit();
}else{
this.fireEvent('specialkey', field, e);
}
if(this.field.triggerBlur && (key == e.ENTER || key == e.ESC || key == e.TAB)){
this.field.triggerBlur();
}
},
/**
* 进入编辑状态并显示编辑器。
* Starts the editing process and shows the editor.
* @param {Mixed} el 要编辑的元素。The element to edit
* @param {String} value 编辑器初始化的值,如不设置该值便是元素的innerHTML。(optional) A value to initialize the editor with. If a value is not provided, it defaults
* to the innerHTML of el.
*/
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);
this.doAutoSize();
this.el.alignTo(this.boundEl, this.alignment);
this.editing = true;
this.show();
},
// private
doAutoSize : function(){
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);
}
}
},
/**
* 设置编辑器高、宽。
* Sets the height and width of this editor.
* @param {Number} width 新宽度。The new width
* @param {Number} height 新高度。The new height
*/
setSize : function(w, h){
delete this.field.lastSize;
this.field.setSize(w, h);
if(this.el){
if(Ext.isGecko2 || Ext.isOpera){
// prevent layer scrollbars
this.el.setSize(w, h);
}
this.el.sync();
}
},
/**
* 按照当前的最齐设置,把编辑器重新对齐到所绑定的字段。
* Realigns the editor to the bound field based on the current alignment config value.
*/
realign : function(){
this.el.alignTo(this.boundEl, this.alignment);
},
/**
* 结束编辑状态,提交变化的内容到所属的字段,并隐藏编辑器。
* Ends the editing process, persists the changed value to the underlying field, and hides the editor.
* @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false)。Override the default behavior and keep the editor visible after edit (defaults to 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();
}
},
/**
* 取消编辑状态并返回到原始值,不作任何的修改。
* Cancels the editing process and hides the editor without persisting any changes. The field value will be
* reverted to the original starting value.
* @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false)。Override the default behavior and keep the editor visible after
* cancel (defaults to false)
*/
cancelEdit : function(remainVisible){
if(this.editing){
var v = this.getValue();
this.setValue(this.startValue);
if(remainVisible !== true){
this.hide();
}
this.fireEvent("canceledit", this, v, this.startValue);
}
},
// 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();
}
},
/**
* 设置编辑器的数据。
* Sets the data value of the editor
* @param {Mixed} value 所属field可支持的任意值。Any valid value supported by the underlying field
*/
setValue : function(v){
this.field.setValue(v);
},
/**
* 获取编辑器的数据。
* Gets the data value of the editor
* @return {Mixed} 数据值。The data value
*/
getValue : function(){
return this.field.getValue();
},
beforeDestroy : function(){
Ext.destroy(this.field);
this.field = null;
}
});
Ext.reg('editor', Ext.Editor); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Layer
* @extends Ext.Element
* 一个由{@link Ext.Element}扩展的对象,支持阴影和shim,受视图限制和自动修复阴影/shim位置。
* An extended {@link Ext.Element} object that supports a shadow and shim, constrain to viewport and
* automatic maintaining of shadow/shim positions.
* @cfg {Boolean} shim false表示为禁用iframe的shim,在某些浏览器里需用到(默认为true)。
* False to disable the iframe shim in browsers which need one (defaults to true)
* @cfg {String/Boolean} shadow True表示为创建元素的阴影{@link Ext.Shadow},采用样式类"x-layer-shadow",或者你可以传入一个字符串表示阴影的模式{@link Ext.Shadow#mode},false表示为关闭阴影(默认为false)。
* True to automatically create an {@link Ext.Shadow}, or a string indicating the
* shadow's display {@link Ext.Shadow#mode}. False to disable the shadow. (defaults to false)
* @cfg {Object} dh DomHelper配置格式的对象,来创建元素(默认为{tag: "div", cls: "x-layer"})。
* DomHelper object config to create element with (defaults to {tag: "div", cls: "x-layer"}).
* @cfg {Boolean} constrain false表示为不受视图的限制(默认为true)。
* False to disable constrain to viewport (defaults to true)
* @cfg {String} cls 元素要添加的CSS样式类。CSS class to add to the element
* @cfg {Number} zindex 开始的z-index(默认为1100)。Starting z-index (defaults to 11000)
* @cfg {Number} shadowOffset 阴影偏移的像素值(默认为3)。Number of pixels to offset the shadow (defaults to 3)
* @constructor
* @param {Object} config 配置项对象。An object with config options.
* @param {String/HTMLElement} existingEl (可选的)使用现有的DOM的元素。如找不到就创建一个。(optional) Uses an existing DOM element. If the element is not found it creates it.
*/
(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;
// 复用iframes,保持在100个左右。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();
Ext.removeNode(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.getDoc().getScroll();
var xy = this.getXY();
var x = xy[0], y = xy[1];
var so = this.shadowOffset;
var w = this.dom.offsetWidth+so, h = this.dom.offsetHeight+so;
// only move it if it needs it
var moved = false;
// first validate right/bottom
if((x + w) > vw+s.left){
x = vw - w - so;
moved = true;
}
if((y + h) > vh+s.top){
y = vh - h - so;
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)。
* Sets the z-index of this layer and adjusts any shadow and shim z-indexes. The layer z-index is automatically
* incremented by two more than the value passed in so that it always shows above any shadow or shim (the shadow
* element, if any, will be assigned z-index + 1, and the shim element, if any, will be assigned the unmodified z-index).
* @param {Number} zindex 要设置的新z-index。The new z-index to set
* @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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.MessageBox
* <p>用来生成不同样式的消息框的实用类。还可以使用它的别名Ext.Msg。
* Utility class for generating different styles of message boxes. The alias Ext.Msg can also be used.<p/>
* <p>需要注意的是 MessageBox 对象是异步的。不同于 JavaScript中原生的<code>alert</code>(它会暂停浏览器的执行),显示 MessageBox 不会中断代码的运行。
* 由于这个原因,如果你的代码需要在用户对 MessageBox 做出反馈<em>之后</em>执行,则必须用到回调函数(详情可见{@link #show}方法中的<code>function</code>参数)。
* Note that the MessageBox is asynchronous. Unlike a regular JavaScript <code>alert</code> (which will halt
* browser execution), showing a MessageBox will not cause the code to stop. For this reason, if you have code
* that should only run <em>after</em> some user feedback from the MessageBox, you must use a callback function
* (see the <code>function</code> parameter for {@link #show} for more details).</p>
* <p>用法示例:Example usage:</p>
*<pre><code>
// 基本的通知: Basic alert:
Ext.Msg.alert('Status', 'Changes saved successfully.');
// 提示用户输入数据并使用回调方法进得处理: Prompt for user data and process the result using a callback:
Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
if (btn == 'ok'){
// process text value and close...
}
});
// 显示一个使用配置选项的对话框: Show a dialog using config options:
Ext.Msg.show({
title:'Save Changes?',
msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
buttons: Ext.Msg.YESNOCANCEL,
fn: processResult,
animEl: 'elId',
icon: Ext.MessageBox.QUESTION
});
</code></pre>
* @singleton
*/
Ext.MessageBox = function(){
var dlg, opt, mask, waitTimer;
var bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl;
var buttons, activeTextEl, bwidth, iconCls = '';
// private
var handleButton = function(button){
if(dlg.isVisible()){
dlg.hide();
Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value, opt], 1);
}
};
// private
var handleHide = function(){
if(opt && opt.cls){
dlg.el.removeClass(opt.cls);
}
progressBar.reset();
};
// private
var handleEsc = function(d, k, e){
if(opt && opt.closable !== false){
dlg.hide();
}
if(e){
e.stopEvent();
}
};
// private
var updateButtons = function(b){
var width = 0;
if(!b){
buttons["ok"].hide();
buttons["cancel"].hide();
buttons["yes"].hide();
buttons["no"].hide();
return width;
}
dlg.footer.dom.style.display = '';
for(var k in buttons){
if(typeof buttons[k] != "function"){
if(b[k]){
buttons[k].show();
buttons[k].setText(typeof b[k] == "string" ? b[k] : Ext.MessageBox.buttonText[k]);
width += buttons[k].el.getWidth()+15;
}else{
buttons[k].hide();
}
}
}
return width;
};
return {
/**
* 返回{@link Ext.Window}对象的元素的引用。
* Returns a reference to the underlying {@link Ext.Window} element
* @return {Ext.Window} The window 对象
*/
getDialog : function(titleText){
if(!dlg){
dlg = new Ext.Window({
autoCreate : true,
title:titleText,
resizable:false,
constrain:true,
constrainHeader:true,
minimizable : false,
maximizable : false,
stateful: false,
modal: true,
shim:true,
buttonAlign:"center",
width:400,
height:100,
minHeight: 80,
plain:true,
footer:true,
closable:true,
close : function(){
if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
handleButton("no");
}else{
handleButton("cancel");
}
}
});
buttons = {};
var bt = this.buttonText;
//TODO: refactor this block into a buttons config to pass into the Window constructor
buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
buttons["ok"].hideMode = buttons["yes"].hideMode = buttons["no"].hideMode = buttons["cancel"].hideMode = 'offsets';
dlg.render(document.body);
dlg.getEl().addClass('x-window-dlg');
mask = dlg.mask;
bodyEl = dlg.body.createChild({
html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><div class="ext-mb-fix-cursor"><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div></div>'
});
iconEl = Ext.get(bodyEl.dom.firstChild);
var contentEl = bodyEl.dom.childNodes[1];
msgEl = Ext.get(contentEl.firstChild);
textboxEl = Ext.get(contentEl.childNodes[2].firstChild);
textboxEl.enableDisplayMode();
textboxEl.addKeyListener([10,13], function(){
if(dlg.isVisible() && opt && opt.buttons){
if(opt.buttons.ok){
handleButton("ok");
}else if(opt.buttons.yes){
handleButton("yes");
}
}
});
textareaEl = Ext.get(contentEl.childNodes[2].childNodes[1]);
textareaEl.enableDisplayMode();
progressBar = new Ext.ProgressBar({
renderTo:bodyEl
});
bodyEl.createChild({cls:'x-clear'});
}
return dlg;
},
/**
* 更新消息框中body元素的文本。
* Updates the message box body text
* @param {String} text (可选)使用指定的文本替换消息框中元素的 innerHTML (默认为XHTML兼容的非换行空格字符 '&#160;')。(optional) Replaces the message box element's innerHTML with the specified string (defaults to
* the XHTML-compliant non-breaking space character '&#160;')
* @return {Ext.MessageBox} this
*/
updateText : function(text){
if(!dlg.isVisible() && !opt.width){
dlg.setSize(this.maxWidth, 100); // resize first so content is never clipped from previous shows
}
msgEl.update(text || ' ');
var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0;
var mw = msgEl.getWidth() + msgEl.getMargins('lr');
var fw = dlg.getFrameWidth('lr');
var bw = dlg.body.getFrameWidth('lr');
if (Ext.isIE && iw > 0){
//3 pixels get subtracted in the icon CSS for an IE margin issue,
//so we have to add it back here for the overall width to be consistent
iw += 3;
}
var w = Math.max(Math.min(opt.width || iw+mw+fw+bw, this.maxWidth),
Math.max(opt.minWidth || this.minWidth, bwidth || 0));
if(opt.prompt === true){
activeTextEl.setWidth(w-iw-fw-bw);
}
if(opt.progress === true || opt.wait === true){
progressBar.setSize(w-iw-fw-bw);
}
if(Ext.isIE && w == bwidth){
w += 4; //Add offset when the content width is smaller than the buttons.
}
dlg.setSize(w, 'auto').center();
return this;
},
/**
* 更新带有进度条的消息框中的文本和进度条。
* 仅仅是由通过 {@link Ext.MessageBox#progress}方法或者是在调用{@link Ext.MessageBox#show}方法时使用参数progress: true显示的消息框中可用。
* Updates a progress-style message box's text and progress bar. Only relevant on message boxes
* initiated via {@link Ext.MessageBox#progress} or {@link Ext.MessageBox#wait},
* or by calling {@link Ext.MessageBox#show} with progress: true.
* @param {Number} value 0 到 1 之间的任意数字(例如: .5,默认为 0)。Any number between 0 and 1 (e.g., .5, defaults to 0)
* @param {String} progressText 进度条中显示的文本(默认为 '')。The progress text to display inside the progress bar (defaults to '')
* @param {String} msg 用于替换消息框中 body 元素内容的文本(默认为 undefined,因此如果没有指定该参数则 body 中任何现存的文本将不会被覆写)。The message box's body text is replaced with the specified string (defaults to undefined
* so that any existing body text will not get overwritten by default unless a new value is passed in)
* @return {Ext.MessageBox} this
*/
updateProgress : function(value, progressText, msg){
progressBar.updateProgress(value, progressText);
if(msg){
this.updateText(msg);
}
return this;
},
/**
* 如果消息框当前可见则返回true。
* Returns true if the message box is currently displayed
* @return {Boolean} 如果消息框当前可见则返回 true,否则返回 false。True if the message box is visible, else false
*/
isVisible : function(){
return dlg && dlg.isVisible();
},
/**
* 如果消息框当前可见则返回true,否则返回false。
* Hides the message box if it is displayed
* @return {Ext.MessageBox} this
*/
hide : function(){
var proxy = dlg ? dlg.activeGhost : null;
if(this.isVisible() || proxy){
dlg.hide();
handleHide();
if (proxy){
proxy.hide();
}
}
return this;
},
/**
* 基于给定的配置选项显示一个消息框,或者重新初始一个现存的消息框。
* MessageBox 对象的所有显示函数(例如:prompt、alert、等等)均为内部调用此函数,
* 虽然这些调用均为此方法的简单的快捷方式并且不提供所有的下列配置选项。
* Displays a new message box, or reinitializes an existing message box, based on the config options
* passed in. All display functions (e.g. prompt, alert, etc.) on MessageBox call this function internally,
* although those calls are basic shortcuts and do not support all of the config options allowed here.
* @param {Object} config 可支持的配置项参数:The following config options are supported: <ul>
* <li><b>animEl</b> : String/Element<div class="sub-desc">消息框显示和关闭时动画展现的目标元素,或它的 ID(默认为 undefined)。
* An id or Element from which the message box should animate as it
* opens and closes (defaults to undefined)</div></li>
* <li><b>buttons</b> : Object/Boolean<div class="sub-desc">Button 配置对象(例如:Ext.MessageBox.OKCANCEL 或者 {ok:'Foo',cancel:'Bar'}),或者 false 表示不显示任何按钮(默认为 false)。
* A button config object (e.g., Ext.MessageBox.OKCANCEL or {ok:'Foo',
* cancel:'Bar'}), or false to not show any buttons (defaults to false)</div></li>
* <li><b>closable</b> : Boolean<div class="sub-desc">值为 false 则隐藏右上角的关闭按钮(默认为 true)。
* 注意由于 progress 和 wait 对话框只能通过程序关闭,因此它们将忽略此参数并总是隐藏关闭按钮。
* False to hide the top-right close button (defaults to true). Note that
* progress and wait dialogs will ignore this property and always hide the close button as they can only
* be closed programmatically.</div></li>
* <li><b>cls</b> : String<div class="sub-desc">应用到消息框容器元素中的自定义 CSS 类。
* A custom CSS class to apply to the message box's container element</div></li>
* <li><b>defaultTextHeight</b> : Number<div class="sub-desc">以像素为单位表示的默认消息框的文本域高度,如果有的话(默认为 75)。
* The default height in pixels of the message box's multiline textarea
* if displayed (defaults to 75)</div></li>
* <li><b>fn</b> : Function<div class="sub-desc">当对话框关闭后执行的回调函数。参数包括按钮(被点击的按钮的名字,如果可用,如:"ok"),文本(活动的文本框的值,如果可用)。
* A callback function which is called when the dialog is dismissed either
* by clicking on the configured buttons, or on the dialog close button, or by pressing
* the return button to enter input.
* <p>
* Progress 和 wait 对话框将忽略此选项,因为它们不会回应使用者的动作,并且只能在程序中被关闭,所以任何必须的函数都可以放在关闭对话框的代码中调用。
* 以下是送入的参数:
* Progress and wait dialogs will ignore this option since they do not respond to user
* actions and can only be closed programmatically, so any required function should be called
* by the same code after it closes the dialog. Parameters passed:<ul>
* <li><b>buttonId</b> : String<div class="sub-desc">
* 按下按钮的id,可以是:The ID of the button pressed, one of:<div class="sub-desc"><ul>
* <li><tt>ok</tt></li>
* <li><tt>yes</tt></li>
* <li><tt>no</tt></li>
* <li><tt>cancel</tt></li>
* </ul></div></div></li>
* <li><b>text</b> : String<div class="sub-desc">输入文本字段的值可以是Value of the input field if either <tt><a href="#show-option-prompt" ext:member="show-option-prompt" ext:cls="Ext.MessageBox">prompt</a></tt>
* or <tt><a href="#show-option-multiline" ext:member="show-option-multiline" ext:cls="Ext.MessageBox">multiline</a></tt> is true</div></li>
* <li><b>opt</b> : Object<div class="sub-desc">进行显示的配置对象。The config object passed to show.</div></li>
* </ul></p></div></li>
* <li><b>scope</b> : Object<div class="sub-desc">回调函数的作用域。The scope of the callback function</div></li>
* <li><b>icon</b> : String<div class="sub-desc">一个指定了背景图片地址的 CSS 类名用于对话框显示图标(例如:Ext.MessageBox.WARNING 或者 'custom-class',默认这 '')。
* A CSS class that provides a background image to be used as the body icon for the
* dialog (e.g. Ext.MessageBox.WARNING or 'custom-class') (defaults to '')</div></li>
* <li><b>iconCls</b> : String<div class="sub-desc">作用在头版图标的标准{@link Ext.Window#iconCls}(默认为'')。The standard {@link Ext.Window#iconCls} to
* add an optional header icon (defaults to '')</div></li>
* <li><b>maxWidth</b> : Number<div class="sub-desc">以像素为单位表示的消息框的最大宽度(默认为 600)。The maximum width in pixels of the message box (defaults to 600)</div></li>
* <li><b>minWidth</b> : Number<div class="sub-desc">以像素为单位表示的消息框的最小宽度(默认为 100)。The minimum width in pixels of the message box (defaults to 100)</div></li>
* <li><b>modal</b> : Boolean<div class="sub-desc">值为 false 时允许用户在消息框在显示时交互(默认为 true) False to allow user interaction with the page while the message box is
* displayed (defaults to true)</div></li>
* <li><b>msg</b> : String<div class="sub-desc">使用指定的文本替换消息框中元素的 innerHTML (默认为XHTML兼容的非换行空格字符 '&#160;') A string that will replace the existing message box body text (defaults to the
* XHTML-compliant non-breaking space character '&#160;')</div></li>
* <li><a id="show-option-multiline"></a><b>multiline</b> : Boolean<div class="sub-desc">
* 值为 true 时显示一个提示用户输入多行文本的对话框(默认为 false)。True to prompt the user to enter multi-line text (defaults to false)</div></li>
* <li><b>progress</b> : Boolean<div class="sub-desc">值为 true 时显示一个进度条(默认为 false)。True to display a progress bar (defaults to false)</div></li>
* <li><b>progressText</b> : String<div class="sub-desc">当 progress = true 时进度条内显示的文本(默认为 '')。The text to display inside the progress bar if progress = true (defaults to '')</div></li>
* <li><a id="show-option-prompt"></a><b>prompt</b> : Boolean<div class="sub-desc">值为 true 时显示一个提示用户输入单行文本的对话框(默认为 false)。True to prompt the user to enter single-line text (defaults to false)</div></li>
* <li><b>proxyDrag</b> : Boolean<div class="sub-desc">值为 true 则在拖拽的时候显示一个轻量级的代理(默认为 false)。True to display a lightweight proxy while dragging (defaults to false)</div></li>
* <li><b>title</b> : String<div class="sub-desc">标题文本。The title text</div></li>
* <li><b>value</b> : String<div class="sub-desc">设置到活动文本框中的文本。The string value to set into the active textbox element if displayed</div></li>
* <li><b>wait</b> : Boolean<div class="sub-desc">值为true时显示一个进度条(默认为 false)。True to display a progress bar (defaults to false)</div></li>
* <li><b>waitConfig</b> : Object<div class="sub-desc">{@link Ext.ProgressBar#waitConfig}对象(仅在 wait = true 时可用)。A {@link Ext.ProgressBar#waitConfig} object (applies only if wait = true)</div></li>
* <li><b>width</b> : Number<div class="sub-desc">以像素为单位表示的对话框的宽度。The width of the dialog in pixels</div></li>
* </ul>
* 用法示例: Example usage:
* <pre><code>
Ext.Msg.show({
title: 'Address',
msg: 'Please enter your address:',
width: 300,
buttons: Ext.MessageBox.OKCANCEL,
multiline: true,
fn: saveAddress,
animEl: 'addAddressBtn',
icon: Ext.MessageBox.INFO
});
</code></pre>
* @return {Ext.MessageBox} this
*/
show : function(options){
if(this.isVisible()){
this.hide();
}
opt = options;
var d = this.getDialog(opt.title || " ");
d.setTitle(opt.title || " ");
var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true);
d.tools.close.setDisplayed(allowClose);
activeTextEl = textboxEl;
opt.prompt = opt.prompt || (opt.multiline ? true : false);
if(opt.prompt){
if(opt.multiline){
textboxEl.hide();
textareaEl.show();
textareaEl.setHeight(typeof opt.multiline == "number" ?
opt.multiline : this.defaultTextHeight);
activeTextEl = textareaEl;
}else{
textboxEl.show();
textareaEl.hide();
}
}else{
textboxEl.hide();
textareaEl.hide();
}
activeTextEl.dom.value = opt.value || "";
if(opt.prompt){
d.focusEl = activeTextEl;
}else{
var bs = opt.buttons;
var db = null;
if(bs && bs.ok){
db = buttons["ok"];
}else if(bs && bs.yes){
db = buttons["yes"];
}
if (db){
d.focusEl = db;
}
}
if(opt.iconCls){
d.setIconClass(opt.iconCls);
}
this.setIcon(opt.icon);
bwidth = updateButtons(opt.buttons);
progressBar.setVisible(opt.progress === true || opt.wait === true);
this.updateProgress(0, opt.progressText);
this.updateText(opt.msg);
if(opt.cls){
d.el.addClass(opt.cls);
}
d.proxyDrag = opt.proxyDrag === true;
d.modal = opt.modal !== false;
d.mask = opt.modal !== false ? mask : false;
if(!d.isVisible()){
// force it to the end of the z-index stack so it gets a cursor in FF
document.body.appendChild(dlg.el.dom);
d.setAnimateTarget(opt.animEl);
d.show(opt.animEl);
}
//workaround for window internally enabling keymap in afterShow
d.on('show', function(){
if(allowClose === true){
d.keyMap.enable();
}else{
d.keyMap.disable();
}
}, this, {single:true});
if(opt.wait === true){
progressBar.wait(opt.waitConfig);
}
return this;
},
/**
* 添加指定的图标到对话框中。默认情况下,'ext-mb-icon' 被应用于默认的样式,给定的样式类需要指定背景图片地址。
* 如果要清除图标则给定一个空字串('')。下面是提供的内建图标样式类,当然你也可以给定一个自定义的类:
* Adds the specified icon to the dialog. By default, the class 'ext-mb-icon' is applied for default
* styling, and the class passed in is expected to supply the background image url. Pass in empty string ('')
* to clear any existing icon. The following built-in icon classes are supported, but you can also pass
* in a custom class name:
* <pre>
Ext.MessageBox.INFO
Ext.MessageBox.WARNING
Ext.MessageBox.QUESTION
Ext.MessageBox.ERROR
*</pre>
* @param {String} icon 一个指定了背景图片地址的 CSS 类名,或者一个空字串表示清除图标。A CSS classname specifying the icon's background image url, or empty string to clear the icon
* @return {Ext.MessageBox} this
*/
setIcon : function(icon){
if(icon && icon != ''){
iconEl.removeClass('x-hidden');
iconEl.replaceClass(iconCls, icon);
bodyEl.addClass('x-dlg-icon');
iconCls = icon;
}else{
iconEl.replaceClass(iconCls, 'x-hidden');
bodyEl.removeClass('x-dlg-icon');
iconCls = '';
}
return this;
},
/**
* 显示一个带有进度条的消息框。此消息框没有按钮并且无法被用户关闭。
* 你必须通过{@link Ext.MessageBox#updateProgress}方法更新进度条,并当进度完成时关闭消息框。
* Displays a message box with a progress bar. This message box has no buttons and is not closeable by
* the user. You are responsible for updating the progress bar as needed via {@link Ext.MessageBox#updateProgress}
* and closing the message box when the process is complete.
* @param {String} title 标题文本。The title bar text
* @param {String} msg 消息框body文本。The message box body text
* @param {String} progressText 进度条显示的文本(默认为 '')。(optional) The text to display inside the progress bar (defaults to '')
* @return {Ext.MessageBox} this
*/
progress : function(title, msg, progressText){
this.show({
title : title,
msg : msg,
buttons: false,
progress:true,
closable:false,
minWidth: this.minProgressWidth,
progressText: progressText
});
return this;
},
/**
* 显示一个带有不断自动更新的进度条的消息框。这个可以被用在一个长时间运行的进程中防止用户交互。你需要在进程完成的时候关闭消息框。
* Displays a message box with an infinitely auto-updating progress bar. This can be used to block user
* interaction while waiting for a long-running process to complete that does not have defined intervals.
* You are responsible for closing the message box when the process is complete.
* @param {String} msg 消息框 body 文本 The message box body text
* @param {String} title (可选) 标题文本。(optional) The title bar text
* @param {Object} config (可选) {@link Ext.ProgressBar#waitConfig}对象。(optional) A {@link Ext.ProgressBar#waitConfig} object
* @return {Ext.MessageBox} this
*/
wait : function(msg, title, config){
this.show({
title : title,
msg : msg,
buttons: false,
closable:false,
wait:true,
modal:true,
minWidth: this.minProgressWidth,
waitConfig: config
});
return this;
},
/**
* 显示一个标准的带有确认按钮的只读消息框(类似于 JavaScript原生的 alert函数、prompt函数)。
* 如果给定了回调函数,则会在用户点击按钮后执行,并且被点击的按钮的 ID 会当做唯一的参数传入到回调函数中(也有可能是右上角的关闭按钮)。
* Displays a standard read-only message box with an OK button (comparable to the basic JavaScript alert prompt).
* If a callback function is passed it will be called after the user clicks the button, and the
* id of the button that was clicked will be passed as the only parameter to the callback
* (could also be the top-right close button).
* @param {String} title 标题文本。The title bar text
* @param {String} msg 消息框body文本。The message box body text
* @param {Function} fn (可选)消息框被关闭后调用的回调函数。(optional) The callback function invoked after the message box is closed
* @param {Object} scope (可选)回调函数的作用域。(optional)The scope of the callback function
* @return {Ext.MessageBox} this
*/
alert : function(title, msg, fn, scope){
this.show({
title : title,
msg : msg,
buttons: this.OK,
fn: fn,
scope : scope
});
return this;
},
/**
* 显示一个带有是和否按钮的确认消息框(等同与JavaScript 原生的confirm函数)。
* 如果给定了回调函数,则会在用户点击按钮后执行,并且被点击的按钮的ID会当做唯一的参数传入到回调函数中(也有可能是右上角的关闭按钮)。
* Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's confirm).
* If a callback function is passed it will be called after the user clicks either button,
* and the id of the button that was clicked will be passed as the only parameter to the callback
* (could also be the top-right close button).
* @param {String} title 标题文本。The title bar text
* @param {String} msg 消息框body文本。The message box body text
* @param {Function} fn (可选)消息框被关闭后调用的回调函数。(optional) The callback function invoked after the message box is closed
* @param {Object} scope (可选)回调函数的作用域。(optional)The scope of the callback function
* @return {Ext.MessageBox} this
*/
confirm : function(title, msg, fn, scope){
this.show({
title : title,
msg : msg,
buttons: this.YESNO,
fn: fn,
scope : scope,
icon: this.QUESTION
});
return this;
},
/**
* 显示一个带有确认和取消按钮的提示框,并接受用户输入文本(等同与JavaScript原生的prompt函数)。
* 提示框可以是一个单行或多行文本框。如果给定了回调函数,则在用户点击任意一个按钮后执行回调函数,
* 并且被点击的按钮的ID(有可能是右上角的关闭按钮)和用户输入的文本都将被当做参数传给回调函数。
* Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to JavaScript's prompt).
* The prompt can be a single-line or multi-line textbox. If a callback function is passed it will be called after the user
* clicks either button, and the id of the button that was clicked (could also be the top-right
* close button) and the text that was entered will be passed as the two parameters to the callback.
* @param {String} title 标题文本。The title bar text
* @param {String} msg 消息框body文本。The message box body text
* @param {Function} fn (可选的)消息框被关闭后调用的回调函数。(optional)The callback function invoked after the message box is closed
* @param {Object} scope (可选的)回调函数的作用域。(optional)The scope of the callback function
* @param {Boolean/Number} multiline (可选的)值为true时则创建一个defaultTextHeight值指定行数的文本域,或者一个以像素为单位表示的高度(默认为 false,表示单行)。
* (optional)True to create a multiline textbox using the defaultTextHeight
* property, or the height in pixels to create the textbox (defaults to false / single-line)
* @param {String} value (可选的)text输入元素的默认值(默认为'')。(optional) Default value of the text input element (defaults to '')
* @return {Ext.MessageBox} this
*/
prompt : function(title, msg, fn, scope, multiline, value){
this.show({
title : title,
msg : msg,
buttons: this.OKCANCEL,
fn: fn,
minWidth:250,
scope : scope,
prompt:true,
multiline: multiline,
value: value
});
return this;
},
/**
* 只显示一个确认按钮的Button配置项。
* Button config that displays a single OK button
* @type Object
*/
OK : {ok:true},
/**
* 只显示一个取消按钮的Button配置项。
* Button config that displays a single Cancel button
* @type Object
*/
CANCEL : {cancel:true},
/**
* 显示确认和取消按钮的Button配置项。
* Button config that displays OK and Cancel buttons
* @type Object
*/
OKCANCEL : {ok:true, cancel:true},
/**
* 显示是和否按钮的Button配置项。
* Button config that displays Yes and No buttons
* @type Object
*/
YESNO : {yes:true, no:true},
/**
* 显示是、否和取消按钮的Button配置项。
* Button config that displays Yes, No and Cancel buttons
* @type Object
*/
YESNOCANCEL : {yes:true, no:true, cancel:true},
/**
* 显示INFO图标的CSS类。
* The CSS class that provides the INFO icon image
* @type String
*/
INFO : 'ext-mb-info',
/**
* 显示WARNING图标的CSS类。
* The CSS class that provides the WARNING icon image
* @type String
*/
WARNING : 'ext-mb-warning',
/**
* 显示QUESTION图标的CSS类。
* The CSS class that provides the QUESTION icon image
* @type String
*/
QUESTION : 'ext-mb-question',
/**
* 显示ERROR图标的CSS类。
* The CSS class that provides the ERROR icon image
* @type String
*/
ERROR : 'ext-mb-error',
/**
* 以像素为单位表示的消息框中文本域的默认高度(默认为 75)。
* The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
* @type Number
*/
defaultTextHeight : 75,
/**
* 以像素为单位表示的消息框的最大宽度(默认为 600)。
* The maximum width in pixels of the message box (defaults to 600)
* @type Number
*/
maxWidth : 600,
/**
* 以像素为单位表示的消息框的最小宽度(默认为 100)。
* The minimum width in pixels of the message box (defaults to 100)
* @type Number
*/
minWidth : 100,
/**
* 带有进度条的对话框的以像素为单位表示的最小宽度。在与纯文本对话框设置不同的最小宽度时会用到(默认为 250)。
* The minimum width in pixels of the message box if it is a progress-style dialog. This is useful
* for setting a different minimum width than text-only dialogs may need (defaults to 250)
* @type Number
*/
minProgressWidth : 250,
/**
* 一个包含默认的按钮文本字串的对象,为本地化支持时可以被覆写。
* 可用的属性有:ok、cancel、yes 和 no。通常情况下你可以通过包含一个本地资源文件来实现整个框架的本地化。
* 像这样就可以定制默认的文本:Ext.MessageBox.buttonText.yes = "是"; //中文
* An object containing the default button text strings that can be overriden for localized language support.
* Supported properties are: ok, cancel, yes and no. Generally you should include a locale-specific
* resource file for handling language support across the framework.
* Customize the default text like so: Ext.MessageBox.buttonText.yes = "oui"; //french
* @type Object
*/
buttonText : {
ok : "OK",
cancel : "Cancel",
yes : "Yes",
no : "No"
}
};
}();
/**
* {@link Ext.MessageBox} 的缩写。Shorthand for {@link Ext.MessageBox}
*/
Ext.Msg = Ext.MessageBox; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.TabPanel
* @extends Ext.Panel
* <p>
* 一种基础性的tab容器。
* Tab面板可用像标准{@link Ext.Panel}一样参与布局,亦可将多个面板归纳为一组tabs之特殊用途。<br />
* A basic tab container. TabPanels can be used exactly like a standard {@link Ext.Panel} for layout
* purposes, but also have special support for containing child Components that are managed using a CardLayout
* layout manager, and displayed as seperate tabs.
* </p>
* <p><b>Note:</b> TabPanels use their {@link Ext.Panel#header header} or {@link Ext.Panel#footer footer} element
* (depending on the {@link #tabPosition} configuration) to accommodate the tab selector buttons. This means that a TabPanel
* will not display any configured title, and will not display any configured header {@link Ext.Panel#tools tools}.
* To display a header, embed the TabPanel in a {@link Ext.Panel Panel} which uses
* <b><tt>{@link Ext.Container#layout layout: 'fit'}</tt></b>.
* </p>
* <p><b>Note:</b> It is advisable to configure all child items of a TabPanel (and any Container which uses a CardLayout) with
* <b><tt>{@link Ext.Component#hideMode hideMode: 'offsets'}</tt></b> to avoid rendering errors in child components hidden
* using the CSS <tt>display</tt> style.
* </p>
* <p>
* 这里没有单独而设的tab类—,每一张tab便是一个{@link Ext.Panel}。
* 然而,在当Panel放进TabPanel里面的时候,它作为子面板渲染的同时会额外增加若干事件,而这些事件一般的Panel是没有的,如下列出:<br />
* There is no actual tab class each tab is simply a {@link Ext.BoxComponent Component} such
* as a {@link Ext.Panel Panel}. However, when rendered in a TabPanel, each child Component can fire
* additional events that only exist for tabs and are not available from other Component. These are:
* </p>
* <ul>
* <li><b>activate</b>: 当面板变成为活动时触发。Fires when this Component becomes the active tab.
* <div class="mdetail-params">
* <strong style="font-weight: normal;">侦听器(Listeners)调用时会有下列的参数: Listeners will be called with the following arguments:</strong>
* <ul><li><code>tab</code> : Panel<div class="sub-desc">被激活的tab对象。The tab that was activated</div></li></ul>
* </div></li>
* <li><b>deactivate</b>: 当活动的面板变成为不活动的状态触发。Fires when the Component that was the active tab becomes deactivated.
* <div class="mdetail-params">
* <strong style="font-weight: normal;">侦听器(Listeners)调用时会有下列的参数: Listeners will be called with the following arguments:</strong>
* <ul><li><code>tab</code> : Panel<div class="sub-desc">取消活动状态的tab对象。The tab that was deactivated</div></li></ul>
* </div></li>
* </ul>
* <p>
* 要让服务端控制生成新的组件,必须要让服务编能够输出代码。<br />
* To add Components to a TabPanel which are generated dynamically on the server, it is necessary to
* create a server script to generate the Javascript to create the Component required.</p>
* <p>
* 例如,在一个中TabPanel加入一个GridPanel,这是基于服务端所产生的某些参数,你就要先执行Ajax一个的请求,在返回的response对象中得出渲染的内容向TabPanel加入。<br />
* For example, to add a GridPanel to a TabPanel where the GridPanel is generated by the server
* based on certain parameters, you would need to execute an Ajax request to invoke your the script,
* and process the response object to add it to the TabPanel:</p><pre><code>
Ext.Ajax.request({
url: 'gen-invoice-grid.php',
params: {
startDate = Ext.getCmp('start-date').getValue(),
endDate = Ext.getCmp('end-date').getValue()
},
success: function(xhr) {
var newComponent = eval(xhr.responseText);
myTabPanel.add(newComponent);
myTabPanel.setActiveTab(newComponent);
},
failure: function() {
Ext.Msg.alert("Grid create failed", "Server communication failure");
}
});
</code></pre>
* <p>
* 如上便是服务端所返回的代码,通过<tt>eval()</tt>执行就返回一个的{@link Ext.Component#xtype xtype}配置对象,或组件的实例。
* 如下例:<br />
* The server script would need to return an executable Javascript statement which, when processed
* using <tt>eval()</tt> will return either a config object with an {@link Ext.Component#xtype xtype},
* or an instantiated Component. For example:</p><pre><code>
(function() {
function formatDate(value){
return value ? value.dateFormat('M d, Y') : '';
};
var store = new Ext.data.Store({
url: 'get-invoice-data.php',
baseParams: {
startDate: '01/01/2008',
endDate: '01/31/2008'
},
reader: new Ext.data.JsonReader({
record: 'transaction',
id: 'id',
totalRecords: 'total'
}, [
'customer',
'invNo',
{name: 'date', type: 'date', dateFormat: 'm/d/Y'},
{name: 'value', type: 'float'}
])
});
var grid = new Ext.grid.GridPanel({
title: '发票报表 Invoice Report',
bbar: new Ext.PagingToolbar(store),
store: store,
columns: [
{header: "Customer", width: 250, dataIndex: 'customer', sortable: true},
{header: "Invoice Number", width: 120, dataIndex: 'invNo', sortable: true},
{header: "Invoice Date", width: 100, dataIndex: 'date', renderer: formatDate, sortable: true},
{header: "Value", width: 120, dataIndex: 'value', renderer: 'usMoney', sortable: true}
],
});
store.load();
return grid;
})();
</code></pre>
* <p>
* 由于同样是服务端<i>生成的</i>代码,Store这里的<tt>baseParams</tt>就是当前Store所配置的参数。
* Record布局所必需的元数据、ColumnModel信息在服务器上都是已知的,因此这样便可以一次性的输出到代码。 <br />
* Since that code is <i>generated</i> by a server script, the <tt>baseParams</tt> for the Store
* can be configured into the Store. The metadata to allow generation of the Record layout, and the
* ColumnModel is also known on the server, so these can be generated into the code.</p>
* <p>
* Ajax请求成功的处理函数中,就可以用<tt>eval</tt>处理这些代码片断,由Javascript解析器执行,然后匿名函数返回,生成Grid。 <br />
* When that code fragment is passed through the <tt>eval</tt> function in the success handler
* of the Ajax request, the code is executed by the Javascript processor, and the anonymous function
* runs, and returns the grid.</p>
* <p>有几种途径可生成Tab面板本身,下面演示的是纯粹通过代码来创建和渲染tabs。<br />
* There are several other methods available for creating TabPanels. The output of the following
* examples should produce exactly the same appearance. The tabs can be created and rendered completely
* in code, as in this example:</p>
* <pre><code>
var tabs = new Ext.TabPanel({
renderTo: Ext.getBody(),
activeTab: 0,
items: [{
title: 'Tab 1',
html: 'A simple tab'
},{
title: 'Tab 2',
html: 'Another one'
}]
});
</code></pre>
* 整个TabPanel对象也可以由标签,分别几个途径来创建。
* 请参阅{@link #autoTabs}的例子了解由标签创建的全部过程。
* 这些标签必须是符合TabPanel的要求的(div作为容器,然后内含一个或多个'x-tab'样式类的div表示每个标签页)。
* 同时你也可以通过指定id方式来选择哪个是容器的div、哪个是标签页的div,该方式下,标签页的内容会从页面上不同元素中提取,而不需要考虑页面的分配结构,自由度较高。
* 注意该例中class属性为'x-hide-display'的div表示延时渲染标签页,不会导致标签页在TabPanel外部的区域渲染显示出来。
* 你可选择设置{@link #deferredRender}为false表示所有的内容在页面加载时就渲染出来。例如:<br />
* TabPanels can also be rendered from pre-existing markup in a couple of ways. See the {@link #autoTabs} example for
* rendering entirely from markup that is already structured correctly as a TabPanel (a container div with
* one or more nested tab divs with class 'x-tab'). You can also render from markup that is not strictly
* structured by simply specifying by id which elements should be the container and the tabs. Using this method,
* tab content can be pulled from different elements within the page by id regardless of page structure. Note
* that the tab divs in this example contain the class 'x-hide-display' so that they can be rendered deferred
* without displaying outside the tabs. You could alternately set {@link #deferredRender} to false to render all
* content tabs on page load. For example:
* <pre><code>
var tabs = new Ext.TabPanel({
renderTo: 'my-tabs',
activeTab: 0,
items:[
{contentEl:'tab1', title:'Tab 1'},
{contentEl:'tab2', title:'Tab 2'}
]
});
// 注意tab没有被容器套着(尽管也是可以套着的)。Note that the tabs do not have to be nested within the container (although they can be)
<div id="my-tabs"></div>
<div id="tab1" class="x-hide-display">A simple tab</div>
<div id="tab2" class="x-hide-display">Another one</div>
</code></pre>
* @constructor
* @param {Object} config 配置项对象。The configuration options
*/
Ext.TabPanel = Ext.extend(Ext.Panel, {
/**
* @cfg {Boolean} layoutOnTabChange True表示为每当Tab切换时就绘制一次布局。
* Set to true to do a layout of tab items as tabs are changed.
*/
/**
* @cfg {String} tabCls <b>此配置项应用于该Tab<u>子组件</u>的样式。
* This config option is used on <u>child Components</u> of this TabPanel.</b>
* 赋予各个候选栏的CSS样式,表示这是子组件。
* A CSS class name applied to the tab strip item representing the child Component, allowing special
* styling to be applied.
*/
/**
* @cfg {Boolean} monitorResize True表示为自动随着window的大小变化,按照浏览器的大小渲染布局(默认为 true)。
* True to automatically monitor window resize events and rerender the layout on browser resize (defaults to true).
*/
monitorResize : true,
/**
* @cfg {Boolean} deferredRender 内置地,Tab面板是采用{@link Ext.layout.CardLayout}的方法管理tabs。
* 此属性的值将会传递到布局的{@link Ext.layout.CardLayout#deferredRender}配置值中,
* 以决定tab面板是否只有在第一次访问时才渲染(缺省为true)。
* Internally, the TabPanel uses a {@link Ext.layout.CardLayout} to manage its tabs.
* This property will be passed on to the layout as its {@link Ext.layout.CardLayout#deferredRender} config value,
* determining whether or not each tab is rendered only when first accessed (defaults to true).
* <p>
* 注意如果将deferredRender设为<b><tt>true</tt></b>的话,
* 又使用{@link Ext.form.FormPanel form}的话,那表示只有在tab激活之后,全部的表单域(Fields)才会被渲染出来,
* 也就是说不管是提交表单抑或是执行{@link Ext.form.BasicForm#getValues getValues}或{@link Ext.form.BasicForm#setValues setValues}都是无用。
* Be aware that leaving deferredRender as <b><tt>true</tt></b> means that, if the TabPanel is within
* a {@link Ext.form.FormPanel form}, then until a tab is activated, any Fields within that tab will not
* be rendered, and will therefore not be submitted and will not be available to either
* {@link Ext.form.BasicForm#getValues getValues} or {@link Ext.form.BasicForm#setValues setValues}.</p>
*/
deferredRender : true,
/**
* @cfg {Number} tabWidth 每一张新tab的初始宽度,单位为象素(缺省为120)。
* The initial width in pixels of each new tab (defaults to 120).
*/
tabWidth: 120,
/**
* @cfg {Number} minTabWidth 每张tab宽度的最小值,仅当{@link #resizeTabs} = true有效(缺省为30)。
* The minimum width in pixels for each tab when {@link #resizeTabs} = true (defaults to 30).
*/
minTabWidth: 30,
/**
* @cfg {Boolean} resizeTabs True表示为自动调整各个标签页的宽度,以便适应当前TabPanel的候选栏的宽度(默认为false)。
* 这样设置的话,那么每个标签页都可能会一个规定的宽度,原先标签页的宽度将不会保留以便适应显示(尽管{@link #minTabWidth}依然作用)。
* True to automatically resize each tab so that the tabs will completely fill the
* tab strip (defaults to false). Setting this to true may cause specific widths that might be set per tab to
* be overridden in order to fit them all into view (although {@link #minTabWidth} will always be honored).
*/
resizeTabs:false,
/**
* @cfg {Boolean} enableTabScroll 有时标签页会超出TabPanel的整体宽度。
* 为防止此情况下溢出的标签页不可见,就需要将此项设为true以出现标签页可滚动的功能。
* 只当标签页位于上方的位置时有效(默认为false)。
* True to enable scrolling to tabs that may be invisible due to overflowing the
* overall TabPanel width. Only available with tabPosition:'top' (defaults to false).
*/
enableTabScroll: false,
/**
* @cfg {Number} scrollIncrement 每次滚动按钮按下时,被滚动的标签页所移动的距离
* (单位是像素,默认为100,若{@link #resizeTabs}=true,那么默认值将是计算好的标签页宽度)。
* 仅当{@link #enableTabScroll} = true时有效。
* The number of pixels to scroll each time a tab scroll button is pressed (defaults
* to 100, or if {@link #resizeTabs} = true, the calculated tab width). Only applies when {@link #enableTabScroll} = true.
*/
scrollIncrement : 0,
/**
* @cfg {Number} scrollRepeatInterval 当标签页滚动按钮不停地被按下时,两次执行滚动的间隔的毫秒数(默认为400)。
* Number of milliseconds between each scroll while a tab scroll button is continuously pressed (defaults to 400).
*/
scrollRepeatInterval : 400,
/**
* @cfg {Float} scrollDuration 每次滚动所产生动画会持续多久(单位毫秒,默认为0.35)。
* 只当{@link #animScroll} = true时有效。
* The number of milliseconds that each scroll animation should last (defaults to .35).
* Only applies when {@link #animScroll} = true.
*/
scrollDuration : .35,
/**
* @cfg {Boolean} animScroll True 表示为tab滚动时出现动画效果以使tab在视图中消失得更平滑(缺省为true)。
* 只当 {@link #enableTabScroll} = true时有效。
* True to animate tab scrolling so that hidden tabs slide smoothly into view (defaults
* to true). Only applies when {@link #enableTabScroll} = true.
*/
animScroll : true,
/**
* @cfg {String} tabPosition Tab候选栏渲染的位置(默认为 'top')。其它可支持值是'bottom'。
* 注意tab滚动(tab scrolling)只支持'top'的位置。
* The position where the tab strip should be rendered (defaults to 'top'). The only
* other supported value is 'bottom'. Note that tab scrolling is only supported for position 'top'.
*/
tabPosition: 'top',
/**
* @cfg {String} baseCls 作用在面板上CSS样式类(默认为 'x-tab-panel')。
* The base CSS class applied to the panel (defaults to 'x-tab-panel').
*/
baseCls: 'x-tab-panel',
/**
* @cfg {Boolean} autoTabs
* <p>
* Tru 表示为查询DOM中任何带"x-tab'样式类的div元素,转化为tab加入到此面板中(默认为false)。
* 注意查询的执行范围仅限于容器元素内(这样独立的话同一页面内多个tab就不会相冲突了)
* True to query the DOM for any divs with a class of 'x-tab' to be automatically converted
* to tabs and added to this panel (defaults to false). Note that the query will be executed within the scope of
* the container element only (so that multiple tab panels from markup can be supported via this method).</p>
* <p>此时要求markup(装饰元素)结构(即在容器内嵌有'x-tab'类的div元素)才有效。
* 要解除这种限制。或从页面上其它元素的内容拉到tab中,可参阅由markup生成tab的第一个示例。
* This method is only possible when the markup is structured correctly as a container with nested
* divs containing the class 'x-tab'. To create TabPanels without these limitations, or to pull tab content from
* other elements on the page, see the example at the top of the class for generating tabs from markup.</p>
* <p>采用这种方法须注意下列几个问题:
* There are a couple of things to note when using this method:<ul>
* <li>
* 当使用autoTabs的时候(与 不同的tab配置传入到tabPanel{@link #items}集合的方法相反),你同时必须使用{@link #applyTo}正确地指明tab容器的id。
* AutoTabs 方法把现有的内容<em>替换为</em>TabPanel组件。
* When using the autoTabs config (as opposed to passing individual tab configs in the TabPanel's
* {@link #items} collection), you must use {@link #applyTo} to correctly use the specified id as the tab container.
* The autoTabs method <em>replaces</em> existing content with the TabPanel components.</li>
* <li>
* 确保已设{@link #deferredRender}为false,使得每个tab中的内容元素能在页面加载之后立即渲染到TabPanel,
* 否则的话激活tab也不能成功渲染。
* Make sure that you set {@link #deferredRender} to false so that the content elements for each tab will be
* rendered into the TabPanel immediately upon page load, otherwise they will not be transformed until each tab
* is activated and will be visible outside the TabPanel.</li>
* </ul>用法举例:Example usage:</p>
* <pre><code>
var tabs = new Ext.TabPanel({
applyTo: 'my-tabs',
activeTab: 0,
deferredRender: false,
autoTabs: true
});
// 这些装饰元素会按照以上的代码转换为TabPanel对象。This markup will be converted to a TabPanel from the code above
<div id="my-tabs">
<div class="x-tab" title="Tab 1">A simple tab</div>
<div class="x-tab" title="Tab 2">Another one</div>
</div>
</code></pre>
*/
autoTabs : false,
/**
* @cfg {String} autoTabSelector 用于搜索tab的那个CSS选择符,当{@link #autoTabs}时有效(默认为 'div.x-tab')。
* 此值可以是{@link Ext.DomQuery#select}的任意有效值。
* 注意: 选择过程只会在tab的范围内进行(这样独立的话同一页面内多个tab就不会相冲突了)。
* The CSS selector used to search for tabs in existing markup when {@link #autoTabs} = true (defaults to 'div.x-tab').
* This can be any valid selector supported by {@link Ext.DomQuery#select}.
* Note that the query will be executed within the scope of this tab panel only (so that multiple tab panels from
* markup can be supported on a page).
*/
autoTabSelector:'div.x-tab',
/**
* @cfg {String/Number} activeTab 一个字符串或数字(索引)表示,渲染后就活动的那个tab(默认为没有)。
* A string id or the numeric index of the tab that should be initially
* activated on render (defaults to none).
*/
activeTab : null,
/**
* @cfg {Number} tabMargin 此象素值参与大小调整和卷动时的运算,以计算空隙的象素值。
* 如果你在CSS中改变了margin(外补丁),那么这个值也要随着更改,才能正确地计算值(默认为2)。
* The number of pixels of space to calculate into the sizing and scrolling of tabs. If you
* change the margin in CSS, you will need to update this value so calculations are correct with either resizeTabs
* or scrolling tabs. (defaults to 2)
*/
tabMargin : 2,
/**
* @cfg {Boolean} plain True表示为不渲染tab候选栏上背景容器图片(默认为false)。
* True to render the tab strip without a background container image (defaults to false).
*/
plain: false,
/**
* @cfg {Number} wheelIncrement 对于可滚动的tabs,鼠标滚轮翻页一下的步长值,单位为象素(缺省为20)。
* For scrolling tabs, the number of pixels to increment on mouse wheel scrolling (defaults to 20).
*/
wheelIncrement : 20,
/*
* This is a protected property used when concatenating tab ids to the TabPanel id for internal uniqueness.
* It does not generally need to be changed, but can be if external code also uses an id scheme that can
* potentially clash with this one.
*/
idDelimiter : '__',
// private
itemCls : 'x-tab-item',
// private config overrides
elements: 'body',
headerAsText: false,
frame: false,
hideBorders:true,
// private
initComponent : function(){
this.frame = false;
Ext.TabPanel.superclass.initComponent.call(this);
this.addEvents(
/**
* @event beforetabchange
* 当活动tab改变时触发。若句柄返回false则取消tab的切换。
* Fires before the active tab changes. Handlers can return false to cancel the tab change.
* @param {TabPanel} this
* @param {Panel} newTab 活动着的tab对象。The tab being activated
* @param {Panel} currentTab 当前活动tab对象。The current active tab
*/
'beforetabchange',
/**
* @event tabchange
* 当活动tab改变后触发。
* Fires after the active tab has changed.
* @param {TabPanel} this
* @param {Panel} tab 新的活动tab对象。The new active tab
*/
'tabchange',
/**
* @event contextmenu
* 当原始浏览器的右键事件在tab元素上触发时,连动到此事件。
* Relays the contextmenu event from a tab selector element in the tab strip.
* @param {TabPanel} this
* @param {Panel} tab 目标tab对象。The target tab
* @param {EventObject} e
*/
'contextmenu'
);
this.setLayout(new Ext.layout.CardLayout({
deferredRender: this.deferredRender
}));
if(this.tabPosition == 'top'){
this.elements += ',header';
this.stripTarget = 'header';
}else {
this.elements += ',footer';
this.stripTarget = 'footer';
}
if(!this.stack){
this.stack = Ext.TabPanel.AccessStack();
}
this.initItems();
},
// private
onRender : function(ct, position){
Ext.TabPanel.superclass.onRender.call(this, ct, position);
if(this.plain){
var pos = this.tabPosition == 'top' ? 'header' : 'footer';
this[pos].addClass('x-tab-panel-'+pos+'-plain');
}
var st = this[this.stripTarget];
this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{
tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}});
var beforeEl = (this.tabPosition=='bottom' ? this.stripWrap : null);
this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'}, beforeEl);
this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'});
this.strip.createChild({cls:'x-clear'});
this.body.addClass('x-tab-panel-body-'+this.tabPosition);
/**
* @cfg {Template/XTemplate} itemTpl
* <p>
* (可选的) 要处理候选栏上可点击的那些元素,应该在{@link #getTemplateArgs}返回一个数据对像,其类型是{@link Ext.Template Template}或{@link Ext.XTemplate XTemplate}
* (Optional) A {@link Ext.Template Template} or {@link Ext.XTemplate XTemplate} which
* may be provided to process the data object returned from {@link #getTemplateArgs} to produce a clickable selector element in the tab strip.</p>
* <p>
* 主要元素该是<tt><li></tt>元素。为了能使目标元素与其对应子项连接上,TabPanel的原生方法必须传入目标元素<i>id</i>。
* The main element created should be a <tt><li></tt> element. In order for a click event on a selector element to be
* connected to its item, it must take its <i>id</i> from the TabPanel's native {@link #getTemplateArgs}.</p>
* <p>
* 标题文字所在的子元素是须要有<tt>x-tab-strip-inner</tt>的样式。
* The child element which contains the title text must be marked by the CSS class <tt>x-tab-strip-inner</tt>.</p>
* <p>
* 要出现“关闭”按钮的,就要有<tt>x-tab-strip-close</tt>样式。
* To enable closability, the created element should contain an element marked by the CSS class <tt>x-tab-strip-close</tt>.</p>
* <p>
* 若要自定义特别的外观,应制定itemTpl。下面是一个怎样创建tab子项选择符的例子:
* If a custom itemTpl is supplied, it is the developer's responsibility to create CSS style rules to create the desired appearance.</p>
* Below is an example of how to create customized tab selector items:<code><pre>
new Ext.TabPanel({
renderTo: document.body,
minTabWidth: 115,
tabWidth: 135,
enableTabScroll: true,
width: 600,
height: 250,
defaults: {autoScroll:true},
itemTpl: new Ext.XTemplate(
'<li class="{cls}" id="{id}" style="overflow:hidden">',
'<tpl if="closable">',
'<a class="x-tab-strip-close" onclick="return false;"></a>',
'</tpl>',
'<a class="x-tab-right" href="#" onclick="return false;" style="padding-left:6px">',
'<em class="x-tab-left">',
'<span class="x-tab-strip-inner">',
'<img src="{src}" style="float:left;margin:3px 3px 0 0">',
'<span style="margin-left:20px" class="x-tab-strip-text {iconCls}">{text} {extra}</span>',
'</span>',
'</em>',
'</a>',
'</li>'
),
getTemplateArgs: function(item) {
// Call the native method to collect the base data. Like the ID!
var result = Ext.TabPanel.prototype.getTemplateArgs.call(this, item);
// Add stuff used in our template
return Ext.apply(result, {
closable: item.closable,
src: item.iconSrc,
extra: item.extraText || ''
});
},
items: [{
title: 'New Tab 1',
iconSrc: '../shared/icons/fam/grid.png',
html: 'Tab Body 1',
closable: true
}, {
title: 'New Tab 2',
iconSrc: '../shared/icons/fam/grid.png',
html: 'Tab Body 2',
extraText: 'Extra stuff in the tab button'
}]
});
</pre></code>
*/
if(!this.itemTpl){
var tt = new Ext.Template(
'<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>',
'<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">',
'<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>',
'</em></a></li>'
);
tt.disableFormats = true;
tt.compile();
Ext.TabPanel.prototype.itemTpl = tt;
}
this.items.each(this.initTab, this);
},
// private
afterRender : function(){
Ext.TabPanel.superclass.afterRender.call(this);
if(this.autoTabs){
this.readTabs(false);
}
if(this.activeTab !== undefined){
var item = (typeof this.activeTab == 'object') ? this.activeTab : this.items.get(this.activeTab);
delete this.activeTab;
this.setActiveTab(item);
}
},
// private
initEvents : function(){
Ext.TabPanel.superclass.initEvents.call(this);
this.on('add', this.onAdd, this, {target: this});
this.on('remove', this.onRemove, this, {target: this});
this.mon(this.strip, 'mousedown', this.onStripMouseDown, this);
this.mon(this.strip, 'contextmenu', this.onStripContextMenu, this);
if(this.enableTabScroll){
this.mon(this.strip, 'mousewheel', this.onStripContextMenu, this);
}
},
// private
findTargets : function(e){
var item = null;
var itemEl = e.getTarget('li', this.strip);
if(itemEl){
item = this.getComponent(itemEl.id.split(this.idDelimiter)[1]);
if(item.disabled){
return {
close : null,
item : null,
el : null
};
}
}
return {
close : e.getTarget('.x-tab-strip-close', this.strip),
item : item,
el : itemEl
};
},
// private
onStripMouseDown : function(e){
if(e.button != 0){
return;
}
e.preventDefault();
var t = this.findTargets(e);
if(t.close){
if (t.item.fireEvent('close', t.item) !== false) {
this.remove(t.item);
}
return;
}
if(t.item && t.item != this.activeTab){
this.setActiveTab(t.item);
}
},
// private
onStripContextMenu : function(e){
e.preventDefault();
var t = this.findTargets(e);
if(t.item){
this.fireEvent('contextmenu', this, t.item, e);
}
},
/**
* True表示为使用autoTabSelector选择符来扫描此tab面板内的markup,以准备autoTabs的特性。
* True to scan the markup in this tab panel for autoTabs using the autoTabSelector
* @param {Boolean} removeExisting True表示为移除现有的tabs。True to remove existing tabs
*/
readTabs : function(removeExisting){
if(removeExisting === true){
this.items.each(function(item){
this.remove(item);
}, this);
}
var tabs = this.el.query(this.autoTabSelector);
for(var i = 0, len = tabs.length; i < len; i++){
var tab = tabs[i];
var title = tab.getAttribute('title');
tab.removeAttribute('title');
this.add({
title: title,
contentEl: tab
});
}
},
// private
initTab : function(item, index){
var before = this.strip.dom.childNodes[index];
var p = this.getTemplateArgs(item);
var el = before ?
this.itemTpl.insertBefore(before, p) :
this.itemTpl.append(this.strip, p);
Ext.fly(el).addClassOnOver('x-tab-strip-over');
if(item.tabTip){
Ext.fly(el).child('span.x-tab-strip-text', true).qtip = item.tabTip;
}
item.tabEl = el;
item.on('disable', this.onItemDisabled, this);
item.on('enable', this.onItemEnabled, this);
item.on('titlechange', this.onItemTitleChanged, this);
item.on('iconchange', this.onItemIconChanged, this);
item.on('beforeshow', this.onBeforeShowItem, this);
},
/**
* <p>
* 为在tab候选栏中渲染tab选择符,产生模板参数。
* Provides template arguments for rendering a tab selector item in the tab strip.</p>
* <p>
* 该方法返回对象将会为TabPanel的{@link #itemTpl}所用,用于创建符合格式的,可点击的tab选择符元素。必须返回形如以下的对象:
* This method returns an object hash containing properties used by the TabPanel's {@link #itemTpl}
* to create a formatted, clickable tab selector element. The properties which must be returned are:</p><div class="mdetail-params"><ul>
* <li><b>id</b> : String<div class="sub-desc">关联项的Id。A unique identifier which links to the item</div></li>
* <li><b>text</b> : String<div class="sub-desc">显示文本。The text to display</div></li>
* <li><b>cls</b> : String<div class="sub-desc">CSS样式名称。The CSS class name</div></li>
* <li><b>iconCls</b> : String<div class="sub-desc">为设置图标的CSS样式名称。A CSS class to provide appearance for an icon.</div></li>
* </ul></div>
* @param {BoxComponent} item 产生tab候选栏中的选择元素{@link Ext.BoxComponent BoxComponent}。The {@link Ext.BoxComponent BoxComponent} for which to create a selector element in the tab strip.
* @return {Object} 包含要进行渲染的选择符元素的对象。An object hash containing the properties required to render the selector element.
*/
getTemplateArgs: function(item) {
var cls = item.closable ? 'x-tab-strip-closable' : '';
if(item.disabled){
cls += ' x-item-disabled';
}
if(item.iconCls){
cls += ' x-tab-with-icon';
}
if(item.tabCls){
cls += ' ' + item.tabCls;
}
return {
id: this.id + this.idDelimiter + item.getItemId(),
text: item.title,
cls: cls,
iconCls: item.iconCls || ''
};
},
// private
onAdd : function(tp, item, index){
this.initTab(item, index);
if(this.items.getCount() == 1){
this.syncSize();
}
this.delegateUpdates();
},
// private
onBeforeAdd : function(item){
var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item);
if(existing){
this.setActiveTab(item);
return false;
}
Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments);
var es = item.elements;
item.elements = es ? es.replace(',header', '') : es;
item.border = (item.border === true);
},
// private
onRemove : function(tp, item){
Ext.destroy(Ext.get(this.getTabEl(item)));
this.stack.remove(item);
item.un('disable', this.onItemDisabled, this);
item.un('enable', this.onItemEnabled, this);
item.un('titlechange', this.onItemTitleChanged, this);
item.un('iconchange', this.onItemIconChanged, this);
item.un('beforeshow', this.onBeforeShowItem, this);
if(item == this.activeTab){
var next = this.stack.next();
if(next){
this.setActiveTab(next);
}else if(this.items.getCount() > 0){
this.setActiveTab(0);
}else{
this.activeTab = null;
}
}
this.delegateUpdates();
},
// private
onBeforeShowItem : function(item){
if(item != this.activeTab){
this.setActiveTab(item);
return false;
}
},
// private
onItemDisabled : function(item){
var el = this.getTabEl(item);
if(el){
Ext.fly(el).addClass('x-item-disabled');
}
this.stack.remove(item);
},
// private
onItemEnabled : function(item){
var el = this.getTabEl(item);
if(el){
Ext.fly(el).removeClass('x-item-disabled');
}
},
// private
onItemTitleChanged : function(item){
var el = this.getTabEl(item);
if(el){
Ext.fly(el).child('span.x-tab-strip-text', true).innerHTML = item.title;
}
},
//private
onItemIconChanged: function(item, iconCls, oldCls){
var el = this.getTabEl(item);
if(el){
Ext.fly(el).child('span.x-tab-strip-text').replaceClass(oldCls, iconCls);
}
},
/**
* 指定一个子面板,返回此面板在tab候选栏上的DOM元素。
* 访问DOM元素可以修改一些可视化效果,例如更改CSS样式类的名称。
* Gets the DOM element for tab strip item which activates the
* child panel with the specified ID. Access this to change the visual treatment of the
* item, for example by changing the CSS class name.
* @param {Panel/Number} tab tab对象。The tab component, or the tab's index
* @return {HTMLElement} DOM节点。The DOM node
*/
getTabEl : function(item){
var itemId = (typeof item === 'number')?this.items.items[item].getItemId() : item.getItemId();
return document.getElementById(this.id+this.idDelimiter+itemId);
},
// private
onResize : function(){
Ext.TabPanel.superclass.onResize.apply(this, arguments);
this.delegateUpdates();
},
/**
* 暂停一切内置的运算或卷动好让扩充操作(bulk operation)进行。请参阅{@link #endUpdate}。
* Suspends any internal calculations or scrolling while doing a bulk operation. See {@link #endUpdate}
*/
beginUpdate : function(){
this.suspendUpdates = true;
},
/**
* 结束扩充操作(bulk operation)后,重新开始一切内置的运算或滚动效果。请参阅{@link #beginUpdate}。
* Resumes calculations and scrolling at the end of a bulk operation. See {@link #beginUpdate}
*/
endUpdate : function(){
this.suspendUpdates = false;
this.delegateUpdates();
},
/**
* 隐藏Tab候选栏以传入tab。
* Hides the tab strip item for the passed tab
* @param {Number/String/Panel} item tab索引、id或item对象。The tab index, id or item
*/
hideTabStripItem : function(item){
item = this.getComponent(item);
var el = this.getTabEl(item);
if(el){
el.style.display = 'none';
this.delegateUpdates();
}
this.stack.remove(item);
},
/**
* 取消Tab候选栏隐藏的状态以传入tab。
* Unhides the tab strip item for the passed tab
* @param {Number/String/Panel} item item tab索引、id或item对象。The tab index, id or item
*/
unhideTabStripItem : function(item){
item = this.getComponent(item);
var el = this.getTabEl(item);
if(el){
el.style.display = '';
this.delegateUpdates();
}
},
// private
delegateUpdates : function(){
if(this.suspendUpdates){
return;
}
if(this.resizeTabs && this.rendered){
this.autoSizeTabs();
}
if(this.enableTabScroll && this.rendered){
this.autoScrollTabs();
}
},
// private
autoSizeTabs : function(){
var count = this.items.length;
var ce = this.tabPosition != 'bottom' ? 'header' : 'footer';
var ow = this[ce].dom.offsetWidth;
var aw = this[ce].dom.clientWidth;
if(!this.resizeTabs || count < 1 || !aw){ // !aw for display:none
return;
}
var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.tabMargin, this.tabWidth), this.minTabWidth); // -4 for float errors in IE
this.lastTabWidth = each;
var lis = this.strip.query("li:not([className^=x-tab-edge])");
for(var i = 0, len = lis.length; i < len; i++) {
var li = lis[i];
var inner = Ext.fly(li).child('.x-tab-strip-inner', true);
var tw = li.offsetWidth;
var iw = inner.offsetWidth;
inner.style.width = (each - (tw-iw)) + 'px';
}
},
// private
adjustBodyWidth : function(w){
if(this.header){
this.header.setWidth(w);
}
if(this.footer){
this.footer.setWidth(w);
}
return w;
},
/**
* 设置特定的tab为活动面板。此方法触发{@link #beforetabchange}事件,若处理函数返回false则取消tab切换。
* Sets the specified tab as the active tab. This method fires the {@link #beforetabchange} event which
* can return false to cancel the tab change.
* @param {String/Panel} tab 活动面板或其id。The id or tab Panel to activate
*/
setActiveTab : function(item){
item = this.getComponent(item);
if(!item || this.fireEvent('beforetabchange', this, item, this.activeTab) === false){
return;
}
if(!this.rendered){
this.activeTab = item;
return;
}
if(this.activeTab != item){
if(this.activeTab){
var oldEl = this.getTabEl(this.activeTab);
if(oldEl){
Ext.fly(oldEl).removeClass('x-tab-strip-active');
}
this.activeTab.fireEvent('deactivate', this.activeTab);
}
var el = this.getTabEl(item);
Ext.fly(el).addClass('x-tab-strip-active');
this.activeTab = item;
this.stack.add(item);
this.layout.setActiveItem(item);
if(this.layoutOnTabChange && item.doLayout){
item.doLayout();
}
if(this.scrolling){
this.scrollToTab(item, this.animScroll);
}
item.fireEvent('activate', item);
this.fireEvent('tabchange', this, item);
}
},
/**
* 返回当前活动的Tab。
* Gets the currently active tab.
* @return {Panel} 活动的Tab。The active tab
*/
getActiveTab : function(){
return this.activeTab || null;
},
/**
* 根据id获取指定tab。
* Gets the specified tab by id.
* @param {String} id Tab的ID。The tab id
* @return {Panel} The tab
*/
getItem : function(item){
return this.getComponent(item);
},
// private
autoScrollTabs : function(){
this.pos = this.tabPosition=='bottom' ? this.footer : this.header;
var count = this.items.length;
var ow = this.pos.dom.offsetWidth;
var tw = this.pos.dom.clientWidth;
var wrap = this.stripWrap;
var wd = wrap.dom;
var cw = wd.offsetWidth;
var pos = this.getScrollPos();
var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;
if(!this.enableTabScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues
return;
}
if(l <= tw){
wd.scrollLeft = 0;
wrap.setWidth(tw);
if(this.scrolling){
this.scrolling = false;
this.pos.removeClass('x-tab-scrolling');
this.scrollLeft.hide();
this.scrollRight.hide();
if(Ext.isAir || Ext.isSafari){
wd.style.marginLeft = '';
wd.style.marginRight = '';
}
}
}else{
if(!this.scrolling){
this.pos.addClass('x-tab-scrolling');
if(Ext.isAir || Ext.isSafari){
wd.style.marginLeft = '18px';
wd.style.marginRight = '18px';
}
}
tw -= wrap.getMargins('lr');
wrap.setWidth(tw > 20 ? tw : 20);
if(!this.scrolling){
if(!this.scrollLeft){
this.createScrollers();
}else{
this.scrollLeft.show();
this.scrollRight.show();
}
}
this.scrolling = true;
if(pos > (l-tw)){ // ensure it stays within bounds
wd.scrollLeft = l-tw;
}else{ // otherwise, make sure the active tab is still visible
this.scrollToTab(this.activeTab, false);
}
this.updateScrollButtons();
}
},
// private
createScrollers : function(){
this.pos.addClass('x-tab-scrolling-' + this.tabPosition);
var h = this.stripWrap.dom.offsetHeight;
// left
var sl = this.pos.insertFirst({
cls:'x-tab-scroller-left'
});
sl.setHeight(h);
sl.addClassOnOver('x-tab-scroller-left-over');
this.leftRepeater = new Ext.util.ClickRepeater(sl, {
interval : this.scrollRepeatInterval,
handler: this.onScrollLeft,
scope: this
});
this.scrollLeft = sl;
// right
var sr = this.pos.insertFirst({
cls:'x-tab-scroller-right'
});
sr.setHeight(h);
sr.addClassOnOver('x-tab-scroller-right-over');
this.rightRepeater = new Ext.util.ClickRepeater(sr, {
interval : this.scrollRepeatInterval,
handler: this.onScrollRight,
scope: this
});
this.scrollRight = sr;
},
// private
getScrollWidth : function(){
return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos();
},
// private
getScrollPos : function(){
return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0;
},
// private
getScrollArea : function(){
return parseInt(this.stripWrap.dom.clientWidth, 10) || 0;
},
// private
getScrollAnim : function(){
return {duration:this.scrollDuration, callback: this.updateScrollButtons, scope: this};
},
// private
getScrollIncrement : function(){
return this.scrollIncrement || (this.resizeTabs ? this.lastTabWidth+2 : 100);
},
/**
* 滚动到指定的TAB(前提是scrolling要激活)。
* Scrolls to a particular tab if tab scrolling is enabled
* @param {Panel} item 要滚动到项。The item to scroll to
* @param {Boolean} animate True表示有动画效果。True to enable animations
*/
scrollToTab : function(item, animate){
if(!item){ return; }
var el = this.getTabEl(item);
var pos = this.getScrollPos(), area = this.getScrollArea();
var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos;
var right = left + el.offsetWidth;
if(left < pos){
this.scrollTo(left, animate);
}else if(right > (pos + area)){
this.scrollTo(right - area, animate);
}
},
// private
scrollTo : function(pos, animate){
this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false);
if(!animate){
this.updateScrollButtons();
}
},
onWheel : function(e){
var d = e.getWheelDelta()*this.wheelIncrement*-1;
e.stopEvent();
var pos = this.getScrollPos();
var newpos = pos + d;
var sw = this.getScrollWidth()-this.getScrollArea();
var s = Math.max(0, Math.min(sw, newpos));
if(s != pos){
this.scrollTo(s, false);
}
},
// private
onScrollRight : function(){
var sw = this.getScrollWidth()-this.getScrollArea();
var pos = this.getScrollPos();
var s = Math.min(sw, pos + this.getScrollIncrement());
if(s != pos){
this.scrollTo(s, this.animScroll);
}
},
// private
onScrollLeft : function(){
var pos = this.getScrollPos();
var s = Math.max(0, pos - this.getScrollIncrement());
if(s != pos){
this.scrollTo(s, this.animScroll);
}
},
// private
updateScrollButtons : function(){
var pos = this.getScrollPos();
this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('x-tab-scroller-left-disabled');
this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('x-tab-scroller-right-disabled');
},
// private
beforeDestroy : function() {
if(this.items){
this.items.each(function(item){
if(item && item.tabEl){
Ext.get(item.tabEl).removeAllListeners();
item.tabEl = null;
}
}, this);
}
if(this.strip){
this.strip.removeAllListeners();
}
Ext.TabPanel.superclass.beforeDestroy.apply(this);
}
/**
* @cfg {Boolean} collapsible
* @hide
*/
/**
* @cfg {String} header
* @hide
*/
/**
* @cfg {Boolean} headerAsText
* @hide
*/
/**
* @property header
* @type Object
* @hide
*/
/**
* @property title
* @type String
* @hide
*/
/**
* @cfg {Array} tools
* @hide
*/
/**
* @cfg {Array} toolTemplate
* @hide
*/
/**
* @cfg {Boolean} hideCollapseTool
* @hide
*/
/**
* @cfg {Boolean} titleCollapse
* @hide
*/
/**
* @cfg {Boolean} collapsed
* @hide
*/
/**
* @cfg {String} layout
* @hide
*/
/**
* @cfg {Object} layoutConfig
* @hide
*/
});
Ext.reg('tabpanel', Ext.TabPanel);
/**
* 设置特定的tab为活动面板。
* 此方法触发{@link #beforetabchange}事件若返回false则取消tab切换。
* Sets the specified tab as the active tab. This method fires the {@link #beforetabchange} event which
* can return false to cancel the tab change.
* @param {String/Panel} tab 活动面板或其id。The id or tab Panel to activate
* @method activate
*/
Ext.TabPanel.prototype.activate = Ext.TabPanel.prototype.setActiveTab;
// private utility class used by TabPanel
Ext.TabPanel.AccessStack = function(){
var items = [];
return {
add : function(item){
items.push(item);
if(items.length > 10){
items.shift();
}
},
remove : function(item){
var s = [];
for(var i = 0, len = items.length; i < len; i++) {
if(items[i] != item){
s.push(items[i]);
}
}
items = s;
},
next : function(){
return items.pop();
}
};
};
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Slider
* @extends Ext.BoxComponent
* 滑动条控件支持垂直或水平方向滑动,通过键盘方向键调整滑动,配置捕捉点,在滑动轴上点击调整并有动画显示。可以作为item被添加到任何容器中。使用示例:<br />
* Slider which supports vertical or horizontal orientation, keyboard adjustments,
* configurable snapping, axis clicking and animation. Can be added as an item to
* any container. Example usage:
<pre><code>
new Ext.Slider({
renderTo: Ext.getBody(),
width: 200,
value: 50,
increment: 10,
minValue: 0,
maxValue: 100
});
</code></pre>
*/
Ext.Slider = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {Number} value 滑动条的初始值。默认值为 minValue。The value to initialize the slider with. Defaults to minValue.
*/
/**
* @cfg {Boolean} vertical 控制滑动条的垂直或水平方向,默认值为 false 表示水平方向。Orient the Slider vertically rather than horizontally, defaults to false.
*/
vertical: false,
/**
* @cfg {Number} minValue 滑动条的最小值。默认值为 0。The minimum value for the Slider. Defaults to 0.
*/
minValue: 0,
/**
* @cfg {Number} maxValue 滑动条的最大值。默认值为 100。The maximum value for the Slider. Defaults to 100.
*/
maxValue: 100,
/**
* @cfg {Number/Boolean} decimalPrecision. 小数点位数。
* <p>滑动条的值再进行四舍五入时的小数点位数。默认值为 0。The number of decimal places to which to round the Slider's value. Defaults to 0.</p>
* <p>禁用四舍五入,配置为 <tt><b>false</b></tt>。To disable rounding, configure as <tt><b>false</b></tt>.</p>
*/
decimalPrecision: 0,
/**
* @cfg {Number} keyIncrement
* 方向键调整滑动条时,每次改变的数值。默认值为 1。如果配置大于默认值,将使用配置后的数值。How many units to change the Slider when adjusting with keyboard navigation. Defaults to 1. If the increment config is larger, it will be used instead.
*/
keyIncrement: 1,
/**
* @cfg {Number} increment
* 拖放调整滑动条时,每次改变的数值。配置此属性来启用“捕捉”功能。How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'.
*/
increment: 0,
// private
clickRange: [5,15],
/**
* @cfg {Boolean} clickToChange 确定是否要在滑动轴上点击调整。默认值为 true。Determines whether or not clicking on the Slider axis will change the slider. Defaults to true
*/
clickToChange : true,
/**
* @cfg {Boolean} animate 开启或关闭动画。默认值为 true。Turn on or off animation. Defaults to true
*/
animate: true,
/**
* 当滑动时此属性为True。True while the thumb is in a drag operation
* @type boolean
*/
dragging: false,
// private override
initComponent : function(){
if(this.value === undefined){
this.value = this.minValue;
}
Ext.Slider.superclass.initComponent.call(this);
this.keyIncrement = Math.max(this.increment, this.keyIncrement);
this.addEvents(
/**
* @event beforechange
* 当滑动条的值改变前触发此事件。您可以取消该活动,并防止滑块改变,通过事件处理器(event handler)返回false,您可以取消该事件,并阻止滑动条改变。
* Fires before the slider value is changed. By returning false from an event handler,
* you can cancel the event and prevent the slider from changing.
* @param {Ext.Slider} slider The slider
* @param {Number} newValue 滑动条将要改变到的新值。The new value which the slider is being changed to.
* @param {Number} oldValue 滑动条改变之前的旧值。The old value which the slider was previously.
*/
'beforechange',
/**
* @event change
* 当滑动条的值改变后触发此事件。
* Fires when the slider value is changed.
* @param {Ext.Slider} slider The slider
* @param {Number} newValue 滑动条改变后的新值。The new value which the slider has been changed to.
*/
'change',
/**
* @event changecomplete
* 当用户改变滑动条的值和任何拖动操作完成时触发此事件。
* Fires when the slider value is changed by the user and any drag operations have completed.
* @param {Ext.Slider} slider The slider
* @param {Number} newValue 滑动条改变后的新值。The new value which the slider has been changed to.
*/
'changecomplete',
/**
* @event dragstart
* 当拖动操作开始后触发此事件。
* Fires after a drag operation has started.
* @param {Ext.Slider} slider The slider
* @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
*/
'dragstart',
/**
* @event drag
* 拖动操作过程中当鼠标正在移动时触发此事件。
* Fires continuously during the drag operation while the mouse is moving.
* @param {Ext.Slider} slider The slider
* @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
*/
'drag',
/**
* @event dragend
* 当拖动操作结束后触发此事件。
* Fires after the drag operation has completed.
* @param {Ext.Slider} slider The slider
* @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
*/
'dragend'
);
if(this.vertical){
Ext.apply(this, Ext.Slider.Vertical);
}
},
// private override
onRender : function(){
this.autoEl = {
cls: 'x-slider ' + (this.vertical ? 'x-slider-vert' : 'x-slider-horz'),
cn:{cls:'x-slider-end',cn:{cls:'x-slider-inner',cn:[{cls:'x-slider-thumb'},{tag:'a', cls:'x-slider-focus', href:"#", tabIndex: '-1', hidefocus:'on'}]}}
};
Ext.Slider.superclass.onRender.apply(this, arguments);
this.endEl = this.el.first();
this.innerEl = this.endEl.first();
this.thumb = this.innerEl.first();
this.halfThumb = (this.vertical ? this.thumb.getHeight() : this.thumb.getWidth())/2;
this.focusEl = this.thumb.next();
this.initEvents();
},
// private override
initEvents : function(){
this.thumb.addClassOnOver('x-slider-thumb-over');
this.mon(this.el, 'mousedown', this.onMouseDown, this);
this.mon(this.el, 'keydown', this.onKeyDown, this);
this.focusEl.swallowEvent("click", true);
this.tracker = new Ext.dd.DragTracker({
onBeforeStart: this.onBeforeDragStart.createDelegate(this),
onStart: this.onDragStart.createDelegate(this),
onDrag: this.onDrag.createDelegate(this),
onEnd: this.onDragEnd.createDelegate(this),
tolerance: 3,
autoStart: 300
});
this.tracker.initEl(this.thumb);
this.on('beforedestroy', this.tracker.destroy, this.tracker);
},
// private override
onMouseDown : function(e){
if(this.disabled) {return;}
if(this.clickToChange && e.target != this.thumb.dom){
var local = this.innerEl.translatePoints(e.getXY());
this.onClickChange(local);
}
this.focus();
},
// private
onClickChange : function(local){
if(local.top > this.clickRange[0] && local.top < this.clickRange[1]){
this.setValue(Math.round(this.reverseValue(local.left)), undefined, true);
}
},
// private
onKeyDown : function(e){
if(this.disabled){e.preventDefault();return;}
var k = e.getKey();
switch(k){
case e.UP:
case e.RIGHT:
e.stopEvent();
if(e.ctrlKey){
this.setValue(this.maxValue, undefined, true);
}else{
this.setValue(this.value+this.keyIncrement, undefined, true);
}
break;
case e.DOWN:
case e.LEFT:
e.stopEvent();
if(e.ctrlKey){
this.setValue(this.minValue, undefined, true);
}else{
this.setValue(this.value-this.keyIncrement, undefined, true);
}
break;
default:
e.preventDefault();
}
},
// private
doSnap : function(value){
if(!this.increment || this.increment == 1 || !value) {
return value;
}
var newValue = value, inc = this.increment;
var m = value % inc;
if(m != 0){
newValue -= m;
if(m * 2 > inc){
newValue += inc;
}else if(m * 2 < -inc){
newValue -= inc;
}
}
return newValue.constrain(this.minValue, this.maxValue);
},
// private
afterRender : function(){
Ext.Slider.superclass.afterRender.apply(this, arguments);
if(this.value !== undefined){
var v = this.normalizeValue(this.value);
if(v !== this.value){
delete this.value;
this.setValue(v, false);
}else{
this.moveThumb(this.translateValue(v), false);
}
}
},
// private
getRatio : function(){
var w = this.innerEl.getWidth();
var v = this.maxValue - this.minValue;
return v == 0 ? w : (w/v);
},
// private
normalizeValue : function(v){
v = Ext.util.Format.round(v, this.decimalPrecision);
v = this.doSnap(v);
v = v.constrain(this.minValue, this.maxValue);
return v;
},
/**
* 编程方式设置滑动条的数值。确保设置的数值在最小值和最大值之间。
* Programmatically sets the value of the Slider. Ensures that the value is constrained within
* the minValue and maxValue.
* @param {Number} value 设置滑动条的数值,( value 受到 minValue 和 maxValue 属性的约束)。The value to set the slider to. (This will be constrained within minValue and maxValue)
* @param {Boolean} animate 开启或关闭动画,默认值为 true。Turn on or off animation, defaults to true
*/
setValue : function(v, animate, changeComplete){
v = this.normalizeValue(v);
if(v !== this.value && this.fireEvent('beforechange', this, v, this.value) !== false){
this.value = v;
this.moveThumb(this.translateValue(v), animate !== false);
this.fireEvent('change', this, v);
if(changeComplete){
this.fireEvent('changecomplete', this, v);
}
}
},
// private
translateValue : function(v){
var ratio = this.getRatio();
return (v * ratio)-(this.minValue * ratio)-this.halfThumb;
},
reverseValue : function(pos){
var ratio = this.getRatio();
return (pos+this.halfThumb+(this.minValue * ratio))/ratio;
},
// private
moveThumb: function(v, animate){
if(!animate || this.animate === false){
this.thumb.setLeft(v);
}else{
this.thumb.shift({left: v, stopFx: true, duration:.35});
}
},
// private
focus : function(){
this.focusEl.focus(10);
},
// private
onBeforeDragStart : function(e){
return !this.disabled;
},
// private
onDragStart: function(e){
this.thumb.addClass('x-slider-thumb-drag');
this.dragging = true;
this.dragStartValue = this.value;
this.fireEvent('dragstart', this, e);
},
// private
onDrag: function(e){
var pos = this.innerEl.translatePoints(this.tracker.getXY());
this.setValue(Math.round(this.reverseValue(pos.left)), false);
this.fireEvent('drag', this, e);
},
// private
onDragEnd: function(e){
this.thumb.removeClass('x-slider-thumb-drag');
this.dragging = false;
this.fireEvent('dragend', this, e);
if(this.dragStartValue != this.value){
this.fireEvent('changecomplete', this, this.value);
}
},
// private
onResize : function(w, h){
this.innerEl.setWidth(w - (this.el.getPadding('l') + this.endEl.getPadding('r')));
this.syncThumb();
},
//private
onDisable: function(){
Ext.Slider.superclass.onDisable.call(this);
this.thumb.addClass(this.disabledClass);
if(Ext.isIE){
//IE breaks when using overflow visible and opacity other than 1.
//Create a place holder for the thumb and display it.
var xy = this.thumb.getXY();
this.thumb.hide();
this.innerEl.addClass(this.disabledClass).dom.disabled = true;
if (!this.thumbHolder){
this.thumbHolder = this.endEl.createChild({cls: 'x-slider-thumb ' + this.disabledClass});
}
this.thumbHolder.show().setXY(xy);
}
},
//private
onEnable: function(){
Ext.Slider.superclass.onEnable.call(this);
this.thumb.removeClass(this.disabledClass);
if(Ext.isIE){
this.innerEl.removeClass(this.disabledClass).dom.disabled = false;
if (this.thumbHolder){
this.thumbHolder.hide();
}
this.thumb.show();
this.syncThumb();
}
},
/**
* Synchronizes the thumb position to the proper proportion of the total component width based
* on the current slider {@link #value}. This will be called automatically when the Slider
* is resized by a layout, but if it is rendered auto width, this method can be called from
* another resize handler to sync the Slider if necessary.
*/
syncThumb : function(){
if(this.rendered){
this.moveThumb(this.translateValue(this.value));
}
},
/**
* 返回滑动条的当前值
* Returns the current value of the slider
* @return {Number} The current value of the slider
*/
getValue : function(){
return this.value;
}
});
Ext.reg('slider', Ext.Slider);
// private class to support vertical sliders
Ext.Slider.Vertical = {
onResize : function(w, h){
this.innerEl.setHeight(h - (this.el.getPadding('t') + this.endEl.getPadding('b')));
this.syncThumb();
},
getRatio : function(){
var h = this.innerEl.getHeight();
var v = this.maxValue - this.minValue;
return h/v;
},
moveThumb: function(v, animate){
if(!animate || this.animate === false){
this.thumb.setBottom(v);
}else{
this.thumb.shift({bottom: v, stopFx: true, duration:.35});
}
},
onDrag: function(e){
var pos = this.innerEl.translatePoints(this.tracker.getXY());
var bottom = this.innerEl.getHeight()-pos.top;
this.setValue(this.minValue + Math.round(bottom/this.getRatio()), false);
this.fireEvent('drag', this, e);
},
onClickChange : function(local){
if(local.left > this.clickRange[0] && local.left < this.clickRange[1]){
var bottom = this.innerEl.getHeight()-local.top;
this.setValue(this.minValue + Math.round(bottom/this.getRatio()), undefined, true);
}
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Action
* <p>
* Action是可复用性中可以抽象出来,被任意特定组件所继承的特性之一。
* Action使你可以通过所有实现了Actions接口的组件共享处理函数、配置选项对象以及UI的更新(比如{@link Ext.Toolbar}、{@link Ext.Button}和{@link Ext.menu.Menu}组件)。<br />
* An Action is a piece of reusable functionality that can be abstracted out of any particular component so that it
* can be usefully shared among multiple components. Actions let you share handlers, configuration options and UI
* updates across any components that support the Action interface (primarily {@link Ext.Toolbar}, {@link Ext.Button}
* and {@link Ext.menu.Menu} components).</p>
* <p>
* 除了提供的配置选项对象接口之外,任何想要使用Action的组件必需提供下列方法以便在Action所需时调用:
* setText(string)、setIconCls(string)、setDisabled(boolean)、setVisible(boolean)和setHandler(function)。<br />
* Aside from supporting the config object interface, any component that needs to use Actions must also support
* the following method list, as these will be called as needed by the Action class: setText(string), setIconCls(string),
* setDisabled(boolean), setVisible(boolean) and setHandler(function).</p>
* 使用示例:Example usage:<br>
* <pre><code>
// Define the shared action. Each component below will have the same
// display text and icon, and will display the same message on click.
var action = new Ext.Action({
text: 'Do something',
handler: function(){
Ext.Msg.alert('Click', 'You did something.');
},
iconCls: 'do-something'
});
var panel = new Ext.Panel({
title: 'Actions',
width:500,
height:300,
tbar: [
// Add the action directly to a toolbar as a menu button
action, {
text: 'Action Menu',
// Add the action to a menu as a text item
menu: [action]
}
],
items: [
// Add the action to the panel body as a standard button
new Ext.Button(action)
],
renderTo: Ext.getBody()
});
// Change the text for all components using the action
action.setText('Something else');
// 通过itemId来获取容器下的action
// Reference an action through a container using the itemId
var btn = panel.getComponent('myAction');
var aRef = btn.baseAction;
aRef.setText('New text');
</code></pre>
* @constructor
* @param {Object} config 配置选项对象。The configuration options
*/
Ext.Action = function(config){
this.initialConfig = config;
this.itemId = config.itemId = (config.itemId || config.id || Ext.id());
this.items = [];
}
Ext.Action.prototype = {
/**
* @cfg {String} text 使用 action 对象的所有组件的文本(默认为 '')。
* The text to set for all components using this action (defaults to '').
*/
/**
* @cfg {String} iconCls
* 使用 action 对象的组件的图标样式表(默认为 '')。该样式类应该提供一个显示为图标的背景图片。
* The CSS class selector that specifies a background image to be used as the header icon for
* all components using this action (defaults to '').
* <p>用css来指定图标的例子会是这样:An example of specifying a custom icon class would be something like:
* </p><code><pre>
// iconCls是指定图标的配置项。specify the property in the config for the class:
...
iconCls: 'do-something'
// 指定css背景图,作为图标的图片文件。css class that specifies background image to be used as the icon image:
.do-something { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; }
</pre></code>
*/
/**
* @cfg {Boolean} disabled True 则禁用组件,false 则启用组件(默认为 false)。
* True to disable all components using this action, false to enable them (defaults to false).
*/
/**
* @cfg {Boolean} hidden True 则隐藏组件,false 则显示组件(默认为 false)。
* True to hide all components using this action, false to show them (defaults to false).
*/
/**
* @cfg {Function} handler 每个使用 action 对象的组件的主要事件触发时调用的处理函数(默认为 undefined)。
* The function that will be invoked by each component tied to this action
* when the component's primary event is triggered (defaults to undefined).
*/
/**
* @cfg {Object} scope {@link #handler}函数执行的作用域。
* The scope in which the {@link #handler} function will execute.
*/
// private
isAction : true,
/**
* 设置使用 action 对象的所有组件的文本。
* Sets the text to be displayed by all components using this action.
* @param {String} text 显示的文本。The text to display
*/
setText : function(text){
this.initialConfig.text = text;
this.callEach('setText', [text]);
},
/**
* 获取使用 action 对象的组件当前显示的文本。
* Gets the text currently displayed by all components using this action.
*/
getText : function(){
return this.initialConfig.text;
},
/**
* 设置使用 action 对象的组件的图标样式表。该样式类应该提供一个显示为图标的背景图片。
* Sets the icon CSS class for all components using this action. The class should supply
* a background image that will be used as the icon image.
* @param {String} cls 提供图标图片的 CSS 样式类。The CSS class supplying the icon image
*/
setIconClass : function(cls){
this.initialConfig.iconCls = cls;
this.callEach('setIconClass', [cls]);
},
/**
* 获取使用 action 对象的组件的图标样式表。
* Gets the icon CSS class currently used by all components using this action.
*/
getIconClass : function(){
return this.initialConfig.iconCls;
},
/**
* 设置所有使用 action 对象的组件的 disabled 状态。{@link #enable} 和 {@link #disable} 方法的快捷方式。
* Sets the disabled state of all components using this action. Shortcut method for {@link #enable} and {@link #disable}.
* @param {Boolean} disabled True 则禁用组件,false 则启用组件。True to disable the component, false to enable it
*/
setDisabled : function(v){
this.initialConfig.disabled = v;
this.callEach('setDisabled', [v]);
},
/**
* 启用所有使用 action 对象的组件。
* Enables all components using this action.
*/
enable : function(){
this.setDisabled(false);
},
/**
* 禁用所有使用 action 对象的组件。
* Disables all components using this action.
*/
disable : function(){
this.setDisabled(true);
},
/**
* 如果组件当前使用的 action 对象是禁用的,则返回 true,否则返回 false。只读。
* Returns true if the components using this action are currently disabled, else returns false. Read-only.
* @type Boolean
* @property isDisabled
*/
isDisabled : function(){
return this.initialConfig.disabled;
},
/**
* 设置所有使用 action 对象的组件的 hidden 状态。{@link #hide} 和 {@link #show} 方法的快捷方式。
* Sets the hidden state of all components using this action. Shortcut method for {@link #hide} and {@link #show}.
* @param {Boolean} hidden True 则隐藏组件,false 则显示组件。 True to hide the component, false to show it
*/
setHidden : function(v){
this.initialConfig.hidden = v;
this.callEach('setVisible', [!v]);
},
/**
* 显示所有使用 action 对象的组件。
* Shows all components using this action.
*/
show : function(){
this.setHidden(false);
},
/**
* 隐藏所有使用 action 对象的组件。
* Hides all components using this action.
*/
hide : function(){
this.setHidden(true);
},
/**
* 如果组件当前使用的 action 对象是隐藏的,则返回 true,否则返回 false。只读。
* Returns true if the components using this action are currently hidden, else returns false. Read-only.
* @type Boolean
* @property isHidden
*/
isHidden : function(){
return this.initialConfig.hidden;
},
/**
* 为每个使用 action 对象的组件设置主要事件触发时调用的处理函数。
* Sets the function that will be called by each component using this action when its primary event is triggered.
* @param {Function} fn 对象的组件调用的函数。调用该函数时没有参数。The function that will be invoked by the action's components. The function
* will be called with no arguments.
* @param {Object} scope 函数运行的作用域。The scope in which the function will execute
*/
setHandler : function(fn, scope){
this.initialConfig.handler = fn;
this.initialConfig.scope = scope;
this.callEach('setHandler', [fn, scope]);
},
/**
* 绑定到当前 action 对象上的所有组件都执行一次指定的函数。传入的函数将接受一个由 action 对象所支持的配置选项对象组成的参数。
* Executes the specified function once for each component currently tied to this action. The function passed
* in should accept a single argument that will be an object that supports the basic Action config/method interface.
* @param {Function} fn 每个组件执行的函数。The function to execute for each component
* @param {Object} scope 函数运行的作用域。The scope in which the function will execute
*/
each : function(fn, scope){
Ext.each(this.items, fn, scope);
},
// private
callEach : function(fnName, args){
var cs = this.items;
for(var i = 0, len = cs.length; i < len; i++){
cs[i][fnName].apply(cs[i], args);
}
},
// private
addComponent : function(comp){
this.items.push(comp);
comp.on('destroy', this.removeComponent, this);
},
// private
removeComponent : function(comp){
this.items.remove(comp);
},
/**
* 手动执行动作,采用的是原配置对象上的默认句柄函数。参数也可以一并传递。
* Executes this action manually using the default handler specified in the original config object. Any arguments
* passed to this function will be passed on to the handler function.
* @param {Mixed} arg1 (可选的)传入到处理器句柄的参数。(optional) Variable number of arguments passed to the handler function
* @param {Mixed} arg2 (可选的)(optional)
* @param {Mixed} etc... (可选的)(optional)
*/
execute : function(){
this.initialConfig.handler.apply(this.initialConfig.scope || window, arguments);
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.DataView
* @extends Ext.BoxComponent
* 能够为自己设计模板和特定格式而提供的一种数据显示机制。
* DataView采用{@link Ext.XTemplate}为其模板处理的机制,并依靠{@link Ext.data.Store}来绑定数据,这样的话store中数据发生变化时便会自动更新前台。
* DataView亦提供许多针对对象项(item)的内建事件,如单击、双击、mouseover、mouseout等等,还包括一个内建的选区模型(selection model)。
* <b>要实现以上这些功能,必须要为DataView对象设置一个itemSelector协同工作。</b><br />
* A mechanism for displaying data using custom layout templates and formatting. DataView uses an {@link Ext.XTemplate}
* as its internal templating mechanism, and is bound to an {@link Ext.data.Store}
* so that as the data in the store changes the view is automatically updated to reflect the changes. The view also
* provides built-in behavior for many common events that can occur for its contained items including click, doubleclick,
* mouseover, mouseout, etc. as well as a built-in selection model. <b>In order to use these features, an {@link #itemSelector}
* config must be provided for the DataView to determine what nodes it will be working with.</b>
* <p>
* 下面给出的例子是已将DataView绑定到一个{@link Ext.data.Store}对象并在一个上{@link Ext.Panel}渲染。<br />
* The example below binds a DataView to a {@link Ext.data.Store} and renders it into an {@link Ext.Panel}.</p>
* <pre><code>
var store = new Ext.data.JsonStore({
url: 'get-images.php',
root: 'images',
fields: [
'name', 'url',
{name:'size', type: 'float'},
{name:'lastmod', type:'date', dateFormat:'timestamp'}
]
});
store.load();
var tpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap" id="{name}">',
'<div class="thumb"><img src="{url}" title="{name}"></div>',
'<span class="x-editable">{shortName}</span></div>',
'</tpl>',
'<div class="x-clear"></div>'
);
var panel = new Ext.Panel({
id:'images-view',
frame:true,
width:535,
autoHeight:true,
collapsible:true,
layout:'fit',
title:'Simple DataView',
items: new Ext.DataView({
store: store,
tpl: tpl,
autoHeight:true,
multiSelect: true,
overClass:'x-view-over',
itemSelector:'div.thumb-wrap',
emptyText: 'No images to display'
})
});
panel.render(document.body);
</code></pre>
* @constructor 创建一个新的DataView对象。Create a new DataView
* @param {Object} config 配置对象。The config object
*/
Ext.DataView = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {String/Array} tpl 构成这个DataView的HTML片断,或片断的数组,其格式应如{@link Ext.XTemplate}构造器的一样。
* The HTML fragment or an array of fragments that will make up the template used by this DataView. This should
* be specified in the same format expected by the constructor of {@link Ext.XTemplate}.
*/
/**
* @cfg {Ext.data.Store} store 此DataView所绑定的{@link Ext.data.Store}。
* The {@link Ext.data.Store} to bind this DataView to.
*/
/**
* @cfg {String} itemSelector <b>此项是必须的设置</b>。任何符号{@link Ext.DomQuery}格式的CSS选择符(如div.some-class or span:first-child),以确定DataView所使用的节点是哪一种元素。
* This is a required setting</b>. A simple CSS selector (e.g. div.some-class or span:first-child) that will be
* used to determine what nodes this DataView will be working with.
*/
/**
* @cfg {Boolean} multiSelect
* True表示为允许同时可以选取多个对象项,false表示只能同时选择单个对象项或根本没有选区,取决于{@link #singleSelect}的值(默认为false)。
* True to allow selection of more than one item at a time, false to allow selection of only a single item
* at a time or no selection at all, depending on the value of {@link #singleSelect} (defaults to false).
*/
/**
* @cfg {Boolean} singleSelect
* True表示为同一时间只允许选取一个对象项,false表示没有选区也是可以的(默认为false)。
* 注意当{@link #multiSelect} = true时,该项的设置会被忽略。
* True to allow selection of exactly one item at a time, false to allow no selection at all (defaults to false).
* Note that if {@link #multiSelect} = true, this value will be ignored.
*/
/**
* @cfg {Boolean} simpleSelect
* True表示为不需要用户按下Shift或Ctrl键就可以实现多选,false表示用户一定要用户按下Shift或Ctrl键才可以多选对象项(默认为false)。
* True to enable multiselection by clicking on multiple items without requiring the user to hold Shift or Ctrl,
* false to force the user to hold Ctrl or Shift to select more than on item (defaults to false).
*/
/**
* @cfg {String} overClass 视图中每一项mouseover事件触发时所应用到的CSS样式类(默认为undefined)。
* A CSS class to apply to each item in the view on mouseover (defaults to undefined).
*/
/**
* @cfg {String} loadingText 当数据加载进行时显示的字符串(默认为undefined)。
* A string to display during data load operations (defaults to undefined). If specified, this text will be
* displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's
* contents will continue to display normally until the new data is loaded and the contents are replaced.
*/
/**
* @cfg {String} selectedClass 视图中每个选中项所应用到的CSS样式类(默认为'x-view-selected')。
* A CSS class to apply to each selected item in the view (defaults to 'x-view-selected').
*/
selectedClass : "x-view-selected",
/**
* @cfg {String} emptyText
* 没有数据显示时,向用户提示的信息(默认为'')。
* The text to display in the view when there is no data to display (defaults to '').
*/
emptyText : "",
/**
* @cfg {Boolean} deferEmptyText True表示为emptyText推迟到Store首次加载后才生效。
* True to defer emptyText being applied until the store's first load
*/
deferEmptyText: true,
/**
* @cfg {Boolean} trackOver True表示为激活mouseenter与mouseleave事件。
* True to enable mouseenter and mouseleave events
*/
trackOver: false,
//private
last: false,
// private
initComponent : function(){
Ext.DataView.superclass.initComponent.call(this);
if(typeof this.tpl == "string" || Ext.isArray(this.tpl)){
this.tpl = new Ext.XTemplate(this.tpl);
}
this.addEvents(
/**
* @event beforeclick
* 单击执行之前触发,返回 false 则取消默认的动作。
* Fires before a click is processed. Returns false to cancel the default action.
* @param {Ext.DataView} this
* @param {Number} index 目标节点的索引。The index of the target node
* @param {HTMLElement} node 目标节点。The target node
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"beforeclick",
/**
* @event click
* 当模板节点单击时触发事件,如返回 false 则取消默认的动作。
* Fires when a template node is clicked.
* @param {Ext.DataView} this
* @param {Number} index 目标节点的索引。The index of the target node
* @param {HTMLElement} node 目标节点。The target node
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"click",
/**
* @event mouseenter
* 当鼠标进入模板节点上触发。必须设置好trackOver:true或overCls中的一项。
* Fires when the mouse enters a template node. trackOver:true or an overCls must be set to enable this event.
* @param {Ext.DataView} this
* @param {Number} index 目标节点的索引。The index of the target node
* @param {HTMLElement} node 目标节点。The target node
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"mouseenter",
/**
* @event mouseleave
* 当鼠标离开模板节点上触发。必须设置好trackOver:true或overCls中的一项。
* Fires when the mouse leaves a template node. trackOver:true or an overCls must be set to enable this event.
* @param {Ext.DataView} this
* @param {Number} index 目标节点的索引。The index of the target node
* @param {HTMLElement} node 目标节点。The target node
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"mouseleave",
/**
* @event containerclick
* 当点击发生时但又不在模板节点上发生时触发。
* Fires when a click occurs and it is not on a template node.
* @param {Ext.DataView} this
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"containerclick",
/**
* @event dblclick
* 当模板节点双击时触发事件。
* Fires when a template node is double clicked.
* @param {Ext.DataView} this
* @param {Number} index 目标节点的索引。The index of the target node
* @param {HTMLElement} node 目标节点。The target node
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"dblclick",
/**
* @event contextmenu
* 当模板节右击时触发事件。
* Fires when a template node is right clicked.
* @param {Ext.DataView} this
* @param {Number} index 目标节点的索引。The index of the target node
* @param {HTMLElement} node 目标节点。The target node
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"contextmenu",
/**
* @event containercontextmenu
* 在一个非模板节点区域上右键按下时触发。
* Fires when a right click occurs that is not on a template node.
* @param {Ext.DataView} this
* @param {Ext.EventObject} e 原始事件对象。The raw event object
*/
"containercontextmenu",
/**
* @event selectionchange
* 当选取改变时触发。
* Fires when the selected nodes change.
* @param {Ext.DataView} this
* @param {Array} selections 已选取节点所组成的数组。Array of the selected nodes
*/
"selectionchange",
/**
* @event beforeselect
* 选取生成之前触发,如返回false,则选区不会生成。
* Fires before a selection is made. If any handlers return false, the selection is cancelled.
* @param {Ext.DataView} this
* @param {HTMLElement} node 要选取的节点。The node to be selected
* @param {Array} selections 当前已选取节点所组成的数组。Array of currently selected nodes
*/
"beforeselect"
);
this.all = new Ext.CompositeElementLite();
this.selected = new Ext.CompositeElementLite();
},
// private
afterRender : function(){
Ext.DataView.superclass.afterRender.call(this);
this.mon(this.getTemplateTarget(), {
"click": this.onClick,
"dblclick": this.onDblClick,
"contextmenu": this.onContextMenu,
scope:this
});
if(this.overClass || this.trackOver){
this.mon(this.getTemplateTarget(), {
"mouseover": this.onMouseOver,
"mouseout": this.onMouseOut,
scope:this
});
}
if(this.store){
this.setStore(this.store, true);
}
},
/**
* 刷新视图。重新加载store的数据并重新渲染模板。
* Refreshes the view by reloading the data from the store and re-rendering the template.
*/
refresh : function(){
this.clearSelections(false, true);
var el = this.getTemplateTarget();
el.update("");
var records = this.store.getRange();
if(records.length < 1){
if(!this.deferEmptyText || this.hasSkippedEmptyText){
el.update(this.emptyText);
}
this.all.clear();
}else{
this.tpl.overwrite(el, this.collectData(records, 0));
this.all.fill(Ext.query(this.itemSelector, el.dom));
this.updateIndexes(0);
}
this.hasSkippedEmptyText = true;
},
getTemplateTarget: function(){
return this.el;
},
/**
* 重写该函数,可对每个节点的数据进行格式化,再交给DataView的{@link #tpl template}模板进一步处理。
* Function which can be overridden to provide custom formatting for each Record that is used by this
* DataView's {@link #tpl template} to render each node.
* @param {Array/Object} data 原始数据,是Data Model所绑定的视图的colData数组,或Updater数据对象绑定的JSON对象。
* The raw data object that was used to create the Record.
* @param {Number} recordIndex 将要参与进行渲染Record对象的索引,是数字。the index number of the Record being prepared for rendering.
* @param {Record} record 将要参与进行渲染Record对象。The Record being prepared for rendering.
* @return {Array/Object} 已格式化的数据,供{@link #tpl template}的overwrite()方法内置使用。既可以是数字式标记的数组(如{0})或是一个对象(如{foo: 'bar'})。
* The formatted data in a format expected by the internal {@link #tpl template}'s overwrite() method.
* (either an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}))
*/
prepareData : function(data){
return data;
},
/**
* <p>
* 返回数据对象的函数,配合DataView的{@link #tpl template}来渲染整个DataView。你也可以重写这个函数。
* Function which can be overridden which returns the data object passed to this
* DataView's {@link #tpl template} to render the whole DataView.</p>
* <p>
* 这应该是由数据对象所组成的数组,
* 所谓数据对象,就是利用这些数据,让其送入{@link Ext.XTemplate XTemplate}模板中迭代,
* 解析其中的<tt>'<tpl for=".">'</tt>产生HTML片断。其中,可加入<i>named</i>的属性以表示不重复的数据,例如头部、总数等的地方。
* This is usually an Array of data objects, each element of which is processed by an
* {@link Ext.XTemplate XTemplate} which uses <tt>'<tpl for=".">'</tt> to iterate over its supplied
* data object as an Array. However, <i>named</i> properties may be placed into the data object to
* provide non-repeating data such as headings, totals etc.</p>
* @param {Array} records 渲染到DataView的{@link Ext.data.Record}数组。An Array of {@link Ext.data.Record}s to be rendered into the DataView.
* @return {Array} 数据对象数组,将由XTemplate循化处理。也可以携带<i>named</i>的属性。An Array of data objects to be processed by a repeating XTemplate. May also
* contain <i>named</i> properties.
*/
collectData : function(records, startIndex){
var r = [];
for(var i = 0, len = records.length; i < len; i++){
r[r.length] = this.prepareData(records[i].data, startIndex+i, records[i]);
}
return r;
},
// private
bufferRender : function(records){
var div = document.createElement('div');
this.tpl.overwrite(div, this.collectData(records));
return Ext.query(this.itemSelector, div);
},
// private
onUpdate : function(ds, record){
var index = this.store.indexOf(record);
var sel = this.isSelected(index);
var original = this.all.elements[index];
var node = this.bufferRender([record], index)[0];
this.all.replaceElement(index, node, true);
if(sel){
this.selected.replaceElement(original, node);
this.all.item(index).addClass(this.selectedClass);
}
this.updateIndexes(index, index);
},
// private
onAdd : function(ds, records, index){
if(this.all.getCount() == 0){
this.refresh();
return;
}
var nodes = this.bufferRender(records, index), n, a = this.all.elements;
if(index < this.all.getCount()){
n = this.all.item(index).insertSibling(nodes, 'before', true);
a.splice.apply(a, [index, 0].concat(nodes));
}else{
n = this.all.last().insertSibling(nodes, 'after', true);
a.push.apply(a, nodes);
}
this.updateIndexes(index);
},
// private
onRemove : function(ds, record, index){
this.deselect(index);
this.all.removeElement(index, true);
this.updateIndexes(index);
if (this.store.getCount() == 0){
this.refresh();
}
},
/**
* 刷新store里面各个节点的数据。
* Refreshes an individual node's data from the store.
* @param {Number} index store里面的数据索引。The item's data index in the store
*/
refreshNode : function(index){
this.onUpdate(this.store, this.store.getAt(index));
},
// private
updateIndexes : function(startIndex, endIndex){
var ns = this.all.elements;
startIndex = startIndex || 0;
endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1));
for(var i = startIndex; i <= endIndex; i++){
ns[i].viewIndex = i;
}
},
/**
* 刷新不同的节点的数据(来自store)。
* Returns the store associated with this DataView.
* @return {Ext.data.Store} store中的数据的索引。
*/
getStore : function(){
return this.store;
},
/**
* 改变在使用的Data Store并刷新view。
* Changes the data store bound to this view and refreshes it.
* @param {Store} store 绑定这个view的store对象。The store to bind to this view
*/
setStore : function(store, initial){
if(!initial && this.store){
this.store.un("beforeload", this.onBeforeLoad, this);
this.store.un("datachanged", this.refresh, this);
this.store.un("add", this.onAdd, this);
this.store.un("remove", this.onRemove, this);
this.store.un("update", this.onUpdate, this);
this.store.un("clear", this.refresh, this);
}
if(store){
store = Ext.StoreMgr.lookup(store);
store.on("beforeload", this.onBeforeLoad, this);
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则代表它不属于模板的任何一个节点。
* Returns the template node the passed child belongs to, or null if it doesn't belong to one.
* @param {HTMLElement} node
* @return {HTMLElement} 模板节点。The template node
*/
findItemFromChild : function(node){
return Ext.fly(node).findParent(this.itemSelector, this.getTemplateTarget());
},
// private
onClick : function(e){
var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
if(item){
var index = this.indexOf(item);
if(this.onItemClick(item, index, e) !== false){
this.fireEvent("click", this, index, item, e);
}
}else{
if(this.fireEvent("containerclick", this, e) !== false){
this.onContainerClick(e);
}
}
},
onContainerClick : function(e){
this.clearSelections();
},
// private
onContextMenu : function(e){
var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
if(item){
this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
}else{
this.fireEvent("containercontextmenu", this, e)
}
},
// private
onDblClick : function(e){
var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
if(item){
this.fireEvent("dblclick", this, this.indexOf(item), item, e);
}
},
// private
onMouseOver : function(e){
var item = e.getTarget(this.itemSelector, this.getTemplateTarget());
if(item && item !== this.lastItem){
this.lastItem = item;
Ext.fly(item).addClass(this.overClass);
this.fireEvent("mouseenter", this, this.indexOf(item), item, e);
}
},
// private
onMouseOut : function(e){
if(this.lastItem){
if(!e.within(this.lastItem, true, true)){
Ext.fly(this.lastItem).removeClass(this.overClass);
this.fireEvent("mouseleave", this, this.indexOf(this.lastItem), this.lastItem, e);
delete this.lastItem;
}
}
},
// private
onItemClick : function(item, index, e){
if(this.fireEvent("beforeclick", this, index, item, e) === false){
return false;
}
if(this.multiSelect){
this.doMultiSelection(item, index, e);
e.preventDefault();
}else if(this.singleSelect){
this.doSingleSelection(item, index, e);
e.preventDefault();
}
return true;
},
// private
doSingleSelection : function(item, index, e){
if(e.ctrlKey && this.isSelected(index)){
this.deselect(index);
}else{
this.select(index, false);
}
},
// private
doMultiSelection : function(item, index, e){
if(e.shiftKey && this.last !== false){
var last = this.last;
this.selectRange(last, index, e.ctrlKey);
this.last = last; // reset the last
}else{
if((e.ctrlKey||this.simpleSelect) && this.isSelected(index)){
this.deselect(index);
}else{
this.select(index, e.ctrlKey || e.shiftKey || this.simpleSelect);
}
}
},
/**
* 返回选中节点的数量。
* Gets the number of selected nodes.
* @return {Number} 节点数量。The node count
*/
getSelectionCount : function(){
return this.selected.getCount()
},
/**
* 返回当前选中的节点。
* Gets the currently selected nodes.
* @return {Array} 数组。An array of HTMLElements
*/
getSelectedNodes : function(){
return this.selected.elements;
},
/**
* 返回选中的节点的索引。
* Gets the indexes of the selected nodes.
* @return {Array} 数字索引的数组。An array of numeric indexes
*/
getSelectedIndexes : function(){
var indexes = [], s = this.selected.elements;
for(var i = 0, len = s.length; i < len; i++){
indexes.push(s[i].viewIndex);
}
return indexes;
},
/**
* 返回所选记录组成的数组。
* Gets an array of the selected records
* @return {Array} {@link Ext.data.Record}对象数组。An array of {@link Ext.data.Record} objects
*/
getSelectedRecords : function(){
var r = [], s = this.selected.elements;
for(var i = 0, len = s.length; i < len; i++){
r[r.length] = this.store.getAt(s[i].viewIndex);
}
return r;
},
/**
* 从一个节点数组中返回记录节点。
* Gets an array of the records from an array of nodes
* @param {Array} nodes 参与运算的节点。The nodes to evaluate
* @return {Array} {@link Ext.data.Record}记录对象的数组。The {@link Ext.data.Record} objects
*/
getRecords : function(nodes){
var r = [], s = nodes;
for(var i = 0, len = s.length; i < len; i++){
r[r.length] = this.store.getAt(s[i].viewIndex);
}
return r;
},
/**
* 返回节点的记录。
* Gets a record from a node
* @param {HTMLElement} node 涉及的节点。The node to evaluate
* @return {Record} {@link Ext.data.Record}记录对象的数组。The {@link Ext.data.Record} object
*/
getRecord : function(node){
return this.store.getAt(node.viewIndex);
},
/**
* 清除所有选区。
* Clears all selections.
* @param {Boolean} suppressEvent (可选的)True跃过触发selectionchange的事件。(optional)True to skip firing of the selectionchange event
*/
clearSelections : function(suppressEvent, skipUpdate){
if((this.multiSelect || this.singleSelect) && this.selected.getCount() > 0){
if(!skipUpdate){
this.selected.removeClass(this.selectedClass);
}
this.selected.clear();
this.last = false;
if(!suppressEvent){
this.fireEvent("selectionchange", this, this.selected.elements);
}
}
},
/**
* 传入一个节点的参数,如果是属于已选取的话便返回true否则返回false。
* Returns true if the passed node is selected, else false.
* @param {HTMLElement/Number} node 节点或节点索引。The node or node index to check
* @return {Boolean} true表示选中否则返回false。True if selected, else false
*/
isSelected : function(node){
return this.selected.contains(this.getNode(node));
},
/**
* 反选节点
* Deselects a node。
* @param {HTMLElement/Number} node 反选的节点。The node to deselect
*/
deselect : function(node){
if(this.isSelected(node)){
node = this.getNode(node);
this.selected.removeElement(node);
if(this.last == node.viewIndex){
this.last = false;
}
Ext.fly(node).removeClass(this.selectedClass);
this.fireEvent("selectionchange", this, this.selected.elements);
}
},
/**
* 选取节点。
* Selects a set of nodes.
* @param {Array/HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID。
* An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
* @param {Boolean} keepExisting (可选项)true代表保留当前选区 (optional)true to keep existing selections
* @param {Boolean} suppressEvent (可选项)true表示为跳过所有selectionchange事件。(optional)true to skip firing of the selectionchange vent
*/
select : function(nodeInfo, keepExisting, suppressEvent){
if(Ext.isArray(nodeInfo)){
if(!keepExisting){
this.clearSelections(true);
}
for(var i = 0, len = nodeInfo.length; i < len; i++){
this.select(nodeInfo[i], true, true);
}
if(!suppressEvent){
this.fireEvent("selectionchange", this, this.selected.elements);
}
} else{
var node = this.getNode(nodeInfo);
if(!keepExisting){
this.clearSelections(true);
}
if(node && !this.isSelected(node)){
if(this.fireEvent("beforeselect", this, node, this.selected.elements) !== false){
Ext.fly(node).addClass(this.selectedClass);
this.selected.add(node);
this.last = node.viewIndex;
if(!suppressEvent){
this.fireEvent("selectionchange", this, this.selected.elements);
}
}
}
}
},
/**
* 选取某段范围的节点。在start与end之间范围内的节点都会被选取。
* Selects a range of nodes. All nodes between start and end are selected.
* @param {Number} start 索引头,在范围中第一个节点的索引。The index of the first node in the range
* @param {Number} end 索引尾,在范围中最后一个节点的索引。The index of the last node in the range
* @param {Boolean} keepExisting (可选项)true代表保留当前选区。(optional) True to retain existing selections
*/
selectRange : function(start, end, keepExisting){
if(!keepExisting){
this.clearSelections(true);
}
this.select(this.getNodes(start, end), true);
},
/**
* 获取多个模板节点。
* Gets a template node.
* @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID。
* An HTMLElement template node, index of a template node or the id of a template node
* @return {HTMLElement} 若找不到返回null。The node or null if it wasn't found
*/
getNode : function(nodeInfo){
if(typeof nodeInfo == "string"){
return document.getElementById(nodeInfo);
}else if(typeof nodeInfo == "number"){
return this.all.elements[nodeInfo];
}
return nodeInfo;
},
/**
* 获取某个范围的模板节点。
* Gets a range nodes.
* @param {Number} start (可选的)索引头,在范围中第一个节点的索引。(optional) The index of the first node in the range
* @param {Number} end (可选的)索引尾,在范围中最后一个节点的索引。 (optional) The index of the last node in the range
* @return {Array} 节点数组。An array of nodes
*/
getNodes : function(start, end){
var ns = this.all.elements;
start = start || 0;
end = typeof end == "undefined" ? Math.max(ns.length - 1, 0) : end;
var nodes = [], i;
if(start <= end){
for(i = start; i <= end && ns[i]; i++){
nodes.push(ns[i]);
}
} else{
for(i = start; i >= end && ns[i]; i--){
nodes.push(ns[i]);
}
}
return nodes;
},
/**
* 传入一个node作为参数,找到它的索引。
* Finds the index of the passed node.
* @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID。
* An HTMLElement template node, index of a template node or the id of a template node
* @return {Number} 节点索引或-1。The index of the node or -1
*/
indexOf : function(node){
node = this.getNode(node);
if(typeof node.viewIndex == "number"){
return node.viewIndex;
}
return this.all.indexOf(node);
},
// private
onBeforeLoad : function(){
if(this.loadingText){
this.clearSelections(false, true);
this.getTemplateTarget().update('<div class="loading-indicator">'+this.loadingText+'</div>');
this.all.clear();
}
},
onDestroy : function(){
Ext.DataView.superclass.onDestroy.call(this);
this.setStore(null);
}
});
Ext.reg('dataview', Ext.DataView); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Shadow
* 为所有元素提供投影效果的一个简易类。注意元素必须为绝对定位,而且投影并没有填充的效果(shimming)。
* 这只是适用简单的场合——如想提供更高阶的投影效果,请参阅{@link Ext.Layer}类。<br />
* Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned,
* and the shadow does not provide any shimming. This should be used only in simple cases -- for more advanced
* functionality that can also provide the same shadow effect, see the {@link Ext.Layer} class.
* @constructor
* Create a new Shadow
* @param {Object} config 配置项对象 The config object
*/
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 投影显示的模式。有下列选项:The shadow display mode. Supports the following options:<br />
* sides: 投影限显示在两边和底部。Shadow displays on both sides and bottom only<br />
* frame: 投影在四边均匀出现。Shadow displays equally on all four sides<br />
* drop: 传统的物理效果的,底部和右边(这是默认值)。Traditional bottom-right drop shadow (default)
*/
/**
* @cfg {String} offset 元素和投影之间的偏移象素值(默认为4)。
* The number of pixels to offset the shadow from the element (defaults to 4)
*/
offset: 4,
// private
defaultMode: "drop",
/**
* 在目标元素上显示投影。
* Displays the shadow under the target element
* @param {Mixed} targetEl 指定要显示投影的那个元素。The id or element under which the shadow should display
*/
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";
},
/**
* 返回投影是否在显示。
* Returns true if the shadow is visible, else false
*/
isVisible : function(){
return this.el ? true : false;
},
/**
* 当值可用时直接对称位置。
* Show方法必须至少在调用realign方法之前调用一次,以保证能够初始化。
* Direct alignment when values are already available. Show must be called at least once before
* calling this method to ensure it is initialized.
* @param {Number} left 目标元素left位置。The target element left position
* @param {Number} top 目标元素top位置。The target element top position
* @param {Number} width 目标元素宽度。The target element width
* @param {Number} height 目标元素高度。The target element 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";
}
}
},
/**
* 隐藏投影。
* Hides this shadow
*/
hide : function(){
if(this.el){
this.el.dom.style.display = "none";
Ext.Shadow.Pool.push(this.el);
delete this.el;
}
},
/**
* 调整该投影的z-index。
* Adjust the z-index of this shadow
* @param {Number} zindex 新z-index。The new 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://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.PagingToolbar
* @extends Ext.Toolbar
* <p>一个要和{@link Ext.data.Store}参与绑定并且自动提供翻页控制的工具栏。
* A specialized toolbar that is bound to a {@link Ext.data.Store} and provides automatic paging control. This
* Component {@link Ext.data.Store#load load}s blocks of data into the Store passing parameters who's names are
* specified by the store's {@link Ext.data.Store#paramNames paramNames} property.</p>
* @constructor 创建一个新的翻页工具栏。Create a new PagingToolbar
* @param {Object} config 配置对象。The config object
*/
(function() {
var T = Ext.Toolbar;
Ext.PagingToolbar = Ext.extend(Ext.Toolbar, {
/**
* @cfg {Ext.data.Store} store 翻页工具栏应该使用{@link Ext.data.Store}作为它的数据源(在需要的时候)。
* The {@link Ext.data.Store} the paging toolbar should use as its data source (required).
*/
/**
* @cfg {Boolean} displayInfo 为true时展示展现信息(默认为false)。
* True to display the displayMsg (defaults to false)
*/
/**
* @cfg {Number} pageSize 每页要展现的记录数(默认为 20)。
* The number of records to display per page (defaults to 20)
*/
/**
* @cfg {Boolean} prependButtons True表示为在分页按钮<i>之前</i>随便插入可配置的条目。默认为false。
* True to insert any configured items <i>before</i> the paging buttons. Defaults to false.
*/
pageSize: 20,
/**
* @cfg {String} displayMsg
* 用来显示翻页的情况信息 (默认为"Displaying {0} - {1} of {2}").
* 注意这个字符串里大括号中的数字是一种标记,其中的数字分别代表起始值,结束值和总数.当重写这个字符串的时候如果这些值是要显示的,那么这些标识应该被保留下来
* The paging status message to display (defaults to "Displaying {0} - {1} of {2}"). Note that this string is
* formatted using the braced numbers 0-2 as tokens that are replaced by the values for start, end and total
* respectively. These tokens should be preserved when overriding this string if showing those values is desired.
*/
displayMsg : 'Displaying {0} - {1} of {2}',
/**
* @cfg {String} emptyMsg 没有数据记录的时候所展示的信息(默认为"No data to display")。
* The message to display when no records are found (defaults to "No data to display")
*/
emptyMsg : 'No data to display',
/**
* 可定制的默认翻页文本(默认为 to "Page")。
* Customizable piece of the default paging text (defaults to "Page")
* @type String
*/
beforePageText : "Page",
/**
* 可定制的默认翻页文本(默认为"of %0")。注意该字符串中{0}作为一种表识会被替换为真实的总页数。如要宣示总页数,那么在重写该值的时候也要写出这个{0}。
* Customizable piece of the default paging text (defaults to "of {0}"). Note that this string is
* formatted using {0} as a token that is replaced by the number of total pages. This token should be
* preserved when overriding this string if showing the total page count is desired.
* @type String
*/
afterPageText : "of {0}",
/**
* 可定制的默认翻页文本(默认为 "First Page")。
* Customizable piece of the default paging text (defaults to "First Page")
* @type String
*/
firstText : "First Page",
/**
* 可定制的默认翻页文本(defaults to "Previous Page")。
* Customizable piece of the default paging text (defaults to "Previous Page")
* @type String
*/
prevText : "Previous Page",
/**
* 可定制的默认翻页文本(defaults to "Next Page")。
* Customizable piece of the default paging text (defaults to "Next Page")
* @type String
*/
nextText : "Next Page",
/**
* 可定制的默认翻页文本(defaults to "Last Page")。
* Customizable piece of the default paging text (defaults to "Last Page")
* @type String
*/
lastText : "Last Page",
/**
* 可定制的默认翻页文本 (defaults to "Refresh")。
* Customizable piece of the default paging text (defaults to "Refresh")
* @type String
*/
refreshText : "Refresh",
/**
* 加载调用时的参数名对象映射(默认为 {start: 'start', limit: 'limit'})。
* Object mapping of parameter names for load calls (defaults to {start: 'start', limit: 'limit'})
*/
paramNames : {start: 'start', limit: 'limit'},
// private
constructor: function(config) {
var pagingItems = [this.first = new T.Button({
tooltip: this.firstText,
iconCls: "x-tbar-page-first",
disabled: true,
handler: this.onClick,
scope: this
}), this.prev = new T.Button({
tooltip: this.prevText,
iconCls: "x-tbar-page-prev",
disabled: true,
handler: this.onClick,
scope: this
}), '-', this.beforePageText,
this.inputItem = new T.Item({
height: 18,
autoEl: {
tag: "input",
type: "text",
size: "3",
value: "1",
cls: "x-tbar-page-number"
}
}), this.afterTextItem = new T.TextItem({
text: String.format(this.afterPageText, 1)
}), '-', this.next = new T.Button({
tooltip: this.nextText,
iconCls: "x-tbar-page-next",
disabled: true,
handler: this.onClick,
scope: this
}), this.last = new T.Button({
tooltip: this.lastText,
iconCls: "x-tbar-page-last",
disabled: true,
handler: this.onClick,
scope: this
}), '-', this.refresh = new T.Button({
tooltip: this.refreshText,
iconCls: "x-tbar-loading",
handler: this.onClick,
scope: this
})];
var userItems = config.items || config.buttons || [];
if (config.prependButtons) {
config.items = userItems.concat(pagingItems);
}else{
config.items = pagingItems.concat(userItems);
}
delete config.buttons;
if(config.displayInfo){
config.items.push('->');
config.items.push(this.displayItem = new T.TextItem({}));
}
Ext.PagingToolbar.superclass.constructor.apply(this, arguments);
this.addEvents(
/**
* @event change
* 当页数改变后触发。
* Fires after the active page has been changed.
* @param {Ext.PagingToolbar} this
* @param {Object} changeEvent 携带以下属性的对象:An object that has these properties:<ul>
* <li><code>total</code> : Number <div class="sub-desc">记录的总数,该值由服务端的真实数据集所返回。The total number of records in the dataset as
* returned by the server</div></li>
* <li><code>activePage</code> : Number <div class="sub-desc">当前页码 The current page number</div></li>
* <li><code>pages</code> : Number <div class="sub-desc">总页数,该值是服务端数据集的真实总数,并设置到{@link #pageSize}。The total number of pages (calculated from
* the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
* </ul>
*/
'change',
/**
* @event beforechange
* 当页数改变之前就触发。返回false就取消页数的变换。
* Fires just before the active page is changed.
* Return false to prevent the active page from being changed.
* @param {Ext.PagingToolbar} this
* @param {Object} beforeChangeEvent 携带以下属性的对象:An object that has these properties:<ul>
* <li><code>start</code> : Number <div class="sub-desc">下一页将是从第几行的数据读起。The starting row number for the next page of records to
* be retrieved from the server</div></li>
* <li><code>limit</code> : Number <div class="sub-desc">从服务端取得的记录的笔数。The number of records to be retrieved from the server</div></li>
* </ul>
* (注意:属性<b>start</b>以及<b>limit</b>的名称均由store的{@link Ext.data.Store#paramNames paramNames}属性所决定。)
* (note: the names of the <b>start</b> and <b>limit</b> properties are determined
* by the store's {@link Ext.data.Store#paramNames paramNames} property.)
*/
'beforechange'
);
this.cursor = 0;
this.bind(this.store);
},
initComponent: function(){
Ext.PagingToolbar.superclass.initComponent.call(this);
this.on('afterlayout', this.onFirstLayout, this, {single: true});
},
// private
onFirstLayout: function(ii) {
this.mon(this.inputItem.el, "keydown", this.onPagingKeyDown, this);
this.mon(this.inputItem.el, "blur", this.onPagingBlur, this);
this.mon(this.inputItem.el, "focus", this.onPagingFocus, this);
this.field = this.inputItem.el.dom;
if(this.dsLoaded){
this.onLoad.apply(this, this.dsLoaded);
}
},
// private
updateInfo : function(){
if(this.displayItem){
var count = this.store.getCount();
var msg = count == 0 ?
this.emptyMsg :
String.format(
this.displayMsg,
this.cursor+1, this.cursor+count, this.store.getTotalCount()
);
this.displayItem.setText(msg);
}
},
// private
onLoad : function(store, r, o){
if(!this.rendered){
this.dsLoaded = [store, r, o];
return;
}
this.cursor = (o.params && o.params[this.paramNames.start]) ? o.params[this.paramNames.start] : 0;
var d = this.getPageData(), ap = d.activePage, ps = d.pages;
this.afterTextItem.setText(String.format(this.afterPageText, d.pages));
this.field.value = ap;
this.first.setDisabled(ap == 1);
this.prev.setDisabled(ap == 1);
this.next.setDisabled(ap == ps);
this.last.setDisabled(ap == ps);
this.refresh.enable();
this.updateInfo();
this.fireEvent('change', this, d);
},
// private
getPageData : function(){
var total = this.store.getTotalCount();
return {
total : total,
activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
};
},
/**
* 改变活动的页码。
* Change the active page
* @param {Integer} page 要显示的页码。The page to display
*/
changePage: function(page){
this.doLoad(((page-1) * this.pageSize).constrain(0, this.store.getTotalCount()));
},
// private
onLoadError : function(){
if(!this.rendered){
return;
}
this.refresh.enable();
},
// private
readPage : function(d){
var v = this.field.value, pageNum;
if (!v || isNaN(pageNum = parseInt(v, 10))) {
this.field.value = d.activePage;
return false;
}
return pageNum;
},
onPagingFocus: function(){
this.field.select();
},
//private
onPagingBlur: function(e){
this.field.value = this.getPageData().activePage;
},
// private
onPagingKeyDown : function(e){
var k = e.getKey(), d = this.getPageData(), pageNum;
if (k == e.RETURN) {
e.stopEvent();
pageNum = this.readPage(d);
if(pageNum !== false){
pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
this.doLoad(pageNum * this.pageSize);
}
}else if (k == e.HOME || k == e.END){
e.stopEvent();
pageNum = k == e.HOME ? 1 : d.pages;
this.field.value = pageNum;
}else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){
e.stopEvent();
if(pageNum = this.readPage(d)){
var increment = e.shiftKey ? 10 : 1;
if(k == e.DOWN || k == e.PAGEDOWN){
increment *= -1;
}
pageNum += increment;
if(pageNum >= 1 & pageNum <= d.pages){
this.field.value = pageNum;
}
}
}
},
// private
beforeLoad : function(){
if(this.rendered && this.refresh){
this.refresh.disable();
}
},
// private
doLoad : function(start){
var o = {}, pn = this.paramNames;
o[pn.start] = start;
o[pn.limit] = this.pageSize;
if(this.fireEvent('beforechange', this, o) !== false){
this.store.load({params:o});
}
},
// private
onClick : function(button){
var store = this.store;
switch(button){
case this.first:
this.doLoad(0);
break;
case this.prev:
this.doLoad(Math.max(0, this.cursor-this.pageSize));
break;
case this.next:
this.doLoad(this.cursor+this.pageSize);
break;
case this.last:
var total = store.getTotalCount();
var extra = total % this.pageSize;
var lastStart = extra ? (total - extra) : total-this.pageSize;
this.doLoad(lastStart);
break;
case this.refresh:
this.doLoad(this.cursor);
break;
}
},
/**
* 从指定的{@link Ext.data.Store}数据源解除翻页工具栏绑定。
* Unbinds the paging toolbar from the specified {@link Ext.data.Store}
* @param {Ext.data.Store} store 要解除绑定的数据源。The data store to unbind
*/
unbind : function(store){
store = Ext.StoreMgr.lookup(store);
store.un("beforeload", this.beforeLoad, this);
store.un("load", this.onLoad, this);
store.un("loadexception", this.onLoadError, this);
this.store = undefined;
},
/**
* 在数据源{@link Ext.data.Store}上绑定指定翻页工具栏。
* Binds the paging toolbar to the specified {@link Ext.data.Store}
* @param {Ext.data.Store} store 要绑定的数据源。The data store to bind
*/
bind : function(store){
store = Ext.StoreMgr.lookup(store);
store.on("beforeload", this.beforeLoad, this);
store.on("load", this.onLoad, this);
store.on("loadexception", this.onLoadError, this);
this.store = store;
this.paramNames.start = store.paramNames.start;
this.paramNames.limit = store.paramNames.limit;
if (store.getCount() > 0){
this.onLoad(store, null, {});
}
},
// private
onDestroy : function(){
if(this.store){
this.unbind(this.store);
}
Ext.PagingToolbar.superclass.onDestroy.call(this);
}
});
})();
Ext.reg('paging', Ext.PagingToolbar); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* // Internal developer documentation -- will not show up in API docs
* @class Ext.dd.PanelProxy
* 为{@link Ext.Panel}对象定制的拖拽代理的实现。该主要被Panel对象在内部调用以实现拖拽,因此不需要直接创建。
* A custom drag proxy implementation specific to {@link Ext.Panel}s. This class is primarily used internally
* for the Panel's drag drop implementation, and should never need to be created directly.
* @constructor
* @param {Ext.Panel} panel 要代理的{@link Ext.Panel}对象。The {@link Ext.Panel} to proxy for
* @param {Object} config 配置选项对象。Configuration options
*/
Ext.dd.PanelProxy = function(panel, config){
this.panel = panel;
this.id = this.panel.id +'-ddproxy';
Ext.apply(this, config);
};
Ext.dd.PanelProxy.prototype = {
/**
* @cfg {Boolean} insertProxy 如果值为 true 则在拖拽Panel时插入一个代理占位元素,值为 false 则在拖拽时没有代理(默认为 true)。
* True to insert a placeholder proxy element while dragging the panel,
* false to drag with no proxy (defaults to true).
*/
insertProxy : true,
// private overrides
setStatus : Ext.emptyFn,
reset : Ext.emptyFn,
update : Ext.emptyFn,
stop : Ext.emptyFn,
sync: Ext.emptyFn,
/**
* 获取代理元素。
* Gets the proxy's element
* @return {Element} 代理元素。The proxy's element
*/
getEl : function(){
return this.ghost;
},
/**
* 获取代理的影子元素。
* Gets the proxy's ghost element
* @return {Element} 代理的影子元素。The proxy's ghost element
*/
getGhost : function(){
return this.ghost;
},
/**
* 获取代理元素。
* Gets the proxy's element
* @return {Element} 代理元素。The proxy's element
*/
getProxy : function(){
return this.proxy;
},
/**
* 隐藏代理。
* Hides the proxy
*/
hide : function(){
if(this.ghost){
if(this.proxy){
this.proxy.remove();
delete this.proxy;
}
this.panel.el.dom.style.display = '';
this.ghost.remove();
delete this.ghost;
}
},
/**
* 显示代理。
* Shows the proxy
*/
show : function(){
if(!this.ghost){
this.ghost = this.panel.createGhost(undefined, undefined, Ext.getBody());
this.ghost.setXY(this.panel.el.getXY())
if(this.insertProxy){
this.proxy = this.panel.el.insertSibling({cls:'x-panel-dd-spacer'});
this.proxy.setSize(this.panel.getSize());
}
this.panel.el.dom.style.display = 'none';
}
},
// private
repair : function(xy, callback, scope){
this.hide();
if(typeof callback == "function"){
callback.call(scope || this);
}
},
/**
* 将代理元素移动到 DOM 中不同的位置。通常该方法被用来当拖拽Panel对象时保持两者位置的同步。
* Moves the proxy to a different position in the DOM. This is typically called while dragging the Panel
* to keep the proxy sync'd to the Panel's location.
* @param {HTMLElement} parentNode 代理元素的父级DOM节点。The proxy's parent DOM node
* @param {HTMLElement} before (可选的)代理被插入的位置的前一个侧边节点(如果不指定则默认为父节点的最后一个子节点) (optional)The sibling node before which the proxy should be inserted (defaults
* to the parent's last child if not specified)
*/
moveProxy : function(parentNode, before){
if(this.proxy){
parentNode.insertBefore(this.proxy.dom, before);
}
}
};
// private - DD implementation for Panels
Ext.Panel.DD = function(panel, cfg){
this.panel = panel;
this.dragData = {panel: panel};
this.proxy = new Ext.dd.PanelProxy(panel, cfg);
Ext.Panel.DD.superclass.constructor.call(this, panel.el, cfg);
var h = panel.header;
if(h){
this.setHandleElId(h.id);
}
(h ? h : this.panel.body).setStyle('cursor', 'move');
this.scroll = false;
};
Ext.extend(Ext.Panel.DD, Ext.dd.DragSource, {
showFrame: Ext.emptyFn,
startDrag: Ext.emptyFn,
b4StartDrag: function(x, y) {
this.proxy.show();
},
b4MouseDown: function(e) {
var x = e.getPageX();
var y = e.getPageY();
this.autoOffset(x, y);
},
onInitDrag : function(x, y){
this.onStartDrag(x, y);
return true;
},
createFrame : Ext.emptyFn,
getDragEl : function(e){
return this.proxy.ghost.dom;
},
endDrag : function(e){
this.proxy.hide();
this.panel.saveState();
},
autoOffset : function(x, y) {
x -= this.startPageX;
y -= this.startPageY;
this.setDelta(x, y);
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.SplitButton
* @extends Ext.Button
* 一个提供了内建下拉箭头的分割按钮,该箭头还可以触发按钮默认的click 之外的事件。
* 典型的应用场景是,用来显示一个为主按钮提供附加选项的下拉菜单,并且可以为arrowclick事件设置单独一个的处理函数。<br />
* A split button that provides a built-in dropdown arrow that can fire an event separately from the default
* click event of the button. Typically this would be used to display a dropdown menu that provides additional
* options to the primary button action, but any custom handler can provide the arrowclick implementation. Example usage:
* <pre><code>
//显示一个下拉菜单 display a dropdown menu:
new Ext.SplitButton({
renderTo: 'button-ct', // 容器的id the container id
text: 'Options',
handler: optionsHandler, // 按钮本身被按下时触发的事件 handle a click on the button itself
menu: new Ext.menu.Menu({
items: [
// 当箭头被按下时就出现下面这些下拉菜单。these items will render as dropdown menu items when the arrow is clicked:
{text: 'Item 1', handler: item1Handler},
{text: 'Item 2', handler: item2Handler}
]
})
});
// 除了显示菜单以外,你还可以让下拉箭头发挥更多的功能,——在点击那刹那。
// Instead of showing a menu, you provide any type of custom
// functionality you want when the dropdown arrow is clicked:
new Ext.SplitButton({
renderTo: 'button-ct',
text: 'Options',
handler: optionsHandler,
arrowHandler: myCustomHandler
});
</code></pre>
* @cfg {Function} arrowHandler 点击箭头时调用的函数(可以用来代替click事件)。A function called when the arrow button is clicked (can be used instead of click event)
* @cfg {String} arrowTooltip 箭头的title属性。The title attribute of the arrow
* @constructor 创建一个菜单按钮。Create a new menu button
* @param {Object} config 配置选项对象。The config object
*/
Ext.SplitButton = Ext.extend(Ext.Button, {
// private
arrowSelector : 'em',
split: true,
// private
initComponent : function(){
Ext.SplitButton.superclass.initComponent.call(this);
/**
* @event arrowclick
* 当点击按钮的箭头时触发。
* Fires when this button's arrow is clicked
* @param {MenuButton} this
* @param {EventObject} e 事件对象。The click event
*/
this.addEvents("arrowclick");
},
// private
onRender : function(){
Ext.SplitButton.superclass.onRender.apply(this, arguments);
if(this.arrowTooltip){
btn.child(this.arrowSelector).dom[this.tooltipType] = this.arrowTooltip;
}
},
/**
* 设置按钮的箭头点击处理函数。
* Sets this button's arrow click handler.
* @param {Function} handler 点击箭头时调用的函数。The function to call when the arrow is clicked
* @param {Object} scope (可选的)处理函数的作用域。(optional) Scope for the function passed above
*/
setArrowHandler : function(handler, scope){
this.arrowHandler = handler;
this.scope = scope;
},
getMenuClass : function(){
return this.menu && this.arrowAlign != 'bottom' ? 'x-btn-split' : 'x-btn-split-bottom';
},
isClickOnArrow : function(e){
return this.arrowAlign != 'bottom' ?
e.getPageX() > this.el.child(this.buttonSelector).getRegion().right :
e.getPageY() > this.el.child(this.buttonSelector).getRegion().bottom;
},
// private
onClick : function(e, t){
e.preventDefault();
if(!this.disabled){
if(this.isClickOnArrow(e)){
if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){
this.showMenu();
}
this.fireEvent("arrowclick", this, e);
if(this.arrowHandler){
this.arrowHandler.call(this.scope || this, this, e);
}
}else{
if(this.enableToggle){
this.toggle();
}
this.fireEvent("click", this, e);
if(this.handler){
this.handler.call(this.scope || this, this, e);
}
}
}
},
// private
isMenuTriggerOver : function(e){
return this.menu && e.target.tagName == 'em';
},
// private
isMenuTriggerOut : function(e, internal){
return this.menu && e.target.tagName != 'em';
}
});
Ext.reg('splitbutton', Ext.SplitButton); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.layout.ToolbarLayout
* @extends Ext.layout.ContainerLayout
*/
Ext.layout.ToolbarLayout = Ext.extend(Ext.layout.ContainerLayout, {
monitorResize: true,
triggerWidth: 16,
lastOverflow: false,
noItemsMenuText: '<div class="x-toolbar-no-items">(None)</div>',
// private
onLayout : function(ct, target){
if(!this.leftTr){
target.addClass('x-toolbar-layout-ct');
target.insertHtml('beforeEnd',
'<table cellspacing="0" class="x-toolbar-ct"><tbody><tr><td class="x-toolbar-left" align="left"><table cellspacing="0"><tbody><tr class="x-toolbar-left-row"></tr></tbody></table></td><td class="x-toolbar-right" align="right"><table cellspacing="0" class="x-toolbar-right-ct"><tbody><tr><td><table cellspacing="0"><tbody><tr class="x-toolbar-right-row"></tr></tbody></table></td><td><table cellspacing="0"><tbody><tr class="x-toolbar-extras-row"></tr></tbody></table></td></tr></tbody></td></tr></tbody></table>');
this.leftTr = target.child('tr.x-toolbar-left-row', true);
this.rightTr = target.child('tr.x-toolbar-right-row', true);
this.extrasTr = target.child('tr.x-toolbar-extras-row', true);
}
var side = this.leftTr;
var pos = 0;
var items = ct.items.items;
for(var i = 0, len = items.length, c; i < len; i++, pos++) {
c = items[i];
if(c.isFill){
side = this.rightTr;
pos = 0;
}else if(!c.rendered){
c.render(this.insertCell(c, side, pos));
}else{
if(!c.xtbHidden && !this.isValidParent(c, side.childNodes[pos])){
var td = this.insertCell(c, side, pos);
td.appendChild(c.getDomPositionEl().dom);
c.container = Ext.get(td);
}
}
}
//strip extra empty cells
this.cleanup(this.leftTr);
this.cleanup(this.rightTr);
this.cleanup(this.extrasTr);
this.fitToSize(target);
},
cleanup : function(row){
var cn = row.childNodes;
for(var i = cn.length-1, c; i >= 0 && (c = cn[i]); i--){
if(!c.firstChild){
row.removeChild(c);
}
}
},
insertCell : function(c, side, pos){
var td = document.createElement('td');
td.className='x-toolbar-cell';
side.insertBefore(td, side.childNodes[pos]||null);
return td;
},
hideItem: function(item){
var h = (this.hiddens = this.hiddens || []);
h.push(item);
item.xtbHidden = true;
item.xtbWidth = item.getDomPositionEl().dom.parentNode.offsetWidth;
item.hide();
},
unhideItem: function(item){
item.show();
item.xtbHidden = false;
this.hiddens.remove(item);
if(this.hiddens.length < 1){
delete this.hiddens;
}
},
getItemWidth : function(c){
return c.hidden ? (c.xtbWidth || 0) : c.getDomPositionEl().dom.parentNode.offsetWidth;
},
fitToSize :function(t){
if(this.container.enableOverflow === false){
return;
}
var w = t.dom.clientWidth;
var lw = this.lastWidth || 0;
this.lastWidth = w;
var iw = t.dom.firstChild.offsetWidth;
var clipWidth = w - this.triggerWidth;
var hideIndex = -1;
if(iw > w || (this.hiddens && w > lw)){
var i, items = this.container.items.items, len = items.length, c;
var loopWidth = 0;
for(i = 0; i < len; i++) {
c = items[i];
if(!c.isFill){
loopWidth += this.getItemWidth(c);
if(loopWidth > clipWidth){
if(!c.xtbHidden){
this.hideItem(c);
}
}else{
if(c.xtbHidden){
this.unhideItem(c);
}
}
}
}
}
if(this.hiddens){
this.initMore();
if(!this.lastOverflow){
this.container.fireEvent('overflowchange', this.container, true);
this.lastOverflow = true;
}
}else if(this.more){
this.clearMenu();
this.more.destroy();
delete this.more;
if(this.lastOverflow){
this.container.fireEvent('overflowchange', this.container, false);
this.lastOverflow = false;
}
}
},
createMenuConfig: function(c, hideOnClick){
var cfg = {
text: c.text,
iconCls: c.iconCls,
icon: c.icon,
disabled: c.disabled,
handler: c.handler,
scope: c.scope,
menu: c.menu
};
cfg.hideOnClick = hideOnClick;
delete cfg.xtype;
delete cfg.id;
return cfg;
},
// private
addComponentToMenu: function(m, c){
if(c instanceof Ext.Toolbar.Separator){
m.add('-');
}else if(typeof c.isXType == 'function'){
if(c.isXType('splitbutton')){
m.add(this.createMenuConfig(c, true));
}else if(c.isXType('button')){
m.add(this.createMenuConfig(c, !c.menu));
}else if(c.isXType('buttongroup')){
m.add('-');
c.items.each(function(item){
this.addComponentToMenu(m, item);
}, this);
m.add('-');
}
}
},
clearMenu: function(){
var m = this.moreMenu;
if(m && m.items){
this.moreMenu.items.each(function(item){
delete item.menu;
});
}
},
// private
beforeMoreShow : function(m){
this.clearMenu();
m.removeAll();
for(var i = 0, h = this.container.items.items, len = h.length, c; i < len; i++){
c = h[i];
if(c.xtbHidden){
this.addComponentToMenu(m, c);
}
}
// put something so the menu isn't empty
// if no compatible items found
if(m.items.length < 1){
m.add(this.noItemsMenuText);
}
},
initMore : function(){
if(!this.more){
this.moreMenu = new Ext.menu.Menu({
listeners: {
beforeshow: this.beforeMoreShow,
scope: this
}
});
this.more = new Ext.Button({
iconCls: 'x-toolbar-more-icon',
cls: 'x-toolbar-more',
menu: this.moreMenu
});
var td = this.insertCell(this.more, this.extrasTr, 100);
this.more.render(td);
}
}
/**
* @property activeItem
* @hide
*/
});
Ext.Container.LAYOUTS['toolbar'] = Ext.layout.ToolbarLayout;
/**
* @class Ext.Toolbar
* @extends Ext.Container
* 基本工具栏类。工具栏元素可以通过它们的构造函数明确地被创建,或者通过它们的xtype类型来实现。
* 也有一些简单的字符串代表特定的对象,用于创建各种工具条。
* Basic Toolbar class. Toolbar elements can be created explicitly via their constructors, or implicitly
* via their xtypes. Some items also have shortcut strings for creation.
* @constructor 创建一个新的工具栏 Creates a new Toolbar
* @param {Object/Array} config 要添加的一个配置对象或者一个要按钮数组 A config object or an array of buttons to add
*/
Ext.Toolbar = function(config){
if(Ext.isArray(config)){
config = {items: config, layout: 'toolbar'};
} else {
config = Ext.apply({
layout: 'toolbar'
}, config);
if(config.buttons) {
config.items = config.buttons;
}
}
Ext.Toolbar.superclass.constructor.call(this, config);
};
(function(){
var T = Ext.Toolbar;
Ext.extend(T, Ext.Container, {
defaultType: 'button',
trackMenus : true,
internalDefaults: {removeMode: 'container', hideParent: true},
toolbarCls: 'x-toolbar',
initComponent : function(){
T.superclass.initComponent.call(this);
this.addEvents('overflowchange');
},
// private
onRender : function(ct, position){
if(!this.el){
if(!this.autoCreate){
this.autoCreate = {
cls: this.toolbarCls + ' x-small-editor'
}
}
this.el = ct.createChild(Ext.apply({ id: this.id },this.autoCreate), position);
}
},
/**
* 增加一个元素到工具栏上 -- 这个函数可以把许多混合类型的参数添加到工具栏上。
* Adds element(s) to the toolbar -- this function takes a variable number of
* arguments of mixed type and adds them to the toolbar.
* @param {Mixed} arg1 下面的所有参数都是有效的: The following types of arguments are all valid:<br />
* <ul>
* <li>{@link Ext.Toolbar.Button} config: 一个有效的按钮配置对象(等价于{@link #addButton})。A valid button config object (equivalent to {@link #addButton})</li>
* <li>HtmlElement: 任何一个标准的HTML元素(等价于 {@link #addElement})。Any standard HTML element (equivalent to {@link #addElement})</li>
* <li>Field: 任何一个form域(等价于 {@link #addField})。Any form field (equivalent to {@link #addField})</li>
* <li>Item: 任何一个{@link Ext.Toolbar.Item}的子类(等价于{@link #addItem})。Any subclass of {@link Ext.Toolbar.Item} (equivalent to {@link #addItem})</li>
* <li>String: 任何一种类型的字符串(在{@link Ext.Toolbar.TextItem}里被封装,等价于{@link #addText})。Any generic string (gets wrapped in a {@link Ext.Toolbar.TextItem}, equivalent to {@link #addText}).
* 注意:下面这些特殊的字符串被特殊处理。Note that there are a few special strings that are treated differently as explained next.</li>
* <li>'separator' or '-': 创建一个分隔符元素(等价于 {@link #addSeparator})。Creates a separator element (equivalent to {@link #addSeparator})</li>
* <li>' ': 创建一个空白分隔元素(等价于 {@link #addSpacer})。Creates a spacer element (equivalent to {@link #addSpacer})</li>
* <li>'->': 创建一个填充元素(等价于 {@link #addFill})。Creates a fill element (equivalent to {@link #addFill})</li>
* </ul>
* @param {Mixed} arg2
* @param {Mixed} etc.
*/
add : function(){
var a = arguments, l = a.length;
for(var i = 0; i < l; i++){
var el = a[i];
if(el.isFormField){ // 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.tag){ // DomHelper spec
this.addDom(el);
}else if(el.tagName){ // element
this.addElement(el);
}else if(typeof el == "object"){ // must be button config?
if(el.xtype){
this.addItem(Ext.create(el, 'button'));
}else{
this.addButton(el);
}
}
}
},
/**
* 添加一个分隔符。
* Adds a separator
* @return {Ext.Toolbar.Item} 分隔符项 The separator item
*/
addSeparator : function(){
return this.addItem(new T.Separator());
},
/**
* 添加一个空白分隔符。
* Adds a spacer element
* @return {Ext.Toolbar.Spacer} 空白项 The spacer item
*/
addSpacer : function(){
return this.addItem(new T.Spacer());
},
/**
* 使得后来添加的元素都像CSS样式:float:right那般向右靠拢。
* Forces subsequent additions into the float:right toolbar
*/
addFill : function(){
this.addItem(new T.Fill());
},
/**
* 在工具栏上添加任何一个标准的HTML元素。
* Adds any standard HTML element to the toolbar
* @param {Mixed} el 要加入的元素本身或元素其。id The element or id of the element to add
* @return {Ext.Toolbar.Item} 元素项。The element's item
*/
addElement : function(el){
var item = new T.Item({el:el});
this.addItem(item);
return item;
},
/**
* 添加任何一个Toolbar.Item或者其子类。
* Adds any Toolbar.Item or subclass
* @param {Ext.Toolbar.Item} item 元素项
* @return {Ext.Toolbar.Item} 元素项 The item
*/
addItem : function(item){
Ext.Toolbar.superclass.add.apply(this, arguments);
return item;
},
/**
* 添加一个按钮(或者一组按钮)。可以查看{@link Ext.Toolbar.Button}获取更多的配置信息。
* Adds a button (or buttons). See {@link Ext.Toolbar.Button} for more info on the config.
* @param {Object/Array} config 按钮的配置项或配置项的数组。A button config or array of configs
* @return {Ext.Toolbar.Button/Array}
*/
addButton : function(config){
if(Ext.isArray(config)){
var buttons = [];
for(var i = 0, len = config.length; i < len; i++) {
buttons.push(this.addButton(config[i]));
}
return buttons;
}
var b = config;
if(!b.events){
b = config.split ?
new T.SplitButton(config) :
new T.Button(config);
}
this.initMenuTracking(b);
this.addItem(b);
return b;
},
// private
initMenuTracking : function(item){
if(this.trackMenus && item.menu){
this.mon(item, {
'menutriggerover' : this.onButtonTriggerOver,
'menushow' : this.onButtonMenuShow,
'menuhide' : this.onButtonMenuHide,
scope: this
});
}
},
/**
* 在工具栏上添加文本。
* Adds text to the toolbar
* @param {String} text 添加的文本。The text to add
* @return {Ext.Toolbar.Item} 元素。The element's item
*/
addText : function(text){
var t = new T.TextItem(text);
this.addItem(t);
return t;
},
/**
* 在指定的索引位置那里插入任何一个{@link Ext.Toolbar.Item}/{@link Ext.Toolbar.Button}项。
* Inserts any {@link Ext.Toolbar.Item}/{@link Ext.Toolbar.Button} at the specified index.
* @param {Number} index item插入的地方(索引值) The index where the item is to be inserted
* @param {Object/Ext.Toolbar.Item/Ext.Toolbar.Button/Array} item 要插入的按钮本身或按钮其配置项,或配置项的数组 item The button, or button config object to be
* inserted, or an array of buttons/configs.
* @return {Ext.Toolbar.Button/Item}
*/
insertButton : function(index, item){
if(Ext.isArray(item)){
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 T.Button)){
item = new T.Button(item);
}
Ext.Toolbar.superclass.insert.call(this, index, item);
return item;
},
/**
* 在工具栏上添加一个从{@link Ext.DomHelper}配置传递过来的元素。
* Adds a new element to the toolbar from the passed {@link Ext.DomHelper} config
* @param {Object} config
* @return {Ext.Toolbar.Item} 元素 The element's item
*/
addDom : function(config){
var item = new T.Item({autoEl: config});
this.addItem(item);
return item;
},
/**
* 添加一个动态的可展现的 Ext.form field(TextField、ComboBox等等)。
* 注意:这个域应该还没有被展现。对于一个已经被展现了的域,应使用{@link #addElement}。
* Adds a dynamically rendered Ext.form field (TextField, ComboBox, etc). Note: the field should not have
* been rendered yet. For a field that has already been rendered, use {@link #addElement}.
* @param {Ext.form.Field} field
* @return {Ext.Toolbar.Item}
*/
addField : function(field){
this.addItem(field);
return field;
},
applyDefaults : function(c){
c = Ext.Toolbar.superclass.applyDefaults.call(this, c);
var d = this.internalDefaults;
if(c.events){
Ext.applyIf(c.initialConfig, d);
Ext.apply(c, d);
}else{
Ext.applyIf(c, d);
}
return c;
},
// private
onDisable : function(){
this.items.each(function(item){
if(item.disable){
item.disable();
}
});
},
// private
onEnable : function(){
this.items.each(function(item){
if(item.enable){
item.enable();
}
});
},
// private
onButtonTriggerOver : function(btn){
if(this.activeMenuBtn && this.activeMenuBtn != btn){
this.activeMenuBtn.hideMenu();
btn.showMenu();
this.activeMenuBtn = btn;
}
},
// private
onButtonMenuShow : function(btn){
this.activeMenuBtn = btn;
},
// private
onButtonMenuHide : function(btn){
delete this.activeMenuBtn;
}
});
Ext.reg('toolbar', Ext.Toolbar);
/**
* @class Ext.Toolbar.Item
* 被其他类所继承的基类,以获取一些基本的工具栏项功能。
* The base class that other non-ineracting Toolbar Item classes should extend in order to
* get some basic common toolbar item functionality.
* @constructor 创建一个新的项。Creates a new Item
* @param {HTMLElement} el
*/
T.Item = Ext.extend(Ext.BoxComponent, {
hideParent: true, // Hiding a Toolbar.Item hides its containing TD
enable:Ext.emptyFn,
disable:Ext.emptyFn,
focus:Ext.emptyFn
});
Ext.reg('tbitem', T.Item);
/**
* @class Ext.Toolbar.Separator
* @extends Ext.Toolbar.Item
* 在项与项之间添加一个垂直的分隔符。用法举例:
* A simple class that adds a vertical separator bar between toolbar items. Example usage:
* <pre><code>
new Ext.Panel({
tbar : [
'Item 1',
{xtype: 'tbseparator'}, // or '-'
'Item 2'
]
});
</code></pre>
* @constructor 创建一个新的分隔符。Creates a new Separator
*/
T.Separator = Ext.extend(T.Item, {
onRender : function(ct, position){
this.el = ct.createChild({tag:'span', cls:'xtb-sep'}, position);
}
});
Ext.reg('tbseparator', T.Separator);
/**
* @class Ext.Toolbar.Spacer
* @extends Ext.Toolbar.Item
* 在项与项之间添加一个水平的空白位置。
* A simple element that adds extra horizontal space between items in a toolbar.
* <pre><code>
new Ext.Panel({
tbar : [
'Item 1',
{xtype: 'tbspacer'}, // or ' '
'Item 2'
]
});
</code></pre>
* @constructor 创建一个新的Spacer对象 Creates a new Spacer
*/
T.Spacer = Ext.extend(T.Item, {
onRender : function(ct, position){
this.el = ct.createChild({tag:'div', cls:'xtb-spacer', style: this.width?'width:'+this.width+'px':''}, position);
}
});
Ext.reg('tbspacer', T.Spacer);
/**
* @class Ext.Toolbar.Fill
* @extends Ext.Toolbar.Spacer
* 添加一个填充空白的元素,把后面的元素全都放到工具栏的右侧。
* A non-rendering placeholder item which instructs the Toolbar's Layout to begin using
* the right-justified button container.
* <pre><code>
new Ext.Panel({
tbar : [
'Item 1',
{xtype: 'tbfill'}, // or '->'
'Item 2'
]
});
</code></pre>
* @constructor 创建一个新的Fill对象。Creates a new Fill
*/
T.Fill = Ext.extend(T.Item, {
// private
render : Ext.emptyFn,
isFill : true
});
Ext.reg('tbfill', T.Fill);
/**
* @class Ext.Toolbar.TextItem
* @extends Ext.Toolbar.Item
* 只是简单地渲染一段文本字符串。
* A simple class that renders text directly into a toolbar.
* <pre><code>
new Ext.Panel({
tbar : [
{xtype: 'tbtext', text: 'Item 1'} // 或简单地就是 or simply 'Item 1'
]
});
</code></pre>
* @constructor 创建一个新的TextItem对象。Creates a new TextItem
* @param {String/Object} text 文本字符串,或是一个包含<tt>text</tt>属性的配置对象 A text string, or a config object containing a <tt>text</tt> property
*/
T.TextItem = Ext.extend(T.Item, {
constructor: function(config){
if (typeof config == 'string') {
config = { autoEl: {cls: 'xtb-text', html: config }};
} else {
config.autoEl = {cls: 'xtb-text', html: config.text || ''};
}
T.TextItem.superclass.constructor.call(this, config);
},
setText: function(t) {
if (this.rendered) {
this.el.dom.innerHTML = t;
} else {
this.autoEl.html = t;
}
}
});
Ext.reg('tbtext', T.TextItem);
// 向后兼容 backwards compat
T.Button = Ext.extend(Ext.Button, {});
T.SplitButton = Ext.extend(Ext.SplitButton, {});
Ext.reg('tbbutton', T.Button);
Ext.reg('tbsplit', T.SplitButton);
})();
Ext.ButtonGroup = Ext.extend(Ext.Panel, {
baseCls: 'x-btn-group',
layout:'table',
defaultType: 'button',
frame: true,
internalDefaults: {removeMode: 'container', hideParent: true},
initComponent : function(){
this.layoutConfig = this.layoutConfig || {};
Ext.applyIf(this.layoutConfig, {
columns : this.columns
});
if(!this.title){
this.addClass('x-btn-group-notitle');
}
this.on('afterlayout', this.onAfterLayout, this);
Ext.ButtonGroup.superclass.initComponent.call(this);
},
applyDefaults : function(c){
c = Ext.ButtonGroup.superclass.applyDefaults.call(this, c);
var d = this.internalDefaults;
if(c.events){
Ext.applyIf(c.initialConfig, d);
Ext.apply(c, d);
}else{
Ext.applyIf(c, d);
}
return c;
},
onAfterLayout : function(){
var bodyWidth = this.body.getFrameWidth('lr') + this.body.dom.firstChild.offsetWidth;
this.body.setWidth(bodyWidth);
this.el.setWidth(bodyWidth + this.getFrameWidth());
}
});
Ext.reg('buttongroup', Ext.ButtonGroup); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeNodeUI
* 为实现Ext树节点UI而提供的类。TreeNode的UI是与tree的实现相分离,以方便自定义tree节点的外观。
* <br>
* <p>
* 不应该直接实例化该类,要制定Tree的用户界面,你应该继承这个类。
* </p>
* <p>
* 可通过{@link Ext.tree.TreeNode#getUI}方法访问Ext TreeNode的用户界面组件。</p>
*/
Ext.tree.TreeNodeUI = function(node){
this.node = node;
this.rendered = false;
this.animating = false;
this.wasLeaf = true;
this.ecc = 'x-tree-ec-icon x-tree-elbow';
this.emptyIcon = Ext.BLANK_IMAGE_URL;
};
Ext.tree.TreeNodeUI.prototype = {
// private
removeChild : function(node){
if(this.rendered){
this.ctNode.removeChild(node.ui.getEl());
}
},
// private
beforeLoad : function(){
this.addClass("x-tree-node-loading");
},
// private
afterLoad : function(){
this.removeClass("x-tree-node-loading");
},
// private
onTextChange : function(node, text, oldText){
if(this.rendered){
this.textNode.innerHTML = text;
}
},
// private
onDisableChange : function(node, state){
this.disabled = state;
if (this.checkbox) {
this.checkbox.disabled = state;
}
if(state){
this.addClass("x-tree-node-disabled");
}else{
this.removeClass("x-tree-node-disabled");
}
},
// private
onSelectedChange : function(state){
if(state){
this.focus();
this.addClass("x-tree-selected");
}else{
//this.blur();
this.removeClass("x-tree-selected");
}
},
// private
onMove : function(tree, node, oldParent, newParent, index, refNode){
this.childIndent = null;
if(this.rendered){
var targetNode = newParent.ui.getContainer();
if(!targetNode){//target not rendered
this.holder = document.createElement("div");
this.holder.appendChild(this.wrap);
return;
}
var insertBefore = refNode ? refNode.ui.getEl() : null;
if(insertBefore){
targetNode.insertBefore(this.wrap, insertBefore);
}else{
targetNode.appendChild(this.wrap);
}
this.node.renderIndent(true);
}
},
/**
* 为节点的UI元素添加一到多个CSS样式类。重复的样式类会省略。
* @param {String/Array} className 添加的样式类或数组。
*/
addClass : function(cls){
if(this.elNode){
Ext.fly(this.elNode).addClass(cls);
}
},
/**
* 移除节点的一到多个CSS样式类。
* @param {String/Array} className 待删除的样式类或数组。
*/
removeClass : function(cls){
if(this.elNode){
Ext.fly(this.elNode).removeClass(cls);
}
},
// private
remove : function(){
if(this.rendered){
this.holder = document.createElement("div");
this.holder.appendChild(this.wrap);
}
},
// private
fireEvent : function(){
return this.node.fireEvent.apply(this.node, arguments);
},
// private
initEvents : function(){
this.node.on("move", this.onMove, this);
if(this.node.disabled){
this.addClass("x-tree-node-disabled");
if (this.checkbox) {
this.checkbox.disabled = true;
}
}
if(this.node.hidden){
this.hide();
}
var ot = this.node.getOwnerTree();
var dd = ot.enableDD || ot.enableDrag || ot.enableDrop;
if(dd && (!this.node.isRoot || ot.rootVisible)){
Ext.dd.Registry.register(this.elNode, {
node: this.node,
handles: this.getDDHandles(),
isHandle: false
});
}
},
// private
getDDHandles : function(){
return [this.iconNode, this.textNode, this.elNode];
},
/**
* 隐藏本节点。
*/
hide : function(){
this.node.hidden = true;
if(this.wrap){
this.wrap.style.display = "none";
}
},
/**
* 显示本节点。
*/
show : function(){
this.node.hidden = false;
if(this.wrap){
this.wrap.style.display = "";
}
},
// private
onContextMenu : function(e){
if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) {
e.preventDefault();
this.focus();
this.fireEvent("contextmenu", this.node, e);
}
},
// private
onClick : function(e){
if(this.dropping){
e.stopEvent();
return;
}
if(this.fireEvent("beforeclick", this.node, e) !== false){
var a = e.getTarget('a');
if(!this.disabled && this.node.attributes.href && a){
this.fireEvent("click", this.node, e);
return;
}else if(a && e.ctrlKey){
e.stopEvent();
}
e.preventDefault();
if(this.disabled){
return;
}
if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){
this.node.toggle();
}
this.fireEvent("click", this.node, e);
}else{
e.stopEvent();
}
},
// private
onDblClick : function(e){
e.preventDefault();
if(this.disabled){
return;
}
if(this.checkbox){
this.toggleCheck();
}
if(!this.animating && this.node.hasChildNodes()){
this.node.toggle();
}
this.fireEvent("dblclick", this.node, e);
},
onOver : function(e){
this.addClass('x-tree-node-over');
},
onOut : function(e){
this.removeClass('x-tree-node-over');
},
// private
onCheckChange : function(){
var checked = this.checkbox.checked;
// fix for IE6
this.checkbox.defaultChecked = checked;
this.node.attributes.checked = checked;
this.fireEvent('checkchange', this.node, checked);
},
// private
ecClick : function(e){
if(!this.animating && (this.node.hasChildNodes() || this.node.attributes.expandable)){
this.node.toggle();
}
},
// private
startDrop : function(){
this.dropping = true;
},
// delayed drop so the click event doesn't get fired on a drop
endDrop : function(){
setTimeout(function(){
this.dropping = false;
}.createDelegate(this), 50);
},
// private
expand : function(){
this.updateExpandIcon();
this.ctNode.style.display = "";
},
// private
focus : function(){
if(!this.node.preventHScroll){
try{this.anchor.focus();
}catch(e){}
}else{
try{
var noscroll = this.node.getOwnerTree().getTreeEl().dom;
var l = noscroll.scrollLeft;
this.anchor.focus();
noscroll.scrollLeft = l;
}catch(e){}
}
},
/**
* 设置树节点的checked状态值到传入的值,或,如果没有传入值,就轮回选中的状态。
* 如果节点没有checkbox,这将不会有效果。
* @param {Boolean} value(可选的)新的选中状态。
*/
toggleCheck : function(value){
var cb = this.checkbox;
if(cb){
cb.checked = (value === undefined ? !cb.checked : value);
this.onCheckChange();
}
},
// private
blur : function(){
try{
this.anchor.blur();
}catch(e){}
},
// private
animExpand : function(callback){
var ct = Ext.get(this.ctNode);
ct.stopFx();
if(!this.node.hasChildNodes()){
this.updateExpandIcon();
this.ctNode.style.display = "";
Ext.callback(callback);
return;
}
this.animating = true;
this.updateExpandIcon();
ct.slideIn('t', {
callback : function(){
this.animating = false;
Ext.callback(callback);
},
scope: this,
duration: this.node.ownerTree.duration || .25
});
},
// private
highlight : function(){
var tree = this.node.getOwnerTree();
Ext.fly(this.wrap).highlight(
tree.hlColor || "C3DAF9",
{endColor: tree.hlBaseColor}
);
},
// private
collapse : function(){
this.updateExpandIcon();
this.ctNode.style.display = "none";
},
// private
animCollapse : function(callback){
var ct = Ext.get(this.ctNode);
ct.enableDisplayMode('block');
ct.stopFx();
this.animating = true;
this.updateExpandIcon();
ct.slideOut('t', {
callback : function(){
this.animating = false;
Ext.callback(callback);
},
scope: this,
duration: this.node.ownerTree.duration || .25
});
},
// private
getContainer : function(){
return this.ctNode;
},
// private
getEl : function(){
return this.wrap;
},
// private
appendDDGhost : function(ghostNode){
ghostNode.appendChild(this.elNode.cloneNode(true));
},
// private
getDDRepairXY : function(){
return Ext.lib.Dom.getXY(this.iconNode);
},
// private
onRender : function(){
this.render();
},
// private
render : function(bulkRender){
var n = this.node, a = n.attributes;
var targetNode = n.parentNode ?
n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom;
if(!this.rendered){
this.rendered = true;
this.renderElements(n, a, targetNode, bulkRender);
if(a.qtip){
if(this.textNode.setAttributeNS){
this.textNode.setAttributeNS("ext", "qtip", a.qtip);
if(a.qtipTitle){
this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle);
}
}else{
this.textNode.setAttribute("ext:qtip", a.qtip);
if(a.qtipTitle){
this.textNode.setAttribute("ext:qtitle", a.qtipTitle);
}
}
}else if(a.qtipCfg){
a.qtipCfg.target = Ext.id(this.textNode);
Ext.QuickTips.register(a.qtipCfg);
}
this.initEvents();
if(!this.node.expanded){
this.updateExpandIcon(true);
}
}else{
if(bulkRender === true) {
targetNode.appendChild(this.wrap);
}
}
},
// private
renderElements : function(n, a, targetNode, bulkRender){
// add some indent caching, this helps performance when rendering a large tree
this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
var cb = typeof a.checked == 'boolean';
var href = a.href ? a.href : Ext.isGecko ? "" : "#";
var buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">',
'<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
'<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />',
'<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '',
'<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ',
a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,"</span></a></div>",
'<ul class="x-tree-node-ct" style="display:none;"></ul>',
"</li>"].join('');
var nel;
if(bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())){
this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf);
}else{
this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf);
}
this.elNode = this.wrap.childNodes[0];
this.ctNode = this.wrap.childNodes[1];
var cs = this.elNode.childNodes;
this.indentNode = cs[0];
this.ecNode = cs[1];
this.iconNode = cs[2];
var index = 3;
if(cb){
this.checkbox = cs[3];
// fix for IE6
this.checkbox.defaultChecked = this.checkbox.checked;
index++;
}
this.anchor = cs[index];
this.textNode = cs[index].firstChild;
},
/**
* 返回焦点所在的节点UI的<a> 元素。
* @return {HtmlElement} DOM anchor元素。
*/
getAnchor : function(){
return this.anchor;
},
/**
* 返回文本节点
* @return {HtmlNode} DOM格式的文本文字
*/
getTextEl : function(){
return this.textNode;
},
/**
* 返回图标<img>元素
* @return {HtmlElement} DOM格式的图片元素
*/
getIconEl : function(){
return this.iconNode;
},
/**
* 返回节点的checked status。如果节点没有渲染checkbox,返回false。
* @return {Boolean} The checked flag.
*/
isChecked : function(){
return this.checkbox ? this.checkbox.checked : false;
},
// private
updateExpandIcon : function(){
if(this.rendered){
var n = this.node, c1, c2;
var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow";
var hasChild = n.hasChildNodes();
if(hasChild || n.attributes.expandable){
if(n.expanded){
cls += "-minus";
c1 = "x-tree-node-collapsed";
c2 = "x-tree-node-expanded";
}else{
cls += "-plus";
c1 = "x-tree-node-expanded";
c2 = "x-tree-node-collapsed";
}
if(this.wasLeaf){
this.removeClass("x-tree-node-leaf");
this.wasLeaf = false;
}
if(this.c1 != c1 || this.c2 != c2){
Ext.fly(this.elNode).replaceClass(c1, c2);
this.c1 = c1; this.c2 = c2;
}
}else{
if(!this.wasLeaf){
Ext.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf");
delete this.c1;
delete this.c2;
this.wasLeaf = true;
}
}
var ecc = "x-tree-ec-icon "+cls;
if(this.ecc != ecc){
this.ecNode.className = ecc;
this.ecc = ecc;
}
}
},
// private
getChildIndent : function(){
if(!this.childIndent){
var buf = [];
var p = this.node;
while(p){
if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){
if(!p.isLast()) {
buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />');
} else {
buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />');
}
}
p = p.parentNode;
}
this.childIndent = buf.join("");
}
return this.childIndent;
},
// private
renderIndent : function(){
if(this.rendered){
var indent = "";
var p = this.node.parentNode;
if(p){
indent = p.ui.getChildIndent();
}
if(this.indentMarkup != indent){ // don't rerender if not required
this.indentNode.innerHTML = indent;
this.indentMarkup = indent;
}
this.updateExpandIcon();
}
},
destroy : function(){
if(this.elNode){
Ext.dd.Registry.unregister(this.elNode.id);
}
delete this.elNode;
delete this.ctNode;
delete this.indentNode;
delete this.ecNode;
delete this.iconNode;
delete this.checkbox;
delete this.anchor;
delete this.textNode;
if (this.holder){
delete this.wrap;
Ext.removeNode(this.holder);
delete this.holder;
}else{
Ext.removeNode(this.wrap);
delete this.wrap;
}
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeEditor
* @extends Ext.Editor
* 为树节点提供即时的编辑功能,所有合法{@link Ext.form.Field}都可作为其编辑字段。
* Provides editor functionality for inline tree node editing. Any valid {@link Ext.form.Field} can be used
* as the editor field.
* @constructor
* @param {TreePanel} tree
* @param {Object} config Either a prebuilt {@link Ext.form.Field} instance or a Field config object 既可以是内建的{@link Ext.form.Field}实例也可以Field的配置项对象
*/
Ext.tree.TreeEditor = function(tree, config){
config = config || {};
var field = config.events ? config : new Ext.form.TextField(config);
Ext.tree.TreeEditor.superclass.constructor.call(this, field);
this.tree = tree;
if(!tree.rendered){
tree.on('render', this.initEditor, this);
}else{
this.initEditor(tree);
}
};
Ext.extend(Ext.tree.TreeEditor, Ext.Editor, {
/**
* @cfg {String} alignment
* 要对象的方向(参阅{@link Ext.Element#alignTo}了解更多,默认为"l-l")。
* The position to align to (see {@link Ext.Element#alignTo} for more details, defaults to "l-l").
*/
alignment: "l-l",
// inherit
autoSize: false,
/**
* @cfg {Boolean} hideEl
* True表示为,当编辑器显示时隐藏绑定的元素(缺省为false)。
* True to hide the bound element while the editor is displayed (defaults to false)
*/
hideEl : false,
/**
* @cfg {String} cls
* 编辑器用到的CSS样式类(默认为"x-small-editor x-tree-editor")。
* CSS class to apply to the editor (defaults to "x-small-editor x-tree-editor")
*/
cls: "x-small-editor x-tree-editor",
/**
* @cfg {Boolean} shim
* 如果要避免有select元素或iframe元素遮挡编辑器显示,就使用一个“垫片(shim)”来提供显示(默认为false)。
* True to shim the editor if selects/iframes could be displayed beneath it (defaults to false)
*/
shim:false,
// inherit
shadow:"frame",
/**
* @cfg {Number} maxWidth
* 编辑器最大的宽度,单位是橡树。注意如果最大尺寸超过放置树元素的尺寸,那么将自动为你适应容器的尺寸,包括滚动条和client offsets into account prior to each edit。
* The maximum width in pixels of the editor field (defaults to 250). Note that if the maxWidth would exceed
* the containing tree element's size, it will be automatically limited for you to the container width, taking
* scroll and client offsets into account prior to each edit.
*/
maxWidth: 250,
/**
* @cfg {Number} editDelay
* 该节点点击一开始,持续多久才等级双击的事件(双击的事件执行时会翻转当前的编辑模式,默认为350)。
* 如果在同一个节点上,两次点击都是发生在该时间(time span),那么节点的编辑器将会显示,否则它将被作为规则点击处理。
* The number of milliseconds between clicks to register a double-click
* that will trigger editing on the current node (defaults to 350). If two clicks occur on the same node within this time span,
* the editor for the node will display, otherwise it will be processed as a regular click.
*/
editDelay : 350,
initEditor : function(tree){
tree.on('beforeclick', this.beforeNodeClick, this);
this.on('complete', this.updateNode, this);
this.on('beforestartedit', this.fitToTree, this);
this.on('startedit', this.bindScroll, this, {delay:10});
this.on('specialkey', this.onSpecialKey, this);
},
// private
fitToTree : function(ed, el){
var td = this.tree.getTreeEl().dom, nd = el.dom;
if(td.scrollLeft > nd.offsetLeft){ // ensure the node left point is visible
td.scrollLeft = nd.offsetLeft;
}
var w = Math.min(
this.maxWidth,
(td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - /*cushion*/5);
this.setSize(w, '');
},
// private
triggerEdit : function(node){
this.completeEdit();
this.editNode = node;
this.startEdit(node.ui.textNode, node.text);
},
// private
bindScroll : function(){
this.tree.getTreeEl().on('scroll', this.cancelEdit, this);
},
// private
beforeNodeClick : function(node, e){
var sinceLast = (this.lastClick ? this.lastClick.getElapsed() : 0);
this.lastClick = new Date();
if(sinceLast > this.editDelay && this.tree.getSelectionModel().isSelected(node)){
e.stopEvent();
this.triggerEdit(node);
return false;
}
},
// private
updateNode : function(ed, value){
this.tree.getTreeEl().un('scroll', this.cancelEdit, this);
this.editNode.setText(value);
},
// private
onHide : function(){
Ext.tree.TreeEditor.superclass.onHide.call(this);
if(this.editNode){
this.editNode.ui.focus();
}
},
// private
onSpecialKey : function(field, e){
var k = e.getKey();
if(k == e.ESC){
e.stopEvent();
this.cancelEdit();
}else if(k == e.ENTER && !e.hasModifier()){
e.stopEvent();
this.completeEdit();
}
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeFilter
* 注意这个类是试验性的所以不会更新节点的缩进(连线)或者展开收回图标
* @param {TreePanel} tree
* @param {Object} config 配置项(可选的)
*/
Ext.tree.TreeFilter = function(tree, config){
this.tree = tree;
this.filtered = {};
Ext.apply(this, config);
};
Ext.tree.TreeFilter.prototype = {
clearBlank:false,
reverse:false,
autoClear:false,
remove:false,
/**
* 通过指定的属性过滤数据
* @param {String/RegExp} value既可以是属性值开头的字符串也可以是针对这个属性的正则表达式
* @param {String} attr (可选)这个被传递的属性是你的属性的集合中的。默认是"text"
* @param {TreeNode} startNode (可选)从这个节点开始是过滤的
*/
filter : function(value, attr, startNode){
attr = attr || "text";
var f;
if(typeof value == "string"){
var vlen = value.length;
// auto clear empty filter
if(vlen == 0 && this.clearBlank){
this.clear();
return;
}
value = value.toLowerCase();
f = function(n){
return n.attributes[attr].substr(0, vlen).toLowerCase() == value;
};
}else if(value.exec){ // regex?
f = function(n){
return value.test(n.attributes[attr]);
};
}else{
throw 'Illegal filter type, must be string or regex';
}
this.filterBy(f, null, startNode);
},
/**
* 通过一个函数过滤,这个被传递的函数将被这棵树中的每个节点调用(或从startNode开始)。如果函数返回true,那么该节点将保留否则它将被过滤掉.
* 如果一个节点被过滤掉,那么它的子节点也都被过滤掉了
* @param {Function} fn 过滤函数
* @param {Object} scope (可选的)函数的作用域(默认是现在这个节点)
*/
filterBy : function(fn, scope, startNode){
startNode = startNode || this.tree.root;
if(this.autoClear){
this.clear();
}
var af = this.filtered, rv = this.reverse;
var f = function(n){
if(n == startNode){
return true;
}
if(af[n.id]){
return false;
}
var m = fn.call(scope || n, n);
if(!m || rv){
af[n.id] = n;
n.ui.hide();
return false;
}
return true;
};
startNode.cascade(f);
if(this.remove){
for(var id in af){
if(typeof id != "function"){
var n = af[id];
if(n && n.parentNode){
n.parentNode.removeChild(n);
}
}
}
}
},
/**
* 清理现在的过滤。注意:设置的过滤带有remove选项的不能被清理
*/
clear : function(){
var t = this.tree;
var af = this.filtered;
for(var id in af){
if(typeof id != "function"){
var n = af[id];
if(n){
n.ui.show();
}
}
}
this.filtered = {};
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreePanel
* @extends Ext.Panel
* <p>
* TreePanel为树状的数据结构提供了树状结构UI表示层。
* </p>
* <p>{@link Ext.tree.TreeNode TreeNode}s是加入到TreePanel的节点,可采用其{@link Ext.tree.TreeNode#attributes attributes}属性
* 来定义程序的元数据</p>
* <p><b>TreePanel渲染之前必须有一个{@link #root}根节点的对象</b>。除了可以用{@link #root}配置选项指定外,还可以使用{@link #setRootNode}的方法。
* <p>An example of tree rendered to an existing div:</p><pre><code>
var tree = new Ext.tree.TreePanel({
renderTo: 'tree-div',
useArrows: true,
autoScroll: true,
animate: true,
enableDD: true,
containerScroll: true,
border: false,
// auto create TreeLoader
dataUrl: 'get-nodes.php',
root: {
nodeType: 'async',
text: 'Ext JS',
draggable: false,
id: 'source'
}
});
tree.getRootNode().expand();
* </code></pre>
* <p>The example above would work with a data packet similar to this:</p><pre><code>
[{
"text": "adapter",
"id": "source\/adapter",
"cls": "folder"
}, {
"text": "dd",
"id": "source\/dd",
"cls": "folder"
}, {
"text": "debug.js",
"id": "source\/debug.js",
"leaf": true,
"cls": "file"
}]
* </code></pre>
* <p>An example of tree within a Viewport:</p><pre><code>
new Ext.Viewport({
layout: 'border',
items: [{
region: 'west',
collapsible: true,
title: 'Navigation',
xtype: 'treepanel',
width: 200,
autoScroll: true,
split: true,
loader: new Ext.tree.TreeLoader(),
root: new Ext.tree.AsyncTreeNode({
expanded: true,
children: [{
text: 'Menu Option 1',
leaf: true
}, {
text: 'Menu Option 2',
leaf: true
}, {
text: 'Menu Option 3',
leaf: true
}]
}),
rootVisible: false,
listeners: {
click: function(n) {
Ext.Msg.alert('Navigation Tree Click', 'You clicked: "' + n.attributes.text + '"');
}
}
}, {
region: 'center',
xtype: 'tabpanel',
// remaining code not shown ...
}]
});
</code></pre>
* @cfg {Ext.tree.TreeNode} root 树的根节点
* @cfg {Boolean} rootVisible false表示隐藏根节点(默认为true)
* @cfg {Boolean} lines false禁止显示树的虚线(默认为true)
* @cfg {Boolean} enableDD true表示允许拖放
* @cfg {Boolean} enableDrag true表示仅激活拖动
* @cfg {Boolean} enableDrop true表示仅激活投下
* @cfg {Object} dragConfig 自定义的配置对象,作用到{@link Ext.tree.TreeDragZone}实例
* @cfg {Object} dropConfig 自定义的配置对象,作用到{@link Ext.tree.TreeDropZone}实例
* @cfg {String} ddGroup 此TreePanel所隶属的DD组
* @cfg {String} ddAppendOnly True if the tree should only allow append drops (用于树的排序)
* @cfg {Boolean} ddScroll true表示激活主干部分的滚动
* @cfg {Boolean} containerScroll true用ScrollerManagee登记该容器
* @cfg {Boolean} hlDrop false表示在置下时禁止节点的高亮(默认为Ext.enableFx的值)
* @cfg {String} hlColor 节点对象高亮的颜色(默认为C3DAF9)
* @cfg {Boolean} animate true表示激活展开、闭合的动画(默认为Ext.enableFx的值)
* @cfg {Boolean} singleExpand true表示只有一个节点的分支可展开
* @cfg {Boolean} selModel 此TreePanel所用的选区模型(默认为{@link Ext.tree.DefaultSelectionModel})
* @cfg {Ext.tree.TreeLoader} loader 此TreePanel所用的{@link Ext.tree.TreeLoader}对象
* @cfg {String} pathSeparator 分离路径的标识符(默认为‘/’)
*
* @constructor
* @param {Object} config 配置项对象
*/
Ext.tree.TreePanel = Ext.extend(Ext.Panel, {
rootVisible : true,
animate: Ext.enableFx,
lines : true,
enableDD : false,
hlDrop : Ext.enableFx,
pathSeparator: "/",
initComponent : function(){
Ext.tree.TreePanel.superclass.initComponent.call(this);
if(!this.eventModel){
this.eventModel = new Ext.tree.TreeEventModel(this);
}
this.nodeHash = {};
/**
* 树的根节点对象
* @type Ext.tree.TreeNode
* @property root
*/
if(this.root){
this.setRootNode(this.root);
}
this.addEvents(
/**
* @event append
* 当新节点添加到树中的某个节点作为子节点时触发
* Fires when a new child node is appended to a node in this tree.
* @param {Tree} tree 所在的树对象
* @param {Node} parent 父节点
* @param {Node} node 新添加的节点
* @param {Number} index 刚加入节点的索引位置
*/
"append",
/**
* @event remove
* 从该树中的某个节点移除下级的节点是触发
* Fires when a child node is removed from a node in this tree.
* @param {Tree} tree 所在的树对象
* @param {Node} parent 父节点
* @param {Node} node 被移除节点对象
*/
"remove",
/**
* @event movenode
* 树中的某个节点被移除到新位置时触发
* Fires when a node is moved to a new location in the tree
* @param {Tree} tree 所在的树对象
* @param {Node} node 节点对象 moved
* @param {Node} oldParent 改节点的原始值
* @param {Node} newParent 该节点的新值
* @param {Number} index 移动到索引位置
*/
"movenode",
/**
* @event insert
* 当有一个新的集合插入到该树的某个节点上触发
* Fires when a new child node is inserted in a node in this tree.
* @param {Tree} tree 所在的树对象
* @param {Node} parent 父节点
* @param {Node} node 要插入的下级项
* @param {Node} refNode 说明在这个节点之前加入
*/
"insert",
/**
* @event beforeappend
* 当这棵树有下级项(child)被被添加到另外一个地方的时候触发,若有false返回就取消添加
* Fires before a new child is appended to a node in this tree, return false to cancel the append.
* @param {Tree} tree 所在的树对象
* @param {Node} parent 父节点
* @param {Node} node 要添加的子节点
*/
"beforeappend",
/**
* @event beforeremove
* 当这棵树有下级项(child)被被移动到另外一个地方的时候触发,若有false返回就取消移动
* Fires before a child is removed from a node in this tree, return false to cancel the remove.
* @param {Tree} tree 所在的树对象
* @param {Node} parent 父节点
* @param {Node} node 要被移除的节点
*/
"beforeremove",
/**
* @event beforemovenode
* Fires before a node is moved to a new location in the tree. Return false to cancel the move.
* 当这棵树有节点被被移动到另外一个地方的时候触发,若有false返回就取消移动
* @param {Tree} tree 所在的树对象
* @param {Node} node 节点对象 being moved
* @param {Node} oldParent 节点上一级对象
* @param {Node} newParent The new parent 节点对象 is moving to
* @param {Number} index The index it is being moved to
*/
"beforemovenode",
/**
* @event beforeinsert
* 当这棵树有新项(new child)被插入的时候触发,若有false返回就取消插入。
* Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
* @param {Tree} tree 所在的树对象
* @param {Node} parent 父节点
* @param {Node} node 要插入的子节点
* @param {Node} refNode 节点对象 The child node is being inserted before
*/
"beforeinsert",
/**
* @event beforeload
* 在节点加载之前触发,若有false返回就取消事件。
* Fires before a node is loaded, return false to cancel
* @param {Node} node 被加载的节点对象
*/
"beforeload",
/**
* @event load
* 在节点加载后触发。
* Fires when a node is loaded
* @param {Node} node 已加载的节点对象
*/
"load",
/**
* @event textchange
* 在节点的文本修过后触发
* Fires when the text for a node is changed
* @param {Node} node 节点对象
* @param {String} text 新文本
* @param {String} oldText 旧文本
*/
"textchange",
/**
* @event beforeexpandnode
* 在节点展开之前触发,若有false返回就取消事件
* Fires before a node is expanded, return false to cancel.
* @param {Node} node 节点对象
* @param {Boolean} deep 深度
* @param {Boolean} anim 动画
*/
"beforeexpandnode",
/**
* @event beforecollapsenode
* 在节点闭合之前触发,若有false返回就取消事件
* Fires before a node is collapsed, return false to cancel.
* @param {Node} node 节点对象
* @param {Boolean} deep 深度
* @param {Boolean} anim 动画
*/
"beforecollapsenode",
/**
* @event expandnode
* 当节点展开时触发
* Fires when a node is expanded
* @param {Node} node 节点对象
*/
"expandnode",
/**
* @event disabledchange
* 当节点的disabled状态改变后触发
* Fires when the disabled status of a node changes
* @param {Node} node 节点对象
* @param {Boolean} disabled 禁止
*/
"disabledchange",
/**
* @event collapsenode
* 当节点闭合后触发
* Fires when a node is collapsed
* @param {Node} node 节点对象
*/
"collapsenode",
/**
* @event beforeclick
* 当单击在某个节点进行之前触发。返回false则取消默认的动作。
* Fires before click processing on a node. Return false to cancel the default action.
* @param {Node} node 节点对象
* @param {Ext.EventObject} e 事件对象
*/
"beforeclick",
/**
* @event click
* 当节点单击时触发
* Fires when a node is clicked
* @param {Node} node 节点对象
* @param {Ext.EventObject} e 事件对象
*/
"click",
/**
* @event checkchange
* 当一个带有checkbox控件的节点的checked属性被改变时触发
* Fires when a node with a checkbox's checked property changes
* @param {Node} this 这个节点
* @param {Boolean} checked
*/
"checkchange",
/**
* @event dblclick
* 当节点双击时触发
* Fires when a node is double clicked
* @param {Node} node 节点对象
* @param {Ext.EventObject} e 事件对象
*/
"dblclick",
/**
* @event contextmenu
* 当节点被右击时触发
* Fires when a node is right clicked
* @param {Node} node 节点对象
* @param {Ext.EventObject} e 事件对象
*/
"contextmenu",
/**
* @event beforechildrenrendered
* 就在节点的子节点被渲染之前触发
* Fires right before the child nodes for a node are rendered
* @param {Node} node 节点对象
*/
"beforechildrenrendered",
/**
* @event startdrag
* Fires when a node starts being dragged
* 当节点开始拖动时触发
* @param {Ext.tree.TreePanel} this treePanel
* @param {Ext.tree.TreeNode} node 节点
* @param {event} e 原始浏览器事件对象
*/
"startdrag",
/**
* @event enddrag
* Fires when a drag operation is complete
* 当一次拖动操作完成后触发
* @param {Ext.tree.TreePanel} this treePanel
* @param {Ext.tree.TreeNode} node 节点
* @param {event} e 原始浏览器事件对象
*/
"enddrag",
/**
* @event dragdrop
* Fires when a dragged node is dropped on a valid DD target
* 当一个拖动节点在一个有效的DD目标上置下时触发
* @param {Ext.tree.TreePanel} this treePanel
* @param {Ext.tree.TreeNode} node 节点
* @param {DD} dd 被投下的dd对象
* @param {event} e 原始浏览器事件对象
*/
"dragdrop",
/**
* @event beforenodedrop
* 当一个DD对象在置下到某个节点之前触发,用于预处理(preprocessing)
* 返回false则取消置下
* 传入的dropEvent处理函数有以下的属性:<br />
* <ul style="padding:5px;padding-left:16px;">
* <li>tree - TreePanel对象</li>
* <li>target - 投下的节点对象(目标)</li>
* <li>data - 拖动的数据源</li>
* <li>point - 投下的方式-添加、上方或下方</li>
* <li>source - 拖动源</li>
* <li>rawEvent - 原始鼠标事件</li>
* <li>dropNode - 由源提供的置下节点,<b>或</b>在该对象设置你要插入的节点</li>
* <li>cancel - 设置为true表示签名投下为不允许</li>
* </ul>
* @param {Object} dropEvent 事件对象
*/
"beforenodedrop",
/**
* @event nodedrop
* 当树节点有一个DD对象被投放后触发。传入的dropEvent处理函数有以下的属性:<br />
* <ul style="padding:5px;padding-left:16px;">
* <li>tree - TreePanel对象</li>
* <li>target - 投下的节点对象(目标)</li>
* <li>data - 拖动的数据源</li>
* <li>point - 投下的方式-添加、上方或下方</li>
* <li>source - 拖动源</li>
* <li>rawEvent - 原始鼠标事件</li>
* <li>dropNode - 投下的节点</li>
* </ul>
* @param {Object} dropEvent 事件对象
*/
"nodedrop",
/**
* @event nodedragover
* 当树节点成为拖动目标时触发,返回false签名这次置下将不允许。传入的dropEvent处理函数有以下的属性:
* <br />
* <ul style="padding:5px;padding-left:16px;">
* <li>tree - TreePanel对象</li>
* <li>target - 投下的节点对象(目标)</li>
* <li>data - 拖动的数据源</li>
* <li>point - 投下的方式-添加、上方或下方</li>
* <li>source - 拖动源</li>
* <li>rawEvent - 原始鼠标事件</li>
* <li>dropNode - 由源提供的投下节点</li>
* <li>cancel - 设置为true表示签名投下为不允许</li>
* </ul>
* @param {Object} dragOverEvent 事件对象
*/
"nodedragover"
);
if(this.singleExpand){
this.on("beforeexpandnode", this.restrictExpand, this);
}
},
// private
proxyNodeEvent : function(ename, a1, a2, a3, a4, a5, a6){
if(ename == 'collapse' || ename == 'expand' || ename == 'beforecollapse' || ename == 'beforeexpand' || ename == 'move' || ename == 'beforemove'){
ename = ename+'node';
}
// args inline for performance while bubbling events
return this.fireEvent(ename, a1, a2, a3, a4, a5, a6);
},
/**
* 返回树的根节点
* @return {Node}
*/
getRootNode : function(){
return this.root;
},
/**
* 在初始化过程中设置该树的根节点
* Sets the root node for this tree during initialization.
* @param {Node} node
* @return {Node}
*/
setRootNode : function(node){
this.root = node;
node.ownerTree = this;
node.isRoot = true;
this.registerNode(node);
if(!this.rootVisible){
var uiP = node.attributes.uiProvider;
node.ui = uiP ? new uiP(node) : new Ext.tree.RootTreeNodeUI(node);
}
return node;
},
/**
*
* 返回树的ID
* @param {String} id ID
* @return {Node}
*/
getNodeById : function(id){
return this.nodeHash[id];
},
// private
registerNode : function(node){
this.nodeHash[node.id] = node;
},
// private
unregisterNode : function(node){
delete this.nodeHash[node.id];
},
// private
toString : function(){
return "[Tree"+(this.id?" "+this.id:"")+"]";
},
// private
restrictExpand : function(node){
var p = node.parentNode;
if(p){
if(p.expandedChild && p.expandedChild.parentNode == p){
p.expandedChild.collapse();
}
p.expandedChild = node;
}
},
/**
* 返回选中的节点,或已选中的节点的特定的属性(例如:“id”)
* @param {String} attribute (可选的)默认为null(返回实际节点)
* @param {TreeNode} startNode (可选的)开始的节点对象 to start from,默认为根节点
* @return {Array}
*/
getChecked : function(a, startNode){
startNode = startNode || this.root;
var r = [];
var f = function(){
if(this.attributes.checked){
r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a]));
}
}
startNode.cascade(f);
return r;
},
/**
* 返回TreePanel所在的容器元素
* @return {Element} 返回TreePanel容器的元素
*/
getEl : function(){
return this.el;
},
/**
* 返回该树的 {@link Ext.tree.TreeLoader}对象
* @return {Ext.tree.TreeLoader} 该树的TreeLoader
*/
getLoader : function(){
return this.loader;
},
/**
* 展开所有节点
*/
expandAll : function(){
this.root.expand(true);
},
/**
* 闭合所有节点
*/
collapseAll : function(){
this.root.collapse(true);
},
/**
* 返回这个treePanel所用的选区模型
* @return {TreeSelectionModel} TreePanel用着的选区模型
*/
getSelectionModel : function(){
if(!this.selModel){
this.selModel = new Ext.tree.DefaultSelectionModel();
}
return this.selModel;
},
/**
* 展开指定的路径。路径可以从{@link Ext.data.Node#getPath}对象上获取
* @param {String} path 路径
* @param {String} attr (可选的)路径中使用的属性(参阅{@link Ext.data.Node#getPath}了解个功能)
* @param {Function} callback (可选的)当展开完成时执行的回调。回调执行时会有以下两个参数
* (bSuccess, oLastNode)bSuccess表示展开成功而oLastNode就表示展开的最后一个节点
*/
expandPath : function(path, attr, callback){
attr = attr || "id";
var keys = path.split(this.pathSeparator);
var curNode = this.root;
if(curNode.attributes[attr] != keys[1]){ // invalid root
if(callback){
callback(false, null);
}
return;
}
var index = 1;
var f = function(){
if(++index == keys.length){
if(callback){
callback(true, curNode);
}
return;
}
var c = curNode.findChild(attr, keys[index]);
if(!c){
if(callback){
callback(false, curNode);
}
return;
}
curNode = c;
c.expand(false, false, f);
};
curNode.expand(false, false, f);
},
/**
* 选择树的指定的路径。路径可以从{@link Ext.data.Node#getPath}对象上获取
* @param {String} path 路径
* @param {String} attr (可选的)路径中使用的属性(参阅{@link Ext.data.Node#getPath}了解个功能)
* @param {Function} callback (可选的)当展开完成时执行的回调。回调执行时会有以下两个参数
* (bSuccess, oLastNode)bSuccess表示选区已成功创建而oLastNode就表示展开的最后一个节点
*/
selectPath : function(path, attr, callback){
attr = attr || "id";
var keys = path.split(this.pathSeparator);
var v = keys.pop();
if(keys.length > 0){
var f = function(success, node){
if(success && node){
var n = node.findChild(attr, v);
if(n){
n.select();
if(callback){
callback(true, n);
}
}else if(callback){
callback(false, n);
}
}else{
if(callback){
callback(false, n);
}
}
};
this.expandPath(keys.join(this.pathSeparator), attr, f);
}else{
this.root.select();
if(callback){
callback(true, this.root);
}
}
},
/**
* 返回tree所属的元素
* @return {Ext.Element} 元素
*/
getTreeEl : function(){
return this.body;
},
// private
onRender : function(ct, position){
Ext.tree.TreePanel.superclass.onRender.call(this, ct, position);
this.el.addClass('x-tree');
this.innerCt = this.body.createChild({tag:"ul",
cls:"x-tree-root-ct " +
(this.lines ? "x-tree-lines" : "x-tree-no-lines")});
},
// private
initEvents : function(){
Ext.tree.TreePanel.superclass.initEvents.call(this);
if(this.containerScroll){
Ext.dd.ScrollManager.register(this.body);
}
if((this.enableDD || this.enableDrop) && !this.dropZone){
/**
* 若干置下有效的话,tree所用的dropZone
* @type Ext.tree.TreeDropZone
* @property dropZone
*/
this.dropZone = new Ext.tree.TreeDropZone(this, this.dropConfig || {
ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
});
}
if((this.enableDD || this.enableDrag) && !this.dragZone){
/**
* 若干拖动有效的话,tree所用的dragZone
* @type Ext.tree.TreeDragZone
* @property dragZone
*/
this.dragZone = new Ext.tree.TreeDragZone(this, this.dragConfig || {
ddGroup: this.ddGroup || "TreeDD",
scroll: this.ddScroll
});
}
this.getSelectionModel().init(this);
},
// private
afterRender : function(){
Ext.tree.TreePanel.superclass.afterRender.call(this);
this.root.render();
if(!this.rootVisible){
this.root.renderChildren();
}
},
onDestroy : function(){
if(this.rendered){
this.body.removeAllListeners();
Ext.dd.ScrollManager.unregister(this.body);
if(this.dropZone){
this.dropZone.unreg();
}
if(this.dragZone){
this.dragZone.unreg();
}
}
this.root.destroy();
this.nodeHash = null;
Ext.tree.TreePanel.superclass.onDestroy.call(this);
}
/**
* @cfg {String/Number} activeItem
* @hide
*/
/**
* @cfg {Boolean} autoDestroy
* @hide
*/
/**
* @cfg {Object/String/Function} autoLoad
* @hide
*/
/**
* @cfg {Boolean} autoWidth
* @hide
*/
/**
* @cfg {Boolean/Number} bufferResize
* @hide
*/
/**
* @cfg {String} defaultType
* @hide
*/
/**
* @cfg {Object} defaults
* @hide
*/
/**
* @cfg {Boolean} hideBorders
* @hide
*/
/**
* @cfg {Mixed} items
* @hide
*/
/**
* @cfg {String} layout
* @hide
*/
/**
* @cfg {Object} layoutConfig
* @hide
*/
/**
* @cfg {Boolean} monitorResize
* @hide
*/
/**
* @property items
* @hide
*/
/**
* @method add
* @hide
*/
/**
* @method cascade
* @hide
*/
/**
* @method doLayout
* @hide
*/
/**
* @method find
* @hide
*/
/**
* @method findBy
* @hide
*/
/**
* @method findById
* @hide
*/
/**
* @method findByType
* @hide
*/
/**
* @method getComponent
* @hide
*/
/**
* @method getLayout
* @hide
*/
/**
* @method getUpdater
* @hide
*/
/**
* @method insert
* @hide
*/
/**
* @method load
* @hide
*/
/**
* @method remove
* @hide
*/
/**
* @event add
* @hide
*/
/**
* @event afterLayout
* @hide
*/
/**
* @event beforeadd
* @hide
*/
/**
* @event beforeremove
* @hide
*/
/**
* @event remove
* @hide
*/
});
Ext.reg('treepanel', Ext.tree.TreePanel); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeDropZone
* @extends Ext.dd.DropZone
* @constructor
* @param {String/HTMLElement/Element} tree 要允许落下的{@link Ext.tree.TreePanel}
* @param {Object} config
*/
if(Ext.dd.DropZone){
Ext.tree.TreeDropZone = function(tree, config){
/**
* @cfg {Boolean} allowParentInsert
* Allow inserting a dragged node between an expanded parent node and its first child that will become a
* sibling of the parent when dropped (defaults to false)
*/
this.allowParentInsert = false;
/**
* @cfg {String} allowContainerDrop
* True if drops on the tree container (outside of a specific tree node) are allowed (defaults to false)
*/
this.allowContainerDrop = false;
/**
* @cfg {String} appendOnly
* True if the tree should only allow append drops (use for trees which are sorted, defaults to false)
*/
this.appendOnly = false;
Ext.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config);
/**
* The TreePanel for this drop zone
* @type Ext.tree.TreePanel
* @property tree
*/
this.tree = tree;
/**
* Arbitrary data that can be associated with this tree and will be included in the event object that gets
* passed to any nodedragover event handler (defaults to {})
* @type Ext.tree.TreePanel
* @property dragOverData
*/
this.dragOverData = {};
// private
this.lastInsertClass = "x-tree-no-status";
};
Ext.extend(Ext.tree.TreeDropZone, Ext.dd.DropZone, {
/**
* @cfg {String} ddGroup
* 该对象隶属于组的名称。如果已指定组,那该对象只会与同组下其他拖放成员相交互(默认为“TreeDD”)。
*/
ddGroup : "TreeDD",
/**
* @cfg {String} expandDelay
* 在拖动到一个可落下的节点时,到目标上方,距离展开树节点 等待的毫秒数。(默认为1000)
*/
expandDelay : 1000,
// private
expandNode : function(node){
if(node.hasChildNodes() && !node.isExpanded()){
node.expand(false, null, this.triggerCacheRefresh.createDelegate(this));
}
},
// private
queueExpand : function(node){
this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]);
},
// private
cancelExpand : function(){
if(this.expandProcId){
clearTimeout(this.expandProcId);
this.expandProcId = false;
}
},
// private
isValidDropPoint : function(n, pt, dd, e, data){
if(!n || !data){ return false; }
var targetNode = n.node;
var dropNode = data.node;
// default drop rules
if(!(targetNode && targetNode.isTarget && pt)){
return false;
}
if(pt == "append" && targetNode.allowChildren === false){
return false;
}
if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){
return false;
}
if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){
return false;
}
// reuse the object
var overEvent = this.dragOverData;
overEvent.tree = this.tree;
overEvent.target = targetNode;
overEvent.data = data;
overEvent.point = pt;
overEvent.source = dd;
overEvent.rawEvent = e;
overEvent.dropNode = dropNode;
overEvent.cancel = false;
var result = this.tree.fireEvent("nodedragover", overEvent);
return overEvent.cancel === false && result !== false;
},
// private
getDropPoint : function(e, n, dd){
var tn = n.node;
if(tn.isRoot){
return tn.allowChildren !== false ? "append" : false; // always append for root
}
var dragEl = n.ddel;
var t = Ext.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight;
var y = Ext.lib.Event.getPageY(e);
var noAppend = tn.allowChildren === false || tn.isLeaf();
if(this.appendOnly || tn.parentNode.allowChildren === false){
return noAppend ? false : "append";
}
var noBelow = false;
if(!this.allowParentInsert){
noBelow = tn.hasChildNodes() && tn.isExpanded();
}
var q = (b - t) / (noAppend ? 2 : 3);
if(y >= t && y < (t + q)){
return "above";
}else if(!noBelow && (noAppend || y >= b-q && y <= b)){
return "below";
}else{
return "append";
}
},
// private
onNodeEnter : function(n, dd, e, data){
this.cancelExpand();
},
// private
onNodeOver : function(n, dd, e, data){
var pt = this.getDropPoint(e, n, dd);
var node = n.node;
// auto node expand check
if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){
this.queueExpand(node);
}else if(pt != "append"){
this.cancelExpand();
}
// set the insert point style on the target node
var returnCls = this.dropNotAllowed;
if(this.isValidDropPoint(n, pt, dd, e, data)){
if(pt){
var el = n.ddel;
var cls;
if(pt == "above"){
returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between";
cls = "x-tree-drag-insert-above";
}else if(pt == "below"){
returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between";
cls = "x-tree-drag-insert-below";
}else{
returnCls = "x-tree-drop-ok-append";
cls = "x-tree-drag-append";
}
if(this.lastInsertClass != cls){
Ext.fly(el).replaceClass(this.lastInsertClass, cls);
this.lastInsertClass = cls;
}
}
}
return returnCls;
},
// private
onNodeOut : function(n, dd, e, data){
this.cancelExpand();
this.removeDropIndicators(n);
},
// private
onNodeDrop : function(n, dd, e, data){
var point = this.getDropPoint(e, n, dd);
var targetNode = n.node;
targetNode.ui.startDrop();
if(!this.isValidDropPoint(n, point, dd, e, data)){
targetNode.ui.endDrop();
return false;
}
// first try to find the drop node
var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null);
var dropEvent = {
tree : this.tree,
target: targetNode,
data: data,
point: point,
source: dd,
rawEvent: e,
dropNode: dropNode,
cancel: !dropNode
};
var retval = this.tree.fireEvent("beforenodedrop", dropEvent);
if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){
targetNode.ui.endDrop();
return false;
}
// allow target changing
targetNode = dropEvent.target;
if(point == "append" && !targetNode.isExpanded()){
targetNode.expand(false, null, function(){
this.completeDrop(dropEvent);
}.createDelegate(this));
}else{
this.completeDrop(dropEvent);
}
return true;
},
// private
completeDrop : function(de){
var ns = de.dropNode, p = de.point, t = de.target;
if(!(ns instanceof Array)){
ns = [ns];
}
var n;
for(var i = 0, len = ns.length; i < len; i++){
n = ns[i];
if(p == "above"){
t.parentNode.insertBefore(n, t);
}else if(p == "below"){
t.parentNode.insertBefore(n, t.nextSibling);
}else{
t.appendChild(n);
}
}
n.ui.focus();
if(this.tree.hlDrop){
n.ui.highlight();
}
t.ui.endDrop();
this.tree.fireEvent("nodedrop", de);
},
// private
afterNodeMoved : function(dd, data, e, targetNode, dropNode){
if(this.tree.hlDrop){
dropNode.ui.focus();
dropNode.ui.highlight();
}
this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e);
},
// private
getTree : function(){
return this.tree;
},
// private
removeDropIndicators : function(n){
if(n && n.ddel){
var el = n.ddel;
Ext.fly(el).removeClass([
"x-tree-drag-insert-above",
"x-tree-drag-insert-below",
"x-tree-drag-append"]);
this.lastInsertClass = "_noclass";
}
},
// private
beforeDragDrop : function(target, e, id){
this.cancelExpand();
return true;
},
// private
afterRepair : function(data){
if(data && Ext.enableFx){
data.node.ui.highlight();
}
this.hideProxy();
}
});
} | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.MultiSelectionModel
* @extends Ext.util.Observable
* 一个多选择区的TreePanel。
*/
Ext.tree.MultiSelectionModel = function(config){
this.selNodes = [];
this.selMap = {};
this.addEvents(
/**
* @event selectionchange
* 当选中的选区有变动时触发
* @param {MultiSelectionModel} this
* @param {Array} nodes 选中节点组成的数组
*/
"selectionchange"
);
Ext.apply(this, config);
Ext.tree.MultiSelectionModel.superclass.constructor.call(this);
};
Ext.extend(Ext.tree.MultiSelectionModel, Ext.util.Observable, {
init : function(tree){
this.tree = tree;
tree.getTreeEl().on("keydown", this.onKeyDown, this);
tree.on("click", this.onNodeClick, this);
},
onNodeClick : function(node, e){
this.select(node, e, e.ctrlKey);
},
/**
* 将节点放入选择区
* @param {TreeNode} node 要放入的节点
* @param {EventObject} e 为选择区分配的event对象
* @param {Boolean} keepExisting 如果为true,则保存选择区中已存在的节点
* @return {TreeNode} 选中的节点
*/
select : function(node, e, keepExisting){
if(keepExisting !== true){
this.clearSelections(true);
}
if(this.isSelected(node)){
this.lastSelNode = node;
return node;
}
this.selNodes.push(node);
this.selMap[node.id] = node;
this.lastSelNode = node;
node.ui.onSelectedChange(true);
this.fireEvent("selectionchange", this, this.selNodes);
return node;
},
/**
* 如果传入的节点在选择区则从中删除
* @param {TreeNode} node 待删除的节点
*/
unselect : function(node){
if(this.selMap[node.id]){
node.ui.onSelectedChange(false);
var sn = this.selNodes;
var index = sn.indexOf(node);
if(index != -1){
this.selNodes.splice(index, 1);
}
delete this.selMap[node.id];
this.fireEvent("selectionchange", this, this.selNodes);
}
},
/**
* 清理选择区中的节点
*/
clearSelections : function(suppressEvent){
var sn = this.selNodes;
if(sn.length > 0){
for(var i = 0, len = sn.length; i < len; i++){
sn[i].ui.onSelectedChange(false);
}
this.selNodes = [];
this.selMap = {};
if(suppressEvent !== true){
this.fireEvent("selectionchange", this, this.selNodes);
}
}
},
/**
* 如果节点已经在选择区中则返回true
* @param {TreeNode} node 检查的节点
* @return {Boolean}
*/
isSelected : function(node){
return this.selMap[node.id] ? true : false;
},
/**
* 返回选择区中所有的节点
* @return {Array}
*/
getSelectedNodes : function(){
return this.selNodes;
},
onKeyDown : Ext.tree.DefaultSelectionModel.prototype.onKeyDown,
selectNext : Ext.tree.DefaultSelectionModel.prototype.selectNext,
selectPrevious : Ext.tree.DefaultSelectionModel.prototype.selectPrevious
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.DefaultSelectionModel
* @extends Ext.util.Observable
* 默认是一个单选择区的TreePanel
*/
Ext.tree.DefaultSelectionModel = function(config){
this.selNode = null;
this.addEvents(
/**
* @event selectionchange
* 当选中的选区有变动时触发
* @param {DefaultSelectionModel} this
* @param {TreeNode} node 新选区
*/
"selectionchange",
/**
* @event beforeselect
* 选中的节点加载之前触发,返回false则取消。
* @param {DefaultSelectionModel} this
* @param {TreeNode} node 新选区
* @param {TreeNode} node 旧选区
*/
"beforeselect"
);
Ext.apply(this, config);
Ext.tree.DefaultSelectionModel.superclass.constructor.call(this);
};
Ext.extend(Ext.tree.DefaultSelectionModel, Ext.util.Observable, {
init : function(tree){
this.tree = tree;
tree.getTreeEl().on("keydown", this.onKeyDown, this);
tree.on("click", this.onNodeClick, this);
},
onNodeClick : function(node, e){
this.select(node);
},
/**
* Select a node. 如果该节点不在选择区,则该节点放入选择区
* @param {TreeNode} node 要选择的节点
* @return {TreeNode} 选择的节点
*/
select : function(node){
var last = this.selNode;
if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){
if(last){
last.ui.onSelectedChange(false);
}
this.selNode = node;
node.ui.onSelectedChange(true);
this.fireEvent("selectionchange", this, node, last);
}
return node;
},
/**
* 如果该节点在选择区中,则将该节点移除选择区
* @param {TreeNode} node 被移除的节点
*/
unselect : function(node){
if(this.selNode == node){
this.clearSelections();
}
},
/**
* 清空选择区,并返回选择区中的节点
*/
clearSelections : function(){
var n = this.selNode;
if(n){
n.ui.onSelectedChange(false);
this.selNode = null;
this.fireEvent("selectionchange", this, null);
}
return n;
},
/**
* 得到选择区中的节点
* @return {TreeNode} 选中的节点
*/
getSelectedNode : function(){
return this.selNode;
},
/**
* 如果节点在选择区中则返回true
* @param {TreeNode} node 待检查的节点
* @return {Boolean}
*/
isSelected : function(node){
return this.selNode == node;
},
/**
* 将选择区中的节点在这棵树中上一个节点放入选择区,而且是智能的检索。
* @return TreeNode 新选区
*/
selectPrevious : function(){
var s = this.selNode || this.lastSelNode;
if(!s){
return null;
}
var ps = s.previousSibling;
if(ps){
if(!ps.isExpanded() || ps.childNodes.length < 1){
return this.select(ps);
} else{
var lc = ps.lastChild;
while(lc && lc.isExpanded() && lc.childNodes.length > 0){
lc = lc.lastChild;
}
return this.select(lc);
}
} else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){
return this.select(s.parentNode);
}
return null;
},
/**
* 将选择区中的节点在这棵树中下一个节点放入选择区,而且是智能的检索。
* @return TreeNode 新选区
*/
selectNext : function(){
var s = this.selNode || this.lastSelNode;
if(!s){
return null;
}
if(s.firstChild && s.isExpanded()){
return this.select(s.firstChild);
}else if(s.nextSibling){
return this.select(s.nextSibling);
}else if(s.parentNode){
var newS = null;
s.parentNode.bubble(function(){
if(this.nextSibling){
newS = this.getOwnerTree().selModel.select(this.nextSibling);
return false;
}
});
return newS;
}
return null;
},
onKeyDown : function(e){
var s = this.selNode || this.lastSelNode;
// undesirable, but required
var sm = this;
if(!s){
return;
}
var k = e.getKey();
switch(k){
case e.DOWN:
e.stopEvent();
this.selectNext();
break;
case e.UP:
e.stopEvent();
this.selectPrevious();
break;
case e.RIGHT:
e.preventDefault();
if(s.hasChildNodes()){
if(!s.isExpanded()){
s.expand();
}else if(s.firstChild){
this.select(s.firstChild, e);
}
}
break;
case e.LEFT:
e.preventDefault();
if(s.hasChildNodes() && s.isExpanded()){
s.collapse();
}else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){
this.select(s.parentNode, e);
}
break;
};
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.AsyncTreeNode
* @extends Ext.tree.TreeNode
* @cfg {TreeLoader} loader 加载这个节点使用的TreeLoader(默认是加载该节点所在树的TreeLoader)
* @constructor
* @param {Object/String} attributes 该节点的属性/配置对象,也可以是带有文本的一个字符串
*/
Ext.tree.AsyncTreeNode = function(config){
this.loaded = false;
this.loading = false;
Ext.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments);
/**
* @event beforeload
* 节点加载之前触发,返回false则取消。
* @param {Node} this This node
*/
this.addEvents('beforeload', 'load');
/**
* @event load
* 此节点加载完毕后触发
* @param {Node} this This node
*/
/**
* 节点使用的Loader(默认使用tree定义的loader)
* @type Ext.tree.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);
},
/**
* 如果该节点正在被加载则返回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);
},
/**
* 如果该节点被加载过则返回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);
}
},
/**
* 重新加载该节点。
* @param {Function} callback
*/
reload : function(callback){
this.collapse(false, false);
while(this.firstChild){
this.removeChild(this.firstChild).destroy();
}
this.childrenRendered = false;
this.loaded = false;
if(this.isHiddenRoot()){
this.expanded = false;
}
this.expand(false, false, callback);
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeEventModel
* Ext.tree.TreeEventModel类。
*/
Ext.tree.TreeEventModel = function(tree){
this.tree = tree;
this.tree.on('render', this.initEvents, this);
}
Ext.tree.TreeEventModel.prototype = {
initEvents : function(){
var el = this.tree.getTreeEl();
el.on('click', this.delegateClick, this);
if(this.tree.trackMouseOver !== false){
this.tree.innerCt.on('mouseover', this.delegateOver, this);
this.tree.innerCt.on('mouseout', this.delegateOut, this);
}
el.on('dblclick', this.delegateDblClick, this);
el.on('contextmenu', this.delegateContextMenu, this);
},
getNode : function(e){
var t;
if(t = e.getTarget('.x-tree-node-el', 10)){
var id = Ext.fly(t, '_treeEvents').getAttributeNS('ext', 'tree-node-id');
if(id){
return this.tree.getNodeById(id);
}
}
return null;
},
getNodeTarget : function(e){
var t = e.getTarget('.x-tree-node-icon', 1);
if(!t){
t = e.getTarget('.x-tree-node-el', 6);
}
return t;
},
delegateOut : function(e, t){
if(!this.beforeEvent(e)){
return;
}
t = this.getNodeTarget(e);
if(t && !e.within(t, true)){
this.onNodeOut(e, this.getNode(e));
}
},
delegateOver : function(e, t){
if(!this.beforeEvent(e)){
return;
}
if(Ext.isGecko && !this.trackingDoc){ // prevent hanging in FF
Ext.getBody().on('mouseover', this.trackExit, this);
this.trackingDoc = true;
}
if(this.lastEcOver){ // prevent hung highlight
this.onIconOut(e, this.lastEcOver);
delete this.lastEcOver;
}
if(e.getTarget('.x-tree-ec-icon', 1)){
this.lastEcOver = this.getNode(e);
this.onIconOver(e, this.lastEcOver);
}
if(t = this.getNodeTarget(e)){
this.onNodeOver(e, this.getNode(e));
}
},
delegateOver : function(e, t){
if(!this.beforeEvent(e)){
return;
}
if(Ext.isGecko && !this.trackingDoc){ // prevent hanging in FF
Ext.getBody().on('mouseover', this.trackExit, this);
this.trackingDoc = true;
}
if(this.lastEcOver){ // prevent hung highlight
this.onIconOut(e, this.lastEcOver);
delete this.lastEcOver;
}
if(e.getTarget('.x-tree-ec-icon', 1)){
this.lastEcOver = this.getNode(e);
this.onIconOver(e, this.lastEcOver);
}
if(t = this.getNodeTarget(e)){
this.onNodeOver(e, this.getNode(e));
}
},
delegateClick : function(e, t){
if(!this.beforeEvent(e)){
return;
}
if(e.getTarget('input[type=checkbox]', 1)){
this.onCheckboxClick(e, this.getNode(e));
}
else if(e.getTarget('.x-tree-ec-icon', 1)){
this.onIconClick(e, this.getNode(e));
}
else if(this.getNodeTarget(e)){
this.onNodeClick(e, this.getNode(e));
}
},
delegateDblClick : function(e, t){
if(this.beforeEvent(e) && this.getNodeTarget(e)){
this.onNodeDblClick(e, this.getNode(e));
}
},
delegateContextMenu : function(e, t){
if(this.beforeEvent(e) && this.getNodeTarget(e)){
this.onNodeContextMenu(e, this.getNode(e));
}
},
onNodeClick : function(e, node){
node.ui.onClick(e);
},
onNodeOver : function(e, node){
this.lastOverNode = node;
node.ui.onOver(e);
},
onNodeOut : function(e, node){
node.ui.onOut(e);
},
onIconClick : function(e, node){
node.ui.ecClick(e);
},
onCheckboxClick : function(e, node){
node.ui.onCheckChange(e);
},
onNodeDblClick : function(e, node){
node.ui.onDblClick(e);
},
onNodeContextMenu : function(e, node){
node.ui.onContextMenu(e);
},
beforeEvent : function(e){
if(this.disabled){
e.stopEvent();
return false;
}
return true;
},
disable: function(){
this.disabled = true;
},
enable: function(){
this.disabled = false;
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeLoader
* @extends Ext.util.Observable
* 树加载器(TreeLoader)的目的是从URL延迟加载树节点{@link Ext.tree.TreeNode}的子节点。
* 返回值必须是以树格式的javascript数组。例如:<br />
* A TreeLoader provides for lazy loading of an {@link Ext.tree.TreeNode}'s child
* nodes from a specified URL. The response must be a JavaScript Array definition
* whose elements are node definition objects. eg:
* <pre><code>
[{
id: 1,
text: 'A leaf Node',
leaf: true
},{
id: 2,
text: 'A folder Node',
children: [{
id: 3,
text: 'A child Node',
leaf: true
}]
}]
</code></pre>
* <br><br>
* 向服务端发送请求后,只有当展开时才会读取子节点信息。需要取值的节点id被传到服务端并用于产生正确子节点。<br />
* A server request is sent, and child nodes are loaded only when a node is expanded.
* The loading node's id is passed to the server under the parameter name "node" to
* enable the server to produce the correct child nodes.
* <br><br>
* 当需要传递更多的参数时,可以把一个事件句柄邦定在"beforeload"事件上,然后把数据放到TreeLoader的baseParams属性上:<br />
* To pass extra parameters, an event handler may be attached to the "beforeload"
* event, and the parameters specified in the TreeLoader's baseParams property:
* <pre><code>
myTreeLoader.on("beforeload", function(treeLoader, node) {
this.baseParams.category = node.attributes.category;
}, this);
</code></pre>
* 如上代码,将会传递一个该节点的,名为"category"的参数到服务端上。<br />
* This would pass an HTTP parameter called "category" to the server containing
* the value of the Node's "category" attribute.
* @constructor 创建一个Treeloader。Creates a new Treeloader.
* @param {Object} config 该Treeloader的配置属性。A config object containing config properties.
*/
Ext.tree.TreeLoader = function(config){
this.baseParams = {};
Ext.apply(this, config);
this.addEvents(
/**
* @event beforeload
* 在为子节点获取JSON文本进行网路请求之前触发。
* Fires before a network request is made to retrieve the Json text which specifies a node's children.
* @param {Object} tree 本TreeLoader对象。This TreeLoader object.
* @param {Object} node 已加载好的{@link Ext.tree.TreeNode}的对象。The {@link Ext.tree.TreeNode} object being loaded.
* @param {Object} callback 在{@link #load}调用中指定的回调函数。The callback function specified in the {@link #load} call.
*/
"beforeload",
/**
* @event load
* 当节点加载成功时触发。
* Fires when the node has been successfuly loaded.
* @param {Object} tree 本TreeLoader对象。This TreeLoader object.
* @param {Object} node 已加载好的{@link Ext.tree.TreeNode}的对象。The {@link Ext.tree.TreeNode} object being loaded.
* @param {Object} response 服务器响应的数据对象。The response object containing the data from the server.
*/
"load",
/**
* @event loadexception
* 当网路连接失败时触发。
* Fires if the network request failed.
* @param {Object} tree 本TreeLoader对象。This TreeLoader object.
* @param {Object} node 已加载好的{@link Ext.tree.TreeNode}的对象。The {@link Ext.tree.TreeNode} object being loaded.
* @param {Object} response 服务器响应的数据对象。The response object containing the data from the server.
*/
"loadexception"
);
Ext.tree.TreeLoader.superclass.constructor.call(this);
};
Ext.extend(Ext.tree.TreeLoader, Ext.util.Observable, {
/**
* @cfg {String} dataUrl 进行请求的URL。URL处返回节点对象的序列,表示要加载的子节点。
* The URL from which to request a Json string which
* specifies an array of node definition objects representing the child nodes
* to be loaded.
*/
/**
* @cfg {String} requestMethod 下载数据的HTTP请求方法(默认{@link Ext.Ajax#method}的值)。
* The HTTP request method for loading data (defaults to the value of {@link Ext.Ajax#method}).
*/
/**
* @cfg {String} url 相当于{@link #dataUrl}。
* Equivalent to {@link #dataUrl}.
*/
/**
* @cfg {Boolean} preloadChildren 若为true,则loader在节点第一次访问时加载"children"的属性。
* If set to true, the loader recursively loads "children" attributes when doing the first load on nodes.
*/
/**
* @cfg {Object} baseParams (可选的)一个分别对每个节点进行参数传递的集合对象。
* (optional) An object containing properties which
* specify HTTP parameters to be passed to each request for child nodes.
*/
/**
* @cfg {Object} baseAttrs (可选)一个对所有节点进行参数传递的集合对象。如果已经传递这个参数了,则他们优先。
* (optional)An object containing attributes to be added to all nodes
* created by this loader. If the attributes sent by the server have an attribute in this object,
* they take priority.
*/
/**
* @cfg {Object} uiProviders (可选的)一个针对制定节点{@link Ext.tree.TreeNodeUI}进行参数传递的集合对象。
* 如果传入了该<i>uiProvider</i>参数,返回string而非TreeNodeUI对象。
* (optional) An object containing properties which
* specify custom {@link Ext.tree.TreeNodeUI} implementations. If the optional
* <i>uiProvider</i> attribute of a returned child node is a string rather
* than a reference to a TreeNodeUI implementation, then that string value
* is used as a property name in the uiProviders object.
*/
uiProviders : {},
/**
* @cfg {Boolean} clearOnLoad (可选)默认为true。在读取数据前移除已存在的节点。
* (optional) Default to true. Remove previously existing
* child nodes before loading.
*/
clearOnLoad : true,
/**
* 从URL中读取树节点{@link Ext.tree.TreeNode}。
* 本函数在节点展开时自动调用,但也可以被用于reload节点(或是在{@link #clearOnLoad}属性为false时增加新节点)。
* Load an {@link Ext.tree.TreeNode} from the URL specified in the constructor.
* This is called automatically when a node is expanded, but may be used to reload
* a node (or append new children if the {@link #clearOnLoad} option is false.)
* @param {Ext.tree.TreeNode} node
* @param {Function} callback
*/
load : function(node, callback){
if(this.clearOnLoad){
while(node.firstChild){
node.removeChild(node.firstChild);
}
}
if(this.doPreload(node)){ // preloaded json children
if(typeof callback == "function"){
callback();
}
}else if(this.dataUrl||this.url){
this.requestData(node, callback);
}
},
doPreload : function(node){
if(node.attributes.children){
if(node.childNodes.length < 1){ // preloaded?
var cs = node.attributes.children;
node.beginUpdate();
for(var i = 0, len = cs.length; i < len; i++){
var cn = node.appendChild(this.createNode(cs[i]));
if(this.preloadChildren){
this.doPreload(cn);
}
}
node.endUpdate();
}
return true;
}else {
return false;
}
},
getParams: function(node){
var buf = [], bp = this.baseParams;
for(var key in bp){
if(typeof bp[key] != "function"){
buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&");
}
}
buf.push("node=", encodeURIComponent(node.id));
return buf.join("");
},
requestData : function(node, callback){
if(this.fireEvent("beforeload", this, node, callback) !== false){
this.transId = Ext.Ajax.request({
method:this.requestMethod,
url: this.dataUrl||this.url,
success: this.handleResponse,
failure: this.handleFailure,
scope: this,
argument: {callback: callback, node: node},
params: this.getParams(node)
});
}else{
// if the load is cancelled, make sure we notify
// the node that we are done
if(typeof callback == "function"){
callback();
}
}
},
isLoading : function(){
return !!this.transId;
},
abort : function(){
if(this.isLoading()){
Ext.Ajax.abort(this.transId);
}
},
/**
* <p>
* 覆盖此函数以自定义TreeNode的节点,或在创建的时刻修改节点的属性
* Override this function for custom TreeNode node implementation, or to
* modify the attributes at creation time.</p>
* Example:<code><pre>
new Ext.tree.TreePanel({
...
new Ext.tree.TreeLoader({
url: 'dataUrl',
createNode: function(attr) {
// 允许合并项用拖动就可两项合并在一起
// Allow consolidation consignments to have
// consignments dropped into them.
if (attr.isConsolidation) {
attr.iconCls = 'x-consol',
attr.allowDrop = true;
}
return Ext.tree.TreeLoader.prototype.call(this, attr);
}
}),
...
});
</pre></code>
* @param {Object} attr 创建新节点的属性。The attributes from which to create the new node.
*/
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);
}
if(attr.nodeType){
return new Ext.tree.TreePanel.nodeTypes[attr.nodeType](attr);
}else{
return attr.leaf ?
new Ext.tree.TreeNode(attr) :
new Ext.tree.AsyncTreeNode(attr);
}
},
processResponse : function(response, node, callback){
var json = response.responseText;
try {
var o = eval("("+json+")");
node.beginUpdate();
for(var i = 0, len = o.length; i < len; i++){
var n = this.createNode(o[i]);
if(n){
node.appendChild(n);
}
}
node.endUpdate();
if(typeof callback == "function"){
callback(this, node);
}
}catch(e){
this.handleFailure(response);
}
},
handleResponse : function(response){
this.transId = false;
var a = response.argument;
this.processResponse(response, a.node, a.callback);
this.fireEvent("load", this, a.node, response);
},
handleFailure : function(response){
this.transId = false;
var a = response.argument;
this.fireEvent("loadexception", this, a.node, response);
if(typeof a.callback == "function"){
a.callback(this, a.node);
}
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeNode
* @extends Ext.data.Node
* @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;
/**
* @cfg {String} text jhj该节点所显示的文本。The text for this node
*/
,text:null
/**
* @cfg {Boolean} expanded 如果为"true",该节点被展开。true to start the node expanded
*/
,expanded:null
/**
* @cfg {Boolean} allowDrag 如果dd为on时,设置为fals将使得该节点不能拖拽。False to make this node undraggable if {@link #draggable} = true (defaults to true)
*/
,allowDrag:null
/**
* @cfg {Boolean} allowDrop 为false时该节点不能将拖拽的对象放在该节点下。False if this node cannot have child nodes dropped on it (defaults to true)
*/
,allowDrop:null
/**
* @cfg {Boolean} disabled 为true该节点被禁止。true to start the node disabled
*/
,allowDrop:null
/**
* @cfg {String} icon 设置该节点上图标的路径.这种方式是首选的,比使用cls或iconCls属性和为这个图标加一个CSS的background-image都好。 The path to an icon for the node. The preferred way to do this
* is to use the cls or iconCls attributes and add the icon via a CSS background image.
*/
,allowDrop:null
/**
* @cfg {String} cls 为该节点设置css样式类。A css class to be added to the node
*/
,allowDrop:null
/**
* @cfg {String} iconCls 为该节点上的图标元素应用背景。 A css class to be added to the nodes icon element for applying css background images
*/
,allowDrop:null
/**
* @cfg {String} href 设置该节点url连接(默认是#)。 URL of the link used for the node (defaults to #)
*/
,allowDrop:null
/**
* @cfg {String} hrefTarget 设置该连接应用到那个frame。 target frame for the link
*/
,allowDrop:null
/**
* @cfg {Boolean} hidden True表示一开始就隐藏(默认为false)。True to render hidden. (Defaults to false).
*/
,allowDrop:null
/**
* @cfg {String} qtip 该节点设置用于提示的文本。An Ext QuickTip for the node
*/
,allowDrop:null
/**
* @cfg {Boolean} expandable If set to true, the node will always show a plus/minus icon, even when empty
*/
,allowDrop:null
/**
* @cfg {String} qtipCfg 为该节点设置QuickTip类(用于替换qtip属性)。An Ext QuickTip config for the node (used instead of qtip)
*/
,allowDrop:null
/**
* @cfg {Boolean} singleClickExpand 为true时当节点被单击时展开。 True for single click expand on this node
*/
,allowDrop:null
/**
* @cfg {Function} uiProvider 该节点所使用的UI类(默认时Ext.tree.TreeNodeUI)。 A UI <b>class</b> to use for this node (defaults to Ext.tree.TreeNodeUI)
*/
,allowDrop:null
/**
* @cfg {Boolean} checked 为true将为该节点添加checkbox选择框,为false将不添加(默认为undefined是不添加checkbox的)。True to render a checked checkbox for this node, false to render an unchecked checkbox
* (defaults to undefined with no checkbox rendered)
*/
,allowDrop:null
/**
* @cfg {Boolean} draggable True表示该节点可以拖动的(默认为false)。True to make this node draggable (defaults to false)
*/
,allowDrop:null
/**
* @cfg {Boolean} isTarget False表示该节点不能够充当置落地点的用途(默认为true)。False to not allow this node to act as a drop target (defaults to true)
*/
,allowDrop:null
/**
* @cfg {Boolean} allowChildren Flase表示该节点不允许有子节点(默认为true)。False to not allow this node to have child nodes (defaults to true)
*/
,allowDrop:null
/**
* @cfg {Boolean} editable False表示该节点不能够编辑的。{@link Ext.tree.TreeEditor}不能用(默认为true)。False to not allow this node to be edited by an {@link Ext.tree.TreeEditor} (defaults to true)
*/
,allowDrop:null
/**
* 只读属性,该节点所显示的文本.可以用setText方法改变。
* Read-only. The text for this node. To change it use setText().
* @type String
* @property text
*/
this.text = attributes.text;
/**
* 如果该节点为disabled那为true。
* True if this node is disabled.
* @type Boolean
* @property disabled
*/
this.disabled = attributes.disabled === true;
/**
* True表示该节点市隐藏的。
* True if this node is hidden.
* @type Boolean
* @property hidden
*/
this.hidden = attributes.hidden === true;
this.addEvents(
/**
* @event textchange
* 当这个节点的显示文本被改变时触发。
* Fires when the text for this node is changed
* @param {Node} this 该节点。This node
* @param {String} text 新的文本。The new text
* @param {String} oldText 以前的文本。The old text
*/
"textchange",
/**
* @event beforeexpand
* 当该节点被展开之前触发,返回false将取消事件。
* Fires before this node is expanded, return false to cancel.
* @param {Node} this 该节点。This node
* @param {Boolean} deep 该节点当前是否也展开所有子节点的状态。
* @param {Boolean} anim 该节点当前是否启用动画效果的状态。
*/
"beforeexpand",
/**
* @event beforecollapse
* 当该节点被收回之前触发,返回false将取消事件。
* Fires before this node is collapsed, return false to cancel.
* @param {Node} this This node
* @param {Boolean} deep 该节点当前是否也展开所有子节点的状态。
* @param {Boolean} anim 该节点当前是否启用动画效果的状态。
*/
"beforecollapse",
/**
* @event expand
* 当该节点被展开时触发。
* Fires when this node is expanded
* @param {Node} this 该节点。This node
*/
"expand",
/**
* @event disabledchange
* 当该节点的disabled状态被改变时触发。
* Fires when the disabled status of this node changes
* @param {Node} this 该节点。This node
* @param {Boolean} disabled 该节点的disabled属性的状态。
*/
"disabledchange",
/**
* @event collapse
* 当该节点被收回时触发。
* Fires when this node is collapsed
* @param {Node} this 该节点。This node
*/
"collapse",
/**
* @event beforeclick
* 单击处理之前触发,返回false将停止默认的动作。
* Fires before click processing. Return false to cancel the default action.
* @param {Node} this 该节点。This node
* @param {Ext.EventObject} e 事件对象。The event object
*/
"beforeclick",
/**
* @event click
* 当节点被点击时触发。
* Fires when this node is clicked
* @param {Node} this 该节点。This node
* @param {Ext.EventObject} e 事件对象。The event object
*/
"click",
/**
* @event checkchange
* 当节点的checkbox的状态被改变时触发。
* Fires when a node with a checkbox's checked property changes
* @param {Node} this 该节点。 This node
* @param {Boolean} checked 当前节点checkbox的状态。
*/
"checkchange",
/**
* @event dblclick
* 当节点被双点击时触发。
* Fires when this node is double clicked
* @param {Node} this 该节点。This node
* @param {Ext.EventObject} e 事件对象。The event object
*/
"dblclick",
/**
* @event contextmenu
* 当该节点被右击的时候触发。
* Fires when this node is right clicked
* @param {Node} this 该节点。This node
* @param {Ext.EventObject} e 事件对象。The event object
*/
"contextmenu",
/**
* @event beforechildrenrendered
* 当节点的子节点被渲染之前触发。
* Fires right before the child nodes for this node are rendered
* @param {Node} this 该节点。This node
*/
"beforechildrenrendered"
);
var uiClass = this.attributes.uiProvider || this.defaultUI || Ext.tree.TreeNodeUI;
/**
* 这个节点的UI。
* Read-only. The UI for this node
* @type TreeNodeUI
* @property ui
*/
this.ui = new uiClass(this);
};
Ext.extend(Ext.tree.TreeNode, Ext.data.Node, {
preventHScroll: true,
/**
* 如果该节点被展开则返回true。
* Returns true if this node is expanded
* @return {Boolean}
*/
isExpanded : function(){
return this.expanded;
},
/**
* 返回该节点的UI对象。
* Returns the UI object for this node.
* @return {TreeNodeUI} 树节点的用户界面对象。除非有另外指定{@link #uiProvider},否则这就是一个{@link Ext.tree.TreeNodeUI}实例。
* The object which is providing the user interface for this tree
* node. Unless otherwise specified in the {@link #uiProvider}, this will be an instance
* of {@link Ext.tree.TreeNodeUI}
*/
getUI : function(){
return this.ui;
},
getLoader : function(){
var owner;
return this.loader || ((owner = this.getOwnerTree()) && owner.loader ? owner.loader : new Ext.tree.TreeLoader());
},
// private override
setFirstChild : function(node){
var of = this.firstChild;
Ext.tree.TreeNode.superclass.setFirstChild.call(this, node);
if(this.childrenRendered && of && node != of){
of.renderIndent(true, true);
}
if(this.rendered){
this.renderIndent(true, true);
}
},
// private override
setLastChild : function(node){
var ol = this.lastChild;
Ext.tree.TreeNode.superclass.setLastChild.call(this, node);
if(this.childrenRendered && ol && node != ol){
ol.renderIndent(true, true);
}
if(this.rendered){
this.renderIndent(true, true);
}
},
// these methods are overridden to provide lazy rendering support
// private override
appendChild : function(n){
if(!n.render && !Ext.isArray(n)){
n = this.getLoader().createNode(n);
}
var node = Ext.tree.TreeNode.superclass.appendChild.call(this, n);
if(node && this.childrenRendered){
node.render();
}
this.ui.updateExpandIcon();
return node;
},
// private override
removeChild : function(node){
this.ownerTree.getSelectionModel().unselect(node);
Ext.tree.TreeNode.superclass.removeChild.apply(this, arguments);
// if it's been rendered remove dom node
if(this.childrenRendered){
node.ui.remove();
}
if(this.childNodes.length < 1){
this.collapse(false, false);
}else{
this.ui.updateExpandIcon();
}
if(!this.firstChild && !this.isHiddenRoot()) {
this.childrenRendered = false;
}
return node;
},
// private override
insertBefore : function(node, refNode){
if(!node.render){
node = this.getLoader().createNode(node);
}
var newNode = Ext.tree.TreeNode.superclass.insertBefore.call(this, node, refNode);
if(newNode && refNode && this.childrenRendered){
node.render();
}
this.ui.updateExpandIcon();
return newNode;
},
/**
* 设置该节点的显示文本。
* Sets the text for this node
* @param {String} text
*/
setText : function(text){
var oldText = this.text;
this.text = text;
this.attributes.text = text;
if(this.rendered){ // event without subscribing
this.ui.onTextChange(this, text, oldText);
}
this.fireEvent("textchange", this, text, oldText);
},
/**
* 选取该节点所在树选择的选区模型。
* Triggers selection of this node
*/
select : function(){
this.getOwnerTree().getSelectionModel().select(this);
},
/**
* 取消选择该节点所在树的选区模型。
* Triggers deselection of this node
*/
unselect : function(){
this.getOwnerTree().getSelectionModel().unselect(this);
},
/**
* 如果该节点被选中则返回true。
* Returns true if this node is selected
* @return {Boolean}
*/
isSelected : function(){
return this.getOwnerTree().getSelectionModel().isSelected(this);
},
/**
* 展开这个节点。
* Expand this node.
* @param {Boolean} deep (可选的)如果为true展开所有的子节点。(optional)True to expand all children as well
* @param {Boolean} anim (可选的)如果为false不启用动画效果。(optional)false to cancel the default animation
* @param {Function} callback 当展开完成时调用这个callback(不等待所有子节点都展开完成后才执行)。调用带有一个参数,就是该节点。
* (optional)A callback to be called when expanding this node completes (does not wait for deep expand to complete).
* Called with 1 parameter, this node.
*/
expand : function(deep, anim, callback){
if(!this.expanded){
if(this.fireEvent("beforeexpand", this, deep, anim) === false){
return;
}
if(!this.childrenRendered){
this.renderChildren();
}
this.expanded = true;
if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){
this.ui.animExpand(function(){
this.fireEvent("expand", this);
if(typeof callback == "function"){
callback(this);
}
if(deep === true){
this.expandChildNodes(true);
}
}.createDelegate(this));
return;
}else{
this.ui.expand();
this.fireEvent("expand", this);
if(typeof callback == "function"){
callback(this);
}
}
}else{
if(typeof callback == "function"){
callback(this);
}
}
if(deep === true){
this.expandChildNodes(true);
}
},
isHiddenRoot : function(){
return this.isRoot && !this.getOwnerTree().rootVisible;
},
/**
* 展开该节点。
* Collapse this node.
* @param {Boolean} deep (可选的)为true则也展开所有的子结点。(optional)True to collapse all children as well
* @param {Boolean} anim (可选的)如果为false不启用动画效果。(optional)false to cancel the default animation
*/
collapse : function(deep, anim){
if(this.expanded && !this.isHiddenRoot()){
if(this.fireEvent("beforecollapse", this, deep, anim) === false){
return;
}
this.expanded = false;
if((this.getOwnerTree().animate && anim !== false) || anim){
this.ui.animCollapse(function(){
this.fireEvent("collapse", this);
if(deep === true){
this.collapseChildNodes(true);
}
}.createDelegate(this));
return;
}else{
this.ui.collapse();
this.fireEvent("collapse", this);
}
}
if(deep === true){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].collapse(true, false);
}
}
},
// private
delayedExpand : function(delay){
if(!this.expandProcId){
this.expandProcId = this.expand.defer(delay, this);
}
},
// private
cancelExpand : function(){
if(this.expandProcId){
clearTimeout(this.expandProcId);
}
this.expandProcId = false;
},
/**
* 轮回该节点的展开/收回状态。
* Toggles expanded/collapsed state of the node
*/
toggle : function(){
if(this.expanded){
this.collapse();
}else{
this.expand();
}
},
/**
* 确保所有的父节点都被展开了(没理解这个函数的作用)。
* Ensures all parent nodes are expanded, and if necessary, scrolls the node into view.
* @param {Function} callback (可选的)节点隐藏后调用的函数。(optional) A function to call when the node has been made visible.
*/
ensureVisible : function(callback){
var tree = this.getOwnerTree();
tree.expandPath(this.parentNode ? this.parentNode.getPath() : this.getPath(), false, function(){
var node = tree.getNodeById(this.id); // Somehow if we don't do this, we lose changes that happened to node in the meantime
tree.getTreeEl().scrollChildIntoView(node.ui.anchor);
Ext.callback(callback);
}.createDelegate(this));
},
/**
* 展开所有的子节点。
* Expand all child nodes
* @param {Boolean} deep 如果为true,子节点如果还有子节点也将被展开。(optional)true if the child nodes should also expand their child nodes
*/
expandChildNodes : function(deep){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].expand(deep);
}
},
/**
* 收回所有的子节点。
* Collapse all child nodes
* @param {Boolean} deep 如果为true,子节点如果还有子节点也将被收回。(optional)true if the child nodes should also collapse their child nodes
*/
collapseChildNodes : function(deep){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].collapse(deep);
}
},
/**
* 禁用这个节点。
* Disables this node
*/
disable : function(){
this.disabled = true;
this.unselect();
if(this.rendered && this.ui.onDisableChange){ // event without subscribing
this.ui.onDisableChange(this, true);
}
this.fireEvent("disabledchange", this, true);
},
/**
* 启用该节点。
* Enables this node
*/
enable : function(){
this.disabled = false;
if(this.rendered && this.ui.onDisableChange){ // event without subscribing
this.ui.onDisableChange(this, false);
}
this.fireEvent("disabledchange", this, false);
},
// private
renderChildren : function(suppressEvent){
if(suppressEvent !== false){
this.fireEvent("beforechildrenrendered", this);
}
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++){
cs[i].render(true);
}
this.childrenRendered = true;
},
// private
sort : function(fn, scope){
Ext.tree.TreeNode.superclass.sort.apply(this, arguments);
if(this.childrenRendered){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++){
cs[i].render(true);
}
}
},
// private
render : function(bulkRender){
this.ui.render(bulkRender);
if(!this.rendered){
// make sure it is registered
this.getOwnerTree().registerNode(this);
this.rendered = true;
if(this.expanded){
this.expanded = false;
this.expand(false, false);
}
}
},
// private
renderIndent : function(deep, refresh){
if(refresh){
this.ui.childIndent = null;
}
this.ui.renderIndent();
if(deep === true && this.childrenRendered){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++){
cs[i].renderIndent(true, refresh);
}
}
},
beginUpdate : function(){
this.childrenRendered = false;
},
endUpdate : function(){
if(this.expanded && this.rendered){
this.renderChildren();
}
},
destroy : function(){
if(this.childNodes){
for(var i = 0,l = this.childNodes.length; i < l; i++){
this.childNodes[i].destroy();
}
this.childNodes = null;
}
if(this.ui.destroy){
this.ui.destroy();
}
},
// private
onIdChange: function(id){
this.ui.onIdChange(id);
}
});
Ext.tree.TreePanel.nodeTypes.node = Ext.tree.TreeNode; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeSorter
* 提供一个可排序节点的Tree面板。
* @cfg {Boolean} folderSort 设置为真时则同级的叶节点排在
* @cfg {String} property 用节点上的那个属性排序(默认是text属性)
* @cfg {String} dir 排序的方式(升序或降序)(默认时升序)
* @cfg {String} leafAttr 叶子节点在目录排序中的属性(defaults to "leaf")
* @cfg {Boolean} caseSensitive 排序时大小写敏感(默认时false)
* @cfg {Function} sortType 在排序之前可以写一个强转函数用来转换节点的值
* @constructor
* @param {TreePanel} tree
* @param {Object} config
*/
Ext.tree.TreeSorter = function(tree, config){
Ext.apply(this, config);
tree.on("beforechildrenrendered", this.doSort, this);
tree.on("append", this.updateSort, this);
tree.on("insert", this.updateSort, this);
var dsc = this.dir && this.dir.toLowerCase() == "desc";
var p = this.property || "text";
var sortType = this.sortType;
var fs = this.folderSort;
var cs = this.caseSensitive === true;
var leafAttr = this.leafAttr || 'leaf';
this.sortFn = function(n1, n2){
if(fs){
if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){
return 1;
}
if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){
return -1;
}
}
var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase());
var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase());
if(v1 < v2){
return dsc ? +1 : -1;
}else if(v1 > v2){
return dsc ? -1 : +1;
}else{
return 0;
}
};
};
Ext.tree.TreeSorter.prototype = {
doSort : function(node){
node.sort(this.sortFn);
},
compareNodes : function(n1, n2){
return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1);
},
updateSort : function(tree, node){
if(node.childrenRendered){
this.doSort.defer(1, this, [node]);
}
}
}; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.RootTreeNodeUI
* This class provides the default UI implementation for <b>root</b> Ext TreeNodes.
* The RootTreeNode UI implementation allows customizing the appearance of the root tree node.<br>
* <p>
* If you are customizing the Tree's user interface, you
* may need to extend this class, but you should never need to instantiate this class.<br>
*/
Ext.tree.RootTreeNodeUI = Ext.extend(Ext.tree.TreeNodeUI, {
// private
render : function(){
if(!this.rendered){
var targetNode = this.node.ownerTree.innerCt.dom;
this.node.expanded = true;
targetNode.innerHTML = '<div class="x-tree-root-node"></div>';
this.wrap = this.ctNode = targetNode.firstChild;
}
},
collapse : Ext.emptyFn,
expand : Ext.emptyFn
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.tree.TreeDragZone
* @extends Ext.dd.DragZone
* @constructor
* @param {String/HTMLElement/Element} tree 要进行拖动的{@link Ext.tree.TreePanel}
* @param {Object} config 配置项对象
*/
if(Ext.dd.DragZone){
Ext.tree.TreeDragZone = function(tree, config){
Ext.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config);
/**
* The TreePanel for this drag zone
* @type Ext.tree.TreePanel
* @property tree
*/
this.tree = tree;
};
Ext.extend(Ext.tree.TreeDragZone, Ext.dd.DragZone, {
/**
* @cfg {String} ddGroup
* 该对象隶属于组的名称。如果已指定组,那该对象只会与同组下其他拖放成员相交互(默认为“TreeDD”)。
*/
ddGroup : "TreeDD",
// private
onBeforeDrag : function(data, e){
var n = data.node;
return n && n.draggable && !n.disabled;
},
// private
onInitDrag : function(e){
var data = this.dragData;
this.tree.getSelectionModel().select(data.node);
this.tree.eventModel.disable();
this.proxy.update("");
data.node.ui.appendDDGhost(this.proxy.ghost.dom);
this.tree.fireEvent("startdrag", this.tree, data.node, e);
},
// private
getRepairXY : function(e, data){
return data.node.ui.getDDRepairXY();
},
// private
onEndDrag : function(data, e){
this.tree.eventModel.enable.defer(100, this.tree.eventModel);
this.tree.fireEvent("enddrag", this.tree, data.node, e);
},
// private
onValidDrop : function(dd, e, id){
this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e);
this.hideProxy();
},
// private
beforeInvalidDrop : function(e, id){
// this scrolls the original position back into view
var sm = this.tree.getSelectionModel();
sm.clearSelections();
sm.select(this.dragData.node);
}
});
} | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.ColorPalette
* @extends Ext.Component
* 选择颜色使用的简单的调色板。调色板可在任意窗口内渲染。
* Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
* 这里是一个典型用例:Here's an example of typical usage:
* <pre><code>
var cp = new Ext.ColorPalette({value:'993300'}); // 初始化时选中的颜色 initial selected color
cp.render('my-div');
cp.on('select', function(palette, selColor){
// 用selColor来做此事情 do something with selColor
});
</code></pre>
* @constructor 创建一个ColorPalette对象。Create a new ColorPalette
* @param {Object} config 配置项对象 The config object
*/
Ext.ColorPalette = function(config){
Ext.ColorPalette.superclass.constructor.call(this, config);
this.addEvents(
/**
* @event select
* 颜色被选取时触发。
* Fires when a color is selected
* @param {ColorPalette} this
* @param {String} color 6位16进制颜色编码(没有#符号)。The 6-digit color hex code (without the # symbol)
*/
'select'
);
if(this.handler){
this.on("select", this.handler, this.scope, true);
}
};
Ext.extend(Ext.ColorPalette, Ext.Component, {
/**
* @cfg {String} tpl 用于渲染该组件的XTemplate字符串。
* An existing XTemplate instance to be used in place of the default template for rendering the component.
*/
/**
* @cfg {String} itemCls 容器元素应用的 CSS 样式类(默认为 "x-color-palette")。
* The CSS class to apply to the containing element (defaults to "x-color-palette")
*/
itemCls : "x-color-palette",
/**
* @cfg {String} value
* 初始化时高亮的颜色(必须为不包含 # 符号的6位16进制颜色编码)。注意16进制编码是区分大小写的。
* The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
* the hex codes are case-sensitive.
*/
value : null,
clickEvent:'click',
// private
ctype: "Ext.ColorPalette",
/**
* @cfg {Boolean} allowReselect 如果值为 true,则在触发{@link #select}事件时重选已经选择的颜色。
* If set to true then reselecting a color that is already selected fires the {@link #select} event
*/
allowReselect : false,
/**
* <p>一个由6位16进制颜色编码组成的数组(不包含#符号)。此数组可以包含任意个数颜色,
* 且每个16进制编码必须是唯一的。调色板的宽度可以通过设置样式表中的'x-color-palette'类的width属性来控制(或者指定一个制定的类),
* 因此你可以通过调整颜色的个数和调色板的宽度来使调色板保持对称。
* An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
* of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
* the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
* of colors with the width setting until the box is symmetrical.</p>
* <p>你可以根据需要覆写单个的颜色: You can override individual colors if needed:</p>
* <pre><code>
var cp = new Ext.ColorPalette();
cp.colors[0] = "FF0000"; // 把第一个选框换成红色 change the first box to red
</code></pre>
或者自己提供一个定制的数组来实现完全控制: Or you can provide a custom array of your own for complete control:
<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 = this.tpl || new Ext.XTemplate(
'<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on"> </span></em></a></tpl>'
);
var el = document.createElement("div");
el.id = this.getId();
el.className = this.itemCls;
t.overwrite(el, this.colors);
container.dom.insertBefore(el, position);
this.el = Ext.get(el);
this.mon(this.el, this.clickEvent, this.handleClick, this, {delegate: 'a'});
if(this.clickEvent != 'click'){
this.mon(this.el, '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());
}
},
/**
* 在调色板中选择指定的颜色(触发{@link #select}事件)。
* Selects the specified color in the palette (fires the {@link #select} event)
* @param {String} color 6位16进制颜色编码(如果含有#符号则自动舍去)。A valid 6-digit color hex code (# will be stripped if included)
*/
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);
}
}
/**
* @cfg {String} autoEl @hide
*/
});
Ext.reg('colorpalette', Ext.ColorPalette); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Tip
* @extends Ext.Panel
* 这是 {@link Ext.QuickTip} 和 {@link Ext.Tooltip} 对象的基类,提供了所有基于提示的类所必须的基础布局和定位。
* 这个类可以直接用于简单的、静态定位、需要编程显示的提示,还可以提供实现自定义扩展的提示。
* @constructor
* 创建一个 Tip 对象
* @param {Object} config 配置选项对象
*/
Ext.Tip = Ext.extend(Ext.Panel, {
/**
* @cfg {Boolean} closable 值为 true 则在工具提示的头部渲染一个关闭按钮(默认为 false)。
*/
/**
* @cfg {Number} minWidth 以像素为单位表示的提示的最小宽度(默认为 40)。
*/
minWidth : 40,
/**
* @cfg {Number} maxWidth 以像素为单位表示的提示的最大宽度(默认为 300)。
*/
maxWidth : 300,
/**
* @cfg {Boolean/String} shadow 值为 true 或者 "sides" 时展现默认效果,值为 "frame" 时则在4个方向展现阴影,值为 "drop" 时则在右下角展现阴影(默认为 "sides")。
*/
shadow : "sides",
/**
* @cfg {String} defaultAlign <b>试验性的</b>。默认为 {@link Ext.Element#alignTo} 锚点定位值,用来让该提示定位到它所属元素的关联位置(默认为 "tl-bl?")。
*/
defaultAlign : "tl-bl?",
autoRender: true,
quickShowInterval : 250,
// private panel overrides
frame:true,
hidden:true,
baseCls: 'x-tip',
floating:{shadow:true,shim:true,useDisplay:true,constrain:false},
autoHeight:true,
closeAction: 'hide',
// private
initComponent : function(){
Ext.Tip.superclass.initComponent.call(this);
if(this.closable && !this.title){
this.elements += ',header';
}
},
// private
afterRender : function(){
Ext.Tip.superclass.afterRender.call(this);
if(this.closable){
this.addTool({
id: 'close',
handler: this[this.closeAction],
scope: this
});
}
},
/**
* 在指定的 XY 坐标处显示该提示。用法示例:
* <pre><code>
// 在 x:50、y:100 处显示提示
tip.showAt([50,100]);
</code></pre>
* @param {Array} xy 一个由 x、y 坐标组成的数组
*/
showAt : function(xy){
Ext.Tip.superclass.show.call(this);
if(this.measureWidth !== false && (!this.initialConfig || typeof this.initialConfig.width != 'number')){
var bw = this.body.getTextWidth();
if(this.title){
bw = Math.max(bw, this.header.child('span').getTextWidth(this.title));
}
bw += this.getFrameWidth() + (this.closable ? 20 : 0) + this.body.getPadding("lr");
this.setWidth(bw.constrain(this.minWidth, this.maxWidth));
}
if(this.constrainPosition){
xy = this.el.adjustForConstraints(xy);
}
this.setPagePosition(xy[0], xy[1]);
},
/**
* <b>试验性的</b>。根据标准的 {@link Ext.Element#alignTo} 锚点定位值在另一个元素的关联位置上显示该提示。用法示例:
* <pre><code>
// 在默认位置显示该提示 ('tl-br?')
tip.showBy('my-el');
// 将该提示的左上角对齐到元素的右上角
tip.showBy('my-el', 'tl-tr');
</code></pre>
* @param {Mixed} el 一个 HTMLElement、Ext.Element 或者要对齐的目标元素的 ID 文本
* @param {String} position (可选)一个有效的 {@link Ext.Element#alignTo} 锚点定位值(默认为 'tl-br?' 或者 {@link #defaultAlign} 中指定的值,如果设置过该值的话)。
*/
showBy : function(el, pos){
if(!this.rendered){
this.render(Ext.getBody());
}
this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign));
},
initDraggable : function(){
this.dd = new Ext.Tip.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable);
this.header.addClass('x-tip-draggable');
}
});
// private - custom Tip DD implementation
Ext.Tip.DD = function(tip, config){
Ext.apply(this, config);
this.tip = tip;
Ext.Tip.DD.superclass.constructor.call(this, tip.el.id, 'WindowDD-'+tip.id);
this.setHandleElId(tip.header.id);
this.scroll = false;
};
Ext.extend(Ext.Tip.DD, Ext.dd.DD, {
moveOnly:true,
scroll:false,
headerOffsets:[100, 25],
startDrag : function(){
this.tip.el.disableShadow();
},
endDrag : function(e){
this.tip.el.enableShadow(true);
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.QuickTip
* @extends Ext.ToolTip
* 一个专门的tooltip类 for tooltips that can be specified in markup and automatically managed by the 全局
* {@link Ext.QuickTips} instance. 更多信息请参看QuickTips类 header for 附带的例子和详细用法.
* @constructor
* 创建一个新提示
* @param {Object} config 配置选项
*/
Ext.QuickTip = Ext.extend(Ext.ToolTip, {
/**
* @cfg {Mixed} target 目标HTML元素,与这个quicktip相关联的Ext.Element或id (默认为document).
*/
/**
* @cfg {Boolean} interceptTitles为True表示如果DOM的title值可用时则使用此值 (默认为false).
*/
interceptTitles : false,
// 私有
tagConfig : {
namespace : "ext",
attribute : "qtip",
width : "qwidth",
target : "target",
title : "qtitle",
hide : "hide",
cls : "qclass",
align : "qalign"
},
// 私有
initComponent : function(){
this.target = this.target || Ext.getDoc();
this.targets = this.targets || {};
Ext.QuickTip.superclass.initComponent.call(this);
},
/**
* 配置一个新的quick tip实例并将其分配到一个目标元素.支持下列各项配置值
* (用法参见 {@link Ext.QuickTips} 类的header):
* <div class="mdetail-params"><ul>
* <li>autoHide</li>
* <li>cls</li>
* <li>dismissDelay (overrides the singleton value)</li>
* <li>target (required)</li>
* <li>text (required)</li>
* <li>title</li>
* <li>width</li></ul></div>
* @param {Object} config 配置对象
*/
register : function(config){
var cs = config instanceof Array ? config : arguments;
for(var i = 0, len = cs.length; i < len; i++){
var c = cs[i];
var target = c.target;
if(target){
if(target instanceof Array){
for(var j = 0, jlen = target.length; j < jlen; j++){
this.targets[Ext.id(target[j])] = c;
}
} else{
this.targets[Ext.id(target)] = c;
}
}
}
},
/**
* 从元素中移除quick tip并且销毁它.
* @param {String/HTMLElement/Element} el 将要被移除的quick tip的所属元素
*/
unregister : function(el){
delete this.targets[Ext.id(el)];
},
// 私有
onTargetOver : function(e){
if(this.disabled){
return;
}
this.targetXY = e.getXY();
var t = e.getTarget();
if(!t || t.nodeType !== 1 || t == document || t == document.body){
return;
}
if(this.activeTarget && t == this.activeTarget.el){
this.clearTimer('hide');
this.show();
return;
}
if(t && this.targets[t.id]){
this.activeTarget = this.targets[t.id];
this.activeTarget.el = t;
this.delayShow();
return;
}
var ttp, et = Ext.fly(t), cfg = this.tagConfig;
var ns = cfg.namespace;
if(this.interceptTitles && t.title){
ttp = t.title;
t.qtip = ttp;
t.removeAttribute("title");
e.preventDefault();
} else{
ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute);
}
if(ttp){
var autoHide = et.getAttributeNS(ns, cfg.hide);
this.activeTarget = {
el: t,
text: ttp,
width: et.getAttributeNS(ns, cfg.width),
autoHide: autoHide != "user" && autoHide !== 'false',
title: et.getAttributeNS(ns, cfg.title),
cls: et.getAttributeNS(ns, cfg.cls),
align: et.getAttributeNS(ns, cfg.align)
};
this.delayShow();
}
},
// 私有
onTargetOut : function(e){
this.clearTimer('show');
if(this.autoHide !== false){
this.delayHide();
}
},
// 继承文档
showAt : function(xy){
var t = this.activeTarget;
if(t){
if(!this.rendered){
this.render(Ext.getBody());
}
if(t.width){
this.setWidth(t.width);
this.measureWidth = false;
} else{
this.measureWidth = true;
}
this.setTitle(t.title || '');
this.body.update(t.text);
this.autoHide = t.autoHide;
this.dismissDelay = t.dismissDelay || this.dismissDelay;
if(this.lastCls){
this.el.removeClass(this.lastCls);
delete this.lastCls;
}
if(t.cls){
this.el.addClass(t.cls);
this.lastCls = t.cls;
}
if(t.align){ // TODO: this doesn't seem to work consistently
xy = this.el.getAlignToXY(t.el, t.align);
this.constrainPosition = false;
} else{
this.constrainPosition = true;
}
}
Ext.QuickTip.superclass.showAt.call(this, xy);
},
// 继承文档
hide: function(){
delete this.activeTarget;
Ext.QuickTip.superclass.hide.call(this);
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.ToolTip
* @extends Ext.Tip
* 一个标准的快捷提示实现,用于悬浮在目标元素之上时出现的提示信息。
* @constructor
* 建立快捷提示新对象
* @param {Object} config 配置项对象
*/
Ext.ToolTip = Ext.extend(Ext.Tip, {
/**
* @cfg {Mixed} target HTMLElement目标元素,既可是Ext.Element或是与这个快捷提示相关联的id。
*/
/**
* @cfg {Boolean} autoHide
* 值为 true 时在鼠标移出目标元素自动隐藏快捷提示(默认为 true)。与{@link #dismissDelay}协同生效(默认为true)。
* 若{@link closable},一个关闭的按钮会出现在快捷提示的开头。
*/
/**
* @cfg {Number} showDelay
* 以毫秒表示的当鼠标进入目标元素后显示快捷提示的延迟时间(默认为 500)
*/
showDelay: 500,
/**
* @cfg {Number} hideDelay
* 以毫秒表示的隐藏快捷提示的延迟时间。设置为0立即隐藏快捷提示。
*/
hideDelay: 200,
/**
* @cfg {Number} dismissDelay
* 以毫秒表示的隐藏快捷提示的延迟时间, 仅在 autoDismiss = true 时生效(默认为 5000)。要禁止隐藏,设置dismissDelay = 0
*/
dismissDelay: 5000,
/**
* @cfg {Array} mouseOffset Tooltip显示时,距离鼠标位置一定的XY偏移(默认[15,18])。
*/
mouseOffset: [15,18],
/**
* @cfg {Boolean} trackMouse 值为 true 时当鼠标经过目标对象时快捷提示将跟随鼠标移动(默认为 false)
*/
trackMouse : false,
constrainPosition: true,
// private
initComponent: function(){
Ext.ToolTip.superclass.initComponent.call(this);
this.lastActive = new Date();
this.initTarget();
},
// private
initTarget : function(){
if(this.target){
this.target = Ext.get(this.target);
this.mon(this.target, {
mouseover: this.onTargetOver,
mouseout: this.onTargetOut,
mousemove: this.onMouseMove,
scope: this
})
}
},
// private
onMouseMove : function(e){
this.targetXY = e.getXY();
if(!this.hidden && this.trackMouse){
this.setPagePosition(this.getTargetXY());
}
},
// private
getTargetXY : function(){
return [this.targetXY[0]+this.mouseOffset[0], this.targetXY[1]+this.mouseOffset[1]];
},
// private
onTargetOver : function(e){
if(this.disabled || e.within(this.target.dom, true)){
return;
}
this.clearTimer('hide');
this.targetXY = e.getXY();
this.delayShow();
},
// private
delayShow : function(){
if(this.hidden && !this.showTimer){
if(this.lastActive.getElapsed() < this.quickShowInterval){
this.show();
}else{
this.showTimer = this.show.defer(this.showDelay, this);
}
}else if(!this.hidden && this.autoHide !== false){
this.show();
}
},
// private
onTargetOut : function(e){
if(this.disabled || e.within(this.target.dom, true)){
return;
}
this.clearTimer('show');
if(this.autoHide !== false){
this.delayHide();
}
},
// private
delayHide : function(){
if(!this.hidden && !this.hideTimer){
this.hideTimer = this.hide.defer(this.hideDelay, this);
}
},
/**
* 隐藏快捷提示。
*/
hide: function(){
this.clearTimer('dismiss');
this.lastActive = new Date();
Ext.ToolTip.superclass.hide.call(this);
},
/**
* 在当前事件对象XY的位置上显示快捷提示。
*
*/
show : function(){
this.showAt(this.getTargetXY());
},
// inherit docs
showAt : function(xy){
this.lastActive = new Date();
this.clearTimers();
Ext.ToolTip.superclass.showAt.call(this, xy);
if(this.dismissDelay && this.autoHide !== false){
this.dismissTimer = this.hide.defer(this.dismissDelay, this);
}
},
// private
clearTimer : function(name){
name = name + 'Timer';
clearTimeout(this[name]);
delete this[name];
},
// private
clearTimers : function(){
this.clearTimer('show');
this.clearTimer('dismiss');
this.clearTimer('hide');
},
// private
onShow : function(){
Ext.ToolTip.superclass.onShow.call(this);
Ext.getDoc().on('mousedown', this.onDocMouseDown, this);
},
// private
onHide : function(){
Ext.ToolTip.superclass.onHide.call(this);
Ext.getDoc().un('mousedown', this.onDocMouseDown, this);
},
// private
onDocMouseDown : function(e){
if(this.autoHide !== false && !e.within(this.el.dom)){
this.disable();
this.enable.defer(100, this);
}
},
// private
onDisable : function(){
this.clearTimers();
this.hide();
},
// private
adjustPosition : function(x, y){
// keep the position from being under the mouse
var ay = this.targetXY[1], h = this.getSize().height;
if(this.constrainPosition && y <= ay && (y+h) >= ay){
y = ay-h-5;
}
return {x : x, y: y};
},
// private
onDestroy : function(){
Ext.ToolTip.superclass.onDestroy.call(this);
if(this.target){
this.target.un('mouseover', this.onTargetOver, this);
this.target.un('mouseout', this.onTargetOut, this);
this.target.un('mousemove', this.onMouseMove, this);
}
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.QuickTips
* <p>为所有元素提供有吸引力和可定制的工具提示。QuickTips 是一个单态(singleton)类,被用来为多个元素的提示进行通用地、全局地配置和管理。
* 想要最大化地定制一个工具提示,你可以考虑使用 {@link Ext.Tip} 或者 {@link Ext.ToolTip}。</p>
* <p>Quicktips 对象可以直接通过标签的属性来配置,或者在程序中通过 {@link #register} 方法注册提示。</p>
* <p>单态的 {@link Ext.QuickTip} 对象实例可以通过 {@link #getQuickTip} 方法得到,并且提供所有的方法和所有 Ext.QuickTip 对象中的配置属性。
* 这些设置会被应用于所有显示的工具提示。</p>
* <p>下面是可用的配置属性的汇总。详细的说明可以参见 {@link #getQuickTip}</p>
* <p><b>QuickTips 单态配置项(所有均为可选项)</b></p>
* <div class="mdetail-params"><ul><li>dismissDelay</li>
* <li>hideDelay</li>
* <li>maxWidth</li>
* <li>minWidth</li>
* <li>showDelay</li>
* <li>trackMouse</li></ul></div>
* <p><b>目标元素配置项(除有说明的均为可选项)</b></p>
* <div class="mdetail-params"><ul><li>autoHide</li>
* <li>cls</li>
* <li>dismissDelay (将覆写单态同名选项值)</li>
* <li>target (必须)</li>
* <li>text (必须)</li>
* <li>title</li>
* <li>width</li></ul></div>
* <p>下面是一个用来说明其中的一些配置选项如何使用的例子:</p>
* <pre><code>
// 初始化单态类。所有基于标签的提示将开始启用。
Ext.QuickTips.init();
// 应用配置选项到对象上
Ext.apply(Ext.QuickTips.getQuickTip(), {
maxWidth: 200,
minWidth: 100,
showDelay: 50,
trackMouse: true
});
// 手动注册一个工具提示到指定的元素上
Ext.QuickTips.register({
target: 'my-div',
title: 'My Tooltip',
text: 'This tooltip was added in code',
width: 100,
dismissDelay: 20
});
</code></pre>
* <p>在标签中注册一个快捷提示,只需要简单地一个或多个有效的 QuickTip 属性并加上 <b>ext:</b> 作为命名空间前缀。
* HTML 元素自身将自动地被设置为快捷提示的目标。下面是可用的属性的汇总(除有说明的均为可选项):</p>
* <ul><li><b>hide</b>:指定为 "user" 等同于设置 autoHide = false。其他任何值则相当于 autoHide = true。</li>
* <li><b>qclass</b>:应用于快捷提示的 CSS 类(等同于目标元素中的 'cls' 配置)。</li>
* <li><b>qtip (必须)</b>:快捷提示的文本(等同于目标元素中的 'text' 配置)。</li>
* <li><b>qtitle</b>:快捷提示的标题(等同于目标元素中的 'title' 配置)。</li>
* <li><b>qwidth</b>:快捷提示的宽度(等同于目标元素中的 'width' 配置)。</li></ul>
* <p>下面是一个说明如何通过使用标签在 HTML 元素上显示快捷提示的例子:</p>
* <pre><code>
// 往一个 HTML 的按钮中添加快捷提示
<input type="button" value="OK" ext:qtitle="OK Button" ext:qwidth="100"
ext:qtip="This is a quick tip from markup!"></input>
</code></pre>
* @singleton
*/
Ext.QuickTips = function(){
var tip, locks = [];
return {
/**
* 初始化全局 QuickTips 实例
*/
init : function(){
if(!tip){
tip = new Ext.QuickTip({elements:'header,body'});
}
},
/**
* 打开全局快速提示功能.
*/
enable : function(){
if(tip){
locks.pop();
if(locks.length < 1){
tip.enable();
}
}
},
/**
* 关闭全局快速提示功能.
*/
disable : function(){
if(tip){
tip.disable();
}
locks.push(1);
},
/**
* 获取一个值,该值指示此quick tips是否可以对用户交互作出响应。
* @return {Boolean}
*/
isEnabled : function(){
return tip && !tip.disabled;
},
/**
* 获得全局QuickTips实例.
*/
getQuickTip : function(){
return tip;
},
/**
* 配置一个新的quick tip实例并将其分配到一个目标元素. 详细信息请查看
* {@link Ext.QuickTip#register}.
* @param {Object} config 配置对象
*/
register : function(){
tip.register.apply(tip, arguments);
},
/**
* 从目标元素中移除并销毁所有已注册的quick tip
* @param {String/HTMLElement/Element} el 将要被移除的quick tip的所属元素.
*/
unregister : function(){
tip.unregister.apply(tip, arguments);
},
/**
* {@link #register}的别名.
* @param {Object} config 配置对象
*/
tips :function(){
tip.register.apply(tip, arguments);
}
}
}(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.CycleButton
* @extends Ext.SplitButton
* 一个包含{@link Ext.menu.CheckItem}元素的特殊分割按钮。
* 按钮会在点击时自动循环选中每个菜单项,并以该项为活动项触发按钮的{@link #change}事件(或者调用按钮的{@link #changeHandler}函数,如果设置过的话)。
* 通过点击箭头区域即可像普通分割按钮那样显示下拉列表。使用示例:
* A specialized SplitButton that contains a menu of {@link Ext.menu.CheckItem} elements. The button automatically
* cycles through each menu item on click, raising the button's {@link #change} event (or calling the button's
* {@link #changeHandler} function, if supplied) for the active menu item. Clicking on the arrow section of the
* button displays the dropdown menu just like a normal SplitButton. Example usage:
* <pre><code>
var btn = new Ext.CycleButton({
showText: true,
prependText: 'View as ',
items: [{
text:'text only',
iconCls:'view-text',
checked:true
},{
text:'HTML',
iconCls:'view-html'
}],
changeHandler:function(btn, item){
Ext.Msg.alert('Change View', item.text);
}
});
</code></pre>
* @constructor 创建一个分割按钮。Create a new split button
* @param {Object} config 配置选项对象。The config object
*/
Ext.CycleButton = Ext.extend(Ext.SplitButton, {
/**
* @cfg {Array} items 一个由{@link Ext.menu.CheckItem} <b>config配置项</b>对象组成的数组,用来创建按钮的菜单项(例如:{text:'Foo', iconCls:'foo-icon'})。
* An array of {@link Ext.menu.CheckItem} <b>config</b> objects to be used when creating the
* button's menu items (e.g., {text:'Foo', iconCls:'foo-icon'})
*/
/**
* @cfg {Boolean} showText 值为 True 时则将活动项的文本显示为按钮的文本(默认为 false)。
* True to display the active item's text as the button text (defaults to false)
*/
/**
* @cfg {String} prependText 当没有活动项时按钮显示的文本(仅仅当 showText = true 时有效,默认为 '')。
* A static string to prepend before the active item's text when displayed as the
* button's text (only applies when showText = true, defaults to '')
*/
/**
* @cfg {Function} changeHandler 每次改变活动项时被调用的函数。
* 如果没有指定该配置项,则分割按钮将触发活动项的{@link #change}事件。
* 调用该函数时将携带下列参数:(SplitButton this, Ext.menu.CheckItem item)。
* A callback function that will be invoked each time the active menu
* item in the button's menu has changed. If this callback is not supplied, the SplitButton will instead
* fire the {@link #change} event on active item change. The changeHandler function will be called with the
* following argument list: (SplitButton this, Ext.menu.CheckItem item)
*/
/**
* @cfg {String} forceIcon 对该按钮设置图标,利用了CSS背景图的方法。无论下拉菜单选择了哪一项都会显示这个图标。该项覆盖了原有改变按钮图标原来适应选择项图标的做法。
* A css class which sets an image to be used as the static icon for this button. This
* icon will always be displayed regardless of which item is selected in the dropdown list. This overrides the
* default behavior of changing the button's icon to match the selected item's icon on change.
*/
// private
getItemText : function(item){
if(item && this.showText === true){
var text = '';
if(this.prependText){
text += this.prependText;
}
text += item.text;
return text;
}
return undefined;
},
/**
* 设置按钮的活动菜单项。
* Sets the button's active menu item.
* @param {Ext.menu.CheckItem} item 被设置的活动项。The item to activate
* @param {Boolean} suppressEvent 值为True时阻止触发按钮的change事件(默认为false)。True to prevent the button's change event from firing (defaults to false)
*/
setActiveItem : function(item, suppressEvent){
if(typeof item != 'object'){
item = this.menu.items.get(item);
}
if(item){
if(!this.rendered){
this.text = this.getItemText(item);
this.iconCls = item.iconCls;
}else{
var t = this.getItemText(item);
if(t){
this.setText(t);
}
this.setIconClass(item.iconCls);
}
this.activeItem = item;
if(!item.checked){
item.setChecked(true, true);
}
if(this.forceIcon){
this.setIconClass(this.forceIcon);
}
if(!suppressEvent){
this.fireEvent('change', this, item);
}
}
},
/**
* 获取当前活动菜单项。
* Gets the currently active menu item.
* @return {Ext.menu.CheckItem} 活动项。The active item
*/
getActiveItem : function(){
return this.activeItem;
},
// private
initComponent : function(){
this.addEvents(
/**
* @event change
* 在按钮的活动项改变之后触发。
* 注意,如果按钮指定了{@link #changeHandler}函数,则会调用该函数而不触发此事件。
* Fires after the button's active menu item has changed. Note that if a {@link #changeHandler} function
* is set on this CycleButton, it will be called instead on active item change and this change event will
* not be fired.
* @param {Ext.CycleButton} this
* @param {Ext.menu.CheckItem} item 选中的菜单项。The menu item that was selected
*/
"change"
);
if(this.changeHandler){
this.on('change', this.changeHandler, this.scope||this);
delete this.changeHandler;
}
this.itemCount = this.items.length;
this.menu = {cls:'x-cycle-menu', items:[]};
var checked;
for(var i = 0, len = this.itemCount; i < len; i++){
var item = this.items[i];
item.group = item.group || this.id;
item.itemIndex = i;
item.checkHandler = this.checkHandler;
item.scope = this;
item.checked = item.checked || false;
this.menu.items.push(item);
if(item.checked){
checked = item;
}
}
this.setActiveItem(checked, true);
Ext.CycleButton.superclass.initComponent.call(this);
this.on('click', this.toggleSelected, this);
},
// private
checkHandler : function(item, pressed){
if(pressed){
this.setActiveItem(item);
}
},
/**
* 通常情况下该函数仅仅被内部调用,但也可以在外部调用使得按钮将活动项指向菜单中的下一个选项。
* 如果当前项是菜单中的最后一项,则活动项会被设置为菜单中的第一项。
* This is normally called internally on button click, but can be called externally to advance the button's
* active item programmatically to the next one in the menu. If the current item is the last one in the menu
* the active item will be set to the first item in the menu.
*/
toggleSelected : function(){
this.menu.render();
var nextIdx, checkItem;
for (var i = 1; i < this.itemCount; i++) {
nextIdx = (this.activeItem.itemIndex + i) % this.itemCount;
// check the potential item
checkItem = this.menu.items.itemAt(nextIdx);
// if its not disabled then check it.
if (!checkItem.disabled) {
checkItem.setChecked(true);
break;
}
}
}
});
Ext.reg('cycle', Ext.CycleButton); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.TextArea
* @extends Ext.form.TextField
* 多行文本域。可以直接用于替代textarea,支持自动调整大小。 <br />
* Multiline text field.
* Can be used as a direct replacement for traditional textarea fields, plus adds support for auto-sizing.
* @constructor 创建一个新的TextArea对象 Creates a new TextArea
* @param {Object} config 配置选项 Configuration options
*/
Ext.form.TextArea = Ext.extend(Ext.form.TextField, {
/**
* @cfg {Number} growMin 当grow = true时允许的高度下限(默认为60)
* The minimum height to allow when grow = true (defaults to 60)
*/
growMin : 60,
/**
* @cfg {Number} growMax 当grow = true时允许的高度上限(默认为1000)
* The maximum height to allow when grow = true (defaults to 1000)
*/
growMax: 1000,
growAppend : ' \n ',
growPad : 0,
enterIsSpecial : false,
/**
* @cfg {Boolean} preventScrollbars 为True时在为本域中将禁止滑动条,不论域中文本的数量(相当于设置overflow为hidden,默认值为false)。
* True to prevent scrollbars from appearing regardless of how much text is in the field (equivalent to setting overflow: hidden, defaults to false)
*/
preventScrollbars: false,
/**
* @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为{tag: "textarea", style: "width:100px;height:60px;", autocomplete: "off"}。
* A DomHelper element spec, or true for a default element spec (defaults to {tag: "textarea", style: "width:100px;height:60px;", autocomplete: "off"})
*/
// private
onRender : function(ct, position){
if(!this.el){
this.defaultAutoCreate = {
tag: "textarea",
style:"width:100px;height:60px;",
autocomplete: "off"
};
}
Ext.form.TextArea.superclass.onRender.call(this, ct, position);
if(this.grow){
this.textSizeEl = Ext.DomHelper.append(document.body, {
tag: "pre", cls: "x-form-grow-sizer"
});
if(this.preventScrollbars){
this.el.setStyle("overflow", "hidden");
}
this.el.setHeight(this.growMin);
}
},
onDestroy : function(){
if(this.textSizeEl){
Ext.removeNode(this.textSizeEl);
}
Ext.form.TextArea.superclass.onDestroy.call(this);
},
fireKey : function(e){
if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){
this.fireEvent("specialkey", this, e);
}
},
// private
onKeyUp : function(e){
if(!e.isNavKeyPress() || e.getKey() == e.ENTER){
this.autoSize();
}
Ext.form.TextArea.superclass.onKeyUp.call(this, e);
},
/**
* 自动适应文本行数,直到所设置的最大行数。仅当grow = true时触发自适应高度事件。若高度发送变化就会触发{@link #autosize}事件
* Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
* This only takes effect if grow = true, and fires the {@link #autosize} event if the height changes.
*/
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 += this.growAppend;
}
ts.innerHTML = v;
var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin)+this.growPad);
if(h != this.lastHeight){
this.lastHeight = h;
this.el.setHeight(h);
this.fireEvent("autosize", this, h);
}
}
});
Ext.reg('textarea', Ext.form.TextArea); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.TimeField
* @extends Ext.form.ComboBox
* 提供一个带有下拉框和自动时间验证的时间输入框。 <br />
* Provides a time input field with a time dropdown and automatic time validation. Example usage:
* <pre><code>
new Ext.form.TimeField({
minValue: '9:00 AM',
maxValue: '6:00 PM',
increment: 30
});
</code></pre>
* @constructor 创建新的TimeField对象 Create a new TimeField
* @param {Object} config 参数
*/
Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, {
/**
* @cfg {Date/String} minValue
* 允许输入的最早的时间。可以是JavaScript Date对象,也可以是一个格式正确的字符串,请参阅{@link #format}和{@link #altFormats}(默认为null)。
* The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
* time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to null).
*/
minValue : null,
/**
* @cfg {Date/String} maxValue
* 允许输入的最晚时间。可以是JavaScriptDate对象,也可以是一个格式正确的字符串,请参阅{@link #format}和{@link #altFormats}(默认为null)。
* The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
* time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to null).
*/
maxValue : null,
/**
* @cfg {String} minText
* 单元格里的时间早于限定的最早时间的错误信息(默认为:'The time in this field must be equal to or after {0}')。
* The error text to display when the date in the cell is before minValue (defaults to 'The time in this field must be equal to or after {0}').
*/
minText : "The time in this field must be equal to or after {0}",
/**
* @cfg {String} maxText
* 单元格里的时间晚于限定的最早时间的错误信息(默认为:'The time in this field must be equal to or before {0}')。
* The error text to display when the time is after maxValue (defaults to 'The time in this field must be equal to or before {0}').
*/
maxText : "The time in this field must be equal to or before {0}",
/**
* @cfg {String} invalidText
* 单元格里的时间不符合格式的错误信息(默认:'m/d/y'的格式)。
* 默认为: The error text to display when the time in the field is invalid (defaults to'{value} is not a valid time').
*/
invalidText : "{0} is not a valid time",
/**
* @cfg {String} format
* 默认的字符串时间的格式,可以被覆盖以支持本地化。表示此格式的该字符串必须符合{@link Date#parseDate}(默认为'g:i A', e.g., '3:15 PM')。
* The default time format string which can be overriden for localization support. The format must be
* valid according to {@link Date#parseDate} (defaults to 'g:i A', e.g., '3:15 PM'). For 24-hour time
* format try 'H:i' instead.
*/
format : "g:i A",
/**
* @cfg {String} altFormats
* 当用户输入数值时对输入数值解析的每一个“段落”,每个“段落”就用这个“|”符号分隔。(默认为'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H')
* Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
* format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H').
*/
altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H",
/**
* @cfg {Number} increment
* 下拉框里显示时间的步长(默认为15分钟)。PS:数字的单位是分钟。
* The number of minutes between each time value in the list (defaults to 15).
*/
increment: 15,
// private override
mode: 'local',
// private override
triggerAction: 'all',
// private override
typeAhead: false,
// private - This is the date to use when generating time values in the absence of either minValue
// or maxValue. Using the current date causes DST issues on DST boundary dates, so this is an
// arbitrary "safe" date that can be any date aside from DST boundary dates.
initDate: '1/1/2008',
// private
initComponent : function(){
Ext.form.TimeField.superclass.initComponent.call(this);
if(typeof this.minValue == "string"){
this.minValue = this.parseDate(this.minValue);
}
if(typeof this.maxValue == "string"){
this.maxValue = this.parseDate(this.maxValue);
}
if(!this.store){
var min = this.parseDate(this.minValue);
if(!min){
min = new Date(this.initDate).clearTime();
}
var max = this.parseDate(this.maxValue);
if(!max){
max = new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1);
}
var times = [];
while(min <= max){
times.push([min.dateFormat(this.format)]);
min = min.add('mi', this.increment);
}
this.store = new Ext.data.ArrayStore({
fields: ['text'],
data : times
});
this.displayField = 'text';
}
},
// inherited docs
getValue : function(){
var v = Ext.form.TimeField.superclass.getValue.call(this);
return this.formatDate(this.parseDate(v)) || '';
},
// inherited docs
setValue : function(value){
Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value)));
},
// private overrides
validateValue : Ext.form.DateField.prototype.validateValue,
parseDate : Ext.form.DateField.prototype.parseDate,
formatDate : Ext.form.DateField.prototype.formatDate,
// private
beforeBlur : function(){
var v = this.parseDate(this.getRawValue());
if(v){
this.setValue(v.dateFormat(this.format));
}
}
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
/**
* @hide
* @method autoSize
*/
});
Ext.reg('timefield', Ext.form.TimeField); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.Hidden
* @extends Ext.form.Field
* 用于存放表单里需要被传递到后台的隐藏值得隐藏域。<br />
* A basic hidden field for storing hidden values in forms that need to be passed in the form submit.
* @constructor 生成一个隐藏字段。Create a new Hidden field.
* @param {Object} config 配置项 Configuration options
*/
Ext.form.Hidden = Ext.extend(Ext.form.Field, {
// private
inputType : 'hidden',
// private
onRender : function(){
Ext.form.Hidden.superclass.onRender.apply(this, arguments);
},
// private
initEvents : function(){
this.originalValue = this.getValue();
},
// These are all private overrides
setSize : Ext.emptyFn,
setWidth : Ext.emptyFn,
setHeight : Ext.emptyFn,
setPosition : Ext.emptyFn,
setPagePosition : Ext.emptyFn,
markInvalid : Ext.emptyFn,
clearInvalid : Ext.emptyFn
});
Ext.reg('hidden', Ext.form.Hidden); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.Radio
* @extends Ext.form.Checkbox
* 单个的radio按钮。与Checkbox类似,提供一种简便,自动的输入方式。如果你给radio按钮组中的每个按钮相同的名字(属性name值相同),按钮组会自动被浏览器编组。<br />
* Single radio field.Same as Checkbox, but provided as a convenience for automatically setting the input type.
* Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
* @constructor 创建一个新的radio按钮对象 Creates a new Radio
* @param {Object} config 配置选项 Configuration options
*/
Ext.form.Radio = Ext.extend(Ext.form.Checkbox, {
inputType: 'radio',
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
markInvalid : Ext.emptyFn,
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
clearInvalid : Ext.emptyFn,
/**
* 如果该radio是组的一部分,将返回已选中的值。
* If this radio is part of a group, it will return the selected value
* @return {String}
*/
getGroupValue : function(){
var p = this.el.up('form') || Ext.getBody();
var c = p.child('input[name='+this.el.dom.name+']:checked', true);
return c ? c.value : null;
},
// private
onClick : function(){
if(this.el.dom.checked != this.checked){
var p = this.el.up('form') || Ext.getBody();
var els = p.select('input[name='+this.el.dom.name+']');
els.each(function(el){
if(el.dom.id == this.id){
this.setValue(true);
}else{
Ext.getCmp(el.dom.id).setValue(false);
}
}, this);
}
},
/**
* 设置该Radio的checked/unchecked状态,
* 或者是这样的一种情况,送入一个字符串,检查旁边的与这个字符串同名的check状态是否选中,来设置本身是否选中。
* Sets either the checked/unchecked status of this Radio, or, if a string value
* is passed, checks a sibling Radio of the same name whose value is the value specified.
* @param {String/Boolean} value是否选中,或者旁边Raido的字符串。Checked value, or the value of the sibling radio button to check.
*/
setValue : function(v){
if (typeof v == 'boolean') {
Ext.form.Radio.superclass.setValue.call(this, v);
} else {
var r = this.el.up('form').child('input[name='+this.el.dom.name+'][value='+v+']', true);
if (r){
r.checked = true;
};
}
}
});
Ext.reg('radio', Ext.form.Radio);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.CheckboxGroup
* @extends Ext.form.Field
* {@link Ext.form.Checkbox}控制器的分组容器。<br />
* A grouping container for {@link Ext.form.Checkbox} controls.
* @constructor
* 创建一个新的 CheckboxGroup。
* Creates a new CheckboxGroup
* @param {Object} config 配置选项。Configuration options
* @xtype checkboxgroup
*/
Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
/**
* @cfg {Array} items 一个{@link Ext.form.Checkbox Checkbox}的数组,或者配置选项。
* An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects
* to arrange in the group.
*/
/**
* @cfg {String/Number/Array} columns 使用自动布局显示 checkbox/radio 组的时候使用的列的数目,这个配置选项可以有多种不同的类型的值。
* <ul><li><b>'auto'</b> : <p class="sub-desc"> 渲染的时候,组件会一列挨着一列,每一列的宽度按照整行的宽度均分。默认的是auto </p></li>
*
* <li><b>Number</b> : <p class="sub-desc"> 如果你指定了一个像 3 这样的数字,那么将会创建指定的数目的列,包含的组建将会根据{@link #vertical}的值
* 自动的分发。</p></li>
*
* <li><b>Array</b> : Object<p class="sub-desc"> 你也可以指定一个整形和浮点型的数字组成的数组来表示各个列的宽度,比如[100, .25, .75]。
* Any integer values will be rendered first,
* 所有的整数型值会被先用来渲染,然后剩下的浮点型值将会被当做剩下的空间的百分比来计算。虽然不用使数据里的浮点型的值的和为一(100%),
* 但是如果你想要让组件填充满容器,你应该是他们的和为一。</p></li></ul>
*
* Specifies the number of columns to use when displaying grouped
* checkbox/radio controls using automatic layout. This config can take several types of values:
* <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width
* of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>
* <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be
* created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>
* <li><b>Array</b> : Object<p class="sub-desc">You can also specify an array of column widths, mixing integer
* (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
* be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
* values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
* container you should do so.</p></li></ul>
*/
columns : 'auto',
/**
* @cfg {Boolean} vertical 如果设置为 true,将包含的组件跨列分发,每一行从头到底完全填充。自动计算每一列的组件的数量以使每一列尽量平衡。
* 默认为 false,每次每一列仅添加一个组件。每一行从头到尾完全填充。
* True to distribute contained controls across columns, completely filling each column
* top to bottom before starting on the next column. The number of controls in each column will be automatically
* calculated to keep columns as even as possible. The default value is false, so that controls will be added
* to columns one at a time, completely filling each row left to right before starting on the next row.
*/
vertical : false,
/**
* @cfg {Boolean} allowBlank 是否允许为空。false则至少要有一个选项被选中,如果没有被选中的选项,会显示{@link @blankText}的错误信息。默认为 true。
* False to validate that at least one item in the group is checked (defaults to true).
* If no items are selected at validation time, {@link @blankText} will be used as the error text.
*/
allowBlank : true,
/**
* @cfg {String} blankText {@link #allowBlank} 验证失败显示的错误信息。默认为:"You must select at least one item in this group"。
* Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
* select at least one item in this group")
*/
blankText : "You must select at least one item in this group",
// 私有的
defaultType : 'checkbox',
// 私有的
groupCls: 'x-form-check-group',
// 私有的
onRender : function(ct, position){
if(!this.el){
var panelCfg = {
cls: this.groupCls,
layout: 'column',
border: false,
renderTo: ct
};
var colCfg = {
defaultType: this.defaultType,
layout: 'form',
border: false,
defaults: {
hideLabel: true,
anchor: '100%'
}
}
if(this.items[0].items){
// The container has standard ColumnLayout configs, so pass them in directly
Ext.apply(panelCfg, {
layoutConfig: {columns: this.items.length},
defaults: this.defaults,
items: this.items
})
for(var i=0, len=this.items.length; i<len; i++){
Ext.applyIf(this.items[i], colCfg);
};
}else{
// The container has field item configs, so we have to generate the column
// panels first then move the items into the columns as needed.
var numCols, cols = [];
if(typeof this.columns == 'string'){ // 'auto' so create a col per item
this.columns = this.items.length;
}
if(!Ext.isArray(this.columns)){
var cs = [];
for(var i=0; i<this.columns; i++){
cs.push((100/this.columns)*.01); // distribute by even %
}
this.columns = cs;
}
numCols = this.columns.length;
// Generate the column configs with the correct width setting
for(var i=0; i<numCols; i++){
var cc = Ext.apply({items:[]}, colCfg);
cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
if(this.defaults){
cc.defaults = Ext.apply(cc.defaults || {}, this.defaults)
}
cols.push(cc);
};
// Distribute the original items into the columns
if(this.vertical){
var rows = Math.ceil(this.items.length / numCols), ri = 0;
for(var i=0, len=this.items.length; i<len; i++){
if(i>0 && i%rows==0){
ri++;
}
if(this.items[i].fieldLabel){
this.items[i].hideLabel = false;
}
cols[ri].items.push(this.items[i]);
};
}else{
for(var i=0, len=this.items.length; i<len; i++){
var ci = i % numCols;
if(this.items[i].fieldLabel){
this.items[i].hideLabel = false;
}
cols[ci].items.push(this.items[i]);
};
}
Ext.apply(panelCfg, {
layoutConfig: {columns: numCols},
items: cols
});
}
this.panel = new Ext.Panel(panelCfg);
this.el = this.panel.getEl();
if(this.forId && this.itemCls){
var l = this.el.up(this.itemCls).child('label', true);
if(l){
l.setAttribute('htmlFor', this.forId);
}
}
var fields = this.panel.findBy(function(c){
return c.isFormField;
}, this);
this.items = new Ext.util.MixedCollection();
this.items.addAll(fields);
}
Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
},
// 私有的
validateValue : function(value){
if(!this.allowBlank){
var blank = true;
this.items.each(function(f){
if(f.checked){
return blank = false;
}
}, this);
if(blank){
this.markInvalid(this.blankText);
return false;
}
}
return true;
},
// 私有的
onDisable : function(){
this.items.each(function(item){
item.disable();
})
},
// 私有的
onEnable : function(){
this.items.each(function(item){
item.enable();
})
},
// 私有的
onResize : function(w, h){
this.panel.setSize(w, h);
this.panel.doLayout();
},
// inherit docs from Field
reset : function(){
Ext.form.CheckboxGroup.superclass.reset.call(this);
this.items.each(function(c){
if(c.reset){
c.reset();
}
}, this);
},
/**
* @cfg {String} name
* @hide
*/
/**
* @method initValue
* @hide
*/
initValue : Ext.emptyFn,
/**
* @method getValue
* @hide
*/
getValue : Ext.emptyFn,
/**
* @method getRawValue
* @hide
*/
getRawValue : Ext.emptyFn,
/**
* @method setValue
* @hide
*/
setValue : Ext.emptyFn,
/**
* @method setRawValue
* @hide
*/
setRawValue : Ext.emptyFn
});
Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.Field
* @extends Ext.BoxComponent
* 表单元素的基类,提供事件操作、尺寸调整、值操作与其它功能。<br />
* 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 = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {String} fieldLabel
* 显示在该字段旁边的标签文本(label text),默认为''。
* <p><b>
* 由于字段的lable不属于字段结构的一部分因此默认下不会渲染。
* 应该交由{@link Ext.layout.FormLayout 表单布局}的布局管理器之所在{@link Ext.form.Container Container}来控制对字段的添加lable。
* </b></p>
* The label text to display next to this field (defaults to '')
* <p><b>A Field's label is not by default rendered as part of the Field's structure.
* The label is rendered by the {@link Ext.layout.FormLayout form layout} layout manager
* of the {@link Ext.form.Container Container} to which the Field is added.</b></p>
*/
/**
* @cfg {String} inputType
* input字段的type属性,诸如 radio、text、password、file等的元素都有type属性。
* 属性是“file”与“怕ssword”就要在这里设置了,因为当前Ext并没有这些单独的组件。
* 注意当你使用<tt>inputType:'file'</tt>时,{@link #emptyText}就避免使用。
* The type attribute for input fields -- e.g. radio, text, password, file (defaults
* to "text"). The types "file" and "password" must be used to render those field types currently -- there are
* no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText}
* is not supported and should be avoided.
*/
/**
* @cfg {Number} tabIndex 字段的tabIndex。注意这只对已渲染的元素有效,applyTo的那些无效(默认为undfined)。
* The tabIndex for this field. Note this only applies to fields that are rendered, not those which are built via applyTo (defaults to undefined).
*/
/**
* @cfg {Mixed} value 字段初始化的值(默认为undefined)。
* A value to initialize this field with (defaults to undefined).
*/
/**
* @cfg {String} name 字段的name属性,HTML的name属性(默认为'')。
* The field's HTML name attribute (defaults to "").
*/
/**
* @cfg {String} cls 给字段所属的元素添加上制定的CSS样式。
* A custom CSS class to apply to the field's underlying element (defaults to "").
*/
/**
* @cfg {String} invalidClass
* 当出现无效字段所使用上的CSS样式(默认为"x-form-invalid)。
* The CSS class to use when marking a field invalid (defaults to "x-form-invalid")
*/
invalidClass : "x-form-invalid",
/**
* @cfg {String} invalidText 表单元素无效时标在上面的文本信息(默认为"The value in this field is invalid")。
* The error text to use when marking a field invalid and no message is provided (defaults to "The value in this field is invalid")
*/
invalidText : "The value in this field is invalid",
/**
* @cfg {String} focusClass 当表单元素获取焦点时的CSS样式(默认为"x-form-focus")。
* The CSS class to use when the field receives focus (defaults to "x-form-focus")
*/
focusClass : "x-form-focus",
/**
* @cfg {String/Boolean} validationEvent 初始化元素验证的事件名,如果设假,则不进行验证(默认"keyup")。
* The event that should initiate field validation. Set to false to disable automatic validation (defaults to "keyup").
*/
validationEvent : "keyup",
/**
* @cfg {Boolean} validateOnBlur 是否当失去焦点时验证此表单元素(默认真)。
* Whether the field should validate when it loses focus (defaults to true).
*/
validateOnBlur : true,
/**
* @cfg {Number} validationDelay 用户输入开始到验证开始的间隔毫秒数(默认250毫秒)。
* The length of time in milliseconds after user input begins until validation is initiated (defaults to 250)
*/
validationDelay : 250,
/**
* @cfg {String/Object} autoCreate 一个指定的DomHelper配置对象,如果为真则为一个默认对象({tag: "input", type: "text", size: "20", autocomplete: "off"})。
* A DomHelper element spec, or true for a default element spec (defaults to {tag: "input", type: "text", size: "20", autocomplete: "off"})
*/
defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"},
/**
* @cfg {String} fieldClass 表单元素一般状态CSS样式(默认为"x-form-field")。
* The default CSS class for the field (defaults to "x-form-field")
*/
fieldClass : "x-form-field",
/**
* @cfg {String} msgTarget 错误提示的显示位置。 可以是以下列表中的任意一项(默认为"qtip")。
* The location where error text should display. Should be one of the following values
* (defaults to 'qtip'):
*<pre>
值Value 说明Description
----------- ----------------------------------------------------------------------
qtip 当鼠标旋停在表单元素上时显示。 Display a quick tip when the user hovers over the field
title 显示浏览器默认"popup"提示。 Display a default browser title attribute popup
under 创建一个包函错误信息的"div"对象(块显示方式)在表单元素下面。 Add a block div beneath the field containing the error text
side 在表单元素右侧加错误图标,鼠标旋停上面时显示错误信息。Add an error icon to the right of the field with a popup on hover
[element id] 直接在指定的对象的"innerHTML"属性里添加错误信息。Add the error text directly to the innerHTML of the specified element
</pre>
*/
msgTarget : 'qtip',
/**
* @cfg {String} msgFx <b>Experimental</b> 表单元素无效提示显示的动画效果(默认为"normal")The effect used when displaying a validation message under the field
* (defaults to 'normal').
*/
msgFx : 'normal',
/**
* @cfg {Boolean} readOnly 如果为真,则在HTML时标明此表单元素为只读 -- 注意:只是设置表单对象的只读属性。 True to mark the field as readOnly in HTML (defaults to false) -- Note: this only
* sets the element's readOnly DOM attribute.
*/
readOnly : false,
/**
* @cfg {Boolean} disabled 为真则标明此表单元素为不可用(默认为假)。
* <p>注意根据<a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML规范</a>,
* 禁用的字段不会被{@link Ext.form.BasicForm#submit 提交}。</p>
* True to disable the field (defaults to false).
* <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>,
* disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p>
*/
disabled : false,
// private
isFormField : true,
// private
hasFocus : false,
// 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',
/**
* @event blur
* 当此元素推动焦点时激发此事件。
* Fires when this field loses input focus.
* @param {Ext.form.Field} this
*/
'blur',
/**
* @event specialkey
* 任何一个关于导航类键(arrows、tab、enter、esc等)被敲击则触发此事件。你可以查看{@link Ext.EventObject#getKey}去断定哪个键被敲击。
* 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.
* @param {Ext.form.Field} this
* @param {Ext.EventObject} e The event object
*/
'specialkey',
/**
* @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',
/**
* @event invalid
* 当此元素被标为无效后触发此事件。
* Fires after the field has been marked as invalid.
* @param {Ext.form.Field} this
* @param {String} msg 验证信息 The validation message
*/
'invalid',
/**
* @event valid
* 在此元素被验证有效后触发此事件。
* Fires after the field has been validated with no errors.
* @param {Ext.form.Field} this
*/
'valid'
);
},
/**
* 试图获取元素的名称。
* 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){
if(!this.el){
var cfg = this.getAutoCreate();
if(!cfg.name){
cfg.name = this.name || this.id;
}
if(this.inputType){
cfg.type = this.inputType;
}
this.autoEl = cfg;
}
Ext.form.Field.superclass.onRender.call(this, ct, 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]);
},
// private
getItemCt : function(){
return this.el.up('.x-form-item', 4);
},
// private
initValue : function(){
if(this.value !== undefined){
this.setValue(this.value);
}else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
this.setValue(this.el.dom.value);
}
// reference to original value for reset
this.originalValue = this.getValue();
},
/**
* 把组件应用到一个现有的对象上。这个被用来代替render()方法。
* 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();
this.initValue();
},
// private
fireKey : function(e){
if(e.isSpecialKey()){
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.mon(this.el, Ext.isIE || Ext.isSafari3 ? "keydown" : "keypress", this.fireKey, this);
this.mon(this.el, 'focus', this.onFocus, this);
// fix weird FF/Win editor issue when changing OS window focus
var o = this.inEditor && Ext.isWindows && Ext.isGecko ? {buffer:10} : null;
this.mon(this.el, 'blur', this.onBlur, this, o);
},
// private
onFocus : function(){
if(this.focusClass){
this.el.addClass(this.focusClass);
}
if(!this.hasFocus){
this.hasFocus = true;
this.startValue = this.getValue();
this.fireEvent("focus", this);
}
},
// private
beforeBlur : Ext.emptyFn,
// private
onBlur : function(){
this.beforeBlur();
if(this.focusClass){
this.el.removeClass(this.focusClass);
}
this.hasFocus = false;
if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
this.validate();
}
var v = this.getValue();
if(String(v) !== String(this.startValue)){
this.fireEvent('change', this, v, this.startValue);
}
this.fireEvent("blur", this);
},
/**
* 它的原始值没有变更,并且它是可用的则返回真。
* Returns whether or not the field value is currently valid
* @param {Boolean} preventMark True表示为禁止标记字段无效True to disable marking the field invalid
* @return {Boolean} True表示为这是有效值,否则为false。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;
},
/**
* 验证域的值。
* Validates the field value
* @return {Boolean} True表示为值有效,否则为false。True if the value is valid, else false
*/
validate : function(){
if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
this.clearInvalid();
return true;
}
return false;
},
// protected - should be overridden by subclasses if necessary to prepare raw values for validation
processValue : function(value){
return value;
},
// private
// Subclasses should provide the validation implementation by overriding this
validateValue : function(value){
return true;
},
/**
* 标记该字段无效,使用{@link #msgTarget}来确定错误信息显示在哪里并设置字段元素的{@link #invalidClass}。
* Mark this field as invalid, using {@link #msgTarget} to determine how to display the error and
* applying {@link #invalidClass} to the field's element.
* @param {String} msg (optional) 验证信息(默认为{@link #invalidText})The validation message (defaults to {@link #invalidText})
*/
markInvalid : function(msg){
if(!this.rendered || this.preventMark){ // not rendered
return;
}
msg = msg || this.invalidText;
var mt = this.getMessageHandler();
if(mt){
mt.mark(this, msg);
}else if(this.msgTarget){
this.el.addClass(this.invalidClass);
var t = Ext.getDom(this.msgTarget);
if(t){
t.innerHTML = msg;
t.style.display = this.msgDisplay;
}
}
this.fireEvent('invalid', this, msg);
},
/**
* 清除元素任何无效标志样式与信息。
* Clear any invalid styles/messages for this field
*/
clearInvalid : function(){
if(!this.rendered || this.preventMark){ // not rendered
return;
}
this.el.removeClass(this.invalidClass);
var mt = this.getMessageHandler();
if(mt){
mt.clear(this);
}else if(this.msgTarget){
this.el.removeClass(this.invalidClass);
var t = Ext.getDom(this.msgTarget);
if(t){
t.innerHTML = '';
t.style.display = 'none';
}
}
this.fireEvent('valid', this);
},
// private
getMessageHandler : function(){
return Ext.form.MessageTargets[this.msgTarget];
},
// private
getErrorCt : function(){
return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
this.el.findParent('.x-form-field-wrap', 5, true); // else direct field wrap
},
// private
alignErrorIcon : function(){
this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
},
/**
* 返回可能无效的原始值。要返回正式的值应该使用{@link #getValue}。
* 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.rendered ? this.el.getValue() : Ext.value(this.value, '');
if(v === this.emptyText){
v = '';
}
return v;
},
/**
* 返回格式化后的数据(未定义或空值则会返回'')。返回原始值可以查看{@link #getRawValue}。
* Returns the normalized data value (undefined or emptyText will be returned as ''). To return the raw value see {@link #getRawValue}.
* @return {Mixed} value The field value
*/
getValue : function(){
if(!this.rendered) {
return this.value;
}
var v = this.el.getValue();
if(v === this.emptyText || v === undefined){
v = '';
}
return v;
},
/**
* 跃过验证直接设置DOM元素值。需要验证的设值方法可以查看{@link #setValue}。
* Sets the underlying DOM field's value directly, bypassing validation. To set the value with validation see {@link #setValue}.
* @param {Mixed} value 要设置的值 The value to set
* @return {Mixed} value 已设置的值 The field value that is set
*/
setRawValue : function(v){
return this.el.dom.value = (v === null || v === undefined ? '' : v);
},
/**
* 设置元素值并加以验证。如果想跃过验证直接设值则请看{@link #setRawValue}。
* Sets a data value into the field and validates it. To set the value directly without validation see {@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();
}
},
// private, does not work for all fields
append :function(v){
this.setValue([this.getValue(), v].join(''));
},
// private
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);
if(this.offsetCt){
var ct = this.getItemCt();
s.width -= ct.getFrameWidth('lr');
s.height -= ct.getFrameWidth('tb');
}
return s;
},
// private
adjustWidth : function(tag, w){
tag = tag.toLowerCase();
if(typeof w == 'number' && !Ext.isSafari && !this.normalWidth){
if(Ext.isIE && (tag == 'input' || tag == 'textarea')){
if(tag == 'input' && !Ext.isStrict){
return this.inEditor ? w : w - 3;
}
if(tag == 'input' && Ext.isStrict){
return w - (Ext.isIE6 ? 4 : 1);
}
if(tag == 'textarea' && Ext.isStrict){
return w-2;
}
}else if(Ext.isOpera && Ext.isStrict){
if(tag == 'input'){
return w + 2;
}
if(tag == 'textarea'){
return w-2;
}
}
}
return w;
}
/**
* @cfg {Boolean} autoWidth @hide
*/
/**
* @cfg {Boolean} autoHeight @hide
*/
/**
* @cfg {String} autoEl @hide
*/
});
Ext.form.MessageTargets = {
'qtip' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
field.el.dom.qtip = msg;
field.el.dom.qclass = 'x-form-invalid-tip';
if(Ext.QuickTips){ // fix for floating editors interacting with DND
Ext.QuickTips.enable();
}
},
clear: function(field){
field.el.removeClass(field.invalidClass);
field.el.dom.qtip = '';
}
},
'title' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
field.el.dom.title = msg;
},
clear: function(field){
field.el.dom.title = '';
}
},
'under' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
if(!field.errorEl){
var elp = field.getErrorCt();
if(!elp){ // field has no container el
field.el.dom.title = msg;
return;
}
field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
field.errorEl.setWidth(elp.getWidth(true)-20);
}
field.errorEl.update(msg);
Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
},
clear: function(field){
field.el.removeClass(field.invalidClass);
if(field.errorEl){
Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
}else{
field.el.dom.title = '';
}
}
},
'side' : {
mark: function(field, msg){
field.el.addClass(field.invalidClass);
if(!field.errorIcon){
var elp = field.getErrorCt();
if(!elp){ // field has no container el
field.el.dom.title = msg;
return;
}
field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
}
field.alignErrorIcon();
field.errorIcon.dom.qtip = msg;
field.errorIcon.dom.qclass = 'x-form-invalid-tip';
field.errorIcon.show();
field.on('resize', field.alignErrorIcon, field);
},
clear: function(field){
field.el.removeClass(field.invalidClass);
if(field.errorIcon){
field.errorIcon.dom.qtip = '';
field.errorIcon.hide();
field.un('resize', field.alignErrorIcon, field);
}else{
field.el.dom.title = '';
}
}
}
};
// 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});
}
}
};
Ext.reg('field', Ext.form.Field);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.VTypes
* 提供一个简单的、易于扩展的、可重写的表单验证功能。<br />
* This is a singleton object which contains a set of commonly used field validation functions.
* The validations provided are basic and intended to be easily customizable and extended. To add
* your own custom VType:<pre><code>
Ext.apply(Ext.form.VTypes, {
IPAddress: function(v) {
return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
},
IPAddressText: 'Must be a numeric IP address'
});
</code></pre>
* @singleton
*/
Ext.form.VTypes = function(){
// 对下列变量进行闭包,所以只会创建一次
// closure these in so they are only created once.
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;
// 所有这些信息和函数都是可重新配置的
// All these messages and functions are configurable
return {
/**
* 用于验证Email地址的函数。
* The function used to validate email addresses. Note that this is a very basic validation -- complete
* validation per the email RFC specifications is very complex and beyond the scope of this class, although
* this function can be overridden if a more comprehensive validation scheme is desired. See the validation
* section of the <a href="http://en.wikipedia.org/wiki/E-mail_address">Wikipedia article on email addresses</a>
* for additional information.
* @param {String} value The email address
*/
'email' : function(v){
return email.test(v);
},
/**
* 当Email验证返回值为false到时候显示的错误信息。
* 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"',
/**
* 只允许email地址格式的正则表达式。
* The keystroke filter mask to be applied on email input. See the {@link #email} method for
* information about more complex email validation.
* @type RegExp
*/
'emailMask' : /[a-z0-9_\.\-@]/i,
/**
* 验证URL地址的函数。
* The function used to validate URLs
* @param {String} value The URL
*/
'url' : function(v){
return url.test(v);
},
/**
* 当URL验证返回值为false到时候显示的错误信息。
* 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"',
/**
* 验证alpha到函数。
* The function used to validate alpha values
* @param {String} value The value
*/
'alpha' : function(v){
return alpha.test(v);
},
/**
* 当alpha验证返回值为false到时候显示的错误信息。
* 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);
},
/**
* 验证数字返回false时候显示的错误信息。
* The error text to display when the alphanumeric validation function returns false
* @type String
*/
'alphanumText' : 'This field should only contain letters, numbers and _',
/**
* 只允文数字(alphanum)的正则表达式。
* The keystroke filter mask to be applied on alphanumeric input
* @type RegExp
*/
'alphanumMask' : /[a-z0-9_]/i
};
}(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.Action
* <p>
* 该类的子类提供在{@link Ext.form.BasicForm Form}上执行的行为。<br />
* The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>
* <p>
* 该类的实例只在{@link Ext.form.BasicForm Form}要执行提交或者加载动作的时候才由Form创建,下列该类的配置选项通过激活表单的动作来设置:
* {@link Ext.form.BasicForm#submit submit}、{@link Ext.form.BasicForm#load load}以及{@link Ext.form.BasicForm#doAction doAction}。<br />
* Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
* the Form needs to perform an action such as submit or load. The Configuration options
* listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},
* {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>
* <p>
* 执行了表单动作的Action的实例被传递到表单的success,failure回调函数(
* {@link Ext.form.BasicForm#submit submit}、{@link Ext.form.BasicForm#load load}和{@link Ext.form.BasicForm#doAction doAction}
* ),以及{@link Ext.form.BasicForm#actioncomplete actioncomplete}和{@link Ext.form.BasicForm#actionfailed actionfailed}事件处理器。<br />
* The instance of Action which performed the action is passed to the success
* and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},
* {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),
* and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and
* {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>
*/
Ext.form.Action = function(form, options){
this.form = form;
this.options = options || {};
};
/**
* 当客户端的表单验证出现错误而中断提交动作的时候返回<tt>false</tt>的错误类型。
* Failure type returned when client side validation of the Form fails
* thus aborting a submit action. Client side validation is performed unless
* {@link #clientValidation} is explicitly set to <tt>false</tt>.
* @type {String}
* @static
*/
Ext.form.Action.CLIENT_INVALID = 'client';
/**
* <p>
* 服务端验证表单出错时返回的错误类型,在response的<tt style="font-weight:bold">errors</tt>属性里指明具体的字段错误信息。
* Failure type returned when server side processing fails and the {@link #result}'s
* <tt style="font-weight:bold">success</tt> property is set to <tt>false</tt>.</p>
* <p>In the case of a form submission, field-specific error messages may be returned in the
* {@link #result}'s <tt style="font-weight:bold">errors</tt> property.</p>
* @type {String}
* @static
*/
Ext.form.Action.SERVER_INVALID = 'server';
/**
* 尝试向远程服务器发送请求遇到通信错误返回的错误类型。可用{@link #response}提取更多信息。
* Failure type returned when a communication error happens when attempting
* to send a request to the remote server. The {@link #response} may be examined to
* provide further information.
* @type {String}
* @static
*/
Ext.form.Action.CONNECT_FAILURE = 'connect';
/**
* 服务端response的<tt style="font-weight:bold">data</tt>属性没有返回任何字段的值得时候返回的错误类型。
* Failure type returned when the response's <tt style="font-weight:bold">success</tt>
* property is set to <tt>false</tt>, or no field values are returned in the response's
* <tt style="font-weight:bold">data</tt> property.
* @type {String}
* @static
*/
Ext.form.Action.LOAD_FAILURE = 'load';
Ext.form.Action.prototype = {
/**
* @cfg {String} url 调用的URL资源。
* The URL that the Action is to invoke.
*/
/**
* @cfg {Boolean} reset 当设置为<tt><b>true</b></tt>的时候,导致表单重置{@link Ext.form.BasicForm.reset reset}
* 如果指定了该值,reset将在表单的{@link #success} 回调函数<b>前</b>和{@link Ext.form.BasicForm.actioncomplete actioncomplete}事件被激发前执行。
* When set to <tt><b>true</b></tt>, causes the Form to be
* {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens
* <b>before</b> the {@link #success} callback is called and before the Form's
* {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.
*/
/**
* @cfg {String} method 获取请求的URL的HTTP方法。默认为{@link Ext.form.BasicForm}的方法。如果没有指定,使用DOM表单的方法。
* The HTTP method to use to access the requested URL. Defaults to the
* {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.
*/
/**
* @cfg {Mixed} params 传递到额外值。它们添加到表单的{@link Ext.form.BasicForm#baseParams}由表单的输入字段传递到指定的URL。
* Extra parameter values to pass. These are added to the Form's {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's input fields.
*/
/**
* @cfg {Number} timeout 在服务端返回{@link #CONNECT_FAILURE}这样的{@link #failureType}之前等待的毫秒数。
* The number of milliseconds to wait for a server response before failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}.
*/
/**
* @cfg {Function} success 当接收到一个有效的成功返回的数据包的时候调用的回调函数。这个函数传递以下的参数:
* The function to call when a valid success return packet is recieved.
* The function is passed the following parameters:<ul class="mdetail-params">
* <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">作出请求动作的表单。The form that requested the action</div></li>
* <li><b>action</b> : Ext.form.Action<div class="sub-desc">Action类。该对象的{@link #result}属性可能被检查,用来执行自定义的后期处理。
* The Action class. The {@link #result}
* property of this object may be examined to perform custom postprocessing.</div></li>
* </ul>
*/
/**
* @cfg {Function} failure 当接收到一个返回失败的数据包或者在Ajax通信时发生错误调用的回调函数。这个函数传递以下的参数:
* The function to call when a failure packet was recieved, or when an error ocurred in the Ajax communication.
* The function is passed the following parameters:<ul class="mdetail-params">
* <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">作出请求动作的表单。The form that requested the action</div></li>
* <li><b>action</b> : Ext.form.Action<div class="sub-desc">Action类。如果发生了Ajax异常,错误类型会在{@link #failureType}里。
* 该对象的{@link #result}属性可能被检查,用来执行自定义的后期处理。
* The Action class. If an Ajax error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
* property of this object may be examined to perform custom postprocessing.</div></li>
* </ul>
*/
/**
* @cfg {Object} scope 回调函数执行的范围。指改回调函数的<tt>this</tt>。
* The scope in which to call the callback functions (The <tt>this</tt> reference for the callback functions).
*/
/**
* @cfg {String} waitMsg 在调用一个action的处理过程中调用{@link Ext.MessageBox#wait}显示的内容。
* The message to be displayed by a call to {@link Ext.MessageBox#wait} during the time the action is being processed.
*/
/**
* @cfg {String} waitTitle 在调用一个action的处理过程中调用{@link Ext.MessageBox#wait}显示的标题。
* The title to be displayed by a call to {@link Ext.MessageBox#wait} during the time the action is being processed.
*/
/**
* 改Action的实例执行的action类型。目前仅支持“提交”和“加载”。
* The type of action this Action instance performs.Currently only "submit" and "load" are supported.
* @type {String}
*/
type : 'default',
/**
* 错误检查类型。可参阅{@link link Ext.form.Action#Action.CLIENT_INVALID CLIENT_INVALID}、
* {@link link Ext.form.Action#Action.SERVER_INVALID SERVER_INVALID}、
* {@link #link Ext.form.ActionAction.CONNECT_FAILURE CONNECT_FAILURE}、{@link Ext.form.Action#Action.LOAD_FAILURE LOAD_FAILURE}。
* The type of failure detected.
* See {@link link Ext.form.Action#Action.CLIENT_INVALID CLIENT_INVALID},
* {@link link Ext.form.Action#Action.SERVER_INVALID SERVER_INVALID},
* {@link #link Ext.form.ActionAction.CONNECT_FAILURE CONNECT_FAILURE}, {@link Ext.form.Action#Action.LOAD_FAILURE LOAD_FAILURE}
* @property failureType
* @type {String}
*/
/**
* 用来执行action的XMLHttpRequest对象。
* The XMLHttpRequest object used to perform the action.
* @property response
* @type {Object}
*/
/**
* 解码了的response对象包含一个boolean类型的<tt style="font-weight:bold">success</tt>属性和一些action的属性。
* The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
* other, action-specific properties.
* @property result
* @type {Object}
*/
// 接口方法
// interface method
run : function(options){
},
// 接口方法
// interface method
success : function(response){
},
// 接口方法
// interface method
handleResponse : function(response){
},
// 默认的连接错误
// default connection failure
failure : function(response){
this.response = response;
this.failureType = Ext.form.Action.CONNECT_FAILURE;
this.form.afterAction(this, false);
},
// 私有的
// private
processResponse : function(response){
this.response = response;
if(!response.responseText){
return true;
}
this.result = this.handleResponse(response);
return this.result;
},
// 内部使用的工具函数
// utility functions used internally
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;
},
// 私有的
// private
getMethod : function(){
return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
},
// 私有的
// private
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;
},
// 私有的
// private
createCallback : function(opts){
var opts = opts || {};
return {
success: this.success,
failure: this.failure,
scope: this,
timeout: (opts.timeout*1000) || (this.form.timeout*1000),
upload: this.form.fileUpload ? this.success : undefined
};
}
};
/**
* @class Ext.form.Action.Submit
* @extends Ext.form.Action
* <p>
* 处理表单{@link Ext.form.BasicForm Form}数据和返回的response对象的类。
* A class which handles submission of data from {@link Ext.form.BasicForm Form}s and processes the returned response.</p>
* <p>
* 该类的实例仅在表单{@link Ext.form.BasicForm Form}{@link Ext.form.BasicForm#submit 提交}的时候创建。
* Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
* {@link Ext.form.BasicForm#submit submit}ting.</p>
* <p>
* 返回的数据包必须包含一个 boolean 类型的<tt style="font-weight:bold">success</tt>属性,还有可选地,一个含有无效字段的<tt style="font-weight:bold">错误信息</tt>的属性。
* A response packet must contain a boolean <tt style="font-weight:bold">success</tt> property, and, optionally
* an <tt style="font-weight:bold">errors</tt> property. The <tt style="font-weight:bold">errors</tt> property contains error
* messages for invalid fields.</p>
* <p>
* 默认情况下,response数据包被认为是一个JSON对象,所以典型的response数据包看起来像是这样的:
* By default, response packets are assumed to be JSON, so a typical response
* packet may look like this:</p><pre><code>
{
success: false,
errors: {
clientCode: "Client not found",
portOfLoading: "This field must not be null"
}
}</code></pre>
* <p>{@link Ext.form.BasicForm}的回调函数或其它处理函数的方法可能会处理其他的数据,放置在响应中。
* JSON解码后的数据可在{@link #result}找到。
* Other data may be placed into the response for processing by the {@link Ext.form.BasicForm} 's callback
* or event handler methods. The object decoded from this JSON is available in the {@link #result} property.</p>
* <p>
* 另外,如果一个{@link #errorReader}指定为{@link Ext.data.XmlReader XmlReader}:
* Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
errorReader: new Ext.data.XmlReader({
record : 'field',
success: '@success'
}, [
'id', 'msg'
]
)
</code></pre>
* <p>那么结果集将会以XML形式返回。then the results may be sent back in XML format:</p><pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<message success="false">
<errors>
<field>
<id>clientCode</id>
<msg><![CDATA[Code not found. <br /><i>This is a test validation message from the server </i>]]></msg>
</field>
<field>
<id>portOfLoading</id>
<msg><![CDATA[Port not found. <br /><i>This is a test validation message from the server </i>]]></msg>
</field>
</errors>
</message>
</code></pre>
* <p>表单的回调函数或者时间处理函数可以向相应的XML里置入其他的元素。
* XML文档在{@link #errorReader}的{@link Ext.data.XmlReader#xmlData xmlData}属性。
* Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
* or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
*/
Ext.form.Action.Submit = function(form, options){
Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
};
Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
/**
* @cfg {Ext.data.DataReader} errorReader <b>可选的。解读JSON对象不需要errorReader。
* Optional. JSON is interpreted with no need for an errorReader.</b>
* <p>
* 从返回结果中读取一条记录的Reader。
* DataReader的<b>success</b>属性指明决定是否提交成功。
* Record对象的数据提供了任何未通过验证(非法)的表单字段的错误信息。
* A Reader which reads a single record from the returned data.
* The DataReader's <b>success</b> property specifies how submission success is determined. The Record's data provides the error messages to apply to any invalid form Fields.</p>.
*/
/**
* @cfg {boolean} clientValidation 表明一个表单的字段是否都合法。在表单最终提交前调用。
* 可以在表单的提交选项中选择避免执行该操作。如果没有定义改属性,执行提交前的表单验证。
* Determines whether a Form's fields are validated in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
* Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation is performed.
*/
type : 'submit',
// 私有的
// private
run : function(){
var o = this.options;
var method = this.getMethod();
var isGet = method == 'GET';
if(o.clientValidation === false || this.form.isValid()){
Ext.Ajax.request(Ext.apply(this.createCallback(o), {
form:this.form.el.dom,
url:this.getUrl(isGet),
method: method,
headers: o.headers,
params:!isGet ? this.getParams() : null,
isUpload: this.form.fileUpload
}));
}else if (o.clientValidation !== false){ // client validation failed
this.failureType = Ext.form.Action.CLIENT_INVALID;
this.form.afterAction(this, false);
}
},
// 私有的
// private
success : function(response){
var result = this.processResponse(response);
if(result === true || result.success){
this.form.afterAction(this, true);
return;
}
if(result.errors){
this.form.markInvalid(result.errors);
this.failureType = Ext.form.Action.SERVER_INVALID;
}
this.form.afterAction(this, false);
},
// 私有的
// private
handleResponse : function(response){
if(this.form.errorReader){
var rs = this.form.errorReader.read(response);
var errors = [];
if(rs.records){
for(var i = 0, len = rs.records.length; i < len; i++) {
var r = rs.records[i];
errors[i] = r.data;
}
}
if(errors.length < 1){
errors = null;
}
return {
success : rs.success,
errors : errors
};
}
return Ext.decode(response.responseText);
}
});
/**
* @class 类 Ext.form.Action.Load
* @extends Ext.form.Action
* <p>
* {@link Ext.form.BasicForm}处理从服务器加载数据到的字段的类。
* A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
* <p>
* 该类的实例仅在{@link Ext.form.BasicForm Form}表单加载的时候才被创建。
* Instances of this class are only created by a {@link Ext.form.BasicForm Form}。 when {@link Ext.form.BasicForm#load load}ing.</p>
*
* <p>
* 相应数据包<b>必须</b>包含一个boolean类型的<tt style="font-weight:bold">success</tt>属性,和<tt style="font-weight:bold">data</tt>属性。
* <tt style="font-weight:bold">data</tt>属性包含了表单字段要加载的数据。每个值对象被传递到字段的{@link Ext.form.Field#setValue setValue}方法里。
* A response packet <b>must</b> contain a boolean <tt style="font-weight:bold">success</tt> property, and
* a <tt style="font-weight:bold">data</tt> property. The <tt style="font-weight:bold">data</tt> property
* contains the values of Fields to load. The individual value object for each Field
* is passed to the Field's {@link Ext.form.Field#setValue setValue} method.</p>
*
* <p>
* 默认情况下,相应数据包会被认为是一个JSON对象,所以典型的相应数据包看起来是这样的:
* By default, response packets are assumed to be JSON, so a typical response packet may look like this:</p><pre><code>
{
success: true,
data: {
clientName: "Fred. Olsen Lines",
portOfLoading: "FXT",
portOfDischarge: "OSL"
}
}</code></pre>
* <p>
* 其他的数据可以由{@link Ext.form.BasicForm Form}的回调函数甚至是事件处理函数置入response对象进行处理。
* 解码的JSON对象在{@link #result}属性里。
* Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s callback
* or event handler methods.
* The object decoded from this JSON is available in the {@link #result} property.</p>
*/
Ext.form.Action.Load = function(form, options){
Ext.form.Action.Load.superclass.constructor.call(this, form, options);
this.reader = this.form.reader;
};
Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
// 私有的// private
type : 'load',
// 私有的// private
run : function(){
Ext.Ajax.request(Ext.apply(
this.createCallback(this.options), {
method:this.getMethod(),
url:this.getUrl(false),
headers: this.options.headers,
params:this.getParams()
}));
},
// 私有的// private
success : function(response){
var result = this.processResponse(response);
if(result === true || !result.success || !result.data){
this.failureType = Ext.form.Action.LOAD_FAILURE;
this.form.afterAction(this, false);
return;
}
this.form.clearInvalid();
this.form.setValues(result.data);
this.form.afterAction(this, true);
},
// 私有的// private
handleResponse : function(response){
if(this.form.reader){
var rs = this.form.reader.read(response);
var data = rs.records && rs.records[0] ? rs.records[0].data : null;
return {
success : rs.success,
data : data
};
}
return Ext.decode(response.responseText);
}
});
Ext.form.Action.ACTION_TYPES = {
'load' : Ext.form.Action.Load,
'submit' : Ext.form.Action.Submit
};
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.RadioGroup
* @extends Ext.form.CheckboxGroup
* 群组{@link Ext.form.Radio}控件的容器。 <br />
* A grouping container for {@link Ext.form.Radio} controls.
* @constructor 创建新的RadioGroup对象 Creates a new RadioGroup
* @param {Object} config 配置项 Configuration options
*/
Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, {
/**
* @cfg {Boolean} allowBlank
* True表示为group里面的每一项都可以允许空白(默认为false)。如果allowBlank = false而且验证的时候没有一项被选中,{@link @blankText}就是用于提示的错误信息。
* True to allow every item in the group to be blank (defaults to false). If allowBlank =
* false and no items are selected at validation time, {@link @blankText} will be used as the error text.
*/
allowBlank : true,
/**
* @cfg {String} blankText
* 若{@link #allowBlank}验证不通过显示的文字(默认为You must select one item in this group")。
* Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
* select one item in this group")
*/
blankText : "You must select one item in this group",
// private
defaultType : 'radio',
// private
groupCls: 'x-form-radio-group'
});
Ext.reg('radiogroup', Ext.form.RadioGroup);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.FieldSet
* @extends Ext.Panel
* 针对某一组字段的标准容器。<br />
* Standard container used for grouping form fields.
* @constructor
* @param {Object} config 配置选项 Configuration options
*/
Ext.form.FieldSet = Ext.extend(Ext.Panel, {
/**
* @cfg {Mixed} checkboxToggle True表示在lengend标签之前fieldset的范围内渲染一个checkbox,或者送入一个DomHelper的配置对象制定checkbox(默认为false)。选择该checkbox会为展开、收起该面板服务。
* True to render a checkbox into the fieldset frame just in front of the legend,
* or a DomHelper config object to create the checkbox. (defaults to false).
* The fieldset will be expanded or collapsed when the checkbox is toggled.
*/
/**
* @cfg {String} checkboxName 分配到fieldset的checkbox的名称,在{@link #checkboxToggle} = true的情况有效。(默认为'[checkbox id]-checkbox')。
* The name to assign to the fieldset's checkbox if {@link #checkboxToggle} = true (defaults to '[checkbox id]-checkbox').
*/
/**
* @cfg {Number} labelWidth 标签的宽度,该属性会影响下级的子容器。
* The width of labels. This property cascades to child containers.
*/
/**
* @cfg {String} itemCls 各字段下面的x-form-item的CSS样式类,该属性会影响下级的子容器。
* A css class to apply to the x-form-item of fields. This property cascades to child containers.
*/
/**
* @cfg {String} baseCls 应用fieldset到基础样式类(默认为'x-fieldset')。
* The base CSS class applied to the fieldset (defaults to 'x-fieldset').
*/
baseCls:'x-fieldset',
/**
* @cfg {String} layout fieldset所在的{@link Ext.Container#layout}的类型(默认为'form')。
* The {@link Ext.Container#layout} to use inside the fieldset (defaults to 'form').
*/
layout: 'form',
/**
* @cfg {Boolean} animCollapse
* True to animate the transition when the panel is collapsed, false to skip the animation (defaults to false).
*/
animCollapse: false,
// private
onRender : function(ct, position){
if(!this.el){
this.el = document.createElement('fieldset');
this.el.id = this.id;
if (this.title || this.header || this.checkboxToggle) {
this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header';
}
}
Ext.form.FieldSet.superclass.onRender.call(this, ct, position);
if(this.checkboxToggle){
var o = typeof this.checkboxToggle == 'object' ?
this.checkboxToggle :
{tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'};
this.checkbox = this.header.insertFirst(o);
this.checkbox.dom.checked = !this.collapsed;
this.mon(this.checkbox, 'click', this.onCheckClick, this);
}
},
// private
onCollapse : function(doAnim, animArg){
if(this.checkbox){
this.checkbox.dom.checked = false;
}
Ext.form.FieldSet.superclass.onCollapse.call(this, doAnim, animArg);
},
// private
onExpand : function(doAnim, animArg){
if(this.checkbox){
this.checkbox.dom.checked = true;
}
Ext.form.FieldSet.superclass.onExpand.call(this, doAnim, animArg);
},
/* //protected
* This function is called by the fieldset's checkbox when it is toggled (only applies when
* checkboxToggle = true). This method should never be called externally, but can be
* overridden to provide custom behavior when the checkbox is toggled if needed.
*/
onCheckClick : function(){
this[this.checkbox.dom.checked ? 'expand' : 'collapse']();
},
// private
beforeDestroy : function(){
Ext.form.FieldSet.superclass.beforeDestroy.call(this);
}
/**
* @cfg {String/Number} activeItem
* @hide
*/
/**
* @cfg {Mixed} applyTo
* @hide
*/
/**
* @cfg {Object/Array} bbar
* @hide
*/
/**
* @cfg {Boolean} bodyBorder
* @hide
*/
/**
* @cfg {Boolean} border
* @hide
*/
/**
* @cfg {Boolean/Number} bufferResize
* @hide
*/
/**
* @cfg {String} buttonAlign
* @hide
*/
/**
* @cfg {Array} buttons
* @hide
*/
/**
* @cfg {Boolean} collapseFirst
* @hide
*/
/**
* @cfg {String} defaultType
* @hide
*/
/**
* @cfg {String} disabledClass
* @hide
*/
/**
* @cfg {String} elements
* @hide
*/
/**
* @cfg {Boolean} floating
* @hide
*/
/**
* @cfg {Boolean} footer
* @hide
*/
/**
* @cfg {Boolean} frame
* @hide
*/
/**
* @cfg {Boolean} header
* @hide
*/
/**
* @cfg {Boolean} headerAsText
* @hide
*/
/**
* @cfg {Boolean} hideCollapseTool
* @hide
*/
/**
* @cfg {String} iconCls
* @hide
*/
/**
* @cfg {Boolean/String} shadow
* @hide
*/
/**
* @cfg {Number} shadowOffset
* @hide
*/
/**
* @cfg {Boolean} shim
* @hide
*/
/**
* @cfg {Object/Array} tbar
* @hide
*/
/**
* @cfg {Boolean} titleCollapse
* @hide
*/
/**
* @cfg {Array} tools
* @hide
*/
/**
* @cfg {String} xtype
* @hide
*/
/**
* @property header
* @hide
*/
/**
* @property footer
* @hide
*/
/**
* @method focus
* @hide
*/
/**
* @method getBottomToolbar
* @hide
*/
/**
* @method getTopToolbar
* @hide
*/
/**
* @method setIconClass
* @hide
*/
/**
* @event activate
* @hide
*/
/**
* @event beforeclose
* @hide
*/
/**
* @event bodyresize
* @hide
*/
/**
* @event close
* @hide
*/
/**
* @event deactivate
* @hide
*/
});
Ext.reg('fieldset', Ext.form.FieldSet);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.TriggerField
* @extends Ext.form.TextField
* 为添加了带有可触发事件的按钮的TextFields(文本域)提供一个方便的封装(很像一个默认combobox)。
* 触发器没有默认行为(action),因此你必须通过重写方法{@link #onTriggerClick}的方式,指派一个方法实现触发器的点击事件处理。
* 你可以直接创建一个TriggerField(触发域),由于它会呈现与combobox相像的效果,你可以通过它提供一种自定义的实现。例如: <br />
* Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
* The trigger has no default action, so you must assign a function to implement the trigger click handler by
* overriding {@link #onTriggerClick}.
* You can create a TriggerField directly, as it renders exactly like a combobox
* for which you can provide a custom implementation. For example:
* <pre><code>
var trigger = new Ext.form.TriggerField();
trigger.onTriggerClick = myTriggerFn;
trigger.applyToMarkup('my-field');
</code></pre>
*
* 然而,你可能会更倾向于将TriggerField作为一个可复用容器的基类。{@link Ext.form.DateField}和{@link Ext.form.ComboBox}就是两个较好的样板。
* However, in general you will most likely want to use TriggerField as the base class for a reusable component.{@link Ext.form.DateField}and {@link Ext.form.ComboBox}are perfect examples of this.
* @cfg {String} triggerClass 配置项triggerClass(字符串)是一个附加的CSS类,用于为触发器按钮设置样式。配置项triggerClass(触发器样式)如果被指定的话则会被<b>附加</b>,否则默认为“x-form-trigger”。
* An additional CSS class used to style the trigger button. The trigger will always get the class 'x-form-trigger' by default and triggerClass will be <b>appended</b> if specified.
* @constructor 创建一个新TriggerField的对象。 Create a new TriggerField.
* @param {Object} config 配置选择(对于有效的{@Ext.form.TextField}配置项也会被传入到TextField) Configuration options (valid {@Ext.form.TextField} config options will also be applied
* to the base TextField)
*/
Ext.form.TriggerField = Ext.extend(Ext.form.TextField, {
/**
* @cfg {String} triggerClass 应用到触发器身上的CSS样式类。
* A CSS class to apply to the trigger
*/
/**
* @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为{tag: "input", type: "text", size: "16", autocomplete: "off"})
* A DomHelper element spec, or true for a default element spec (defaults to {tag: "input", type: "text", size: "16", autocomplete: "off"})
*/
defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
/**
* @cfg {Boolean} hideTrigger 为true时隐藏触发元素,只显示基本文本域(默认为false)。
* True to hide the trigger element and display only the base text field (defaults to false)
*/
hideTrigger:false,
/**
* @hide
* @method autoSize
*/
autoSize: Ext.emptyFn,
// private
monitorTab : true,
// private
deferHeight : true,
// private
mimicing : false,
// private
onResize : function(w, h){
Ext.form.TriggerField.superclass.onResize.call(this, w, h);
if(typeof w == 'number'){
this.el.setWidth(this.adjustWidth('input', w - this.trigger.getWidth()));
}
this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
},
// private
adjustSize : Ext.BoxComponent.prototype.adjustSize,
// private
getResizeEl : function(){
return this.wrap;
},
// private
getPositionEl : function(){
return this.wrap;
},
// private
alignErrorIcon : function(){
if(this.wrap){
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());
}
},
afterRender : function(){
Ext.form.TriggerField.superclass.afterRender.call(this);
var y;
if(Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())){
this.el.position();
this.el.setY(y);
}
},
// private
initTrigger : function(){
this.mon(this.trigger, 'click', this.onTriggerClick, this, {preventDefault:true});
this.trigger.addClassOnOver('x-form-trigger-over');
this.trigger.addClassOnClick('x-form-trigger-click');
},
// private
onDestroy : function(){
if(this.trigger){
this.trigger.removeAllListeners();
this.trigger.remove();
}
if(this.wrap){
this.wrap.remove();
}
Ext.form.TriggerField.superclass.onDestroy.call(this);
},
// private
onFocus : function(){
Ext.form.TriggerField.superclass.onFocus.call(this);
if(!this.mimicing){
this.wrap.addClass('x-trigger-wrap-focus');
this.mimicing = true;
Ext.get(Ext.isIE ? document.body : document).on("mousedown", this.mimicBlur, this, {delay: 10});
if(this.monitorTab){
this.el.on('keydown', this.checkTab, this);
}
}
},
// private
checkTab : function(e){
if(e.getKey() == e.TAB){
this.triggerBlur();
}
},
// private
onBlur : function(){
// do nothing
},
// private
mimicBlur : function(e){
if(!this.wrap.contains(e.target) && this.validateBlur(e)){
this.triggerBlur();
}
},
// private
triggerBlur : function(){
this.mimicing = false;
Ext.get(Ext.isIE ? document.body : document).un("mousedown", this.mimicBlur, this);
if(this.monitorTab && this.el){
this.el.un("keydown", this.checkTab, this);
}
this.beforeBlur();
if(this.wrap){
this.wrap.removeClass('x-trigger-wrap-focus');
}
Ext.form.TriggerField.superclass.onBlur.call(this);
},
beforeBlur : Ext.emptyFn,
// private
// 这个方法须有子类重写(覆盖),需要确认该域是否可以失去焦点(blurred)。
// This should be overriden by any subclass that needs to check whether or not the field can be blurred.
validateBlur : function(e){
return true;
},
// private
onDisable : function(){
Ext.form.TriggerField.superclass.onDisable.call(this);
if(this.wrap){
this.wrap.addClass(this.disabledClass);
this.el.removeClass(this.disabledClass);
}
},
// private
onEnable : function(){
Ext.form.TriggerField.superclass.onEnable.call(this);
if(this.wrap){
this.wrap.removeClass(this.disabledClass);
}
},
// 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事件。默认为空方法,要被某个实现的方法重写后才会有效。
* The function that should handle the trigger's click event. This method does nothing by default until overridden
* by an implementing function.
* @method
* @param {EventObject} e 参数e是({EventObject}类型)
*/
onTriggerClick : Ext.emptyFn
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
});
// TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class
// to be extended by an implementing class. For an example of implementing this class, see the custom
// SearchField implementation here: http://extjs.com/deploy/ext/examples/form/custom.html
Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, {
initComponent : function(){
Ext.form.TwinTriggerField.superclass.initComponent.call(this);
this.triggerConfig = {
tag:'span', cls:'x-form-twin-triggers', cn:[
{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
]};
},
getTrigger : function(index){
return this.triggers[index];
},
initTrigger : function(){
var ts = this.trigger.select('.x-form-trigger', true);
this.wrap.setStyle('overflow', 'hidden');
var triggerField = this;
ts.each(function(t, all, index){
t.hide = function(){
var w = triggerField.wrap.getWidth();
this.dom.style.display = 'none';
triggerField.el.setWidth(w-triggerField.trigger.getWidth());
};
t.show = function(){
var w = triggerField.wrap.getWidth();
this.dom.style.display = '';
triggerField.el.setWidth(w-triggerField.trigger.getWidth());
};
var triggerIndex = 'Trigger'+(index+1);
if(this['hide'+triggerIndex]){
t.dom.style.display = 'none';
}
this.mon(t, 'click', this['on'+triggerIndex+'Click'], this, {preventDefault:true});
t.addClassOnOver('x-form-trigger-over');
t.addClassOnClick('x-form-trigger-click');
}, this);
this.triggers = ts.elements;
},
onTrigger1Click : Ext.emptyFn,
onTrigger2Click : Ext.emptyFn
});
Ext.reg('trigger', Ext.form.TriggerField); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.BasicForm
* @extends Ext.util.Observable
* <p>提供表单的多种动作("actions")功能,并且初始化 Ext.form.Field 类型在现有的标签上。<br />
* Encapsulates the DOM <form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides
* input field management, validation, submission, and form loading services.</p>
* <p>By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}.
* To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.</p>
* <p><h3>File Uploads</h3>{@link #fileUpload File uploads} are not performed using Ajax submission, that
* is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
* manner with the DOM <tt><form></tt> element temporarily modified to have its
* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
* to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
* but removed after the return data has been gathered.</p>
* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
* server is using JSON to send the return object, then the
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
* <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
* "<" as "&lt;", "&" as "&amp;" etc.</p>
* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
* is created containing a <tt>responseText</tt> property in order to conform to the
* requirements of event handlers and callbacks.</p>
* <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
* and some server technologies (notably JEE) may require some custom processing in order to
* retrieve parameter names and parameter values from the packet content.</p>
* @constructor
* @param {Mixed} el 表单对象或它的ID el The form element or its id
* @param {Object} config 配置表单对象的配置项选项 config Configuration options
*/
Ext.form.BasicForm = function(el, config){
Ext.apply(this, config);
/**
* @property items
* 所有表单内元素的集合。 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
* 在任何动作被执行前被触发。如果返回false则取消这个动作。
* Fires before any action is performed. Return false to cancel the action.
* @param {Form} this
* @param {Action} action 要被执行的{@link Ext.form.Action}动作对象 action The {@link Ext.form.Action} to be performed
*/
'beforeaction',
/**
* @event actionfailed
* 当动作失败时被触发。
* Fires when an action fails.
* @param {Form} this
* @param {Action} action 失败的{@link Ext.form.Action}动作对象 action The {@link Ext.form.Action} that failed
*/
'actionfailed',
/**
* @event actioncomplete
* 当动作完成时被触发。Fires when an action is completed.
* @param {Form} this
* @param {Action} action 完成的{@link Ext.form.Action}动作对象 action The {@link Ext.form.Action} that completed
*/
'actioncomplete'
);
if(el){
this.initEl(el);
}
Ext.form.BasicForm.superclass.constructor.call(this);
};
Ext.extend(Ext.form.BasicForm, Ext.util.Observable, {
/**
* @cfg {String} method
* 如不指定,所有动作使用的默认表单请求方法(GET或POST)。
* The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
*/
/**
* @cfg {DataReader} reader
* 当执行"load"动作时,设置一个Ext.data.DataReader对象(如{@link Ext.data.XmlReader}实例)用来读取数据。它是一个可选项,因为这里已经有了一个内建对象来读取JSON数据。
* 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.
*/
/**
* @cfg {DataReader} errorReader
* <p>一个Ext.data.DataReader对象 An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) 当执行"submit"动作出错时被用来读取数据 to be used to read field error messages returned from "submit" actions.
* This is completely optional as there is built-in support for processing JSON.</p>
* <p>The Records which provide messages for the invalid Fields must use the Field name (or id) as the Record ID,
* and must contain a field called "msg" which contains the error message.</p>
* <p>The errorReader does not have to be a full-blown implementation of a DataReader. It simply needs to implement a
* <tt>read(xhr)</tt> function which returns an Array of Records in an object with the following structure:<pre><code>
{
records: recordArray
}
</code></pre>
*/
/**
* @cfg {String} url
* 通讯url地址。该地址也可以由action那里指定。
* The URL to use for form actions if one isn't supplied in the action options.
*/
/**
* @cfg {Boolean} fileUpload
* 当为true时,表单为文件上传类型。Set to true if this form is a file upload.
* <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
* performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
* DOM <tt><form></tt> element temporarily modified to have its
* <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
* to a dynamically generated, hidden <tt><iframe></tt> which is inserted into the document
* but removed after the return data has been gathered.</p>
* <p>The server response is parsed by the browser to create the document for the IFRAME. If the
* server is using JSON to send the return object, then the
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
* must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
* <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
* "<" as "&lt;", "&" as "&amp;" etc.</p>
* <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
* is created containing a <tt>responseText</tt> property in order to conform to the
* requirements of event handlers and callbacks.</p>
* <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
* and some server technologies (notably JEE) may require some custom processing in order to
* retrieve parameter names and parameter values from the packet content.</p>
*/
/**
* @cfg {Object} baseParams
* 表单请求时传递的参数,例{id: '123', foo: 'bar'}。
* Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.
*/
/**
* @cfg {Number} timeout
* 表单动作的超时秒数(默认30秒)。
* Timeout for form actions in seconds (default is 30 seconds).
*/
timeout: 30,
// private
activeAction : null,
/**
* @cfg {Boolean} trackResetOnLoad
* 如果为true,则表单对象的form.reset()方法重置到最后一次加载的数据或setValues()数据,以相对于一开始创建表单那时的数据。
* If set to true, form.reset() resets to the last loaded or setValues() data instead of when the form was first created.
*/
trackResetOnLoad : false,
/**
* @cfg {Boolean} standardSubmit If set to true, standard HTML form submits are used instead of XHR (Ajax) style
* form submissions. (defaults to false)<br>
* <p><b>Note:</b> When using standardSubmit, any the options to {@link #submit} are
* ignored because Ext's Ajax infrastracture is bypassed. To pass extra parameters, you will need to create
* hidden fields within the form.</p>
*/
/**
* 默认的等待提示窗口为Ext.MessageBox.wait。也可以指定一个对象或它的ID做为遮罩目标,如果指定为真则直接遮罩在表单对象上 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.
* @type Mixed
* @property waitMsgTarget
*/
// 私有的
// private
initEl : function(el){
this.el = Ext.get(el);
this.id = this.el.id || Ext.id();
if(!this.standardSubmit){
this.el.on('submit', this.onSubmit, this);
}
this.el.addClass('x-form');
},
/**
* 如果客户端的验证通过则返回真 Get the HTML form Element
* @return Ext.Element
*/
getEl: function(){
return this.el;
},
// 私有的
// private
onSubmit : function(e){
e.stopEvent();
},
// 私有的
// private
destroy: function() {
this.items.each(function(f){
Ext.destroy(f);
});
if(this.el){
this.el.removeAllListeners();
this.el.remove();
}
this.purgeListeners();
},
/**
* 如果客户端的验证通过则返回真。
* 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 ({@link Ext.form.Action.Submit} or
* {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
* to perform application-specific processing.
* @param {String/Object} actionName The name of the predefined action type, 行为名称
* or instance of {@link Ext.form.Action} to perform.
* @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
* All of the config options listed below are supported by both the submit
* and load actions unless otherwise noted (custom actions could also accept
* other config options):<ul>
* 传递给行动作象的选项配制。除非另有声明(自定义的动作仍然可以有附加的选项配制),下面是所有提供给提交与加载动作的选项配制列表。
* <li><b>url</b> : String<p style="margin-left:1em">The url for the action (defaults
* to the form's url.)</p></li>
* <li><b>method</b> : String<p style="margin-left:1em">The form method to use (defaults
* to the form's method, or POST if not defined)</p></li>
* <li><b>params</b> : String/Object<p style="margin-left:1em">The params to pass
* (defaults to the form's baseParams, or none if not defined)</p></li>
* <li><b>headers</b> : Object<p style="margin-left:1em">Request headers to set for the action
* (defaults to the form's default headers)</p></li>
* <li><b>success</b> : Function<p style="margin-left:1em">The callback that will
* be invoked after a successful response. The function is passed the following parameters:<ul>
* <li><code>form</code> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
* <li><code>action</code> : Ext.form.Action<div class="sub-desc">The {@link Ext.form.Action Action} object which
* performed the operation. The {@link Ext.form.Action#result result}
* property of this object may be examined to perform custom postprocessing.</div></li>
* </ul></p></li>
* <li><b>failure</b> : Function<p style="margin-left:1em">The callback that will
* be invoked after a failed transaction attempt. This is invoked for field validation failure,
* communication failure, and in the case of the server returning a failure response packet.
* Which type of failure is indicated in the Action's {@link Ext.form.Action#failureType failureType}.
* The function is passed the following parameters:<ul>
* <li><code>form</code> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
* <li><code>action</code> : Ext.form.Action<div class="sub-desc">The {@link Ext.form.Action Action} object which
* performed the operation. The failure type
* will be in {@link Ext.form.Action#failureType failureType}. The {@link Ext.form.Action#result result}
* property of this object may be examined to perform custom postprocessing.</div></li>
* </ul></p></li>
* <li><b>scope</b> : Object<p style="margin-left:1em">The scope in which to call the
* callback functions (The <tt>this</tt> reference for the callback functions).</p></li>
* <li><b>clientValidation</b> : Boolean<p style="margin-left:1em">Submit Action only.
* Determines whether a Form's fields are validated in a final call to
* {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
* to prevent this. If undefined, pre-submission field validation is performed.</p></li></ul>
* 属性 类型 描述
* ---------------- --------------- ----------------------------------------------------------------------------------
* 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 传递给动作对象的选项配制 (请见 options The options to pass to the action (see {@link #doAction} for details).<br>
* <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
* <p>The following code:</p><pre><code>
myFormPanel.getForm().submit({
clientValidation: true,
url: 'updateConsignment.php',
params: {
newStatus: 'delivered'
},
success: function(form, action) {
Ext.Msg.alert("Success", action.result.msg);
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert("Failure", "Form fields may not be submitted with invalid values");
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert("Failure", "Ajax communication failed");
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert("Failure", action.result.msg);
}
}
});
</code></pre>
* would process the following server response for a successful submission:<pre><code>
{
success: true,
msg: 'Consignment updated'
}
</code></pre>
* and the following server response for a failed submission:<pre><code>
{
success: false,
msg: 'You do not have permission to perform this operation'
}
</code></pre>
* @return {BasicForm} this
*/
submit : function(options){
if(this.standardSubmit){
var v = this.isValid();
if(v){
this.el.dom.submit();
}
return v;
}
this.doAction('submit', options);
return this;
},
/**
* load动作的简写方式。
* Shortcut to do a load action.
* @param {Object} options 传到{@link #doAction}的参数 The options to pass to the action (see {@link #doAction} for details)
* @return {BasicForm} this
*/
load : function(options){
this.doAction('load', options);
return this;
},
/**
* 表单内的元素数据考贝到所传递的Ext.data.Record对象中(beginEdit/endEdit块中进行赋值操作)。
* Persists the values in this form into the passed Ext.data.Record object in a beginEdit/endEdit block.
* @param {Record} 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;
},
/**
* 加载Ext.data.Record对象的数据到表单元素中。 Loads an Ext.data.Record into this form.
* @param {Record} record 加载的record The record to load
* @return {BasicForm} this
*/
loadRecord : function(record){
this.setValues(record.data);
return this;
},
// 私有的
// private
beforeAction : function(action){
var o = action.options;
if(o.waitMsg){
if(this.waitMsgTarget === true){
this.el.mask(o.waitMsg, 'x-mask-loading');
}else if(this.waitMsgTarget){
this.waitMsgTarget = Ext.get(this.waitMsgTarget);
this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
}else{
Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle || 'Please Wait...');
}
}
},
// 私有的
// private
afterAction : function(action, success){
this.activeAction = null;
var o = action.options;
if(o.waitMsg){
if(this.waitMsgTarget === true){
this.el.unmask();
}else if(this.waitMsgTarget){
this.waitMsgTarget.unmask();
}else{
Ext.MessageBox.updateProgress(1);
Ext.MessageBox.hide();
}
}
if(success){
if(o.reset){
this.reset();
}
Ext.callback(o.success, o.scope, [this, action]);
this.fireEvent('actioncomplete', this, action);
}else{
Ext.callback(o.failure, o.scope, [this, action]);
this.fireEvent('actionfailed', this, action);
}
},
/**
* 按传递的ID、索引或名称查询表单中的元素。
* Find a Ext.form.Field in this form by id, dataIndex, name or hiddenName.
* @param {String} id 所要查询的值 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 即可以是像这样的[{id:'fieldId', msg:'The message'},...]的数组,也可以是像这样 {id: msg, id2: msg2} 的一个HASH结构对象。Either an array in the form [{id:'fieldId', msg:'The message'},...], or an object hash of {id: msg, id2: msg2}
* @return {BasicForm} this
*/
markInvalid : function(errors){
if(Ext.isArray(errors)){
for(var i = 0, len = errors.length; i < len; i++){
var fieldError = errors[i];
var f = this.findField(fieldError.id);
if(f){
f.markInvalid(fieldError.msg);
}
}
}else{
var field, id;
for(id in errors){
if(typeof errors[id] != 'function' && (field = this.findField(id))){
field.markInvalid(errors[id]);
}
}
}
return this;
},
/**
* 表单元素批量赋值。
* Set values for fields in this form in bulk.
* @param {Array/Object} values 既可以是数组也或是可以是像这样的一个HASH结构对象。
* Either an arrayor an object hash in the form:<br><br><code><pre>
[{id:'clientName', value:'Fred. Olsen Lines'},
{id:'portOfLoading', value:'FXT'},
{id:'portOfDischarge', value:'OSL'} ]</pre></code><br><br>
* @return {BasicForm} this
*/
setValues : function(values){
if(Ext.isArray(values)){ // array of objects
for(var i = 0, len = values.length; i < len; i++){
var v = values[i];
var f = this.findField(v.id);
if(f){
f.setValue(v.value);
if(this.trackResetOnLoad){
f.originalValue = f.getValue();
}
}
}
}else{ // object hash
var field, id;
for(id in values){
if(typeof values[id] != 'function' && (field = this.findField(id))){
field.setValue(values[id]);
if(this.trackResetOnLoad){
field.originalValue = field.getValue();
}
}
}
}
return this;
},
/**
* <p>
* 返回以键/值形式包函表单所有元素的信息对象。
* 如果表单元素中有相同名称的对象,则返回一个同名数组。 </p>
* <p>
* Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
* If multiple fields exist with the same name they are returned as an array.</p>
* <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
* the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the the
* value can potentionally be the emptyText of a field.</p>
* <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
* the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the the
* value can potentionally be the emptyText of a field.</p>
* @param {Boolean} asString 如果为真则返回一个字串,如果为假则返回一个键/值对象。(默认为假) (optional)false to return the values as an object (defaults to returning as a string)
* @return {String/Object}
*/
getValues : function(asString){
var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
if(asString === true){
return fs;
}
return Ext.urlDecode(fs);
},
getFieldValues : function(){
var o = {};
this.items.each(function(f){
o[f.getName()] = f.getValue();
});
return o;
},
/**
* 清除表单中全部由校验错误的信息。
* 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;
},
/**
* 向表单中加入组件,成为collection中的一员。这样做不会渲染传入的组件,只会通知表单要验证这个field,或分配值给field。
* Add Ext.form Components to this form's Collection.
* This does not result in rendering of
* the passed Component,
* it just enables the form to validate Fields, and distribute values to Fields.
* <p><b>通常你不会用到该函数。要渲染的话,应该是在{@link Ext.Container Container}中加入Field,
* 准确些来说是其子类{@link Ext.form.FormPanel FormPanel}。FormPanel会其Collection内子元素特别处理与协调。</b></p>
* <p><b>You will not usually call this function. In order to be rendered, a Field must be added
* to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
* The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
* collection.</b></p>
* @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;
},
/**
* 遍历表单所有已{@link #add 添加}的{@link Ext.form.Field Field}元素,获取他们的id值,并生成到对应的dom元素上(用{@link Ext.form.Field#applyToMarkup}方法)。
* Iterates through the {@link Ext.form.Field Field}s,which have been {@link #add add}ed to this BasicForm,
* checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
* @return {BasicForm} this
*/
render : function(){
this.items.each(function(f){
if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
f.applyToMarkup(f.id);
}
});
return this;
},
/**
* 遍历表单元素,对每一个元素调用{@link Ext#apply}方法,附加上传入的对象参数。
* Calls {@link Ext#apply} for all fields in this form with the passed object.
* @param {Object} values
* @return {BasicForm} this
*/
applyToFields : function(o){
this.items.each(function(f){
Ext.apply(f, o);
});
return this;
},
/**
* 遍历表单元素,对每一个元素调用{@link Ext#applyIf}方法,附加上传入的对象参数。
* Calls {@link Ext#applyIf} for all field in this form with the passed object.
* @param {Object} values
* @return {BasicForm} this
*/
applyIfToFields : function(o){
this.items.each(function(f){
Ext.applyIf(f, o);
});
return this;
},
callFieldMethod : function(fnName, args){
args = args || [];
this.items.each(function(f){
if(typeof f[fnName] == 'function'){
f[fnName].apply(f, args);
}
});
return this;
}
});
// back compat
Ext.BasicForm = Ext.form.BasicForm; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.TextField
* @extends Ext.form.Field
* 基本的文本字段。可以被当作传统文本转入框的直接代替, 或者当作其他更复杂输入控件的基础类(比如 {@link Ext.form.TextArea} 和 {@link Ext.form.ComboBox})。<br />
* 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}).
* @constructor 创建一个 TextField 对象 Creates a new TextField
* @param {Object} config 配置项 Configuration options
*/
Ext.form.TextField = Ext.extend(Ext.form.Field, {
/**
* @cfg {String} vtypeText
* 在当前字段的{@link #vtype}中,制定一个错误信息代替默认的(默认为null)。如vtype不设置该项就无效。
* A custom error message to display in place of the default message provided
* for the {@link #vtype} currently set for this field (defaults to ''). Only applies if vtype is set, else ignored.
*/
/**
* @cfg {RegExp} stripCharsRe
* 一个JavaScript正则表达式,用于在进行验证该动作之前抽离不需要的内容(默认为null)。
* A JavaScript RegExp object used to strip unwanted content from the value before validation (defaults to null).
*/
/**
* @cfg {Boolean} grow 当值为 true 时表示字段可以根据内容自动伸缩。
* True if this field should automatically grow and shrink to its content
*/
grow : false,
/**
* @cfg {Number} growMin 当 grow = true 时允许的字段最小宽度(默认为 30)
* The minimum width to allow when grow = true (defaults to 30)
*/
growMin : 30,
/**
* @cfg {Number} growMax 当 grow = true 时允许的字段最大宽度(默认为 800)
* The maximum width to allow when grow = true (defaults to 800)
*/
growMax : 800,
/**
* @cfg {String} vtype 中定义的效验类型名(默认为 null)
* A validation type name as defined in {@link Ext.form.VTypes} (defaults to null)
*/
vtype : null,
/**
* @cfg {RegExp} maskRe 一个用来过滤无效按键的正则表达式(默认为 null)
* An input mask regular expression that will be used to filter keystrokes that don't match (defaults to null)
*/
maskRe : null,
/**
* @cfg {Boolean} disableKeyFilter 值为 true 时禁用输入按键过滤(默认为 false)
* True to disable input keystroke filtering (defaults to false)
*/
disableKeyFilter : false,
/**
* @cfg {Boolean} allowBlank 值为 false 时将效验输入字符个数大于0(默认为 true)
* False to validate that the value length > 0 (defaults to true)
*/
allowBlank : true,
/**
* @cfg {Number} minLength 输入字段所需的最小字符数(默认为 0)
* Minimum input field length required (defaults to 0)
*/
minLength : 0,
/**
* @cfg {Number} maxLength 输入字段允许的最大字符数(默认为 Number.MAX_VALUE)
* Maximum input field length allowed (defaults to Number.MAX_VALUE)
*/
maxLength : Number.MAX_VALUE,
/**
* @cfg {String} minLengthText 输入字符数小于最小字符数时显示的文本(默认为"The minimum length for this field is {minLength}")
* Error text to display if the minimum length validation fails (defaults to "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}")
* Error text to display if the maximum length validation fails (defaults to "The maximum length for this field is {maxLength}")
*/
maxLengthText : "The maximum length for this field is {0}",
/**
* @cfg {Boolean} selectOnFocus 值为 ture 时表示字段获取焦点时自动选择字段既有文本(默认为 false)。
* True to automatically select any existing field text when the field receives input focus (defaults to false)
*/
selectOnFocus : false,
/**
* @cfg {String} blankText 当允许为空效验失败时显示的错误文本(默认为 "This field is required")。
* Error text to display if the allow blank validation fails (defaults to "This field is required")
*/
blankText : "This field is required",
/**
* @cfg {Function} validator
* 字段效验时调用的自定义的效验函数(默认为 null)。
* 如果启用此项,则此函数将在所有基础效验({@link #allowBlank}、{@link #minLength}、{@link #maxLength}和任意的{@link #vtype})成功之后被调用,调用函数时传递的参数为该字段的值。且此函数的有效返回应为成功时返回 true,失败时返回错误文本。
* A custom validation function to be called during field validation (defaults to null).
* If specified, this function will be called only after the built-in validations ({@link #allowBlank}, {@link #minLength},
* {@link #maxLength}) and any configured {@link #vtype} all return true. This function will be passed the current field
* value and expected to return boolean true if the value is valid or a string error message if invalid.
*/
validator : null,
/**
* @cfg {RegExp} regex 一个用以在效验时使用的 JavaScript 正则表达式对象(默认为 null)。如果启用此项,则此正则表达式将在所有基础效验成功之后被执行,执行此正则表达式时传递的参数为该字段的值。如果效验失败,则根据{@link #regexText}的设置将字段标记为无效。
* A JavaScript RegExp object to be tested against the field value during validation (defaults to null).
* If available, this regex will be evaluated only after the basic validators all return true, and will be passed the
* current field value. If the test fails, the field will be marked invalid using {@link #regexText}.
*/
regex : null,
/**
* @cfg {String} regexText 当{@link #regex}被设置且效验失败时显示的错误文本(默认为 "")。
* The error text to display if {@link #regex} is used and the test fails during validation (defaults to "")
*/
regexText : "",
/**
* @cfg {String} emptyText 空字段中显示的文本(默认为 null)。注意,只要这个字段是被激活的而且name属性是有被指定的,那么也会发送到服务端。
* The default text to place into an empty field (defaults to null). Note that this
* value will be submitted to the server if this field is enabled and configured with a {@link #name}.
*/
emptyText : null,
/**
* @cfg {String} emptyClass {@link #emptyText}使用的CSS样式类名(默认为 'x-form-empty-field')。此类的添加与移除均由当前字段是否有值来自动处理。
* The CSS class to apply to an empty field to style the {@link #emptyText} (defaults to
* 'x-form-empty-field'). This class is automatically added and removed as needed depending on the current field value.
*/
emptyClass : 'x-form-empty-field',
/**
* @cfg {Boolean} enableKeyEvents True表示,为HTML的input输入字段激活键盘事件的代理(默认为false)
* True to enable the proxying of key events for the HTML input field (defaults to false)
*/
initComponent : function(){
Ext.form.TextField.superclass.initComponent.call(this);
this.addEvents(
/**
* @event autosize
* 当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.
* @param {Ext.form.Field} this 文本输入字段。This text field
* @param {Number} width 新宽度。The new field width
*/
'autosize',
/**
* @event keydown
* 输入字段键盘下降时的事件。该事件只会在enableKeyEvents为true时有效。
* Keydown input field event. This event only fires if enableKeyEvents is set to true.
* @param {Ext.form.TextField} this 文本输入字段。This text field
* @param {Ext.EventObject} e
*/
'keydown',
/**
* @event keyup
* 输入字段键盘升起时的事件。该事件只会在enableKeyEvents为true时有效。
* Keyup input field event. This event only fires if enableKeyEvents is set to true.
* @param {Ext.form.TextField} this 文本输入字段。This text field
* @param {Ext.EventObject} e
*/
'keyup',
/**
* @event keypress
* 输入字段键盘按下时的事件。该事件只会在enableKeyEvents为true时有效。
* Keypress input field event. This event only fires if enableKeyEvents is set to true.
* @param {Ext.form.TextField} this 文本输入字段。This text field
* @param {Ext.EventObject} e
*/
'keypress'
);
},
// private
initEvents : function(){
Ext.form.TextField.superclass.initEvents.call(this);
if(this.validationEvent == 'keyup'){
this.validationTask = new Ext.util.DelayedTask(this.validate, this);
this.mon(this.el, 'keyup', this.filterValidation, this);
}
else if(this.validationEvent !== false){
this.mon(this.el, this.validationEvent, this.validate, this, {buffer: this.validationDelay});
}
if(this.selectOnFocus || this.emptyText){
this.on("focus", this.preFocus, this);
this.mon(this.el, 'mousedown', function(){
if(!this.hasFocus){
this.el.on('mouseup', function(e){
e.preventDefault();
}, this, {single:true});
}
}, 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.mon(this.el, 'keypress', this.filterKeys, this);
}
if(this.grow){
this.mon(this.el, 'keyup', this.onKeyUpBuffered, this, {buffer: 50});
this.mon(this.el, 'click', this.autoSize, this);
}
if(this.enableKeyEvents){
this.mon(this.el, 'keyup', this.onKeyUp, this);
this.mon(this.el, 'keydown', this.onKeyDown, this);
this.mon(this.el, 'keypress', this.onKeyPress, this);
}
},
processValue : function(value){
if(this.stripCharsRe){
var newValue = value.replace(this.stripCharsRe, '');
if(newValue !== value){
this.setRawValue(newValue);
return newValue;
}
}
return value;
},
filterValidation : function(e){
if(!e.isNavKeyPress()){
this.validationTask.delay(this.validationDelay);
}
},
//private
onDisable: function(){
Ext.form.TextField.superclass.onDisable.call(this);
if(Ext.isIE){
this.el.dom.unselectable = 'on';
}
},
//private
onEnable: function(){
Ext.form.TextField.superclass.onEnable.call(this);
if(Ext.isIE){
this.el.dom.unselectable = '';
}
},
// private
onKeyUpBuffered : function(e){
if(!e.isNavKeyPress()){
this.autoSize();
}
},
// private
onKeyUp : function(e){
this.fireEvent('keyup', this, e);
},
// private
onKeyDown : function(e){
this.fireEvent('keydown', this, e);
},
// private
onKeyPress : function(e){
this.fireEvent('keypress', this, e);
},
/**
* 将字段值重置为原始值,并清除所有效验信息。如果原始值为空时还将使 emptyText 和 emptyClass 属性生效。
* 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.
*/
reset : function(){
Ext.form.TextField.superclass.reset.call(this);
this.applyEmptyText();
},
applyEmptyText : function(){
if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
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){
if(e.ctrlKey){
return;
}
var k = e.getKey();
if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
return;
}
var c = e.getCharCode(), cc = String.fromCharCode(c);
if(!Ext.isGecko && 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 要效验的值 The value to validate
* @return {Boolean} 值有效时返回true,否则返回 false True if the value is valid, else 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;
},
/**
* 选择此字段中的文本。
* Selects text in this field
* @param {Number} start (可选项) 选择区域的索引起点(默认为 0) (optional)The index where the selection should start (defaults to 0)
* @param {Number} end (可选项) 选择区域的索引终点(默认为文本长度) (optional)The index where the selection should end (defaults to the text length)
*/
selectText : function(start, end){
var v = this.getRawValue();
var doFocus = false;
if(v.length > 0){
start = start === undefined ? 0 : start;
end = end === undefined ? v.length : end;
var d = this.el.dom;
if(d.setSelectionRange){
d.setSelectionRange(start, end);
}else if(d.createTextRange){
var range = d.createTextRange();
range.moveStart("character", start);
range.moveEnd("character", end-v.length);
range.select();
}
doFocus = Ext.isGecko || Ext.isOpera;
}else{
doFocus = true;
}
if(doFocus){
this.focus();
}
},
/**
* 自动增长字段宽度以便容纳字段所允许的最大文本。仅在 grow = true 时有效,并触发{@link #autosize}事件。
* 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 {@link #autosize} event.
*/
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;
Ext.removeNode(d);
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);
}
});
Ext.reg('textfield', Ext.form.TextField);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.NumberField
* @extends Ext.form.TextField
* 数字型文本域,提供自动键击过滤和数字校验。 <br />
* Numeric text field that provides automatic keystroke filtering and numeric validation.
* @constructor 创建一个新的NumberField对象 Creates a new NumberField
* @param {Object} config 配置选项 Configuration options
*/
Ext.form.NumberField = Ext.extend(Ext.form.TextField, {
/**
* @cfg {RegExp} stripCharsRe @hide
*/
/**
* @cfg {String} fieldClass 设置该域的CSS,默认为x-form-field x-form-num-field。
* The default CSS class for the field (defaults to "x-form-field x-form-num-field")
*/
fieldClass: "x-form-field x-form-num-field",
/**
* @cfg {Boolean} allowDecimals 值为 False时将不接受十进制值 (默认为true)。
* False to disallow decimal values (defaults to true)
*/
allowDecimals : true,
/**
* @cfg {String} decimalSeparator 设置十进制数分割符(默认为 '.')(??指的大概是小数点) 。
* Character(s) to allow as the decimal separator (defaults to '.')
*/
decimalSeparator : ".",
/**
* @cfg {Number} decimalPrecision 设置小数点后最大精确位数(默认为 2)。
* The maximum precision to display after the decimal separator (defaults to 2)
*/
decimalPrecision : 2,
/**
* @cfg {Boolean} allowNegative 值为 False时只允许为正数(默认为 true,即默认允许为负数)。
* False to prevent entering a negative sign (defaults to true)
*/
allowNegative : true,
/**
* @cfg {Number} minValue 允许的最小值(默认为Number.NEGATIVE_INFINITY)。
* The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
*/
minValue : Number.NEGATIVE_INFINITY,
/**
* @cfg {Number} maxValue 允许的最大值(默认为Number.MAX_VALUE)。
* The maximum allowed value (defaults to Number.MAX_VALUE)
*/
maxValue : Number.MAX_VALUE,
/**
* @cfg {String} minText 最小值验证失败(ps:超出设置的最小值范围)时显示该错误信息(默认为"The minimum value for this field is {minValue}")。
* Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
*/
minText : "The minimum value for this field is {0}",
/**
* @cfg {String} maxText 最大值验证失败(ps:超出设置的最大值范围)时显示该错误信息(默认为 "The maximum value for this field is {maxValue}")。
* Error text to display if the maximum value validation fails (defaults to "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")。
* Error text to display if the value is not a valid number. For example, this can happen
* if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
*/
nanText : "{0} is not a valid number",
/**
* @cfg {String} baseChars 接受有效数字的一组基础字符(默认为0123456789)。
* The base set of characters to evaluate as valid numbers (defaults to '0123456789').
*/
baseChars : "0123456789",
// private
initEvents : function(){
Ext.form.NumberField.superclass.initEvents.call(this);
var allowed = this.baseChars+'';
if(this.allowDecimals){
allowed += this.decimalSeparator;
}
if(this.allowNegative){
allowed += "-";
}
this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
var keyPress = function(e){
var k = e.getKey();
if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
return;
}
var c = e.getCharCode();
if(allowed.indexOf(String.fromCharCode(c)) === -1){
e.stopEvent();
}
};
this.mon(this.el, 'keypress', keyPress, this);
},
// private
validateValue : function(value){
if(!Ext.form.NumberField.superclass.validateValue.call(this, value)){
return false;
}
if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
return true;
}
value = String(value).replace(this.decimalSeparator, ".");
if(isNaN(value)){
this.markInvalid(String.format(this.nanText, value));
return false;
}
var num = this.parseValue(value);
if(num < this.minValue){
this.markInvalid(String.format(this.minText, this.minValue));
return false;
}
if(num > this.maxValue){
this.markInvalid(String.format(this.maxText, this.maxValue));
return false;
}
return true;
},
getValue : function(){
return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this)));
},
setValue : function(v){
v = typeof v == 'number' ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
Ext.form.NumberField.superclass.setValue.call(this, v);
},
// private
parseValue : function(value){
value = parseFloat(String(value).replace(this.decimalSeparator, "."));
return isNaN(value) ? '' : value;
},
// private
fixPrecision : function(value){
var nan = isNaN(value);
if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
return nan ? '' : value;
}
return parseFloat(parseFloat(value).toFixed(this.decimalPrecision));
},
beforeBlur : function(){
var v = this.parseValue(this.getRawValue());
if(v || v === 0){
this.setValue(this.fixPrecision(v));
}
}
});
Ext.reg('numberfield', Ext.form.NumberField); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.HtmlEditor
* @extends Ext.form.Field
* 提供一个轻量级的HTML编辑器组件。Safari环境下有些工具条的功能还不能使用,所以它会自动隐藏没有用的功能。在配置项的文档中有适当提示了。<br />
* Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be
* automatically hidden when needed. These are noted in the config options where appropriate.
* <br><br>
* 编辑器工具条的提示文本均在{@link #buttonTips}属性中定义。只要单例对象{@link Ext.QuickTips}执行{@link Ext.QuickTips#init initialized}方法便可以显示出来。<br />
* The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not
* enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}.
* <br><br><b>
* 注意: 此组件不支持由 Ext.form.Field 继承而来的 focus/blur 和效验函数。<br />
* Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT supported by this editor.</b>
* <br><br>编辑器组件是非常敏感的,因此它并不能应用于所有标准字段的场景。在 Safari 和 Firefox 中,在任何 display 属性被设置为 'none' 的元素中使用该组件都会造成错误。<br />
* An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
* any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs.
* <br><br>Example usage:
* <pre><code>
// 普通方式渲染
// Simple example rendered with default options:
Ext.QuickTips.init(); //激活提示贴 enable tooltips
new Ext.form.HtmlEditor({
renderTo: Ext.getBody(),
width: 800,
height: 300
});
// 声明xtype是什么,还有一些参数:
// Passed via xtype into a container and with custom options:
Ext.QuickTips.init(); //激活提示贴 enable tooltips
new Ext.Panel({
title: 'HTML Editor',
renderTo: Ext.getBody(),
width: 600,
height: 300,
frame: true,
layout: 'fit',
items: {
xtype: 'htmleditor',
enableColors: false,
enableAlignments: false
}
});
</code></pre>
* @constructor
* Create a new HtmlEditor
* @param {Object} config
*/
Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, {
/**
* @cfg {Boolean} enableFormat 允许粗体、斜体和下划线按钮(默认为 true)。
* Enable the bold, italic and underline buttons (defaults to true)
*/
enableFormat : true,
/**
* @cfg {Boolean} enableFontSize 允许增大/缩小字号按钮(默认为 true)。
* Enable the increase/decrease font size buttons (defaults to true)
*/
enableFontSize : true,
/**
* @cfg {Boolean} enableColors 允许前景/高亮颜色按钮(默认为 true)。
* Enable the fore/highlight color buttons (defaults to true)
*/
enableColors : true,
/**
* @cfg {Boolean} enableAlignments 允许居左、居中、居右按钮(默认为 true)。
* Enable the left, center, right alignment buttons (defaults to true)
*/
enableAlignments : true,
/**
* @cfg {Boolean} enableLists 允许项目和列表符号按钮。Safari 中无效。(默认为 true)。
* Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true)
*/
enableLists : true,
/**
* @cfg {Boolean} enableSourceEdit 允许切换到源码编辑按钮。Safari 中无效。(默认为 true)。
* Enable the switch to source edit button. Not available in Safari. (defaults to true)
*/
enableSourceEdit : true,
/**
* @cfg {Boolean} enableLinks 允许创建链接按钮。Safari 中无效。(默认为 true)。
* Enable the create link button. Not available in Safari. (defaults to true)
*/
enableLinks : true,
/**
* @cfg {Boolean} enableFont 允许字体选项。Safari 中无效。(默认为 true)。
* Enable font selection. Not available in Safari. (defaults to true)
*/
enableFont : true,
/**
* @cfg {String} createLinkText 创建链接时提示的默认文本。
* The default text for the create link prompt
*/
createLinkText : 'Please enter the URL for the link:',
/**
* @cfg {String} defaultLinkValue 创建链接时提示的默认值(默认为 http:/ /)。
* The default value for the create link prompt (defaults to http:/ /)
*/
defaultLinkValue : 'http:/'+'/',
/**
* @cfg {Array} fontFamilies 一个有效的字体列表数组。
* An array of available font families
*/
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)。
* Fires when the editor is fully initialized (including the iframe)
* @param {HtmlEditor} this
*/
'initialize',
/**
* @event activate
* 当编辑器首次获取焦点时触发。所有的插入操作都必须等待此事件完成。
* Fires when the editor is first receives the focus. Any insertion must wait until after this event.
* @param {HtmlEditor} this
*/
'activate',
/**
* @event beforesync
* 在把编辑器的 iframe 中的内容同步更新到文本域之前触发。返回false可取消更新。
* Fires before the textarea is updated with content from the editor iframe. Return false to cancel the sync.
* @param {HtmlEditor} this
* @param {String} html
*/
'beforesync',
/**
* @event beforepush
* 在把文本域中的内容同步更新到编辑器的iframe之前触发。返回 false 可取消更新。
* Fires before the iframe editor is updated with content from the textarea. Return false to cancel the push.
* @param {HtmlEditor} this
* @param {String} html
*/
'beforepush',
/**
* @event sync
* 当把编辑器的 iframe 中的内容同步更新到文本域后触发。
* Fires when the textarea is updated with content from the editor iframe.
* @param {HtmlEditor} this
* @param {String} html
*/
'sync',
/**
* @event push
* 当把文本域中的内容同步更新到编辑器的iframe后触发。
* Fires when the iframe editor is updated with content from the textarea.
* @param {HtmlEditor} this
* @param {String} html
*/
'push',
/**
* @event editmodechange
* 当切换了编辑器的编辑模式后触发。
* Fires when the editor switches edit modes
* @param {HtmlEditor} this
* @param {Boolean} sourceEdit 值为true时表示源码编辑模式,false 表示常规编辑模式。
* True if source edit, false if standard editing.
*/
'editmodechange'
)
},
// private
createFontOptions : function(){
var buf = [], fs = this.fontFamilies, ff, lc;
for(var i = 0, len = fs.length; i< len; i++){
ff = fs[i];
lc = ff.toLowerCase();
buf.push(
'<option value="',lc,'" style="font-family:',ff,';"',
(this.defaultFont == lc ? ' selected="true">' : '>'),
ff,
'</option>'
);
}
return buf.join('');
},
/**
* 受保护的方法一般不会直接调用。重写该方法可添加制定的工具条。
* Protected method that will not generally be called directly. It
* is called when the editor creates its toolbar. Override this method if you need to
* add custom toolbar buttons.
* @param {HtmlEditor} editor
*/
createToolbar : function(editor){
var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled();
function btn(id, toggle, handler){
return {
itemId : id,
cls : 'x-btn-icon x-edit-'+id,
enableToggle:toggle !== false,
scope: editor,
handler:handler||editor.relayBtnCmd,
clickEvent:'mousedown',
tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined,
tabIndex:-1
};
}
// build the toolbar
var tb = new Ext.Toolbar({
renderTo:this.wrap.dom.firstChild
});
// stop form submits
this.mon(tb.el, 'click', function(e){
e.preventDefault();
});
if(this.enableFont && !Ext.isSafari2){
this.fontSelect = tb.el.createChild({
tag:'select',
cls:'x-font-select',
html: this.createFontOptions()
});
this.mon(this.fontSelect, 'change', function(){
var font = this.fontSelect.dom.value;
this.relayCmd('fontname', font);
this.deferFocus();
}, this);
tb.add(
this.fontSelect.dom,
'-'
);
};
if(this.enableFormat){
tb.add(
btn('bold'),
btn('italic'),
btn('underline')
);
};
if(this.enableFontSize){
tb.add(
'-',
btn('increasefontsize', false, this.adjustFont),
btn('decreasefontsize', false, this.adjustFont)
);
};
if(this.enableColors){
tb.add(
'-', {
itemId:'forecolor',
cls:'x-btn-icon x-edit-forecolor',
clickEvent:'mousedown',
tooltip: tipsEnabled ? editor.buttonTips['forecolor'] || undefined : undefined,
tabIndex:-1,
menu : new Ext.menu.ColorMenu({
allowReselect: true,
focus: Ext.emptyFn,
value:'000000',
plain:true,
selectHandler: function(cp, color){
this.execCmd('forecolor', Ext.isSafari || Ext.isIE ? '#'+color : color);
this.deferFocus();
},
scope: this,
clickEvent:'mousedown'
})
}, {
itemId:'backcolor',
cls:'x-btn-icon x-edit-backcolor',
clickEvent:'mousedown',
tooltip: tipsEnabled ? editor.buttonTips['backcolor'] || undefined : 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.isSafari2){
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;
},
/**
* 受保护的方法一般不会直接调用。在编辑器初始化iframe的HTML时,就调用该方法。如果你想修改iframe的内容就覆盖该方法吧(例如修改某些样式)。
* Protected method that will not generally be called directly. It
* is called when the editor initializes the iframe with HTML contents. Override this method if you
* want to change the initialization markup of the iframe (e.g. to add stylesheets).
*/
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
getEditorBody : function(){
return this.doc.body || this.doc.documentElement;
},
// private
getDoc : function(){
return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document);
},
// private
getWin : function(){
return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name];
},
// private
onRender : function(ct, position){
Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position);
this.el.dom.style.border = '0 none';
this.el.dom.setAttribute('tabIndex', -1);
this.el.addClass('x-hidden');
if(Ext.isIE){ // fix IE 1px bogus margin
this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;')
}
this.wrap = this.el.wrap({
cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
});
this.createToolbar(this);
this.tb.items.each(function(item){
if(item.itemId != 'sourceedit'){
item.disable();
}
});
this.tb.doLayout();
this.createIFrame();
if(!this.width){
var sz = this.el.getSize();
this.setSize(sz.width, this.height || sz.height);
}
},
createIFrame: function(){
var iframe = document.createElement('iframe');
iframe.name = Ext.id();
iframe.frameBorder = '0';
iframe.src = Ext.isIE ? Ext.SSL_SECURE_URL : "javascript:;";
this.wrap.dom.appendChild(iframe);
this.iframe = iframe;
this.initFrame();
if(this.autoMonitorDesignMode !== false){
this.monitorTask = Ext.TaskMgr.start({
run: this.checkDesignMode,
scope: this,
interval:100
});
}
},
initFrame : function(){
this.doc = this.getDoc();
this.win = this.getWin();
this.doc.open();
this.doc.write(this.getDocMarkup());
this.doc.close();
var task = { // must defer to wait for browser to be ready
run : function(){
if(this.doc.body || this.doc.readyState == 'complete'){
Ext.TaskMgr.stop(task);
this.doc.designMode="on";
this.initEditor.defer(10, this);
}
},
interval : 10,
duration:10000,
scope: this
};
Ext.TaskMgr.start(task);
},
checkDesignMode : function(){
if(this.wrap && this.wrap.dom.offsetWidth){
var doc = this.getDoc();
if(!doc){
return;
}
if(!doc.editorInitialized || String(doc.designMode).toLowerCase() != 'on'){
this.initFrame();
}
}
},
// private
onResize : function(w, h){
Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments);
if(this.el && this.iframe){
if(typeof w == 'number'){
var aw = w - this.wrap.getFrameWidth('lr');
this.el.setWidth(this.adjustWidth('textarea', aw));
this.iframe.style.width = aw + 'px';
}
if(typeof h == 'number'){
var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight();
this.el.setHeight(this.adjustWidth('textarea', ah));
this.iframe.style.height = ah + 'px';
if(this.doc){
this.getEditorBody().style.height = (ah - (this.iframePad*2)) + 'px';
}
}
}
},
/**
* 在标准模式与源码模式下切换。
* Toggles the editor between standard and source edit mode.
* @param {Boolean} sourceEdit (可选的)True表示源码模式,false表示标准模式 (optional) True for source edit, false for standard
*/
toggleSourceEdit : function(sourceEditMode){
if(sourceEditMode === undefined){
sourceEditMode = !this.sourceEditMode;
}
this.sourceEditMode = sourceEditMode === true;
var btn = this.tb.items.get('sourceedit');
if(btn.pressed !== this.sourceEditMode){
btn.toggle(this.sourceEditMode);
return;
}
if(this.sourceEditMode){
this.tb.items.each(function(item){
if(item.itemId != 'sourceedit'){
item.disable();
}
});
this.syncValue();
this.iframe.className = 'x-hidden';
this.el.removeClass('x-hidden');
this.el.dom.removeAttribute('tabIndex');
this.el.focus();
}else{
if(this.initialized){
this.tb.items.each(function(item){
item.enable();
});
}
this.pushValue();
this.iframe.className = '';
this.el.addClass('x-hidden');
this.el.dom.setAttribute('tabIndex', -1);
this.deferFocus();
}
var lastSize = this.lastSize;
if(lastSize){
delete this.lastSize;
this.setSize(lastSize);
}
this.fireEvent('editmodechange', this, this.sourceEditMode);
},
// private used internally
createLink : function(){
var url = prompt(this.createLinkText, this.defaultLinkValue);
if(url && url != 'http:/'+'/'){
this.relayCmd('createlink', url);
}
},
// private (for BoxComponent)
adjustSize : Ext.BoxComponent.prototype.adjustSize,
// private (for BoxComponent)
getResizeEl : function(){
return this.wrap;
},
// private (for BoxComponent)
getPositionEl : function(){
return this.wrap;
},
// private
initEvents : function(){
this.originalValue = this.getValue();
},
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
markInvalid : Ext.emptyFn,
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
clearInvalid : Ext.emptyFn,
// docs inherit from Field
setValue : function(v){
Ext.form.HtmlEditor.superclass.setValue.call(this, v);
this.pushValue();
},
/**
* 受保护的方法一般不会直接调用。如果你需要自定义HTML cleanup,那么你要重写该方法。
* Protected method that will not generally be called directly. If you need/want
* custom HTML cleanup, this is the method you should override.
* @param {String} html 被执行清理的HTMLThe HTML to be cleaned
* @return {String} 干净的HTML The cleaned 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;
},
/**
* 受保护的方法, 一般不会被直接调用。它会通过读取编辑器中当前选中区域的标记状态触发对工具栏的更新操作。
* Protected method that will not generally be called directly. Syncs the contents of the editor iframe with the textarea.
*/
syncValue : function(){
if(this.initialized){
var bd = this.getEditorBody();
var html = bd.innerHTML;
if(Ext.isSafari){
var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
var m = bs.match(/text-align:(.*?);/i);
if(m && m[1]){
html = '<div style="'+m[0]+'">' + html + '</div>';
}
}
html = this.cleanHtml(html);
if(this.fireEvent('beforesync', this, html) !== false){
this.el.dom.value = html;
this.fireEvent('sync', this, html);
}
}
},
//docs inherit from Field
getValue : function() {
this.syncValue();
return Ext.form.HtmlEditor.superclass.getValue.call(this);
},
/**
* 受保护的方法一般不会直接调用。把textarea的值赋给iframe中的编辑器。
* Protected method that will not generally be called directly. Pushes the value of the textarea
* into the iframe editor.
*/
pushValue : function(){
if(this.initialized){
var v = this.el.dom.value;
if(!this.activated && v.length < 1){
v = ' ';
}
if(this.fireEvent('beforepush', this, v) !== false){
this.getEditorBody().innerHTML = v;
this.fireEvent('push', this, v);
}
}
},
// private
deferFocus : function(){
this.focus.defer(10, this);
},
// docs inherit from Field
focus : function(){
if(this.win && !this.sourceEditMode){
this.win.focus();
}else{
this.el.focus();
}
},
// private
initEditor : function(){
var dbody = this.getEditorBody();
var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat');
ss['background-attachment'] = 'fixed'; // w3c
dbody.bgProperties = 'fixed'; // ie
Ext.DomHelper.applyStyles(dbody, ss);
if(this.doc){
try{
Ext.EventManager.removeAll(this.doc);
}catch(e){}
}
this.doc = this.getDoc();
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.doc.editorInitialized = true;
this.pushValue();
},
// private
onDestroy : function(){
if(this.monitorTask){
Ext.TaskMgr.stop(this.monitorTask);
}
if(this.rendered){
this.tb.items.each(function(item){
if(item.menu){
item.menu.removeAll();
if(item.menu.el){
item.menu.el.destroy();
}
}
item.destroy();
});
this.wrap.dom.innerHTML = '';
this.wrap.remove();
}
},
// private
onFirstFocus : function(){
this.activated = true;
this.tb.items.each(function(item){
item.enable();
});
if(Ext.isGecko){ // prevent silly gecko errors
this.win.focus();
var s = this.win.getSelection();
if(!s.focusNode || s.focusNode.nodeType != 3){
var r = s.getRangeAt(0);
r.selectNodeContents(this.getEditorBody());
r.collapse(true);
this.deferFocus();
}
try{
this.execCmd('useCSS', true);
this.execCmd('styleWithCSS', false);
}catch(e){}
}
this.fireEvent('activate', this);
},
// private
adjustFont: function(btn){
var adjust = btn.itemId == 'increasefontsize' ? 1 : -1;
var v = parseInt(this.doc.queryCommandValue('FontSize') || 2, 10);
if(Ext.isSafari3 || Ext.isAir){
// Safari 3 values
// 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px
if(v <= 10){
v = 1 + adjust;
}else if(v <= 13){
v = 2 + adjust;
}else if(v <= 16){
v = 3 + adjust;
}else if(v <= 18){
v = 4 + adjust;
}else if(v <= 24){
v = 5 + adjust;
}else {
v = 6 + adjust;
}
v = v.constrain(1, 6);
}else{
if(Ext.isSafari){ // safari
adjust *= 2;
}
v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0);
}
this.execCmd('FontSize', v);
},
// private
onEditorEvent : function(e){
this.updateToolbar();
},
/**
* 受保护的方法一般不会直接调用。当编辑器有选中部分经过标签(markup)判断分析的,工具条就会作适当的反应,就是这个方法触发的。
* Protected method that will not generally be called directly. It triggers
* a toolbar update by reading the markup state of the current selection in the editor.
*/
updateToolbar: function(){
if(!this.activated){
this.onFirstFocus();
return;
}
var btns = this.tb.items.map, doc = this.doc;
if(this.enableFont && !Ext.isSafari2){
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.isSafari2 && this.enableLists){
btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist'));
btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist'));
}
Ext.menu.MenuMgr.hideAll();
this.syncValue();
},
// private
relayBtnCmd : function(btn){
this.relayCmd(btn.itemId);
},
/**
* 对编辑的文本执行一条 Midas 指令, 并完成必要的聚焦和工具栏的更新动作。<b>此方法只能在编辑器初始化后被调用。Executes a Midas editor command on the editor document and performs necessary focus and
* toolbar updates. <b>This should only be called after the editor is initialized.</b>
* @param {String} cmd The Midas 指令 command
* @param {String/Boolean} value (可选项) 传递给指令的值(默认为 null) (optional) The value to pass to the command (defaults to null)
*/
relayCmd : function(cmd, value){
(function(){
this.focus();
this.execCmd(cmd, value);
this.updateToolbar();
}).defer(10, this);
},
/**
* 对编辑的文本直接执行一条 Midas 指令。对于可视化的指令, 应采用{@link #relayCmd} 方法。
* <b>此方法只能在编辑器初始化后被调用。</b>
* Executes a Midas editor command directly on the editor document.
* For visual commands, you should use {@link #relayCmd} instead.
* <b>This should only be called after the editor is initialized.</b>
* @param {String} cmd 指令 The Midas command
* @param {String/Boolean} value (可选项) 传递给指令的值(默认为 null) (optional) The value to pass to the command (defaults to 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();
}
}
}
},
/**
* 在光标当前所在位置插入给定的文本。注意:编辑器必须已经初始化且处于活动状态才能插入本文。
* Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
* to insert text.
* @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>
* Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b>
* @return {Ext.Toolbar}
*/
getToolbar : function(){
return this.tb;
},
/**
* 编辑器中工具栏上按钮的工具提示对象的集合。关键在于,对象ID必须与按钮相同且值应为一个有效的QuickTips对象。例如:
* Object collection of toolbar tooltips for the buttons in the editor. The key
* is the command id associated with that button and the value is a valid QuickTips object.
* For example:
<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
*/
/**
* @cfg {Boolean} allowDomMove @hide
*/
/**
* @cfg {String} applyTo @hide
*/
/**
* @cfg {String} autoHeight @hide
*/
/**
* @cfg {String} autoWidth @hide
*/
/**
* @cfg {String} cls @hide
*/
/**
* @cfg {String} disabled @hide
*/
/**
* @cfg {String} disabledClass @hide
*/
/**
* @cfg {String} msgTarget @hide
*/
/**
* @cfg {String} readOnly @hide
*/
/**
* @cfg {String} style @hide
*/
/**
* @cfg {String} validationDelay @hide
*/
/**
* @cfg {String} validationEvent @hide
*/
/**
* @cfg {String} tabIndex @hide
*/
/**
* @property disabled
* @hide
*/
/**
* @method applyToMarkup
* @hide
*/
/**
* @method disable
* @hide
*/
/**
* @method enable
* @hide
*/
/**
* @method validate
* @hide
*/
/**
* @event valid
* @hide
*/
/**
* @method setDisabled
* @hide
*/
/**
* @cfg keys
* @hide
*/
});
Ext.reg('htmleditor', Ext.form.HtmlEditor); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.DisplayField
* @extends Ext.form.Field
* @constructor 创建新的字段 Creates a new Field
* @param {Object} config 配置项 Configuration options
*/
Ext.form.DisplayField = Ext.extend(Ext.form.Field, {
validationEvent : false,
validateOnBlur : false,
defaultAutoCreate : {tag: "div"},
fieldClass : "x-form-display-field",
htmlEncode: false,
// private
initEvents : Ext.emptyFn,
isValid : function(){
return true;
},
validate : function(){
return true;
},
getRawValue : function(){
var v = this.rendered ? this.el.dom.innerHTML : Ext.value(this.value, '');
if(v === this.emptyText){
v = '';
}
if(this.htmlEncode){
v = Ext.util.Format.htmlDecode(v);
}
return v;
},
getValue : function(){
return this.getRawValue();
},
setRawValue : function(v){
if(this.htmlEncode){
v = Ext.util.Format.htmlEncode(v);
}
return this.rendered ? (this.el.dom.innerHTML = (v === null || v === undefined ? '' : v)) : (this.value = v);
},
setValue : function(v){
this.setRawValue(v);
}
});
Ext.reg('displayfield', Ext.form.DisplayField);
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.form.Label
* @extends Ext.BoxComponent
* 简单的Label字段元素。<br />
* Basic Label field.
* @constructor
* 创建一个新的 Label
* Creates a new Label
* @param {Ext.Element/String/Object} config 配置选项。如果传入一个元素(element),那么该元素会作为label组件的内部元素,使用它(传入的element)的ID作为组件的ID,
* 如果传入的是一个字符串,假设之该字符串是一个已存在的元素的ID,它的ID作为label组件的ID。
* 否则,就作为一个普通的配置对象,应用到该组件。<br />
* The configuration options. If an element is passed, it is set as the internal
* element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
* and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
* @xtype label
*/
Ext.form.Label = Ext.extend(Ext.BoxComponent, {
/**
* @cfg {String} text Label内显示的普通文本,默认为''。如果想在Label组件里嵌入HTML标签,请使用{@link #html}。
* The plain text to display within the label (defaults to ''). If you need to include HTML
* tags within the label's innerHTML, use the {@link #html} config instead.
*/
/**
* @cfg {String} forId 该Label将要通过标准的HTML 'for'属性绑定到的页面元素(element)的ID,如果没有指定,那么该属性不会被加到label上。
* The id of the input element to which this label will be bound via the standard HTML 'for'
* attribute. If not specified, the attribute will not be added to the label.
*/
/**
* @cfg {String} html Label的内部 HTML片段。如果指定了{@link #text},将优先使用text属性,html属性将被忽略。
* An HTML fragment that will be used as the label's innerHTML (defaults to '').
* Note that if {@link #text} is specified it will take precedence and this value will be ignored.
*/
// private
onRender : function(ct, position){
if(!this.el){
this.el = document.createElement('label');
this.el.id = this.getId();
this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || '');
if(this.forId){
this.el.setAttribute('for', this.forId);
}
}
Ext.form.Label.superclass.onRender.call(this, ct, position);
},
/**
* 更改Label的内部HTML为指定的字符串。
* Updates the label's innerHTML with the specified string.
* @param {String} text 新指定的在Label内显示的文本。The new label text
* @param {Boolean} encode (可选选项)默认为true,对html片段进行编码,如果为false将在渲染的时候的时候将跳过对HTML的编码,用于想要在Label里使用html标签而不是
* 作为普通的字符串进行渲染。
* (optional) False to skip HTML-encoding the text when rendering it
* to the label (defaults to true which encodes the value). This might be useful if you want to include
* tags in the label's innerHTML rather than rendering them as string literals per the default logic.
* @return {Label} this
*/
setText: function(t, encode){
this.text = t;
if(this.rendered){
this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t;
}
return this;
}
});
Ext.reg('label', Ext.form.Label); | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.