code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* 项目地址: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.FormPanel
* @extends Ext.Panel
* Standard form container.
* <p><b>使用js为类{@link Ext.form.BasicForm}添加动态加载效果的能力<br />Although they are not listed, this class also accepts all the config options required to configure its internal {@link Ext.form.BasicForm}</b></p>
* <p>The BasicForm is configured using the {@link #initialConfig} of the FormPanel - that is the configuration object passed to the constructor.
* This means that if you subclass FormPanel, and you wish to configure the BasicForm, you will need to insert any configuration options
* for the BasicForm into the <tt><b>initialConfig</b></tt> property. Applying BasicForm configuration settings to <b><tt>this</tt></b> will
* not affect the BasicForm's configuration.</p>
* <p>By default, FormPanel uses an {@link Ext.layout.FormLayout} layout manager, which styles and renders fields and labels correctly.
* When nesting additional Containers within a FormPanel, you should ensure that any descendant Containers which
* host input Fields use the {@link Ext.layout.FormLayout} layout manager.</p>
* <p>By default, Ext Forms are submitted through Ajax, using {@link Ext.form.Action}.
* To enable normal browser submission of the Ext Form contained in this FormPanel,
* use the {@link Ext.form.BasicForm#standardSubmit standardSubmit) option:</p><pre><code>
var myForm = new Ext.form.FormPanel({
standardSubmit: true,
items: myFieldset
});</code></pre>
* @constructor
* @param {Object} config 配置选项 Configuration options
*/
Ext.FormPanel = Ext.extend(Ext.Panel, {
/**
* @cfg {String} formId (可选的)FORM标签的id(默认是自动生成的)。
* (optional) The id of the FORM tag (defaults to an auto-generated id).
*/
/**
* @cfg {Number} labelWidth 标签的宽度。该属性级联于子容器。
* The width of labels. This property cascades to child containers and can be overridden
* on any child container (e.g., a fieldset can specify a different labelWidth for its fields).
*/
/**
* @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 {Array} buttons 送入{@link Ext.Button}或其配置组成的数组来创建按钮,在FormPanel的底部。<br>
* An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this FormPanel.<br>
* <p>Buttons in the footer of a FormPanel may be configured with the option <tt>formBind: true</tt>. This causes
* the form's {@link #monitorValid valid state monitor task} to enable/disable those Buttons depending on
* the form's valid/invalid state.</p>
*/
/**
* @cfg {String} buttonAlign 有效值为"left," "center" 和 "right"(默认为"center")。
* Valid values are "left," "center" and "right" (defaults to "center")
*/
buttonAlign:'center',
/**
* @cfg {Number} minButtonWidth 每个button的最小宽度(默认75)。
* Minimum width of all buttons in pixels (defaults to 75)
*/
minButtonWidth:75,
/**
* @cfg {String} labelAlign 有效值为"left," "top" 和 "right" (默认为"left")。该属性级联于没有设定此属性的子容器。
* Valid values are "left," "top" and "right" (defaults to "left").
* This property cascades to child containers and can be overridden on any child container
* (e.g., a fieldset can specify a different labelAlign for its fields).
*/
labelAlign:'left',
/**
* @cfg {Boolean} monitorValid true表示为通过不断触发一个事件,来监视有效值的状态(<b>在客户端进行</b>) If true, the form monitors its valid state <b>client-side</b> and
* regularly fires the {@link #clientvalidation} event passing that state.<br>
* <p>该项须绑定到有配置项formBind:true的按钮的valid state When monitoring valid state, the FormPanel enables/disables any of its configured
* {@link #button}s which have been configured with <tt>formBind: true<tt> depending
* on whether the form is valid or not.</p>
*/
monitorValid : false,
/**
* @cfg {Number} monitorPoll 检验valid state的间隔毫秒数,如monitorValid非真则忽略改项(默认为200)。
* The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
*/
monitorPoll : 200,
layout:'form',
// private
initComponent :function(){
this.form = this.createForm();
Ext.FormPanel.superclass.initComponent.call(this);
this.bodyCfg = {
tag: 'form',
cls: this.baseCls + '-body',
method : this.method || 'POST',
id : this.formId || Ext.id()
};
if(this.fileUpload) {
this.bodyCfg.enctype = 'multipart/form-data';
}
this.initItems();
this.addEvents(
/**
* @event clientvalidation
* 如果配置项monitorValid为true,那么为通知验证的状态(valid state)该事件将不断地触发。
* If the monitorValid config option is true, this event fires repetitively to notify of valid state
* @param {Ext.form.FormPanel} this
* @param {Boolean} valid 如果客户端验证都通过的话传入一个true true if the form has passed client-side validation
*/
'clientvalidation'
);
this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']);
},
// private
createForm: function(){
delete this.initialConfig.listeners;
return new Ext.form.BasicForm(null, this.initialConfig);
},
// private
initFields : function(){
var f = this.form;
var formPanel = this;
var fn = function(c){
if(formPanel.isField(c)){
f.add(c);
}if(c.isFieldWrap){
Ext.applyIf(c, {
labelAlign: c.ownerCt.labelAlign,
labelWidth: c.ownerCt.labelWidth,
itemCls: c.ownerCt.itemCls
});
f.add(c.field);
}else if(c.doLayout && c != formPanel){
Ext.applyIf(c, {
labelAlign: c.ownerCt.labelAlign,
labelWidth: c.ownerCt.labelWidth,
itemCls: c.ownerCt.itemCls
});
if(c.items){
c.items.each(fn, this);
}
}
};
this.items.each(fn, this);
},
// private
getLayoutTarget : function(){
return this.form.el;
},
/**
* 返回该面板包含的{@link Ext.form.BasicForm Form}。
* Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains.
* @return {Ext.form.BasicForm} 返回面板对象包含的 {@link Ext.form.BasicForm Form}以供访问。 The {@link Ext.form.BasicForm Form} which this Panel contains.
*/
getForm : function(){
return this.form;
},
// private
onRender : function(ct, position){
this.initFields();
Ext.FormPanel.superclass.onRender.call(this, ct, position);
this.form.initEl(this.body);
},
// private
beforeDestroy: function(){
Ext.FormPanel.superclass.beforeDestroy.call(this);
this.stopMonitoring();
Ext.destroy(this.form);
},
// Determine if a Component is usable as a form Field.
isField: function(c) {
return !!c.setValue && !!c.getValue && !!c.markInvalid && !!c.clearInvalid;
},
// private
initEvents : function(){
Ext.FormPanel.superclass.initEvents.call(this);
this.on('remove', this.onRemove, this);
this.on('add', this.onAdd, this);
if(this.monitorValid){ // initialize after render
this.startMonitoring();
}
},
// private
onAdd : function(ct, c) {
// If a single form Field, add it
if (this.isField(c)) {
this.form.add(c);
// If a Container, add any Fields it might contain
} else if (c.findBy) {
Ext.applyIf(c, {
labelAlign: c.ownerCt.labelAlign,
labelWidth: c.ownerCt.labelWidth,
itemCls: c.ownerCt.itemCls
});
this.form.add.apply(this.form, c.findBy(this.isField));
}
},
// private
onRemove : function(ct, c) {
// If a single form Field, remove it
if (this.isField(c)) {
Ext.destroy(c.container.up('.x-form-item'));
this.form.remove(c);
// If a Container, remove any Fields it might contain
} else if (c.findByType) {
Ext.each(c.findBy(this.isField), this.form.remove, this.form);
}
},
/**
* 开始监视该表单的验证过程。通常这是由配置项"monitorValid"完成的。
* Starts monitoring of the valid state of this form. Usually this is done by passing the config option "monitorValid"
*/
startMonitoring : function(){
if(!this.bound){
this.bound = true;
Ext.TaskMgr.start({
run : this.bindHandler,
interval : this.monitorPoll || 200,
scope: this
});
}
},
/**
* 停止监视该form的验证状态。
* Stops monitoring of the valid state of this form
*/
stopMonitoring : function(){
this.bound = false;
},
/**
* 这是BasicForm{@link Ext.form.BasicForm#load}方法调用时所在的代理。
* This is a proxy for the underlying BasicForm's {@link Ext.form.BasicForm#load} call.
* @param {Object} options 传入动作的选项(参阅{@link Ext.form.BasicForm#doAction}了解更多)。The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details)
*/
load : function(){
this.form.load.apply(this.form, arguments);
},
// private
onDisable : function(){
Ext.FormPanel.superclass.onDisable.call(this);
if(this.form){
this.form.items.each(function(){
this.disable();
});
}
},
// private
onEnable : function(){
Ext.FormPanel.superclass.onEnable.call(this);
if(this.form){
this.form.items.each(function(){
this.enable();
});
}
},
// private
bindHandler : function(){
if(!this.bound){
return false; // stops binding
}
var valid = true;
this.form.items.each(function(f){
if(!f.isValid(true)){
valid = false;
return false;
}
});
if(this.fbar){
var fitems = this.fbar.items.items;
for(var i = 0, len = fitems.length; i < len; i++){
var btn = fitems[i];
if(btn.formBind === true && btn.disabled === valid){
btn.setDisabled(!valid);
}
}
}
this.fireEvent('clientvalidation', this, valid);
}
});
Ext.reg('form', Ext.FormPanel);
Ext.form.FormPanel = Ext.FormPanel;
| JavaScript |
/*
* 项目地址: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.ComboBox
* @extends Ext.form.TriggerField
* <p>一个提供自动完成、远程加载、分页和许多其他特性的组合框。<br />
* A combobox control with support for autocomplete, remote-loading, paging and many other features.</p>
* A ComboBox works in a similar manner to a traditional HTML <select> field. The difference is that to submit the
* {@link #valueField}, you must specify a {@link #hiddenName} to create a hidden input field to hold the
* value of the valueField. The <i>{@link #displayField}</i> is shown in the text field which is named
* according to the {@link #name}.
* @constructor 创建一个组合框。Create a new ComboBox.
* @param {Object} config 配置选项。config Configuration options
*/
Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, {
/**
* @cfg {Mixed} transform 要转换为组合框的id,DOM节点或者已有的select元素。
* The id, DOM node or element of an existing HTML SELECT to convert to a ComboBox.
* Note that if you specify this and the combo is going to be in a {@link Ext.form.BasicForm} or
* {@link Ext.form.FormPanel}, you must also set {@link #lazyRender} = true.
*/
/**
* @cfg {Boolean} lazyRender 值为true时阻止ComboBox渲染直到该对象被请求(被渲染到Ext.Editor 组件的时候应该使用这个参数,默认为 false)。
* True to prevent the ComboBox from rendering until requested (should always be used when
* rendering into an Ext.Editor, defaults to false).
*/
/**
* @cfg {Boolean/Object} autoCreate 指定一个DomHelper对象,或者设置值为true使用默认元素(默认为:{tag: "input", type: "text", size: "24", autocomplete: "off"})。
* A DomHelper element spec, or true for a default element spec (defaults to:
* {tag: "input", type: "text", size: "24", autocomplete: "off"})
*/
/**
* @cfg {Ext.data.Store/Array} store 该组合框绑定的数据仓库(默认为 undefined)。
* The data source to which this combo is bound (defaults to undefined). This can be
* any {@link Ext.data.Store} subclass, a 1-dimensional array (e.g., ['Foo','Bar']) or a 2-dimensional array (e.g.,
* [['f','Foo'],['b','Bar']]). Arrays will be converted to a {@link Ext.data.ArrayStore} internally.
* 1-dimensional arrays will automatically be expanded (each array item will be the combo value and text) and
* for multi-dimensional arrays, the value in index 0 of each item will be assumed to be the combo value, while
* the value at index 1 is assumed to be the combo text.
*/
/**
* @cfg {String} title 如果提供了,则会创建一个包含此文本的元素并被添加到下拉列表的顶部(默认为 undefined,表示没有头部元素)。 If supplied, a header element is created containing this text and added into the top of
* the dropdown list (defaults to undefined, with no header element)
*/
// private
defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
/**
* @cfg {Number} listWidth 以象素表示的下拉列表的宽度(默认的宽度与ComboBox的width属性一致)。
* The width in pixels of the dropdown list (defaults to the width of the ComboBox field)
*/
/**
* @cfg {String} displayField 组合框用以展示的数据的字段名(如果mode='remote'则默认为 undefined,如果mode = 'local' 则默认为 'text')。
* The underlying data field name to bind to this ComboBox (defaults to undefined if
* mode = 'remote' or 'text' if transforming a select)
*/
/**
* @cfg {String} valueField 组合框用以取值的数据的字段名(如果mode='remote'则默认为 undefined,如果mode = 'local' 则默认为 'value')。
* The underlying data value name to bind to this ComboBox (defaults to undefined if
* mode = 'remote' or 'value' if transforming a select) Note: use of a valueField requires the user to make a selection
* in order for a value to be mapped.
*/
/**
* @cfg {String} hiddenName 如果指定了, 则会动态生成一个以指定名称命名的隐藏域用来存放值数据(默认为)。
* If specified, a hidden form field with this name is dynamically generated to store the
* field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically
* post during a form submission. Note that the hidden field's id will also default to this name if {@link #hiddenId}
* is not specified. The combo's id and the hidden field's ids should be different, since no two DOM nodes should
* share the same id, so if the combo and hidden names are the same, you should specify a unique hiddenId.
*/
/**
* @cfg {String} hiddenId If {@link #hiddenName} is specified, hiddenId can also be provided to give the hidden field
* a unique id (defaults to the hiddenName). The hiddenId and combo {@link #id} should be different, since no two DOM
* nodes should share the same id.
*/
/**
* @cfg {String} hiddenValue Sets the initial value of the hidden field if {@link #hiddenName} is
* specified to contain the selected {@link #valueField}, from the Store. <b>Defaults to the configured
* {@link #value}</b>.
*/
/**
* @cfg {String} listClass 下拉列表元素应用的CSS类(默认为'')。
* CSS class to apply to the dropdown list element (defaults to '')
*/
listClass: '',
/**
* @cfg {String} selectedClass 下拉列表中选中项应用的CSS类(默认为 'x-combo-selected')。
* CSS class to apply to the selected item in the dropdown list (defaults to 'x-combo-selected')
*/
selectedClass: 'x-combo-selected',
/**
* @cfg {String} triggerClass 触发器按钮使用的CSS类。触发器的类固定为'x-form-trigger',而如果指定了triggerClass属性的值则会被<b>附加</b>在其后。
* (默认为 'x-form-arrow-trigger' 用来显示一个向下的箭头图标)。
* An additional CSS class used to style the trigger button. The trigger will always get the
* class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-arrow-trigger'
* which displays a downward arrow icon).
*/
triggerClass : 'x-form-arrow-trigger',
/**
* @cfg {Boolean/String} shadow 值为true或者"sides"为默认效果,"frame"为四方向阴影,"drop" 为右下角方向阴影。
* True or "sides" for the default effect, "frame" for 4-way shadow, and "drop" for bottom-right
*/
shadow:'sides',
/**
* @cfg {String} listAlign 一个有效的方位锚点值。点击{@link Ext.Element#alignTo}查看支持的方向锚点(默认为 'tl-bl')。
* A valid anchor position value. See {@link Ext.Element#alignTo} for details on supported
* anchor positions (defaults to 'tl-bl')
*/
listAlign: 'tl-bl?',
/**
* @cfg {Number} maxHeight 以象素表示的下拉列表最大高度(默认为 300)。
* The maximum height in pixels of the dropdown list before scrollbars are shown (defaults to 300)
*/
maxHeight: 300,
/**
* @cfg {Number} minHeight The minimum height in pixels of the dropdown list when the list is constrained by its
* distance to the viewport edges (defaults to 90)
*/
minHeight: 90,
/**
* @cfg {String} triggerAction 触发器被激活时执行的动作。使用'all'来运行由allQuery属性指定的查询(默认为'query')。
* The action to execute when the trigger is clicked. Use 'all' to run the
* query specified by the allQuery config option (defaults to 'query')
*/
triggerAction: 'query',
/**
* @cfg {Number} minChars 在autocomplete和typeahead 被激活之前用户必须输入的字符数(默认为4,如果editable = false则此属性无效)。
* The minimum number of characters the user must type before autocomplete and typeahead activate
* (defaults to 4 if remote or 0 if local, does not apply if editable = false)
*/
minChars : 4,
/**
* @cfg {Boolean} typeAhead 值为true时在经过指定延迟(typeAheadDelay)后弹出并自动选择输入的文本,如果该文本与已知的值相匹配(默认为false)。
* True to populate and autoselect the remainder of the text being typed after a configurable
* delay ({@link #typeAheadDelay}) if it matches a known value (defaults to false)
*/
typeAhead: false,
/**
* @cfg {Number} queryDelay 以毫秒表示的从开始输入到发出查询语句过滤下拉列表的时长(如果mode='remote'则默认为500,如果mode = 'local' 则默认为10)。
* The length of time in milliseconds to delay between the start of typing and sending the
* query to filter the dropdown list (defaults to 500 if mode = 'remote' or 10 if mode = 'local')
*/
queryDelay: 500,
/**
* @cfg {Number} pageSize 如果值大于0,则在下拉列表的底部显示一个分页工具条,并且在执行过滤查询时将传递起始页和限制参数。
* 只在 mode = 'remote'时生效(默认为 0)。
* If greater than 0, a paging toolbar is displayed in the footer of the dropdown list and the
* filter queries will execute with page start and limit parameters. Only applies when mode = 'remote' (defaults to 0)
*/
pageSize: 0,
/**
* @cfg {Boolean} selectOnFocus 值为 true 时选择任何字段内已有文本时立即取得焦点。
* 只在editable = true时生效(默认为 false)。
* True to select any existing text in the field immediately on focus. Only applies
* when editable = true (defaults to false)
*/
selectOnFocus:false,
/**
* @cfg {String} queryParam 供querystring查询时传递的名字(默认为 'query')。
* Name of the query as it will be passed on the querystring (defaults to 'query')
*/
queryParam: 'query',
/**
* @cfg {String} loadingText 当读取数据时在下拉列表显示的文本。仅当mode = 'remote'时可用(默认为 'Loading...')。
* The text to display in the dropdown list while data is loading. Only applies
* when mode = 'remote' (defaults to 'Loading...')
*/
loadingText: 'Loading...',
/**
* @cfg {Boolean} resizable 值为true时则在下拉列表的底部添加缩放柄(默认为false)。
* True to add a resize handle to the bottom of the dropdown list (defaults to false)
*/
resizable: false,
/**
* @cfg {Number} handleHeight 以像素表示的下拉列表的缩放柄的高度,仅当resizable = true 时可用(默认为 8)。
* The height in pixels of the dropdown list resize handle if resizable = true (defaults to 8)
*/
handleHeight : 8,
/**
* @cfg {Boolean} editable 值为false时防止用户直接在输入框内输入文本,就像传统的选择框一样(默认为 true)。
* False to prevent the user from typing text directly into the field, just like a
* traditional select (defaults to true)
*/
editable: true,
/**
* @cfg {String} allQuery 发送到服务器用以返回不经过滤的所有记录的文本(默认为 '')。
* The text query to send to the server to return all records for the list with no filtering (defaults to '')
*/
allQuery: '',
/**
* @cfg {String} mode 如果ComboBox读取本地数据则将值设为'local'(默认为 'remote' 表示从服务器读取数据)。
* Set to 'local' if the ComboBox loads local data (defaults to 'remote' which loads from the server)
*/
mode: 'remote',
/**
* @cfg {Number} minListWidth 以像素表示的下拉列表的最小宽度(默认为70, 如果listWidth的指定值更高则自动忽略该参数)。
* The minimum width of the dropdown list in pixels (defaults to 70, will be ignored if
* listWidth has a higher value)
*/
minListWidth : 70,
/**
* @cfg {Boolean} forceSelection 值为true时将限定选中的值为列表中的值,值为false则允许用户将任意文本设置到字段(默认为 false)。
* True to restrict the selected value to one of the values in the list, false to
* allow the user to set arbitrary text into the field (defaults to false)
*/
forceSelection:false,
/**
* @cfg {Number} typeAheadDelay 以毫秒表示的 typeahead 文本延迟显示量,仅当 typeAhead = true 时生效(默认为 250)。
* The length of time in milliseconds to wait until the typeahead text is displayed
* if typeAhead = true (defaults to 250)
*/
typeAheadDelay : 250,
/**
* @cfg {String} valueNotFoundText 当使用 name/value 组合框时,如果调用setValue方法时传递的值没有在仓库中找到,且定义了valueNotFoundText则在字段中显示该值(默认为 undefined)。
* When using a name/value combo, if the value passed to setValue is not found in
* the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
* defaut text is used, it means there is no value set and no validation will occur on this field.
*/
/**
* @cfg {Boolean} lazyInit True to not initialize the list for this combo until the field is focused (defaults to true)
*/
lazyInit : true,
/**
* The value of the match string used to filter the store. Delete this property to force a requery.
* @property lastQuery
* @type String
*/
// private
initComponent : function(){
Ext.form.ComboBox.superclass.initComponent.call(this);
this.addEvents(
/**
* @event expand
* 当下拉列表展开的时候触发。
* Fires when the dropdown list is expanded
* @param {Ext.form.ComboBox} combo 组合框本身。This combo box
*/
'expand',
/**
* @event collapse
* 当下拉列表收起的时候触发。
* Fires when the dropdown list is collapsed
* @param {Ext.form.ComboBox} combo 组合框本身。This combo box
*/
'collapse',
/**
* @event beforeselect
* 列表项被选中前触发。返回 false 可以取消选择。
* Fires before a list item is selected. Return false to cancel the selection.
* @param {Ext.form.ComboBox} combo 组合框本身。This combo box
* @param {Ext.data.Record} record 从数据仓库中返回的数据记录。The data record returned from the underlying store
* @param {Number} index 选中项在下拉列表中的索引位置。The index of the selected item in the dropdown list
*/
'beforeselect',
/**
* @event select
* 当列表项被选中时触发。
* Fires when a list item is selected
* @param {Ext.form.ComboBox} combo 组合框本身。This combo box
* @param {Ext.data.Record} record 从数据仓库中返回的数据记录。The data record returned from the underlying store
* @param {Number} index 选中项在下拉列表中的索引位置。The index of the selected item in the dropdown list
*/
'select',
/**
* @event beforequery
* 所有的查询被处理前触发。返回 false 或者设置cancel参数为true可以取消查询。
* Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
* cancel property to true.
* @param {Object} queryEvent 传递的事件对象包含这些属性:An object that has these properties:<ul>
* <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">组合框本身。This combo box</div></li>
* <li><code>query</code> : String <div class="sub-desc">查询语句。The query</div></li>
* <li><code>forceAll</code> : Boolean <div class="sub-desc">值为true时强制为"all"查询。True to force "all" query</div></li>
* <li><code>cancel</code> : Boolean <div class="sub-desc">值为true时取消查询。Set to true to cancel the query</div></li>
* </ul>
*/
'beforequery'
);
if(this.transform){
this.allowDomMove = false;
var s = Ext.getDom(this.transform);
if(!this.hiddenName){
this.hiddenName = s.name;
}
if(!this.store){
this.mode = 'local';
var d = [], opts = s.options;
for(var i = 0, len = opts.length;i < len; i++){
var o = opts[i];
var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
if(o.selected) {
this.value = value;
}
d.push([value, o.text]);
}
this.store = new Ext.data.ArrayStore({
'id': 0,
fields: ['value', 'text'],
data : d
});
this.valueField = 'value';
this.displayField = 'text';
}
s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
if(!this.lazyRender){
this.target = true;
this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
Ext.removeNode(s); // remove it
this.render(this.el.parentNode);
}else{
Ext.removeNode(s); // remove it
}
}
//auto-configure store from local array data
else if(Ext.isArray(this.store)){
if (Ext.isArray(this.store[0])){
this.store = new Ext.data.ArrayStore({
fields: ['value','text'],
data: this.store
});
this.valueField = 'value';
}else{
this.store = new Ext.data.ArrayStore({
fields: ['text'],
data: this.store,
expandData: true
});
this.valueField = 'text';
}
this.displayField = 'text';
this.mode = 'local';
}
this.selectedIndex = -1;
if(this.mode == 'local'){
if(this.initialConfig.queryDelay === undefined){
this.queryDelay = 10;
}
if(this.initialConfig.minChars === undefined){
this.minChars = 0;
}
}
},
// private
onRender : function(ct, position){
Ext.form.ComboBox.superclass.onRender.call(this, ct, position);
if(this.hiddenName){
this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
id: (this.hiddenId||this.hiddenName)}, 'before', true);
// prevent input submission
this.el.dom.removeAttribute('name');
}
if(Ext.isGecko){
this.el.dom.setAttribute('autocomplete', 'off');
}
if(!this.lazyInit){
this.initList();
}else{
this.on('focus', this.initList, this, {single: true});
}
if(!this.editable){
this.editable = true;
this.setEditable(false);
}
},
// private
initValue : function(){
Ext.form.ComboBox.superclass.initValue.call(this);
if(this.hiddenField){
this.hiddenField.value =
this.hiddenValue !== undefined ? this.hiddenValue :
this.value !== undefined ? this.value : '';
}
},
// private
initList : function(){
if(!this.list){
var cls = 'x-combo-list';
this.list = new Ext.Layer({
shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false
});
var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
this.list.setSize(lw, 0);
this.list.swallowEvent('mousewheel');
this.assetHeight = 0;
if(this.syncFont !== false){
this.list.setStyle('font-size', this.el.getStyle('font-size'));
}
if(this.title){
this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
this.assetHeight += this.header.getHeight();
}
this.innerList = this.list.createChild({cls:cls+'-inner'});
this.mon(this.innerList, 'mouseover', this.onViewOver, this);
this.mon(this.innerList, 'mousemove', this.onViewMove, this);
this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
if(this.pageSize){
this.footer = this.list.createChild({cls:cls+'-ft'});
this.pageTb = new Ext.PagingToolbar({
store:this.store,
pageSize: this.pageSize,
renderTo:this.footer
});
this.assetHeight += this.footer.getHeight();
}
if(!this.tpl){
/**
* @cfg {String/Ext.XTemplate} tpl 要转换为组合框的 id, DOM 节点 或者已有的 select 元素 The template string, or {@link Ext.XTemplate}
* instance to use to display each item in the dropdown list. Use
* this to create custom UI layouts for items in the list.
* <p>
* If you wish to preserve the default visual look of list items, add the CSS
* class name <pre>x-combo-list-item</pre> to the template's container element.
* <p>
* <b>The template must contain one or more substitution parameters using field
* names from the Combo's</b> {@link #store Store}. An example of a custom template
* would be adding an <pre>ext:qtip</pre> attribute which might display other fields
* from the Store.
* <p>
* The dropdown list is displayed in a DataView. See {@link Ext.DataView} for details.
*/
this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
/**
* @cfg {String} itemSelector
* <b>This setting is required if a custom XTemplate has been specified in {@link #tpl}
* which assigns a class other than <pre>'x-combo-list-item'</pre> to dropdown list items</b>.
* A simple CSS selector (e.g. div.some-class or span:first-child) that will be
* used to determine what nodes the DataView which handles the dropdown display will
* be working with.
*/
}
/**
* 显示CoboBox选择所使用的{@link Ext.DataView DataView}。
* The {@link Ext.DataView DataView} used to display the ComboBox's options.
* @type Ext.DataView
*/
this.view = new Ext.DataView({
applyTo: this.innerList,
tpl: this.tpl,
singleSelect: true,
selectedClass: this.selectedClass,
itemSelector: this.itemSelector || '.' + cls + '-item'
});
this.mon(this.view, 'click', this.onViewClick, this);
this.bindStore(this.store, true);
if(this.resizable){
this.resizer = new Ext.Resizable(this.list, {
pinned:true, handles:'se'
});
this.mon(this.resizer, 'resize', function(r, w, h){
this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
this.listWidth = w;
this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
this.restrictHeight();
}, this);
this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
}
}
},
/**
* 返回Combo关联的Store对象。
* Returns the store associated with this combo.
* @return {Ext.data.Store} Store对象。The store
*/
getStore : function(){
return this.store;
},
// private
bindStore : function(store, initial){
if(this.store && !initial){
this.store.un('beforeload', this.onBeforeLoad, this);
this.store.un('load', this.onLoad, this);
this.store.un('loadexception', this.collapse, this);
if(!store){
this.store = null;
if(this.view){
this.view.setStore(null);
}
}
}
if(store){
this.store = Ext.StoreMgr.lookup(store);
this.store.on('beforeload', this.onBeforeLoad, this);
this.store.on('load', this.onLoad, this);
this.store.on('loadexception', this.collapse, this);
if(this.view){
this.view.setStore(store);
}
}
},
// private
initEvents : function(){
Ext.form.ComboBox.superclass.initEvents.call(this);
this.keyNav = new Ext.KeyNav(this.el, {
"up" : function(e){
this.inKeyMode = true;
this.selectPrev();
},
"down" : function(e){
if(!this.isExpanded()){
this.onTriggerClick();
}else{
this.inKeyMode = true;
this.selectNext();
}
},
"enter" : function(e){
this.onViewClick();
this.delayedCheck = true;
this.unsetDelayCheck.defer(10, this);
},
"esc" : function(e){
this.collapse();
},
"tab" : function(e){
this.onViewClick(false);
return true;
},
scope : this,
doRelay : function(foo, bar, hname){
if(hname == 'down' || this.scope.isExpanded()){
return Ext.KeyNav.prototype.doRelay.apply(this, arguments);
}
return true;
},
forceKeyDown : true
});
this.queryDelay = Math.max(this.queryDelay || 10,
this.mode == 'local' ? 10 : 250);
this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
if(this.typeAhead){
this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
}
if(this.editable !== false){
this.mon(this.el, 'keyup', this.onKeyUp, this);
}
if(this.forceSelection){
this.on('blur', this.doForce, this);
}
},
// private
onDestroy : function(){
if(this.view){
Ext.destroy(this.view);
}
if(this.list){
this.list.destroy();
}
if (this.dqTask){
this.dqTask.cancel();
this.dqTask = null;
}
this.bindStore(null);
Ext.form.ComboBox.superclass.onDestroy.call(this);
},
// private
unsetDelayCheck : function(){
delete this.delayedCheck;
},
// private
fireKey : function(e){
if(e.isNavKeyPress() && !this.isExpanded() && !this.delayedCheck){
this.fireEvent("specialkey", this, e);
}
},
// private
onResize: function(w, h){
Ext.form.ComboBox.superclass.onResize.apply(this, arguments);
if(this.list && this.listWidth === undefined){
var lw = Math.max(w, this.minListWidth);
this.list.setWidth(lw);
this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
}
},
// private
onEnable: function(){
Ext.form.ComboBox.superclass.onEnable.apply(this, arguments);
if(this.hiddenField){
this.hiddenField.disabled = false;
}
},
// private
onDisable: function(){
Ext.form.ComboBox.superclass.onDisable.apply(this, arguments);
if(this.hiddenField){
this.hiddenField.disabled = true;
}
},
/**
* 允许或防止用户直接编辑字段文本。如果传递值为false,用户将只能选择下拉列表中已经定义的选项。
* 此方法相当于在配置时设置'editable'属性。
* Allow or prevent the user from directly editing the field text. If false is passed,
* the user will only be able to select from the items defined in the dropdown list. This method
* is the runtime equivalent of setting the 'editable' config option at config time.
* @param {Boolean} value 值为true时允许用户直接编辑字段文本。True to allow the user to directly edit the field text
*/
setEditable : function(value){
if(value == this.editable){
return;
}
this.editable = value;
if(!value){
this.el.dom.setAttribute('readOnly', true);
this.el.on('mousedown', this.onTriggerClick, this);
this.el.addClass('x-combo-noedit');
}else{
this.el.dom.removeAttribute('readOnly');
this.el.un('mousedown', this.onTriggerClick, this);
this.el.removeClass('x-combo-noedit');
}
},
// private
onBeforeLoad : function(){
if(!this.hasFocus){
return;
}
this.innerList.update(this.loadingText ?
'<div class="loading-indicator">'+this.loadingText+'</div>' : '');
this.restrictHeight();
this.selectedIndex = -1;
},
// private
onLoad : function(){
if(!this.hasFocus){
return;
}
if(this.store.getCount() > 0){
this.expand();
this.restrictHeight();
if(this.lastQuery == this.allQuery){
if(this.editable){
this.el.dom.select();
}
if(!this.selectByValue(this.value, true)){
this.select(0, true);
}
}else{
this.selectNext();
if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
this.taTask.delay(this.typeAheadDelay);
}
}
}else{
this.onEmptyResults();
}
//this.el.focus();
},
// private
onTypeAhead : function(){
if(this.store.getCount() > 0){
var r = this.store.getAt(0);
var newValue = r.data[this.displayField];
var len = newValue.length;
var selStart = this.getRawValue().length;
if(selStart != len){
this.setRawValue(newValue);
this.selectText(selStart, newValue.length);
}
}
},
// private
onSelect : function(record, index){
if(this.fireEvent('beforeselect', this, record, index) !== false){
this.setValue(record.data[this.valueField || this.displayField]);
this.collapse();
this.fireEvent('select', this, record, index);
}
},
/**
* 返回当前选定项的值或在没有选定项时返回空字串。
* Returns the currently selected field value or empty string if no value is set.
* @return {String} value 选中的值。The selected value
*/
getValue : function(){
if(this.valueField){
return typeof this.value != 'undefined' ? this.value : '';
}else{
return Ext.form.ComboBox.superclass.getValue.call(this);
}
},
/**
* 清除所有当前字段中设定的。
* Clears any text/value currently set in the field
*/
clearValue : function(){
if(this.hiddenField){
this.hiddenField.value = '';
}
this.setRawValue('');
this.lastSelectionText = '';
this.applyEmptyText();
this.value = '';
},
/**
* 将指定的值设定到字段。如果找到匹配的值,字段中将显示相应的记录。
* 如果在已有的选项中没有找到匹配的值,则显示valueNotFoundText属性指定的文本。
* 其他情况下显示为空(但仍然将字段的值设置为指定值)。
* Sets the specified value into the field. If the value finds a match, the corresponding record text
* will be displayed in the field. If the value does not match the data value of an existing item,
* and the valueNotFoundText config option is defined, it will be displayed as the default field text.
* Otherwise the field will be blank (although the value will still be set).
* @param {String} value 匹配的值。The value to match
*/
setValue : function(v){
var text = v;
if(this.valueField){
var r = this.findRecord(this.valueField, v);
if(r){
text = r.data[this.displayField];
}else if(this.valueNotFoundText !== undefined){
text = this.valueNotFoundText;
}
}
this.lastSelectionText = text;
if(this.hiddenField){
this.hiddenField.value = v;
}
Ext.form.ComboBox.superclass.setValue.call(this, text);
this.value = v;
},
// private
findRecord : function(prop, value){
var record;
if(this.store.getCount() > 0){
this.store.each(function(r){
if(r.data[prop] == value){
record = r;
return false;
}
});
}
return record;
},
// private
onViewMove : function(e, t){
this.inKeyMode = false;
},
// private
onViewOver : function(e, t){
if(this.inKeyMode){ // prevent key nav and mouse over conflicts
return;
}
var item = this.view.findItemFromChild(t);
if(item){
var index = this.view.indexOf(item);
this.select(index, false);
}
},
// private
onViewClick : function(doFocus){
var index = this.view.getSelectedIndexes()[0];
var r = this.store.getAt(index);
if(r){
this.onSelect(r, index);
}
if(doFocus !== false){
this.el.focus();
}
},
// private
restrictHeight : function(){
this.innerList.dom.style.height = '';
var inner = this.innerList.dom;
var pad = this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight;
var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight);
var ha = this.getPosition()[1]-Ext.getBody().getScroll().top;
var hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height;
var space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
h = Math.min(h, space, this.maxHeight);
this.innerList.setHeight(h);
this.list.beginUpdate();
this.list.setHeight(h+pad);
this.list.alignTo(this.wrap, this.listAlign);
this.list.endUpdate();
},
// private
onEmptyResults : function(){
this.collapse();
},
/**
* 如果下拉列表已经展开则返回true,否则返回false。
* Returns true if the dropdown list is expanded, else false.
*/
isExpanded : function(){
return this.list && this.list.isVisible();
},
/**
* 根据数据的值选择下拉列表中的选项。本函数不会触发'select'事件。
* 使用此函数必须在数据已经被读取且列表已经展开,否则请使用setValue方法。
* Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
* The store must be loaded and the list expanded for this function to work, otherwise use setValue.
* @param {String} value 要选择的项的值。The data value of the item to select
* @param {Boolean} scrollIntoView 值为false时阻止下拉列表自动滚动到选中项位置(默认为 true)。False to prevent the dropdown list from autoscrolling to display the
* selected item if it is not currently in view (defaults to true)
* @return {Boolean} 如果给定值在列表中则返回true,否则返回。falseTrue if the value matched an item in the list, else false
*/
selectByValue : function(v, scrollIntoView){
if(v !== undefined && v !== null){
var r = this.findRecord(this.valueField || this.displayField, v);
if(r){
this.select(this.store.indexOf(r), scrollIntoView);
return true;
}
}
return false;
},
/**
* 根据列表的索引数选择下拉列表中的一项。
* 本函数不会触发 'select' 事件。使用此函数必须在数据已经被读取且列表已经展开,否则请使用setValue方法。
* Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
* The store must be loaded and the list expanded for this function to work, otherwise use setValue.
* @param {Number} index 选中项在列表中以0开始的索引数。The zero-based index of the list item to select
* @param {Boolean} scrollIntoView 值为false时阻止下拉列表自动滚动到选中项位置(默认为 true)。False to prevent the dropdown list from autoscrolling to display the
* selected item if it is not currently in view (defaults to true)
*/
select : function(index, scrollIntoView){
this.selectedIndex = index;
this.view.select(index);
if(scrollIntoView !== false){
var el = this.view.getNode(index);
if(el){
this.innerList.scrollChildIntoView(el, false);
}
}
},
// private
selectNext : function(){
var ct = this.store.getCount();
if(ct > 0){
if(this.selectedIndex == -1){
this.select(0);
}else if(this.selectedIndex < ct-1){
this.select(this.selectedIndex+1);
}
}
},
// private
selectPrev : function(){
var ct = this.store.getCount();
if(ct > 0){
if(this.selectedIndex == -1){
this.select(0);
}else if(this.selectedIndex != 0){
this.select(this.selectedIndex-1);
}
}
},
// private
onKeyUp : function(e){
if(this.editable !== false && !e.isSpecialKey()){
this.lastKey = e.getKey();
this.dqTask.delay(this.queryDelay);
}
},
// private
validateBlur : function(){
return !this.list || !this.list.isVisible();
},
// private
initQuery : function(){
this.doQuery(this.getRawValue());
},
// private
doForce : function(){
if(this.el.dom.value.length > 0){
this.el.dom.value =
this.lastSelectionText === undefined ? '' : this.lastSelectionText;
this.applyEmptyText();
}
},
/**
* 执行一个查询语句用以过滤下拉列表。在查询之前触发{@link #beforequery}事件,以便可以在需要的时候取消查询动作。
* Execute a query to filter the dropdown list. Fires the {@link #beforequery} event prior to performing the
* query allowing the query action to be canceled if needed.
* @param {String} query 要执行的查询语句。The SQL query to execute
* @param {Boolean} forceAll 值为true时强制执行查询即使当前输入的字符少于 minChars 设置项指定的值。
* 同时还会清除当前数据仓库中保存的前一次结果(默认为false)。
* True to force the query to execute even if there are currently fewer characters
* in the field than the minimum specified by the minChars config option. It also clears any filter previously
* saved in the current store (defaults to false)
*/
doQuery : function(q, forceAll){
if(q === undefined || q === null){
q = '';
}
var qe = {
query: q,
forceAll: forceAll,
combo: this,
cancel:false
};
if(this.fireEvent('beforequery', qe)===false || qe.cancel){
return false;
}
q = qe.query;
forceAll = qe.forceAll;
if(forceAll === true || (q.length >= this.minChars)){
if(this.lastQuery !== q){
this.lastQuery = q;
if(this.mode == 'local'){
this.selectedIndex = -1;
if(forceAll){
this.store.clearFilter();
}else{
this.store.filter(this.displayField, q);
}
this.onLoad();
}else{
this.store.baseParams[this.queryParam] = q;
this.store.load({
params: this.getParams(q)
});
this.expand();
}
}else{
this.selectedIndex = -1;
this.onLoad();
}
}
},
// private
getParams : function(q){
var p = {};
//p[this.queryParam] = q;
if(this.pageSize){
p.start = 0;
p.limit = this.pageSize;
}
return p;
},
/**
* 如果下拉列表当前是展开状态则隐藏它。并在完成的时候触发{@link #collapse}事件。
* Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
*/
collapse : function(){
if(!this.isExpanded()){
return;
}
this.list.hide();
Ext.getDoc().un('mousewheel', this.collapseIf, this);
Ext.getDoc().un('mousedown', this.collapseIf, this);
this.fireEvent('collapse', this);
},
// private
collapseIf : function(e){
if(!e.within(this.wrap) && !e.within(this.list)){
this.collapse();
}
},
/**
* 如果下拉列表当前是隐藏状态则展开它。并在完成的时候触发{@link #expand}事件。
* Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
*/
expand : function(){
if(this.isExpanded() || !this.hasFocus){
return;
}
this.list.alignTo(this.wrap, this.listAlign);
this.list.show();
this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
Ext.getDoc().on('mousewheel', this.collapseIf, this);
Ext.getDoc().on('mousedown', this.collapseIf, this);
this.fireEvent('expand', this);
},
/**
* @method onTriggerClick
* @hide
*/
// private
// Implements the default empty TriggerField.onTriggerClick function
onTriggerClick : function(){
if(this.disabled){
return;
}
if(this.isExpanded()){
this.collapse();
this.el.focus();
}else {
this.onFocus({});
if(this.triggerAction == 'all') {
this.doQuery(this.allQuery, true);
} else {
this.doQuery(this.getRawValue());
}
this.el.focus();
}
}
/**
* @hide
* @method autoSize
*/
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
});
Ext.reg('combo', Ext.form.ComboBox); | JavaScript |
/*
* 项目地址: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.DateField
* @extends Ext.form.TriggerField
* 提供一个下拉的{@link Ext.DatePicker}日期选择、自动效验控件的日期输入字段。<br />
* Provides a date input field with a {@link Ext.DatePicker} dropdown and automatic date validation.
* @constructor 创建一个 DateField 对象 Create a new DateField
* @param {Object} config
*/
Ext.form.DateField = Ext.extend(Ext.form.TriggerField, {
/**
* @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} altFormats
* 用 "|" 符号分隔的多个日期格式化字串,当输入的日期与默认的格式不符时用来尝试格式化输入值(默认为 'm/d/Y|m-d-y|m-d-Y|m/d|m-d|d')。
* Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
* format (defaults to 'm/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d').
*/
altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d",
/**
* @cfg {String} disabledDaysText
* 一个禁用的星期数组,以 0 开始。例如,[0,6] 表示禁用周六和周日(默认为 null)。
* The tooltip to display when the date falls on a disabled day (defaults to 'Disabled')
*/
disabledDaysText : "Disabled",
/**
* @cfg {String} disabledDatesText
* 禁用星期上显示的工具提示(默认为 'Disabled')。
* The tooltip text to display when the date falls on a disabled date (defaults to 'Disabled')
*/
disabledDatesText : "Disabled",
/**
* @cfg {String} minText
* 当字段的日期早于 minValue 属性指定值时显示的错误文本(默认为'The date in this field must be after {minValue}')
* The error text to display when the date in the cell is before minValue (defaults to 'The date in this field must be after {minValue}').
*/
minText : "The date in this field must be equal to or after {0}",
/**
* @cfg {String} maxText
* 当字段的日期晚于 maxValue 属性指定值时显示的错误文本(默认为'The date in this field must be before {maxValue}')
* The error text to display when the date in the cell is after maxValue (defaults to
* ).
*/
maxText : "The date in this field must be equal to or before {0}",
/**
* @cfg {String} invalidText
* 当字段的日期无效时显示的错误文本(默认为'{value} is not a valid date - it must be in the format {format}')
* The error text to display when the date in the field is invalid (defaults to '{value} is not a valid date - it must be in the format {format}').
*/
invalidText : "{0} is not a valid date - it must be in the format {1}",
/**
* @cfg {String} triggerClass
* 用以指定触发按钮的附加CSS样式类。触发按钮的类名将总是 'x-form-trigger',而如果指定了 triggerClass 则会被<b>追加</b>在其后(默认为 'x-form-date-trigger' 用以显示一个日历图标)。
* An additional CSS class used to style the trigger button. The trigger will always get the
* class 'x-form-trigger' and triggerClass will be <b>appended</b> if specified (defaults to 'x-form-date-trigger'
* which displays a calendar icon).
*/
triggerClass : 'x-form-date-trigger',
/**
* @cfg {Boolean} showToday
* False表示隐藏底部的Today按钮并禁止空格的快捷键来选择当日日期(默认为true)。
* False to hide the footer area of the DatePicker containing the Today button and disable the keyboard
* handler for spacebar that selects the current date (defaults to true).
*/
showToday : true,
/**
* @cfg {Date/String} minValue
* 允许最早的日期。可以是JavaScript日期对象或者是一个符合日期格式要求的字符串(默认为null)。
* The minimum allowed date. Can be either a Javascript date object or a string date in a
* valid format (defaults to null).
*/
/**
* @cfg {Date/String} maxValue
* 允许最晚的日期。可以是JavaScript日期对象或者是一个符合日期格式要求的字符串(默认为null)。
* The maximum allowed date. Can be either a Javascript date object or a string date in a
* valid format (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 {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"] 将会禁用那些确切的日期 would disable those exact dates</li>
* <li>["03/08", "09/16"] 将会禁用每年中的那些日子 would disable those days for every year</li>
* <li>["^03/08"]将会只匹配开头(当使用短年份时非常有用 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"].
*/
/**
* @cfg {String/Object} autoCreate
* 指定一个 DomHelper配置对象,或者 true 指定默认的元素(默认为{tag: "input", type: "text", size: "10", autocomplete: "off"})。
* A DomHelper element spec, or true for a default element spec (defaults to {tag: "input", type: "text", size: "10", autocomplete: "off"})
*/
// private
defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
initComponent : function(){
Ext.form.DateField.superclass.initComponent.call(this);
this.addEvents(
/**
* @event select
* 当日期选择器选取日期后触发的事件。
* Fires when a date is selected via the date picker.
* @param {Ext.form.DateField} this
* @param {Date} date 选取的日期 The date that was selected
*/
'select'
);
if(typeof this.minValue == "string"){
this.minValue = this.parseDate(this.minValue);
}
if(typeof this.maxValue == "string"){
this.maxValue = this.parseDate(this.maxValue);
}
this.disabledDatesRE = null;
this.initDisabledDays();
},
// private
initDisabledDays : function(){
if(this.disabledDates){
var dd = this.disabledDates;
var re = "(?:";
for(var i = 0; i < dd.length; i++){
re += dd[i];
if(i != dd.length-1) re += "|";
}
this.disabledDatesRE = new RegExp(re + ")");
}
},
/**
* 更换当前禁用的日期,并刷新日期拾取器。
* Replaces any existing disabled dates with new values and refreshes the DatePicker.
* @param {Array} disabledDates 禁用日子的数组。参阅{@link #disabledDates}的配置了解可支持值的详细内容。 An array of date strings (see the {@link #disabledDates} config
* for details on supported values) used to disable a pattern of dates.
*/
setDisabledDates : function(dd){
this.disabledDates = dd;
this.initDisabledDays();
if(this.menu){
this.menu.picker.setDisabledDates(this.disabledDatesRE);
}
},
/**
* 更换当前禁用的日子,并刷新日期拾取器。
* 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;
if(this.menu){
this.menu.picker.setDisabledDays(dd);
}
},
/**
* 更换现有的{@link #minValue},并刷新日期拾取器。
* Replaces any existing {@link #minValue} with the new value and refreshes the DatePicker.
* @param {Date} value 最早可选择的日期 The minimum date that can be selected
*/
setMinValue : function(dt){
this.minValue = (typeof dt == "string" ? this.parseDate(dt) : dt);
if(this.menu){
this.menu.picker.setMinDate(this.minValue);
}
},
/**
* 更换现有的{@link #maxValue},并刷新日期拾取器。
* Replaces any existing {@link #maxValue} with the new value and refreshes the DatePicker.
* @param {Date} value 最晚可选择的日期 The maximum date that can be selected
*/
setMaxValue : function(dt){
this.maxValue = (typeof dt == "string" ? this.parseDate(dt) : dt);
if(this.menu){
this.menu.picker.setMaxDate(this.maxValue);
}
},
// private
validateValue : function(value){
value = this.formatDate(value);
if(!Ext.form.DateField.superclass.validateValue.call(this, value)){
return false;
}
if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
return true;
}
var svalue = value;
value = this.parseDate(value);
if(!value){
this.markInvalid(String.format(this.invalidText, svalue, this.format));
return false;
}
var time = value.getTime();
if(this.minValue && time < this.minValue.getTime()){
this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
return false;
}
if(this.maxValue && time > this.maxValue.getTime()){
this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
return false;
}
if(this.disabledDays){
var day = value.getDay();
for(var i = 0; i < this.disabledDays.length; i++) {
if(day === this.disabledDays[i]){
this.markInvalid(this.disabledDaysText);
return false;
}
}
}
var fvalue = this.formatDate(value);
if(this.disabledDatesRE && this.disabledDatesRE.test(fvalue)){
this.markInvalid(String.format(this.disabledDatesText, fvalue));
return false;
}
return true;
},
// private
// Provides logic to override the default TriggerField.validateBlur which just returns true
validateBlur : function(){
return !this.menu || !this.menu.isVisible();
},
/**
* 返回当前日期字段的值。
* Returns the current date value of the date field.
* @return {Date} 日期值 The date value
*/
getValue : function(){
return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || "";
},
/**
* 设置日期字段的值。你可以传递一个日期对象或任何可以被转换为有效日期的字串,使用 DateField.format 当作日期格式化字串,与 {@link Date#parseDate} 规则相同。(默认的格式化字串为 "m/d/y")。
* Sets the value of the date field. You can pass a date object or any string that can be parsed into a valid
* date, using DateField.format as the date format, according to the same rules as {@link Date#parseDate}
* (the default format used is "m/d/Y").
* <br />用法: Usage:
* <pre><code>
//所有的调用均设置同样的日期(May 4, 2006) All of these calls set the same date value (May 4, 2006)
//传递一个日期对象: Pass a date object:
var dt = new Date('5/4/2006');
dateField.setValue(dt);
//传递一个日期字串(采用默认的格式化字串): Pass a date string (default format):
dateField.setValue('05/04/2006');
//转换一个日期字串(自定义的格式化字串): Pass a date string (custom format):
dateField.format = 'Y-m-d';
dateField.setValue('2006-05-04');
</code></pre>
* @param {String/Date} date 日期对象或有效的日期字串。The date or valid date string
*/
setValue : function(date){
Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
},
// private
parseDate : function(value){
if(!value || Ext.isDate(value)){
return value;
}
var v = Date.parseDate(value, this.format);
if(!v && this.altFormats){
if(!this.altFormatsArray){
this.altFormatsArray = this.altFormats.split("|");
}
for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){
v = Date.parseDate(value, this.altFormatsArray[i]);
}
}
return v;
},
// private
onDestroy : function(){
if(this.menu) {
this.menu.destroy();
}
if(this.wrap){
this.wrap.remove();
}
Ext.form.DateField.superclass.onDestroy.call(this);
},
// private
formatDate : function(date){
return Ext.isDate(date) ? date.dateFormat(this.format) : date;
},
// private
menuListeners : {
select: function(m, d){
this.setValue(d);
this.fireEvent('select', this, d);
},
show : function(){ // retain focus styling
this.onFocus();
},
hide : function(){
this.focus.defer(10, this);
var ml = this.menuListeners;
this.menu.un("select", ml.select, this);
this.menu.un("show", ml.show, this);
this.menu.un("hide", ml.hide, this);
}
},
/**
* @method onTriggerClick
* @hide
*/
// private
// Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
onTriggerClick : function(){
if(this.disabled){
return;
}
if(this.menu == null){
this.menu = new Ext.menu.DateMenu();
}
Ext.apply(this.menu.picker, {
minDate : this.minValue,
maxDate : this.maxValue,
disabledDatesRE : this.disabledDatesRE,
disabledDatesText : this.disabledDatesText,
disabledDays : this.disabledDays,
disabledDaysText : this.disabledDaysText,
format : this.format,
showToday : this.showToday,
minText : String.format(this.minText, this.formatDate(this.minValue)),
maxText : String.format(this.maxText, this.formatDate(this.maxValue))
});
this.menu.on(Ext.apply({}, this.menuListeners, {
scope:this
}));
this.menu.picker.setValue(this.getValue() || new Date());
this.menu.show(this.el, "tl-bl?");
},
// private
beforeBlur : function(){
var v = this.parseDate(this.getRawValue());
if(v){
this.setValue(v);
}
}
/**
* @cfg {Boolean} grow @hide
*/
/**
* @cfg {Number} growMin @hide
*/
/**
* @cfg {Number} growMax @hide
*/
/**
* @hide
* @method autoSize
*/
});
Ext.reg('datefield', Ext.form.DateField); | JavaScript |
/*
* 项目地址: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.Checkbox
* @extends Ext.form.Field
* 单独的checkbox域,可以直接代替传统checkbox域。<br />
* Single checkbox field. Can be used as a direct replacement for traditional checkbox fields.
* @constructor 创建一个新的CheckBox对象 Creates a new Checkbox
* @param {Object} config 配置项选项 config Configuration options
*/
Ext.form.Checkbox = Ext.extend(Ext.form.Field, {
/**
* @cfg {String} focusClass checkbox得到焦点时所使用的样式表(css)默认为undefined。
* The CSS class to use when the checkbox receives focus (defaults to undefined)
*/
focusClass : undefined,
/**
* @cfg {String} fieldClass checkbox默认的样式表(css)默认为x-form-field。
* The default CSS class for the checkbox (defaults to "x-form-field")
*/
fieldClass: "x-form-field",
/**
* @cfg {Boolean} checked 如果checkbox需要呈现选中状态,设置checked为True(默认为false)。
* True if the the checkbox should render already checked (defaults to false)
*/
checked: false,
/**
* @cfg {String/Object} autoCreate 一个DomHelper创建元素的对象,或者为true,表示采用默认的方式创建元素。(默认为 A DomHelper element spec, or true for a default element spec (defaults to
* {tag: "input", type: "checkbox", autocomplete: "off"})
*/
defaultAutoCreate : { tag: "input", type: 'checkbox', autocomplete: "off"},
/**
* @cfg {String} boxLabel checkbox旁边显示的文字。
* The text that appears beside the checkbox
*/
/**
* @cfg {String} inputValue 应该显示在元素value处的值。
* The value that should go into the generated input element's value attribute
*/
// 私有的
// private
initComponent : function(){
Ext.form.Checkbox.superclass.initComponent.call(this);
this.addEvents(
/**
* @event check
* 当checkbox选中也好,不选中也好,触发该事件。
* Fires when the checkbox is checked or unchecked.
* @param {Ext.form.Checkbox} this This checkbox
* @param {Boolean} checked 是否选中了 The new checked value
*/
'check'
);
},
// 私有的
// private
onResize : function(){
Ext.form.Checkbox.superclass.onResize.apply(this, arguments);
if(!this.boxLabel){
this.el.alignTo(this.wrap, 'c-c');
}
},
// 私有的
// private
initEvents : function(){
Ext.form.Checkbox.superclass.initEvents.call(this);
this.mon(this.el, 'click', this.onClick, this);
this.mon(this.el, 'change', this.onClick, this);
},
// 私有的
// private
getResizeEl : function(){
return this.wrap;
},
// 私有的
// private
getPositionEl : function(){
return this.wrap;
},
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
markInvalid : Ext.emptyFn,
/**
* Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
* @method
*/
clearInvalid : Ext.emptyFn,
// 私有的
// private
onRender : function(ct, position){
Ext.form.Checkbox.superclass.onRender.call(this, ct, position);
if(this.inputValue !== undefined){
this.el.dom.value = this.inputValue;
}
this.wrap = this.el.wrap({cls: "x-form-check-wrap"});
if(this.boxLabel){
this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
}
if(this.checked){
this.setValue(true);
}else{
this.checked = this.el.dom.checked;
}
},
// 私有的
// private
onDestroy : function(){
if(this.wrap){
this.wrap.remove();
}
Ext.form.Checkbox.superclass.onDestroy.call(this);
},
// 私有的
// private
initValue : Ext.emptyFn,
/**
* 返回checkbox的选择状态。
* Returns the checked state of the checkbox.
* @return {Boolean} True表示为已选中,否则false。 True if checked, else false
*/
getValue : function(){
if(this.rendered){
return this.el.dom.checked;
}
return false;
},
// 私有的// private
onClick : function(){
if(this.el.dom.checked != this.checked){
this.setValue(this.el.dom.checked);
}
},
/**
* 设置checkbox的选择状态。
* Sets the checked state of the checkbox.
* @param {Boolean/String} v 传入的参数可以为boolean或者String类型,值为True、'true,'或'1'都表示选中,其他为没有选中。
* checked True, 'true', '1', or 'on' to check the checkbox, any other value will uncheck it.
*/
setValue : function(v){
this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
if(this.el && this.el.dom){
this.el.dom.checked = this.checked;
this.el.dom.defaultChecked = this.checked;
}
this.fireEvent("check", this, this.checked);
}
});
Ext.reg('checkbox', Ext.form.Checkbox); | JavaScript |
/*
* 项目地址: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.grid.CellSelectionModel
* @extends Ext.grid.AbstractSelectionModel
* 本类提供了grid单元格选区的基本实现。
* 执行{@link getSelectedCell}的方法返回一个选区对象,这个对象包含下列的属性:<br />
* This class provides the basic implementation for single cell selection in a grid. The object stored
* as the selection and returned by {@link getSelectedCell} contains the following properties:
* <div class="mdetail-params"><ul>
* <li><b>record</b> : Ext.data.record<p class="sub-desc">提供所选行中的 {@link Ext.data.Record}数据
* The {@link Ext.data.Record Record} which provides the data for the row containing the selection</p></li>
* <li><b>cell</b> : Ext.data.record<p class="sub-desc">一个包含下列属性的对象:An object containing the following properties:
* <div class="mdetail-params"><ul>
* <li><b>rowIndex</b> : Number<p class="sub-desc">选中行的索引 The index of the selected row</p></li>
* <li><b>cellIndex</b> : Number<p class="sub-desc">选中单元格的索引 The index of the selected cell<br>
* <b>注意有时会因为列渲染的问题,单元格索引不应用于Record数据的索引。因此,应该使用当前的字段<i>名称</i>来获取数据值,如:
* Note that due to possible column reordering, the cellIndex should not be used as an index into
* the Record's data. Instead, the <i>name</i> of the selected field should be determined
* in order to retrieve the data value from the record by name:</b><pre><code>
var fieldName = grid.getColumnModel().getDataIndex(cellIndex);
var data = record.get(fieldName);
</code></pre></p></li>
* </ul></div></p></li>
* </ul></div>
* @constructor
* @param {Object} config 针对该模型的配置对象 The object containing the configuration of this model.
*/
Ext.grid.CellSelectionModel = function(config){
Ext.apply(this, config);
this.selection = null;
this.addEvents(
/**
* @event beforecellselect
* 单元格被选中之前触发。
* Fires before a cell is selected.
* @param {SelectionModel} this
* @param {Number} rowIndex 选中的行索引 The selected row index
* @param {Number} colIndex 选中的单元格索引 The selected cell index
*/
"beforecellselect",
/**
* @event cellselect
* 当单元格被选中时触发。
* Fires when a cell is selected.
* @param {SelectionModel} this
* @param {Number} rowIndex 选中的行索引 The selected row index
* @param {Number} colIndex 选中的单元格索引 The selected cell index
*/
"cellselect",
/**
* @event selectionchange
* 当已激活的选区改变时触发。
* Fires when the active selection changes.
* @param {SelectionModel} this
* @param {Object} selection null代表没选区而object (o) 则代表有下列两个属性的对象: nullfor no selection or an object (o) with two properties:
<ul>
<li>o.record: 选区所在的record对象 the record object for the row the selection is in</li>
<li>o.cell: [rowIndex, columnIndex]的数组 An array of [rowIndex, columnIndex]</li>
</ul>
*/
"selectionchange"
);
Ext.grid.CellSelectionModel.superclass.constructor.call(this);
};
Ext.extend(Ext.grid.CellSelectionModel, Ext.grid.AbstractSelectionModel, {
/** @ignore */
initEvents : function(){
this.grid.on("cellmousedown", this.handleMouseDown, this);
this.grid.getGridEl().on(Ext.isIE || Ext.isSafari3 ? "keydown" : "keypress", this.handleKeyDown, this);
var view = this.grid.view;
view.on("refresh", this.onViewChange, this);
view.on("rowupdated", this.onRowUpdated, this);
view.on("beforerowremoved", this.clearSelections, this);
view.on("beforerowsinserted", this.clearSelections, this);
if(this.grid.isEditor){
this.grid.on("beforeedit", this.beforeEdit, this);
}
},
//private
beforeEdit : function(e){
this.select(e.row, e.column, false, true, e.record);
},
//private
onRowUpdated : function(v, index, r){
if(this.selection && this.selection.record == r){
v.onCellSelect(index, this.selection.cell[1]);
}
},
//private
onViewChange : function(){
this.clearSelections(true);
},
/**
* 返回当前选中的单元格,如[0, 0]。
* Returns the currently selected cell's row and column indexes as an array (e.g., [0, 0]).
* @return {Array} 选中的单元格,null就代表没选中。 An array containing the row and column indexes of the selected cell, or null if none selected.
*/
getSelectedCell : function(){
return this.selection ? this.selection.cell : null;
},
/**
* 清除所有选区。
* Clears all selections.
* @param {Boolean} preventNotify true表示改变时不通知gridview。 true to prevent the gridview from being notified about the change.
*/
clearSelections : function(preventNotify){
var s = this.selection;
if(s){
if(preventNotify !== true){
this.grid.view.onCellDeselect(s.cell[0], s.cell[1]);
}
this.selection = null;
this.fireEvent("selectionchange", this, null);
}
},
/**
* 有选区的话返回true。
* Returns true if there is a selection.
* @return {Boolean}
*/
hasSelection : function(){
return this.selection ? true : false;
},
/** @ignore */
handleMouseDown : function(g, row, cell, e){
if(e.button !== 0 || this.isLocked()){
return;
};
this.select(row, cell);
},
/**
* 选中一个单元格。
* Selects a cell.
* @param {Number} rowIndex
* @param {Number} collIndex
*/
select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
this.clearSelections();
r = r || this.grid.store.getAt(rowIndex);
this.selection = {
record : r,
cell : [rowIndex, colIndex]
};
if(!preventViewNotify){
var v = this.grid.getView();
v.onCellSelect(rowIndex, colIndex);
if(preventFocus !== true){
v.focusCell(rowIndex, colIndex);
}
}
this.fireEvent("cellselect", this, rowIndex, colIndex);
this.fireEvent("selectionchange", this, this.selection);
}
},
//private
isSelectable : function(rowIndex, colIndex, cm){
return !cm.isHidden(colIndex);
},
/** @ignore */
handleKeyDown : function(e){
if(!e.isNavKeyPress()){
return;
}
var g = this.grid, s = this.selection;
if(!s){
e.stopEvent();
var cell = g.walkCells(0, 0, 1, this.isSelectable, this);
if(cell){
this.select(cell[0], cell[1]);
}
return;
}
var sm = this;
var walk = function(row, col, step){
return g.walkCells(row, col, step, sm.isSelectable, sm);
};
var k = e.getKey(), r = s.cell[0], c = s.cell[1];
var newCell;
switch(k){
case e.TAB:
if(e.shiftKey){
newCell = walk(r, c-1, -1);
}else{
newCell = walk(r, c+1, 1);
}
break;
case e.DOWN:
newCell = walk(r+1, c, 1);
break;
case e.UP:
newCell = walk(r-1, c, -1);
break;
case e.RIGHT:
newCell = walk(r, c+1, 1);
break;
case e.LEFT:
newCell = walk(r, c-1, -1);
break;
case e.ENTER:
if(g.isEditor && !g.editing){
g.startEditing(r, c);
e.stopEvent();
return;
}
break;
};
if(newCell){
this.select(newCell[0], newCell[1]);
e.stopEvent();
}
},
acceptsNav : function(row, col, cm){
return !cm.isHidden(col) && cm.isCellEditable(col, row);
},
onEditorKey : function(field, e){
var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
if(k == e.TAB){
if(e.shiftKey){
newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
}else{
newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
}
e.stopEvent();
}else if(k == e.ENTER){
ed.completeEdit();
e.stopEvent();
}else if(k == e.ESC){
e.stopEvent();
ed.cancelEdit();
}
if(newCell){
g.startEditing(newCell[0], newCell[1]);
}
}
}); | JavaScript |
/*
* 项目地址: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.grid.GridEditor
* private
* This is a support class used internally by the Grid components
*/
Ext.grid.GridEditor = function(field, config){
Ext.grid.GridEditor.superclass.constructor.call(this, field, config);
field.monitorTab = false;
};
Ext.extend(Ext.grid.GridEditor, Ext.Editor, {
alignment: "tl-tl",
autoSize: "width",
hideEl : false,
cls: "x-small-editor x-grid-editor",
shim:false,
shadow:false
}); | JavaScript |
/*
* 项目地址: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.grid.EditorGridPanel
* @extends Ext.grid.GridPanel
* <p>
* 在GridPanel的基础上扩展的新类用于在指定某些的列可以编辑单元格。 这些可编辑的列取决于{@link Ext.grid.ColumnModel#editor editor}的配置情况。<br />
* This class extends the GridPanel to provide cell editing on selected
* columns. The editable columns are specified by providing an
* {@link Ext.grid.ColumnModel#editor editor} in the column
* configuration.
* </p>
* <p>
* 你可以在ColumnModel插入一个{@link Ext.grid.ColumnModel#isCellEditable isCellEditable}的实作来控制
* 某些列是否可以被编辑。 <br />Editability of columns may be controlled programatically
* by inserting an implementation of
* {@link Ext.grid.ColumnModel#isCellEditable isCellEditable} into your
* ColumnModel.
* </p>
* <p>
* 正在编辑的是什么的值,就取决于列所指定的{@link Ext.grid.ColumnModel#dataIndex dataIndex}是指向{@link Ext.data.Store Store}里面的什么的值。
* (这样的话,如果你使用{@link Ext.grid.ColumnModel#setRenderer renderer(数据重新显示)})来转换了的数据,那么该项一定要说明清楚。<br />
* Editing is performed on the value of the <i>field</i> specified by
* the column's {@link Ext.grid.ColumnModel#dataIndex dataIndex} in the
* backing {@link Ext.data.Store Store} (so if you are using a
* {@link Ext.grid.ColumnModel#setRenderer renderer} in order to
* display transformed data, this must be accounted for).
* </p>
* <p>
* 如果渲染列的时候,其映射关系是“值为内,说明文本为外”的关系,譬如{Ext.form.Field#ComboBox
* ComboBox}的情况, 便是这样{@link Ext.form.Field#valueField value}到{@link Ext.form.Field#displayFieldField description}的关系,
* 那么就会采用适当的编辑器。<br /> If a value-to-description mapping is used to render a
* column, then a {Ext.form.Field#ComboBox ComboBox} which uses the
* same {@link Ext.form.Field#valueField value}-to-{@link Ext.form.Field#displayFieldField description}
* mapping would be an appropriate editor.
* </p>
* 如果在Grid显示数据的时候有更复杂的情形,与{@link Edt.data.Store Store}不一定对称的话,那么就可以利用
* {@link #beforeedit}{@link #afteredit}的事件来转换数据,达成是一致的数据。 <br />If there
* is a more complex mismatch between the visible data in the grid, and
* the editable data in the {@link Edt.data.Store Store}, then code to
* transform the data both before and after editing can be injected
* using the {@link #beforeedit} and {@link #afteredit} events.
* @constructor
* @param {Object}
* config 配置项对象。The config object
* @xtype editorgrid
*/
Ext.grid.EditorGridPanel = Ext.extend(Ext.grid.GridPanel, {
/**
* @cfg {Number} clicksToEdit
* <p>
* 要转换单元格为编辑状态所需的鼠标点击数(默认为两下,即双击)。 The number of clicks on a cell
* required to display the cell's editor (defaults to 2).
* </p>
* <p>
* 把该项设置为“auto”表示鼠标移至<i>选中单元格</i>上面就开始编辑的状态。 Setting this option to
* 'auto' means that mousedown <i>on the selected cell</i> starts
* editing that cell.
* </p>
*/
clicksToEdit : 2,
/**
* @cfg {Boolean} forceValidation True表示即使没有被碰的值过都要去验证(默认为false)。 True to
* force validation even if the value is unmodified (defaults to false)
*/
forceValidation : false,
// private
isEditor : true,
// private
detectEdit : false,
/**
* @cfg {Boolean} autoEncode True表示为对任何值和任何后来输入的值都要自动HTML编码或解码(默认为false)。
* True to automatically HTML encode and decode values pre and post
* edit (defaults to false)
*/
autoEncode : false,
/**
* @cfg {Boolean} trackMouseOver
* @hide
*/
// private
trackMouseOver : false, // causes very odd FF errors
// private
initComponent : function() {
Ext.grid.EditorGridPanel.superclass.initComponent.call(this);
if (!this.selModel) {
/**
* @cfg {Object} selModel
* Grid必须需要一个AbstractSelectionModel的子类来为其选区模型提供服务(如不指定则默认为{@link Ext.grid.CellSelectionModel})。
* 注意凡是选区模型必须是兼容单元格选区的模型,要有<tt>getSelectedCell</tt>方法(基于这些原因{@link Ext.grid.RowSelectionModel}就不兼容了)。
* Any subclass of AbstractSelectionModel that will provide the
* selection model for the grid (defaults to
* {@link Ext.grid.CellSelectionModel} if not specified). Note
* that the SelectionModel must be compatible with the model of
* selecting cells individually, and should support a method
* named <tt>getSelectedCell</tt> (for these reasons,
* {@link Ext.grid.RowSelectionModel} is not compatible).
*/
this.selModel = new Ext.grid.CellSelectionModel();
}
this.activeEditor = null;
this.addEvents(
/**
* @event beforeedit 当一个单元格被切换到编辑之前触发。编辑的事件对象会有下列的属性: Fires
* before cell editing is triggered. The edit event
* object has the following properties <br />
* <ul style="padding:5px;padding-left:16px;">
* <li>grid - grid本身。This grid</li>
* <li>record - 正在编辑的record。The record being edited</li>
* <li>field - 正在编辑的字段名。The field name being edited</li>
* <li>value - 正在设置的值(value)。The value for the field
* being edited.</li>
* <li>row - grid行索引。The grid row index</li>
* <li>column - grid列索引。The grid column index</li>
* <li>cancel - 由处理函数返回的布尔值,决定true为取消编辑,否则为false。Set
* this to true to cancel the edit or return false from
* your handler.</li>
* </ul>
* @param {Object}
* e 一个编辑事件(参见上面的解释)。An edit event (see above for
* description)
*/
"beforeedit",
/**
* @event afteredit 当一个单元格被编辑后触发。 Fires after a cell is edited.
* The edit event object has the following properties
* <br />
* <ul style="padding:5px;padding-left:16px;">
* <li>grid - grid本身。This grid</li>
* <li>record - 正在编辑的record。The record being edited</li>
* <li>field - 正在编辑的字段名。The field name being edited</li>
* <li>value - 正在设置的值(value)。The value being set</li>
* <li>originalValue - 在编辑之前的原始值。The original value for
* the field, before the edit.</li>
* <li>row - grid行索引。The grid row index</li>
* <li>column - grid行索引。The grid column index</li>
* </ul>
* @param {Object}
* e 一个编辑事件(参见上面的解释)。An edit event (see above for
* description)
*/
"afteredit",
/**
* @event validateedit
* 编辑单元格后触发,但发生在更改值被设置到record之前。如果返回false即取消更改。
* 编辑的事件有以下属性: Fires after a cell is edited, but before
* the value is set in the record. Return false to cancel
* the change. The edit event object has the following
* properties <br />
* <ul style="padding:5px;padding-left:16px;">
* <li>grid - grid本身。This grid</li>
* <li>record - 正在编辑的record。The record being edited</li>
* <li>field - 正在编辑的字段名。The field name being edited</li>
* <li>value - 正在设置的值(value)。The value being set</li>
* <li>originalValue - 在编辑之前的原始值。The original value for
* the field, before the edit.</li>
* <li>row - grid行索引。The grid row index</li>
* <li>column - grid行索引。The grid column index</li>
* <li>cancel - 由处理函数返回的布尔值,决定true为取消编辑,否则为false。Set
* this to true to cancel the edit or return false from
* your handler.</li>
* </ul>
* @param {Object}
* e 一个编辑事件(参见上面的解释)。An edit event (see above for
* description)
*/
"validateedit");
},
// private
initEvents : function() {
Ext.grid.EditorGridPanel.superclass.initEvents.call(this);
this.on("bodyscroll", this.stopEditing, this, [true]);
this.on("columnresize", this.stopEditing, this, [true]);
if (this.clicksToEdit == 1) {
this.on("cellclick", this.onCellDblClick, this);
} else {
if (this.clicksToEdit == 'auto' && this.view.mainBody) {
this.view.mainBody.on("mousedown", this.onAutoEditClick, this);
}
this.on("celldblclick", this.onCellDblClick, this);
}
},
// private
onCellDblClick : function(g, row, col) {
this.startEditing(row, col);
},
// private
onAutoEditClick : function(e, t) {
if (e.button !== 0) {
return;
}
var row = this.view.findRowIndex(t);
var col = this.view.findCellIndex(t);
if (row !== false && col !== false) {
this.stopEditing();
if (this.selModel.getSelectedCell) { // cell sm
var sc = this.selModel.getSelectedCell();
if (sc && sc.cell[0] === row && sc.cell[1] === col) {
this.startEditing(row, col);
}
} else {
if (this.selModel.isSelected(row)) {
this.startEditing(row, col);
}
}
}
},
// private
onEditComplete : function(ed, value, startValue) {
this.editing = false;
this.activeEditor = null;
ed.un("specialkey", this.selModel.onEditorKey, this.selModel);
var r = ed.record;
var field = this.colModel.getDataIndex(ed.col);
value = this.postEditValue(value, startValue, r, field);
if (this.forceValidation === true
|| String(value) !== String(startValue)) {
var e = {
grid : this,
record : r,
field : field,
originalValue : startValue,
value : value,
row : ed.row,
column : ed.col,
cancel : false
};
if (this.fireEvent("validateedit", e) !== false && !e.cancel
&& String(value) !== String(startValue)) {
r.set(field, e.value);
delete e.cancel;
this.fireEvent("afteredit", e);
}
}
this.view.focusCell(ed.row, ed.col);
},
/**
* 指定的行/列,进行单元格内容的编辑。 Starts editing the specified for the specified
* row/column
*
* @param {Number}
* rowIndex
* @param {Number}
* colIndex
*/
startEditing : function(row, col) {
this.stopEditing();
if (this.colModel.isCellEditable(col, row)) {
this.view.ensureVisible(row, col, true);
var r = this.store.getAt(row);
var field = this.colModel.getDataIndex(col);
var e = {
grid : this,
record : r,
field : field,
value : r.data[field],
row : row,
column : col,
cancel : false
};
if (this.fireEvent("beforeedit", e) !== false && !e.cancel) {
this.editing = true;
var ed = this.colModel.getCellEditor(col, row);
if (!ed) {
return;
}
if (!ed.rendered) {
ed.render(this.view.getEditorParent(ed));
}
(function () { // complex but required for focus issues in safari, ie
// and opera
ed.row = row;
ed.col = col;
ed.record = r;
ed.on("complete", this.onEditComplete, this, {
single : true
});
ed.on("specialkey", this.selModel.onEditorKey,
this.selModel);
/**
* 当前活动着的编辑器对象。The currently active editor or null
*
* @type Ext.Editor
*/
this.activeEditor = ed;
var v = this.preEditValue(r, field);
ed.startEdit(this.view.getCell(row, col).firstChild,
v === undefined ? '' : v);
}).defer(50, this);
}
}
},
// private
preEditValue : function(r, field) {
var value = r.data[field];
return this.autoEncode && typeof value == 'string' ? Ext.util.Format
.htmlDecode(value) : value;
},
// private
postEditValue : function(value, originalValue, r, field) {
return this.autoEncode && typeof value == 'string' ? Ext.util.Format
.htmlEncode(value) : value;
},
/**
* 停止任何激活的行为。 Stops any active editing
*
* @param {Boolean}
* cancel (可选的)True撤销更改。(optional) True to cancel any changes
*/
stopEditing : function(cancel) {
if (this.activeEditor) {
this.activeEditor[cancel === true ? 'cancelEdit' : 'completeEdit']();
}
this.activeEditor = null;
}
});
Ext.reg('editorgrid', Ext.grid.EditorGridPanel); | 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.grid.GridView
* @extends Ext.util.Observable
* <p>GridView类是对{@link Ext.grid.GridPanel}用户界面的封装。为
* 产生特殊的现实效果,可以该类的一些方法来控制用户界面。注意请不要改变用户界面的DOM结构。 <br />
* This class encapsulates the user interface of an {@link Ext.grid.GridPanel}.
* Methods of this class may be used to access user interface elements to enable
* special display effects. Do not change the DOM structure of the user interface.</p>
* <p>GridView类不提供其所属数据的操作方式。Grid的数据模型是交由{@link Ext.data.Store}所实现的。<br />
* This class does not provide ways to manipulate the underlying data. The data
* model of a Grid is held in an {@link Ext.data.Store}.</p>
* @constructor
* @param {Object} config
*/
Ext.grid.GridView = function(config){
Ext.apply(this, config);
// These events are only used internally by the grid components
this.addEvents(
/**
* @event beforerowremoved
* 当行被移除之前触发。
* Internal UI Event. Fired before a row is removed.
* @param {Ext.grid.GridView} view
* @param {Number} rowIndex 要移除行的索引。 The index of the row to be removed.
* @param {Ext.data.Record} record 已移除的记录。 The Record to be removed
*/
"beforerowremoved",
/**
* @event beforerowsinserted
* 插入行之前触发。
* Internal UI Event. Fired before rows are inserted.
* @param {Ext.grid.GridView} view
* @param {Number} firstRow 被插入第一行的索引。 The index of the first row to be inserted.
* @param {Number} lastRow 被最后一行的索引。The index of the last row to be inserted.
*/
"beforerowsinserted",
/**
* @event beforerefresh
* 在视图刷新之前触发。
* Internal UI Event. Fired before the view is refreshed.
* @param {Ext.grid.GridView} view
*/
"beforerefresh",
/**
* @event rowremoved
* 当有行被移除时触发。
* Internal UI Event. Fired after a row is removed.
* @param {Ext.grid.GridView} view
* @param {Number} rowIndex 被移除行的索引。The index of the row that was removed.
* @param {Ext.data.Record} record 被移除的Record对象。The Record that was removed
*/
"rowremoved",
/**
* @event rowsinserted
* 当有行被插入时触发。
* Internal UI Event. Fired after rows are inserted.
* @param {Ext.grid.GridView} view
* @param {Number} firstRow 插入所在位置的索引。The index of the first inserted.
* @param {Number} lastRow 插入位置上一行的索引。The index of the last row inserted.
*/
"rowsinserted",
/**
* @event rowupdated
* 当有一行的内容被更新后触发。
* Internal UI Event. Fired after a row has been updated.
* @param {Ext.grid.GridView} view
* @param {Number} firstRow 更新行的索引。The index of the row updated.
* @param {Ext.data.record} record 更新后行的Record对象。The Record backing the row updated.
*/
"rowupdated",
/**
* @event refresh
* 当GridView主体刷新完毕后触发。
* Internal UI Event. Fired after the GridView's body has been refreshed.
* @param {Ext.grid.GridView} view
*/
"refresh"
);
Ext.grid.GridView.superclass.constructor.call(this);
};
Ext.extend(Ext.grid.GridView, Ext.util.Observable, {
/**
* 重写该函数就会在渲染过程中修改每一行的CSS样式类。
* 同样地,你也可以通过制定行模板(row template)的参数修改当前行样式,达到控制行渲染的目的,这个参数是<b>rowParams</b>。
* 该函数应该返回一个CSS样式类的名称(如没有就空白字符串''),应用当行所在的div元素上。可支持定义多个样式类的名称,用空白字符分割开即可。如('my-class another-class')
* @param {Record} record 当然行所关联的{@link Ext.data.Record}对象。The {@link Ext.data.Record} corresponding to the current row.
* @param {Number} index 行索引。The row index
* @param {Object} rowParams 传入到行模板(row template)的配置项对象,以便渲染过程中可控制每行的部分是怎么显示的(可选的)。
* 注意该对象只会在{@link #enableRowBody} = true时有效,不然的话会被忽略。对象可以包含下例的属性:
* A config object that is passed to the row template during rendering that allows
* customization of various aspects of a body row, if applicable. Note that this object will only be applied if
* {@link #enableRowBody} = true, otherwise it will be ignored. The object may contain any of these properties:
* <ul>
* <li><code>body</code> : String <div class="sub-desc">渲染成为单元格主体部分内容的HTML片断(默认为'')。
* An HTML fragment to be rendered as the cell's body content (defaults to '').
* </div></li>
* <li><code>bodyStyle</code> : String <div class="sub-desc">加入到行所在TR元素的CSS样式(默认为'')。
* A CSS style string that will be applied to the row's TR style attribute (defaults to '').
* </div></li>
* <li><code>cols</code> : Number <div class="sub-desc">
* 列的数量,与body 行的TDcolspan属性紧密联系(默认为当前grid的列数)。
* The column count to apply to the body row's TD colspan attribute (defaults to the current
* column count of the grid).
* </div>
* </li>
* </ul>
* @param {Store} store 与此GRID所绑定的{@link Ext.data.Store}对象。The {@link Ext.data.Store} this grid is bound to
* @method getRowClass
* @return {String} 行新加入的样式类。a CSS class name to add to the row.
*/
/**
* @cfg {Boolean} enableRowBody True表示为在每一数据行的下方加入一个TR的元素,为行部分提供位置。
* 应使用{@link #getRowClass}方法的rowParams的配置自定义行部分。
* True to add a second TR element per row that can be used to provide a row body
* that spans beneath the data row. Use the {@link #getRowClass} method's rowParams config to customize the row body.
*/
/**
* @cfg {String} emptyText 当GRID没有一行可供显示时出现在body的提示文本(默认为"")。
* Default text to display in the grid body when no rows are available (defaults to '').
*/
/**
* <p><b>
* 仅当所在的GridPanel{@link Ext.grid.GridPanel#enableDragDrop enableDragDrop}配置为<tt>true</tt>时候,该项才会出现。
* This will only be present if the owning GridPanel was configured with {@link Ext.grid.GridPanel#enableDragDrop enableDragDrop} <tt>true</tt>.</b></p>
* <p><b>
* 仅当所在的GridPanel被渲染后,该项才会出现。
* This will only be present after the owning GridPanel has been rendered</b>.</p>
* <p>一个制定的{@link Ext.dd.DragZone DragZone}实现,它提供了DragZone的模板方法的默认实现。
* 详细内容请参阅{@link Ext.grid.GridDragZone}。
* A customized implementation of a {@link Ext.dd.DragZone DragZone} which provides default implementations of the
* template methods of DragZone to enable dragging of the selected rows of a GridPanel. See {@link Ext.grid.GridDragZone} for details.</p>
* @type Ext.grid.GridDragZone
* @property dragZone
*/
/**
* @cfg {Boolean} deferEmptyText True表示为emptyText推迟到Store首次加载后才生效。
* True to defer emptyText being applied until the store's first load
*/
deferEmptyText: true,
/**
* 预留给滚动条的空白位置(默认为19像素)。
* The amount of space to reserve for the scrollbar (defaults to 19 pixels)
* @property scrollOffset
* @type Number
*/
scrollOffset: 19,
/**
* @cfg {Boolean} autoFill True表示为<b>当GRID创建后</b>自动展开各列,自适应整个GRID。
* True表示除了auto expand(自动展开)外,还会对超出的部分进行缩减,让每一列的尺寸适应GRID的宽度大小,阻止水平滚动条的出现。
* True to auto expand the columns to fit the grid <b>when the grid is created</b>.
*/
autoFill: false,
/**
* @cfg {Boolean} forceFit
* True表示为自动展开/缩小列的宽度以适应grid的宽度,这样就不会出现水平的滚动条。
* ColumnModel中任意的{@link Ext.grid.ColumnModel#width width}的设置可覆盖此配置项。
* True to auto expand/contract the size of the columns to fit the grid width and prevent horizontal scrolling.
* This option overrides any {@link Ext.grid.ColumnModel#width width} settings in the ColumnModel.
*/
forceFit: false,
/**
* 排序时头部的CSS样式类(默认为["sort-asc", "sort-desc"])。
* The CSS classes applied to a header when it is sorted. (defaults to ["sort-asc", "sort-desc"])
* @type Array
*/
sortClasses : ["sort-asc", "sort-desc"],
/**
* “升序”菜单项的提示文字。
* The text displayed in the "Sort Ascending" menu item
* @type String
*/
sortAscText : "Sort Ascending",
/**
* “降序”菜单项的提示文字。
* The text displayed in the "Sort Descending" menu item
* @type String
*/
sortDescText : "Sort Descending",
/**
* “列”菜单项的提示文字。
* The text displayed in the "Columns" menu item
* @type String
*/
columnsText : "Columns",
selectedRowClass: "x-grid3-row-selected",
// private
borderWidth: 2,
tdClass: 'x-grid3-cell',
hdCls: 'x-grid3-hd',
markDirty: true,
/**
* @cfg {Number} cellSelectorDepth 在事件委托中搜索单元格的深度(默认为4)。
* The number of levels to search for cells in event delegation (defaults to 4)
*/
cellSelectorDepth: 4,
/**
* @cfg {Number} rowSelectorDepth 在事件委托中搜索行的深度(默认为10)。
* The number of levels to search for rows in event delegation (defaults to 10)
*/
rowSelectorDepth: 10,
/**
* @cfg {String} cellSelector 用于内部搜索单元格的选择符。
* The selector used to find cells internally
*/
cellSelector: 'td.x-grid3-cell',
/**
* @cfg {String} rowSelector 用于内部搜索行的选择符。
* The selector used to find rows internally
*/
rowSelector: 'div.x-grid3-row',
/* -------------------------------- UI Specific ----------------------------- */
// private
initTemplates : function(){
var ts = this.templates || {};
if(!ts.master){
ts.master = new Ext.Template(
'<div class="x-grid3" hidefocus="true">',
'<div class="x-grid3-viewport">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
"</div>",
'<div class="x-grid3-resize-marker"> </div>',
'<div class="x-grid3-resize-proxy"> </div>',
"</div>"
);
}
if(!ts.header){
ts.header = new Ext.Template(
'<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
'<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>',
"</table>"
);
}
if(!ts.hcell){
ts.hcell = new Ext.Template(
'<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id} {css}" style="{style}"><div {tooltip} {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '',
'{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />',
"</div></td>"
);
}
if(!ts.body){
ts.body = new Ext.Template('{rows}');
}
if(!ts.row){
ts.row = new Ext.Template(
'<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
'<tbody><tr>{cells}</tr>',
(this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''),
'</tbody></table></div>'
);
}
if(!ts.cell){
ts.cell = new Ext.Template(
'<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>',
'<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>',
"</td>"
);
}
for(var k in ts){
var t = ts[k];
if(t && typeof t.compile == 'function' && !t.compiled){
t.disableFormats = true;
t.compile();
}
}
this.templates = ts;
this.colRe = new RegExp("x-grid3-td-([^\\s]+)", "");
},
// private
fly : function(el){
if(!this._flyweight){
this._flyweight = new Ext.Element.Flyweight(document.body);
}
this._flyweight.dom = el;
return this._flyweight;
},
// private
getEditorParent : function(ed){
return this.scroller.dom;
},
// private
initElements : function(){
var E = Ext.Element;
var el = this.grid.getGridEl().dom.firstChild;
var cs = el.childNodes;
this.el = new E(el);
this.mainWrap = new E(cs[0]);
this.mainHd = new E(this.mainWrap.dom.firstChild);
if(this.grid.hideHeaders){
this.mainHd.setDisplayed(false);
}
this.innerHd = this.mainHd.dom.firstChild;
this.scroller = new E(this.mainWrap.dom.childNodes[1]);
if(this.forceFit){
this.scroller.setStyle('overflow-x', 'hidden');
}
this.mainBody = new E(this.scroller.dom.firstChild);
this.focusEl = new E(this.scroller.dom.childNodes[1]);
this.focusEl.swallowEvent("click", true);
this.resizeMarker = new E(cs[1]);
this.resizeProxy = new E(cs[2]);
},
// private
getRows : function(){
return this.hasRows() ? this.mainBody.dom.childNodes : [];
},
// finder methods, used with delegation
// private
findCell : function(el){
if(!el){
return false;
}
return this.fly(el).findParent(this.cellSelector, this.cellSelectorDepth);
},
// private
findCellIndex : function(el, requiredCls){
var cell = this.findCell(el);
if(cell && (!requiredCls || this.fly(cell).hasClass(requiredCls))){
return this.getCellIndex(cell);
}
return false;
},
// private
getCellIndex : function(el){
if(el){
var m = el.className.match(this.colRe);
if(m && m[1]){
return this.cm.getIndexById(m[1]);
}
}
return false;
},
// private
findHeaderCell : function(el){
var cell = this.findCell(el);
return cell && this.fly(cell).hasClass(this.hdCls) ? cell : null;
},
// private
findHeaderIndex : function(el){
return this.findCellIndex(el, this.hdCls);
},
/**
* 传入一个元素,返回该元素所在行的HtmlElement元素。
* Return the HtmlElement representing the grid row which contains the passed element.
* @param {Element} el 目标元素。The target element
* @return 行索引,或null就表示目标元素不在此GridView的某行中。The row element, or null if the target element is not within a row of this GridView.
*/
findRow : function(el){
if(!el){
return false;
}
return this.fly(el).findParent(this.rowSelector, this.rowSelectorDepth);
},
/**
*
* 传入一个元素,返回该元素所在的行索引。Return the index of the grid row which contains the passed element.
* @param {Element} el 目标元素。The target element
* @return 行索引,或<b>false</b>就表示目标元素不在此GridView的某行中。The row index, or <b>false</b> if the target element is not within a row of this GridView.
*/
findRowIndex : function(el){
var r = this.findRow(el);
return r ? r.rowIndex : false;
},
// getter methods for fetching elements dynamically in the grid
/**
* 指定一个行索引,返回该行的<TR> HtmlElement。
* Return the <TR> HtmlElement which represents a Grid row for the specified index.
* @param {Number} index 行索引。The row index
* @return {HtmlElement} The <TR>元素。lement.
*/
getRow : function(row){
return this.getRows()[row];
},
/**
* 指定一个单元格的坐标,返回该单元格的<TD> HtmlElement。
* Returns the grid's <TD> HtmlElement at the specified coordinates.
* @param {Number} row 定位单元格的行索引。The row index in which to find the cell.
* @param {Number} col 单元格的列索引。The column index of the cell.
* @return {HtmlElement} 坐标所在的<TD>元素。The <TD> at the specified coordinates.
*/
getCell : function(row, col){
return this.getRow(row).getElementsByTagName('td')[col];
},
/**
* 指定一个列索引,返回该列头部的单元格的<TD> HtmlElement。
* Return the <TD> HtmlElement which represents the Grid's header cell for the specified column index.
* @param {Number} index 列索引。The column index
* @return {HtmlElement} The <TD>。元素 element.
*/
getHeaderCell : function(index){
return this.mainHd.dom.getElementsByTagName('td')[index];
},
// manipulating elements
// private - use getRowClass to apply custom row classes
addRowClass : function(row, cls){
var r = this.getRow(row);
if(r){
this.fly(r).addClass(cls);
}
},
// private
removeRowClass : function(row, cls){
var r = this.getRow(row);
if(r){
this.fly(r).removeClass(cls);
}
},
// private
removeRow : function(row){
Ext.removeNode(this.getRow(row));
this.syncFocusEl(row);
},
// private
removeRows : function(firstRow, lastRow){
var bd = this.mainBody.dom;
for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
Ext.removeNode(bd.childNodes[firstRow]);
}
this.syncFocusEl(firstRow);
},
// scrolling stuff
// private
getScrollState : function(){
var sb = this.scroller.dom;
return {left: sb.scrollLeft, top: sb.scrollTop};
},
// private
restoreScroll : function(state){
var sb = this.scroller.dom;
sb.scrollLeft = state.left;
sb.scrollTop = state.top;
},
/**
* 滚动grid到顶部。
* Scrolls the grid to the top
*/
scrollToTop : function(){
this.scroller.dom.scrollTop = 0;
this.scroller.dom.scrollLeft = 0;
},
// private
syncScroll : function(){
this.syncHeaderScroll();
var mb = this.scroller.dom;
this.grid.fireEvent("bodyscroll", mb.scrollLeft, mb.scrollTop);
},
// private
syncHeaderScroll : function(){
var mb = this.scroller.dom;
this.innerHd.scrollLeft = mb.scrollLeft;
this.innerHd.scrollLeft = mb.scrollLeft; // second time for IE (1/2 time first fails, other browsers ignore)
},
// private
updateSortIcon : function(col, dir){
var sc = this.sortClasses;
var hds = this.mainHd.select('td').removeClass(sc);
hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]);
},
// private
updateAllColumnWidths : function(){
var tw = this.getTotalWidth();
var clen = this.cm.getColumnCount();
var ws = [];
for(var i = 0; i < clen; i++){
ws[i] = this.getColumnWidth(i);
}
this.innerHd.firstChild.firstChild.style.width = tw;
for(var i = 0; i < clen; i++){
var hd = this.getHeaderCell(i);
hd.style.width = ws[i];
}
var ns = this.getRows(), row, trow;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = tw;
if(row.firstChild){
row.firstChild.style.width = tw;
trow = row.firstChild.rows[0];
for (var j = 0; j < clen; j++) {
trow.childNodes[j].style.width = ws[j];
}
}
}
this.onAllColumnWidthsUpdated(ws, tw);
},
// private
updateColumnWidth : function(col, width){
var w = this.getColumnWidth(col);
var tw = this.getTotalWidth();
this.innerHd.firstChild.firstChild.style.width = tw;
var hd = this.getHeaderCell(col);
hd.style.width = w;
var ns = this.getRows(), row;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = tw;
if(row.firstChild){
row.firstChild.style.width = tw;
row.firstChild.rows[0].childNodes[col].style.width = w;
}
}
this.onColumnWidthUpdated(col, w, tw);
},
// private
updateColumnHidden : function(col, hidden){
var tw = this.getTotalWidth();
this.innerHd.firstChild.firstChild.style.width = tw;
var display = hidden ? 'none' : '';
var hd = this.getHeaderCell(col);
hd.style.display = display;
var ns = this.getRows(), row;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = tw;
if(row.firstChild){
row.firstChild.style.width = tw;
row.firstChild.rows[0].childNodes[col].style.display = display;
}
}
this.onColumnHiddenUpdated(col, hidden, tw);
delete this.lastViewWidth; // force recalc
this.layout();
},
// private
doRender : function(cs, rs, ds, startRow, colCount, stripe){
var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1;
var tstyle = 'width:'+this.getTotalWidth()+';';
// buffers
var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r;
for(var j = 0, len = rs.length; j < len; j++){
r = rs[j]; cb = [];
var rowIndex = (j+startRow);
for(var i = 0; i < colCount; i++){
c = cs[i];
p.id = c.id;
p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');
p.attr = p.cellAttr = "";
p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
p.style = c.style;
if(p.value == undefined || p.value === "") p.value = " ";
if(this.markDirty && r.dirty && typeof r.modified[c.name] !== 'undefined'){
p.css += ' x-grid3-dirty-cell';
}
cb[cb.length] = ct.apply(p);
}
var alt = [];
if(stripe && ((rowIndex+1) % 2 == 0)){
alt[0] = "x-grid3-row-alt";
}
if(r.dirty){
alt[1] = " x-grid3-dirty-row";
}
rp.cols = colCount;
if(this.getRowClass){
alt[2] = this.getRowClass(r, rowIndex, rp, ds);
}
rp.alt = alt.join(" ");
rp.cells = cb.join("");
buf[buf.length] = rt.apply(rp);
}
return buf.join("");
},
// private
processRows : function(startRow, skipStripe){
if(this.ds.getCount() < 1){
return;
}
skipStripe = skipStripe || !this.grid.stripeRows;
startRow = startRow || 0;
var rows = this.getRows();
var cls = ' x-grid3-row-alt ';
rows[0].className += ' x-grid3-row-first';
rows[rows.length - 1].className += ' x-grid3-row-last';
for(var i = startRow, len = rows.length; i < len; i++){
var row = rows[i];
row.rowIndex = i;
if(!skipStripe){
var isAlt = ((i+1) % 2 == 0);
var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
if(isAlt == hasAlt){
continue;
}
if(isAlt){
row.className += " x-grid3-row-alt";
}else{
row.className = row.className.replace("x-grid3-row-alt", "");
}
}
}
},
afterRender: function(){
if(!this.ds || !this.cm){
return;
}
this.mainBody.dom.innerHTML = this.renderRows();
this.processRows(0, true);
if(this.deferEmptyText !== true){
this.applyEmptyText();
}
},
// private
renderUI : function(){
var header = this.renderHeaders();
var body = this.templates.body.apply({rows:''});
var html = this.templates.master.apply({
body: body,
header: header
});
var g = this.grid;
g.getGridEl().dom.innerHTML = html;
this.initElements();
// get mousedowns early
Ext.fly(this.innerHd).on("click", this.handleHdDown, this);
this.mainHd.on("mouseover", this.handleHdOver, this);
this.mainHd.on("mouseout", this.handleHdOut, this);
this.mainHd.on("mousemove", this.handleHdMove, this);
this.scroller.on('scroll', this.syncScroll, this);
if(g.enableColumnResize !== false){
this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom);
}
if(g.enableColumnMove){
this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd);
this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom);
}
if(g.enableHdMenu !== false){
if(g.enableColumnHide !== false){
this.colMenu = new Ext.menu.Menu({id:g.id + "-hcols-menu"});
this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
this.colMenu.on("itemclick", this.handleHdMenuClick, this);
}
this.hmenu = new Ext.menu.Menu({id: g.id + "-hctx"});
this.hmenu.add(
{id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
{id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
);
if(g.enableColumnHide !== false){
this.hmenu.add('-',
{id:"columns", text: this.columnsText, menu: this.colMenu, iconCls: 'x-cols-icon'}
);
}
this.hmenu.on("itemclick", this.handleHdMenuClick, this);
//g.on("headercontextmenu", this.handleHdCtx, this);
}
if(g.trackMouseOver){
this.mainBody.on("mouseover", this.onRowOver, this);
this.mainBody.on("mouseout", this.onRowOut, this);
}
if(g.enableDragDrop || g.enableDrag){
this.dragZone = new Ext.grid.GridDragZone(g, {
ddGroup : g.ddGroup || 'GridDD'
});
}
this.updateHeaderSortState();
},
// private
layout : function(){
if(!this.mainBody){
return; // not rendered
}
var g = this.grid;
var c = g.getGridEl();
var csize = c.getSize(true);
var vw = csize.width;
if(vw < 20 || csize.height < 20){ // display: none?
return;
}
if(g.autoHeight){
this.scroller.dom.style.overflow = 'visible';
if(Ext.isSafari){
this.scroller.dom.style.position = 'static';
}
}else{
this.el.setSize(csize.width, csize.height);
var hdHeight = this.mainHd.getHeight();
var vh = csize.height - (hdHeight);
this.scroller.setSize(vw, vh);
if(this.innerHd){
this.innerHd.style.width = (vw)+'px';
}
}
if(this.forceFit){
if(this.lastViewWidth != vw){
this.fitColumns(false, false);
this.lastViewWidth = vw;
}
}else {
this.autoExpand();
this.syncHeaderScroll();
}
this.onLayout(vw, vh);
},
// template functions for subclasses and plugins
// these functions include precalculated values
onLayout : function(vw, vh){
// do nothing
},
onColumnWidthUpdated : function(col, w, tw){
//template method
this.focusEl.setWidth(tw);
},
onAllColumnWidthsUpdated : function(ws, tw){
//template method
this.focusEl.setWidth(tw);
},
onColumnHiddenUpdated : function(col, hidden, tw){
// template method
this.focusEl.setWidth(tw);
},
updateColumnText : function(col, text){
// template method
},
afterMove : function(colIndex){
// template method
},
/* ----------------------------------- Core Specific -------------------------------------------*/
// private
init: function(grid){
this.grid = grid;
this.initTemplates();
this.initData(grid.store, grid.colModel);
this.initUI(grid);
},
// private
getColumnId : function(index){
return this.cm.getColumnId(index);
},
// private
renderHeaders : function(){
var cm = this.cm, ts = this.templates;
var ct = ts.hcell;
var cb = [], p = {};
var len = cm.getColumnCount();
var last = len - 1;
for(var i = 0; i < len; i++){
p.id = cm.getColumnId(i);
p.value = cm.getColumnHeader(i) || "";
p.style = this.getColumnStyle(i, true);
p.tooltip = this.getColumnTooltip(i);
p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');
if(cm.config[i].align == 'right'){
p.istyle = 'padding-right:16px';
} else {
delete p.istyle;
}
cb[cb.length] = ct.apply(p);
}
return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'});
},
// private
getColumnTooltip : function(i){
var tt = this.cm.getColumnTooltip(i);
if(tt){
if(Ext.QuickTips.isEnabled()){
return 'ext:qtip="'+tt+'"';
}else{
return 'title="'+tt+'"';
}
}
return "";
},
// private
beforeUpdate : function(){
this.grid.stopEditing(true);
},
// private
updateHeaders : function(){
this.innerHd.firstChild.innerHTML = this.renderHeaders();
},
/**
* 让指定的行获得焦点。
* Focuses the specified row.
* @param {Number} row 行索引。The row index
*/
focusRow : function(row){
this.focusCell(row, 0, false);
},
/**
* 让指定的单元格获得焦点。
* Focuses the specified cell.
* @param {Number} row 行索引。The row index
* @param {Number} col 列索引。The column index
*/
focusCell : function(row, col, hscroll){
this.syncFocusEl(this.ensureVisible(row, col, hscroll));
if(Ext.isGecko){
this.focusEl.focus();
}else{
this.focusEl.focus.defer(1, this.focusEl);
}
},
resolveCell : function(row, col, hscroll){
if(typeof row != "number"){
row = row.rowIndex;
}
if(!this.ds){
return null;
}
if(row < 0 || row >= this.ds.getCount()){
return null;
}
col = (col !== undefined ? col : 0);
var rowEl = this.getRow(row), cellEl;
if(!(hscroll === false && col === 0)){
while(this.cm.isHidden(col)){
col++;
}
cellEl = this.getCell(row, col);
}
return {row: rowEl, cell: cellEl};
},
getResolvedXY : function(resolved){
if(!resolved){
return null;
}
var s = this.scroller.dom, c = resolved.cell, r = resolved.row;
return c ? Ext.fly(c).getXY() : [this.el.getX(), Ext.fly(r).getY()];
},
syncFocusEl : function(row, col, hscroll){
var xy = row;
if(!Ext.isArray(xy)){
row = Math.min(row, Math.max(0, this.getRows().length-1));
xy = this.getResolvedXY(this.resolveCell(row, col, hscroll));
}
this.focusEl.setXY(xy||this.scroller.getXY());
},
ensureVisible : function(row, col, hscroll){
var resolved = this.resolveCell(row, col, hscroll);
if(!resolved || !resolved.row){
return;
}
var rowEl = resolved.row, cellEl = resolved.cell;
var c = this.scroller.dom;
var ctop = 0;
var p = rowEl, stop = this.el.dom;
while(p && p != stop){
ctop += p.offsetTop;
p = p.offsetParent;
}
ctop -= this.mainHd.dom.offsetHeight;
var cbot = ctop + rowEl.offsetHeight;
var ch = c.clientHeight;
var stop = parseInt(c.scrollTop, 10);
var sbot = stop + ch;
if(ctop < stop){
c.scrollTop = ctop;
}else if(cbot > sbot){
c.scrollTop = cbot-ch;
}
if(hscroll !== false){
var cleft = parseInt(cellEl.offsetLeft, 10);
var cright = cleft + cellEl.offsetWidth;
var sleft = parseInt(c.scrollLeft, 10);
var sright = sleft + c.clientWidth;
if(cleft < sleft){
c.scrollLeft = cleft;
}else if(cright > sright){
c.scrollLeft = cright-c.clientWidth;
}
}
return this.getResolvedXY(resolved);
},
// private
insertRows : function(dm, firstRow, lastRow, isUpdate){
if(!isUpdate && firstRow === 0 && lastRow >= dm.getCount()-1){
this.refresh();
}else{
if(!isUpdate){
this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
}
var html = this.renderRows(firstRow, lastRow);
var before = this.getRow(firstRow);
if(before){
Ext.DomHelper.insertHtml('beforeBegin', before, html);
}else{
Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html);
}
if(!isUpdate){
this.fireEvent("rowsinserted", this, firstRow, lastRow);
this.processRows(firstRow);
}
}
this.syncFocusEl(firstRow);
},
// private
deleteRows : function(dm, firstRow, lastRow){
if(dm.getRowCount()<1){
this.refresh();
}else{
this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
this.removeRows(firstRow, lastRow);
this.processRows(firstRow);
this.fireEvent("rowsdeleted", this, firstRow, lastRow);
}
},
// private
getColumnStyle : function(col, isHeader){
var style = !isHeader ? (this.cm.config[col].css || '') : '';
style += 'width:'+this.getColumnWidth(col)+';';
if(this.cm.isHidden(col)){
style += 'display:none;';
}
var align = this.cm.config[col].align;
if(align){
style += 'text-align:'+align+';';
}
return style;
},
// private
getColumnWidth : function(col){
var w = this.cm.getColumnWidth(col);
if(typeof w == 'number'){
return (Ext.isBorderBox ? w : (w-this.borderWidth > 0 ? w-this.borderWidth:0)) + 'px';
}
return w;
},
// private
getTotalWidth : function(){
return this.cm.getTotalWidth()+'px';
},
// private
fitColumns : function(preventRefresh, onlyExpand, omitColumn){
var cm = this.cm, i;
var tw = cm.getTotalWidth(false);
var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset;
if(aw < 20){ // not initialized, so don't screw up the default widths
return;
}
var extra = aw - tw;
if(extra === 0){
return false;
}
var vc = cm.getColumnCount(true);
var ac = vc-(typeof omitColumn == 'number' ? 1 : 0);
if(ac === 0){
ac = 1;
omitColumn = undefined;
}
var colCount = cm.getColumnCount();
var cols = [];
var extraCol = 0;
var width = 0;
var w;
for (i = 0; i < colCount; i++){
if(!cm.isHidden(i) && !cm.isFixed(i) && i !== omitColumn){
w = cm.getColumnWidth(i);
cols.push(i);
extraCol = i;
cols.push(w);
width += w;
}
}
var frac = (aw - cm.getTotalWidth())/width;
while (cols.length){
w = cols.pop();
i = cols.pop();
cm.setColumnWidth(i, Math.max(this.grid.minColumnWidth, Math.floor(w + w*frac)), true);
}
if((tw = cm.getTotalWidth(false)) > aw){
var adjustCol = ac != vc ? omitColumn : extraCol;
cm.setColumnWidth(adjustCol, Math.max(1,
cm.getColumnWidth(adjustCol)- (tw-aw)), true);
}
if(preventRefresh !== true){
this.updateAllColumnWidths();
}
return true;
},
// private
autoExpand : function(preventUpdate){
var g = this.grid, cm = this.cm;
if(!this.userResized && g.autoExpandColumn){
var tw = cm.getTotalWidth(false);
var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset;
if(tw != aw){
var ci = cm.getIndexById(g.autoExpandColumn);
var currentWidth = cm.getColumnWidth(ci);
var cw = Math.min(Math.max(((aw-tw)+currentWidth), g.autoExpandMin), g.autoExpandMax);
if(cw != currentWidth){
cm.setColumnWidth(ci, cw, true);
if(preventUpdate !== true){
this.updateColumnWidth(ci, cw);
}
}
}
}
},
// private
getColumnData : function(){
// build a map for all the columns
var cs = [], cm = this.cm, colCount = cm.getColumnCount();
for(var i = 0; i < colCount; i++){
var name = cm.getDataIndex(i);
cs[i] = {
name : (typeof name == 'undefined' ? this.ds.fields.get(i).name : name),
renderer : cm.getRenderer(i),
id : cm.getColumnId(i),
style : this.getColumnStyle(i)
};
}
return cs;
},
// private
renderRows : function(startRow, endRow){
// pull in all the crap needed to render rows
var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows;
var colCount = cm.getColumnCount();
if(ds.getCount() < 1){
return "";
}
var cs = this.getColumnData();
startRow = startRow || 0;
endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
// records to render
var rs = ds.getRange(startRow, endRow);
return this.doRender(cs, rs, ds, startRow, colCount, stripe);
},
// private
renderBody : function(){
var markup = this.renderRows();
return this.templates.body.apply({rows: markup});
},
// private
refreshRow : function(record){
var ds = this.ds, index;
if(typeof record == 'number'){
index = record;
record = ds.getAt(index);
}else{
index = ds.indexOf(record);
}
this.insertRows(ds, index, index, true);
this.getRow(index).rowIndex = index;
this.onRemove(ds, record, index+1, true);
this.fireEvent("rowupdated", this, index, record);
},
/**
* 刷新grid UI Refreshs the grid UI
* @param {Boolean} headersToo (可选的)True表示为也刷新头部 (optional) True to also refresh the headers
*/
refresh : function(headersToo){
this.fireEvent("beforerefresh", this);
this.grid.stopEditing(true);
var result = this.renderBody();
this.mainBody.update(result);
if(headersToo === true){
this.updateHeaders();
this.updateHeaderSortState();
}
this.processRows(0, true);
this.layout();
this.applyEmptyText();
this.fireEvent("refresh", this);
},
// private
applyEmptyText : function(){
if(this.emptyText && !this.hasRows()){
this.mainBody.update('<div class="x-grid-empty">' + this.emptyText + '</div>');
}
},
// private
updateHeaderSortState : function(){
var state = this.ds.getSortState();
if(!state){
return;
}
if(!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)){
this.grid.fireEvent('sortchange', this.grid, state);
}
this.sortState = state;
var sortColumn = this.cm.findColumnIndex(state.field);
if(sortColumn != -1){
var sortDir = state.direction;
this.updateSortIcon(sortColumn, sortDir);
}
},
// private
destroy : function(){
if(this.colMenu){
Ext.menu.MenuMgr.unregister(this.colMenu);
this.colMenu.destroy();
delete this.colMenu;
}
if(this.hmenu){
Ext.menu.MenuMgr.unregister(this.hmenu);
this.hmenu.destroy();
delete this.hmenu;
}
if(this.grid.enableColumnMove){
var dds = Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
if(dds){
for(var dd in dds){
if(!dds[dd].config.isTarget && dds[dd].dragElId){
var elid = dds[dd].dragElId;
dds[dd].unreg();
Ext.get(elid).remove();
} else if(dds[dd].config.isTarget){
dds[dd].proxyTop.remove();
dds[dd].proxyBottom.remove();
dds[dd].unreg();
}
if(Ext.dd.DDM.locationCache[dd]){
delete Ext.dd.DDM.locationCache[dd];
}
}
delete Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
}
}
if(this.dragZone){
this.dragZone.unreg();
}
Ext.fly(this.innerHd).removeAllListeners();
Ext.removeNode(this.innerHd);
Ext.destroy(this.resizeMarker, this.resizeProxy, this.focusEl, this.mainBody,
this.scroller, this.mainHd, this.mainWrap, this.dragZone,
this.splitZone, this.columnDrag, this.columnDrop);
this.initData(null, null);
Ext.EventManager.removeResizeListener(this.onWindowResize, this);
this.purgeListeners();
},
// private
onDenyColumnHide : function(){
},
// private
render : function(){
if(this.autoFill){
var ct = this.grid.ownerCt;
if (ct && ct.getLayout()){
ct.on('afterlayout', function(){
this.fitColumns(true, true);
this.updateHeaders();
}, this, {single: true});
}else{
this.fitColumns(true, true);
}
}else if(this.forceFit){
this.fitColumns(true, false);
}else if(this.grid.autoExpandColumn){
this.autoExpand(true);
}
this.renderUI();
},
/* --------------------------------- Model Events and Handlers --------------------------------*/
// private
initData : function(ds, cm){
if(this.ds){
this.ds.un("load", this.onLoad, this);
this.ds.un("datachanged", this.onDataChange, this);
this.ds.un("add", this.onAdd, this);
this.ds.un("remove", this.onRemove, this);
this.ds.un("update", this.onUpdate, this);
this.ds.un("clear", this.onClear, this);
}
if(ds){
ds.on("load", this.onLoad, this);
ds.on("datachanged", this.onDataChange, this);
ds.on("add", this.onAdd, this);
ds.on("remove", this.onRemove, this);
ds.on("update", this.onUpdate, this);
ds.on("clear", this.onClear, this);
}
this.ds = ds;
if(this.cm){
this.cm.un("configchange", this.onColConfigChange, this);
this.cm.un("widthchange", this.onColWidthChange, this);
this.cm.un("headerchange", this.onHeaderChange, this);
this.cm.un("hiddenchange", this.onHiddenChange, this);
this.cm.un("columnmoved", this.onColumnMove, this);
this.cm.un("columnlockchange", this.onColumnLock, this);
}
if(cm){
delete this.lastViewWidth;
cm.on("configchange", this.onColConfigChange, this);
cm.on("widthchange", this.onColWidthChange, this);
cm.on("headerchange", this.onHeaderChange, this);
cm.on("hiddenchange", this.onHiddenChange, this);
cm.on("columnmoved", this.onColumnMove, this);
cm.on("columnlockchange", this.onColumnLock, this);
}
this.cm = cm;
},
// private
onDataChange : function(){
this.refresh();
this.updateHeaderSortState();
this.syncFocusEl(0);
},
// private
onClear : function(){
this.refresh();
this.syncFocusEl(0);
},
// private
onUpdate : function(ds, record){
this.refreshRow(record);
},
// private
onAdd : function(ds, records, index){
this.insertRows(ds, index, index + (records.length-1));
},
// private
onRemove : function(ds, record, index, isUpdate){
if(isUpdate !== true){
this.fireEvent("beforerowremoved", this, index, record);
}
this.removeRow(index);
if(isUpdate !== true){
this.processRows(index);
this.applyEmptyText();
this.fireEvent("rowremoved", this, index, record);
}
},
// private
onLoad : function(){
this.scrollToTop();
},
// private
onColWidthChange : function(cm, col, width){
this.updateColumnWidth(col, width);
},
// private
onHeaderChange : function(cm, col, text){
this.updateHeaders();
},
// private
onHiddenChange : function(cm, col, hidden){
this.updateColumnHidden(col, hidden);
},
// private
onColumnMove : function(cm, oldIndex, newIndex){
this.indexMap = null;
var s = this.getScrollState();
this.refresh(true);
this.restoreScroll(s);
this.afterMove(newIndex);
},
// private
onColConfigChange : function(){
delete this.lastViewWidth;
this.indexMap = null;
this.refresh(true);
},
/* -------------------- UI Events and Handlers ------------------------------ */
// private
initUI : function(grid){
grid.on("headerclick", this.onHeaderClick, this);
},
// private
initEvents : function(){
},
// private
onHeaderClick : function(g, index){
if(this.headersDisabled || !this.cm.isSortable(index)){
return;
}
g.stopEditing(true);
g.store.sort(this.cm.getDataIndex(index));
},
// private
onRowOver : function(e, t){
var row;
if((row = this.findRowIndex(t)) !== false){
this.addRowClass(row, "x-grid3-row-over");
}
},
// private
onRowOut : function(e, t){
var row;
if((row = this.findRowIndex(t)) !== false && !e.within(this.getRow(row), true)){
this.removeRowClass(row, "x-grid3-row-over");
}
},
// private
handleWheel : function(e){
e.stopPropagation();
},
// private
onRowSelect : function(row){
this.addRowClass(row, this.selectedRowClass);
},
// private
onRowDeselect : function(row){
this.removeRowClass(row, this.selectedRowClass);
},
// private
onCellSelect : function(row, col){
var cell = this.getCell(row, col);
if(cell){
this.fly(cell).addClass("x-grid3-cell-selected");
}
},
// private
onCellDeselect : function(row, col){
var cell = this.getCell(row, col);
if(cell){
this.fly(cell).removeClass("x-grid3-cell-selected");
}
},
// private
onColumnSplitterMoved : function(i, w){
this.userResized = true;
var cm = this.grid.colModel;
cm.setColumnWidth(i, w, true);
if(this.forceFit){
this.fitColumns(true, false, i);
this.updateAllColumnWidths();
}else{
this.updateColumnWidth(i, w);
this.syncHeaderScroll();
}
this.grid.fireEvent("columnresize", i, w);
},
// private
handleHdMenuClick : function(item){
var index = this.hdCtxIndex;
var cm = this.cm, ds = this.ds;
switch(item.id){
case "asc":
ds.sort(cm.getDataIndex(index), "ASC");
break;
case "desc":
ds.sort(cm.getDataIndex(index), "DESC");
break;
default:
index = cm.getIndexById(item.id.substr(4));
if(index != -1){
if(item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1){
this.onDenyColumnHide();
return false;
}
cm.setHidden(index, item.checked);
}
}
return true;
},
// private
isHideableColumn : function(c){
return !c.hidden && !c.fixed;
},
// private
beforeColMenuShow : function(){
var cm = this.cm, colCount = cm.getColumnCount();
this.colMenu.removeAll();
for(var i = 0; i < colCount; i++){
if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){
this.colMenu.add(new Ext.menu.CheckItem({
id: "col-"+cm.getColumnId(i),
text: cm.getColumnHeader(i),
checked: !cm.isHidden(i),
hideOnClick:false,
disabled: cm.config[i].hideable === false
}));
}
}
},
// private
handleHdDown : function(e, t){
if(Ext.fly(t).hasClass('x-grid3-hd-btn')){
e.stopEvent();
var hd = this.findHeaderCell(t);
Ext.fly(hd).addClass('x-grid3-hd-menu-open');
var index = this.getCellIndex(hd);
this.hdCtxIndex = index;
var ms = this.hmenu.items, cm = this.cm;
ms.get("asc").setDisabled(!cm.isSortable(index));
ms.get("desc").setDisabled(!cm.isSortable(index));
this.hmenu.on("hide", function(){
Ext.fly(hd).removeClass('x-grid3-hd-menu-open');
}, this, {single:true});
this.hmenu.show(t, "tl-bl?");
}
},
// private
handleHdOver : function(e, t){
var hd = this.findHeaderCell(t);
if(hd && !this.headersDisabled){
this.activeHd = hd;
this.activeHdIndex = this.getCellIndex(hd);
var fly = this.fly(hd);
this.activeHdRegion = fly.getRegion();
if(!this.cm.isMenuDisabled(this.activeHdIndex)){
fly.addClass("x-grid3-hd-over");
this.activeHdBtn = fly.child('.x-grid3-hd-btn');
if(this.activeHdBtn){
this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight-1)+'px';
}
}
}
},
// private
handleHdMove : function(e, t){
if(this.activeHd && !this.headersDisabled){
var hw = this.splitHandleWidth || 5;
var r = this.activeHdRegion;
var x = e.getPageX();
var ss = this.activeHd.style;
if(x - r.left <= hw && this.cm.isResizable(this.activeHdIndex-1)){
ss.cursor = Ext.isAir ? 'move' : Ext.isSafari ? 'e-resize' : 'col-resize'; // col-resize not always supported
}else if(r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)){
ss.cursor = Ext.isAir ? 'move' : Ext.isSafari ? 'w-resize' : 'col-resize';
}else{
ss.cursor = '';
}
}
},
// private
handleHdOut : function(e, t){
var hd = this.findHeaderCell(t);
if(hd && (!Ext.isIE || !e.within(hd, true))){
this.activeHd = null;
this.fly(hd).removeClass("x-grid3-hd-over");
hd.style.cursor = '';
}
},
// private
hasRows : function(){
var fc = this.mainBody.dom.firstChild;
return fc && fc.className != 'x-grid-empty';
},
// back compat
bind : function(d, c){
this.initData(d, c);
}
});
// private
// This is a support class used internally by the Grid components
Ext.grid.GridView.SplitDragZone = function(grid, hd){
this.grid = grid;
this.view = grid.getView();
this.marker = this.view.resizeMarker;
this.proxy = this.view.resizeProxy;
Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this, hd,
"gridSplitters" + this.grid.getGridEl().id, {
dragElId : Ext.id(this.proxy.dom), resizeFrame:false
});
this.scroll = false;
this.hw = this.view.splitHandleWidth || 5;
};
Ext.extend(Ext.grid.GridView.SplitDragZone, Ext.dd.DDProxy, {
b4StartDrag : function(x, y){
this.view.headersDisabled = true;
var h = this.view.mainWrap.getHeight();
this.marker.setHeight(h);
this.marker.show();
this.marker.alignTo(this.view.getHeaderCell(this.cellIndex), 'tl-tl', [-2, 0]);
this.proxy.setHeight(h);
var w = this.cm.getColumnWidth(this.cellIndex);
var minw = Math.max(w-this.grid.minColumnWidth, 0);
this.resetConstraints();
this.setXConstraint(minw, 1000);
this.setYConstraint(0, 0);
this.minX = x - minw;
this.maxX = x + 1000;
this.startPos = x;
Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
},
handleMouseDown : function(e){
var t = this.view.findHeaderCell(e.getTarget());
if(t){
var xy = this.view.fly(t).getXY(), x = xy[0], y = xy[1];
var exy = e.getXY(), ex = exy[0];
var w = t.offsetWidth, adjust = false;
if((ex - x) <= this.hw){
adjust = -1;
}else if((x+w) - ex <= this.hw){
adjust = 0;
}
if(adjust !== false){
this.cm = this.grid.colModel;
var ci = this.view.getCellIndex(t);
if(adjust == -1){
if (ci + adjust < 0) {
return;
}
while(this.cm.isHidden(ci+adjust)){
--adjust;
if(ci+adjust < 0){
return;
}
}
}
this.cellIndex = ci+adjust;
this.split = t.dom;
if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
}
}else if(this.view.columnDrag){
this.view.columnDrag.callHandleMouseDown(e);
}
}
},
endDrag : function(e){
this.marker.hide();
var v = this.view;
var endX = Math.max(this.minX, e.getPageX());
var diff = endX - this.startPos;
v.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
setTimeout(function(){
v.headersDisabled = false;
}, 50);
},
autoOffset : function(){
this.setDelta(0,0);
}
});
| JavaScript |
/*
* 项目地址: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.grid.Column
* Ext.grid.Column类。
*/
Ext.grid.Column = function(config){
Ext.apply(this, config);
if(typeof this.renderer == "string"){
this.renderer = Ext.util.Format[this.renderer];
}
if(typeof this.id == "undefined"){
this.id = ++Ext.grid.Column.AUTO_ID;
}
if(this.editor){
if(this.editor.xtype && !this.editor.events){
this.editor = Ext.create(this.editor, 'textfield');
}
}
}
Ext.grid.Column.AUTO_ID = 0;
Ext.grid.Column.prototype = {
isColumn : true,
renderer : function(value){
if(typeof value == "string" && value.length < 1){
return " ";
}
return value;
},
getEditor: function(rowIndex){
return this.editable !== false ? this.editor : null;
},
getCellEditor: function(rowIndex){
var editor = this.getEditor(rowIndex);
if(editor){
if(!editor.startEdit){
if(!editor.gridEditor){
editor.gridEditor = new Ext.grid.GridEditor(editor);
}
return editor.gridEditor;
}else if(editor.startEdit){
return editor;
}
}
return null;
}
};
Ext.grid.BooleanColumn = Ext.extend(Ext.grid.Column, {
trueText: 'true',
falseText: 'false',
undefinedText: ' ',
constructor: function(cfg){
this.supr().constructor.apply(this, arguments);
var t = this.trueText, f = this.falseText, u = this.undefinedText;
this.renderer = function(v){
if(v === undefined){
return u;
}
if(!v || v === 'false'){
return f;
}
return t;
};
}
});
Ext.grid.NumberColumn = Ext.extend(Ext.grid.Column, {
format : '0,000.00',
constructor: function(cfg){
this.supr().constructor.apply(this, arguments);
this.renderer = Ext.util.Format.numberRenderer(this.format);
}
});
Ext.grid.DateColumn = Ext.extend(Ext.grid.Column, {
format : 'm/d/Y',
constructor: function(cfg){
this.supr().constructor.apply(this, arguments);
this.renderer = Ext.util.Format.dateRenderer(this.format);
}
});
Ext.grid.TemplateColumn = Ext.extend(Ext.grid.Column, {
constructor: function(cfg){
this.supr().constructor.apply(this, arguments);
var tpl = typeof this.tpl == 'object' ? this.tpl : new Ext.XTemplate(this.tpl);
this.renderer = function(value, p, r){
return tpl.apply(r.data);
}
this.tpl = tpl;
}
});
Ext.grid.Column.types = {
gridcolumn : Ext.grid.Column,
booleancolumn: Ext.grid.BooleanColumn,
numbercolumn: Ext.grid.NumberColumn,
datecolumn: Ext.grid.DateColumn,
templatecolumn: Ext.grid.TemplateColumn
}; | 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.grid.RowSelectionModel
* @extends Ext.grid.AbstractSelectionModel
* {@link Ext.grid.GridPanel}的默认选区模型。它支持多选区和键盘选区/导航。{@link #getSelected}方法返回选中的对象,{@link #getSelections}就是多个已选择的{@link Ext.data.Record Record}(支持多选的)。<br />
* The default SelectionModel used by {@link Ext.grid.GridPanel}.
* It supports multiple selections and keyboard selection/navigation. The objects stored
* as selections and returned by {@link #getSelected}, and {@link #getSelections} are
* the {@link Ext.data.Record Record}s which provide the data for the selected rows.
* @constructor
* @param {Object} config
*/
Ext.grid.RowSelectionModel = function(config){
Ext.apply(this, config);
this.selections = new Ext.util.MixedCollection(false, function(o){
return o.id;
});
this.last = false;
this.lastActive = false;
this.addEvents(
/**
* @event selectionchange
* 当选区改变时触发。
* Fires when the selection changes
* @param {SelectionModel} this
*/
"selectionchange",
/**
* @event beforerowselect
* 当行(row)是选中又被选择触发,返回false取消。
* Fires when a row is being selected, return false to cancel.
* @param {SelectionModel} this
* @param {Number} rowIndex The index to be selected
* @param {Boolean} keepExisting 选中的索引。False if other selections will be cleared
* @param {Record} record The record to be selected
*/
"beforerowselect",
/**
* @event rowselect
* 当行(row)被选中时触发。
* Fires when a row is selected.
* @param {SelectionModel} this
* @param {Number} rowIndex 选中的索引。The selected index
* @param {Ext.data.Record} r The selected record
*/
"rowselect",
/**
* @event rowdeselect
* 当行(row)反选时触发。
* Fires when a row is deselected.
* @param {SelectionModel} this
* @param {Number} rowIndex 选中的索引。
* @param {Record} record 记录
*/
"rowdeselect"
);
Ext.grid.RowSelectionModel.superclass.constructor.call(this);
};
Ext.extend(Ext.grid.RowSelectionModel, Ext.grid.AbstractSelectionModel, {
/**
* @cfg {Boolean} singleSelect True表示为同时只能选单行(默认false)。
* True to allow selection of only one row at a time (defaults to false)
*/
singleSelect : false,
/**
* @cfg {Boolean} moveEditorOnEnter
* False表示禁止按下回车键时就是移动到下一行,shift+回车就是网上移动。
* False to turn off moving the editor to the next row down when the enter key is pressed
* or the next row up when shift + enter keys are pressed.
*/
// private
initEvents : function(){
if(!this.grid.enableDragDrop && !this.grid.enableDrag){
this.grid.on("rowmousedown", this.handleMouseDown, this);
}else{ // allow click to work like normal
this.grid.on("rowclick", function(grid, rowIndex, e) {
if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
this.selectRow(rowIndex, false);
grid.view.focusRow(rowIndex);
}
}, this);
}
this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), {
"up" : function(e){
if(!e.shiftKey || this.singleSelect){
this.selectPrevious(false);
}else if(this.last !== false && this.lastActive !== false){
var last = this.last;
this.selectRange(this.last, this.lastActive-1);
this.grid.getView().focusRow(this.lastActive);
if(last !== false){
this.last = last;
}
}else{
this.selectFirstRow();
}
},
"down" : function(e){
if(!e.shiftKey || this.singleSelect){
this.selectNext(false);
}else if(this.last !== false && this.lastActive !== false){
var last = this.last;
this.selectRange(this.last, this.lastActive+1);
this.grid.getView().focusRow(this.lastActive);
if(last !== false){
this.last = last;
}
}else{
this.selectFirstRow();
}
},
scope: this
});
var view = this.grid.view;
view.on("refresh", this.onRefresh, this);
view.on("rowupdated", this.onRowUpdated, this);
view.on("rowremoved", this.onRemove, this);
},
// private
onRefresh : function(){
var ds = this.grid.store, index;
var s = this.getSelections();
this.clearSelections(true);
for(var i = 0, len = s.length; i < len; i++){
var r = s[i];
if((index = ds.indexOfId(r.id)) != -1){
this.selectRow(index, true);
}
}
if(s.length != this.selections.getCount()){
this.fireEvent("selectionchange", this);
}
},
// private
onRemove : function(v, index, r){
if(this.selections.remove(r) !== false){
this.fireEvent('selectionchange', this);
}
},
// private
onRowUpdated : function(v, index, r){
if(this.isSelected(r)){
v.onRowSelect(index);
}
},
/**
* 选择多个记录。
* Select records.
* @param {Array} records 要选择的record。The records to select
* @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。 (optional)True to keep existing selections
*/
selectRecords : function(records, keepExisting){
if(!keepExisting){
this.clearSelections();
}
var ds = this.grid.store;
for(var i = 0, len = records.length; i < len; i++){
this.selectRow(ds.indexOf(records[i]), true);
}
},
/**
* 获取已选择的行数。
* Gets the number of selected rows.
* @return {Number}
*/
getCount : function(){
return this.selections.length;
},
/**
* 选择GRID的第一行。
* Selects the first row in the grid.
*/
selectFirstRow : function(){
this.selectRow(0);
},
/**
* 选择最后一行。
* Select the last row.
* @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。(optional) True to keep existing selections
*/
selectLastRow : function(keepExisting){
this.selectRow(this.grid.store.getCount() - 1, keepExisting);
},
/**
* 选取上次选取的最后一行。
* Selects the row immediately following the last selected row.
* @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。(optional)True to keep existing selections
* @return {Boolean} True if there is a next row, else false
*/
selectNext : function(keepExisting){
if(this.hasNext()){
this.selectRow(this.last+1, keepExisting);
this.grid.getView().focusRow(this.last);
return true;
}
return false;
},
/**
* 选取上次选取的最前一行。
* Selects the row that precedes the last selected row.
* @param {Boolean} keepExisting (可选的)true表示为保持当前现有的选区。(optional)True to keep existing selections
* @return {Boolean} True表示为有前一行,false表示没有。True if there is a previous row, else false
*/
selectPrevious : function(keepExisting){
if(this.hasPrevious()){
this.selectRow(this.last-1, keepExisting);
this.grid.getView().focusRow(this.last);
return true;
}
return false;
},
/**
* 若有下一个可选取的记录返回true。
* Returns true if there is a next record to select
* @return {Boolean}
*/
hasNext : function(){
return this.last !== false && (this.last+1) < this.grid.store.getCount();
},
/**
* 若有前一个可选取的记录返回true。
* Returns true if there is a previous record to select
* @return {Boolean}
*/
hasPrevious : function(){
return !!this.last;
},
/**
* 返回以选取的纪录。
* Returns the selected records
* @return {Array} 已选取记录的数组。Array of selected records
*/
getSelections : function(){
return [].concat(this.selections.items);
},
/**
* 返回选区中的第一个记录。
* Returns the first selected record.
* @return {Record}
*/
getSelected : function(){
return this.selections.itemAt(0);
},
/**
* 对选区执行传入函数。
* 如果函数返回false,枚举将会中止,each函数就会返回false,否则返回true。
* Calls the passed function with each selection. If the function returns false, iteration is
* stopped and this function returns false. Otherwise it returns true.
* @param {Function} fn
* @param {Object} scope (optional)
* @return {Boolean} true表示为已枚举所有的记录。true if all selections were iterated
*/
each : function(fn, scope){
var s = this.getSelections();
for(var i = 0, len = s.length; i < len; i++){
if(fn.call(scope || this, s[i], i) === false){
return false;
}
}
return true;
},
/**
* 清除全部的选区。
* Clears all selections.
*/
clearSelections : function(fast){
if(this.isLocked()) return;
if(fast !== true){
var ds = this.grid.store;
var s = this.selections;
s.each(function(r){
this.deselectRow(ds.indexOfId(r.id));
}, this);
s.clear();
}else{
this.selections.clear();
}
this.last = false;
},
/**
* 选择所有的行
* Selects all rows.
*/
selectAll : function(){
if(this.isLocked()) return;
this.selections.clear();
for(var i = 0, len = this.grid.store.getCount(); i < len; i++){
this.selectRow(i, true);
}
},
/**
* 返回True表示有选中。
* Returns True if there is a selection.
* @return {Boolean}
*/
hasSelection : function(){
return this.selections.length > 0;
},
/**
* 返回True表示有特定的行是被选中的。
* Returns True if the specified row is selected.
* @param {Number/Record} record Record对象或Record的id。The record or index of the record to check
* @return {Boolean}
*/
isSelected : function(index){
var r = typeof index == "number" ? this.grid.store.getAt(index) : index;
return (r && this.selections.key(r.id) ? true : false);
},
/**
* 返回True表示特定的记录是否被选中。
* Returns True if the specified record id is selected.
* @param {String} id 要检查的记录id。The id of record to check
* @return {Boolean}
*/
isIdSelected : function(id){
return (this.selections.key(id) ? true : false);
},
// private
handleMouseDown : function(g, rowIndex, e){
if(e.button !== 0 || this.isLocked()){
return;
};
var view = this.grid.getView();
if(e.shiftKey && !this.singleSelect && this.last !== false){
var last = this.last;
this.selectRange(last, rowIndex, e.ctrlKey);
this.last = last; // reset the last
view.focusRow(rowIndex);
}else{
var isSelected = this.isSelected(rowIndex);
if(e.ctrlKey && isSelected){
this.deselectRow(rowIndex);
}else if(!isSelected || this.getCount() > 1){
this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);
view.focusRow(rowIndex);
}
}
},
/**
* 选取多行。
* Selects multiple rows.
* @param {Array} rows 要选取行的索引的集合。Array of the indexes of the row to select
* @param {Boolean} keepExisting (可选的)表示为保持现有的选区。 (optional)True to keep existing selections (defaults to false)
*/
selectRows : function(rows, keepExisting){
if(!keepExisting){
this.clearSelections();
}
for(var i = 0, len = rows.length; i < len; i++){
this.selectRow(rows[i], true);
}
},
/**
* 选取某个范围内的行(rows)。所有在startRow和endRow之间的行都会被选中。
* Selects a range of rows. All rows in between startRow and endRow are also selected.
* @param {Number} startRow 范围内的第一行之索引。The index of the first row in the range
* @param {Number} endRow 范围内的最后一行之索引。The index of the last row in the range
* @param {Boolean} keepExisting (可选的)表示为保持现有的选区。 (optional)True to retain existing selections
*/
selectRange : function(startRow, endRow, keepExisting){
if(this.isLocked()) return;
if(!keepExisting){
this.clearSelections();
}
if(startRow <= endRow){
for(var i = startRow; i <= endRow; i++){
this.selectRow(i, true);
}
}else{
for(var i = startRow; i >= endRow; i--){
this.selectRow(i, true);
}
}
},
/**
* 反选某个范围内的行(rows)。所有在startRow和endRow之间的行都会被选反。
* Deselects a range of rows. All rows in between startRow and endRow are also deselected.
* @param {Number} startRow 范围内的第一行之索引。The index of the first row in the range
* @param {Number} endRow 范围内的最后一行之索引。The index of the last row in the range
*/
deselectRange : function(startRow, endRow, preventViewNotify){
if(this.isLocked()) return;
for(var i = startRow; i <= endRow; i++){
this.deselectRow(i, preventViewNotify);
}
},
/**
* 选择一行。
* Selects a row.
* @param {Number} row 要选择行的索引。The index of the row to select
* @param {Boolean} keepExisting (optional) (可选的)表示为保持现有的选区。True to keep existing selections
*/
selectRow : function(index, keepExisting, preventViewNotify){
if(this.isLocked() || (index < 0 || index >= this.grid.store.getCount()) || this.isSelected(index)) return;
var r = this.grid.store.getAt(index);
if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){
if(!keepExisting || this.singleSelect){
this.clearSelections();
}
this.selections.add(r);
this.last = this.lastActive = index;
if(!preventViewNotify){
this.grid.getView().onRowSelect(index);
}
this.fireEvent("rowselect", this, index, r);
this.fireEvent("selectionchange", this);
}
},
/**
* 反选一个行。
* Deselects a row.
* @param {Number} row 反选行的索引。The index of the row to deselect
*/
deselectRow : function(index, preventViewNotify){
if(this.isLocked()) return;
if(this.last == index){
this.last = false;
}
if(this.lastActive == index){
this.lastActive = false;
}
var r = this.grid.store.getAt(index);
if(r){
this.selections.remove(r);
if(!preventViewNotify){
this.grid.getView().onRowDeselect(index);
}
this.fireEvent("rowdeselect", this, index, r);
this.fireEvent("selectionchange", this);
}
},
// private
restoreLast : function(){
if(this._last){
this.last = this._last;
}
},
// private
acceptsNav : function(row, col, cm){
return !cm.isHidden(col) && cm.isCellEditable(col, row);
},
// private
onEditorKey : function(field, e){
var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor;
var shift = e.shiftKey;
if(k == e.TAB){
e.stopEvent();
ed.completeEdit();
if(shift){
newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
}else{
newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
}
}else if(k == e.ENTER){
e.stopEvent();
ed.completeEdit();
if(this.moveEditorOnEnter !== false){
if(shift){
newCell = g.walkCells(ed.row - 1, ed.col, -1, this.acceptsNav, this);
}else{
newCell = g.walkCells(ed.row + 1, ed.col, 1, this.acceptsNav, this);
}
}
}else if(k == e.ESC){
ed.cancelEdit();
}
if(newCell){
g.startEditing(newCell[0], newCell[1]);
}
}
}); | JavaScript |
/*
* 项目地址: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.grid.HeaderDragZone
* 这是一个Grid组件内部会使用的类。
* This is a support class used internally by the Grid components
*/
Ext.grid.HeaderDragZone = function(grid, hd, hd2){
this.grid = grid;
this.view = grid.getView();
this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd);
if(hd2){
this.setHandleElId(Ext.id(hd));
this.setOuterHandleElId(Ext.id(hd2));
}
this.scroll = false;
};
Ext.extend(Ext.grid.HeaderDragZone, Ext.dd.DragZone, {
maxDragWidth: 120,
getDragData : function(e){
var t = Ext.lib.Event.getTarget(e);
var h = this.view.findHeaderCell(t);
if(h){
return {ddel: h.firstChild, header:h};
}
return false;
},
onInitDrag : function(e){
this.view.headersDisabled = true;
var clone = this.dragData.ddel.cloneNode(true);
clone.id = Ext.id();
clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px";
this.proxy.update(clone);
return true;
},
afterValidDrop : function(){
var v = this.view;
setTimeout(function(){
v.headersDisabled = false;
}, 50);
},
afterInvalidDrop : function(){
var v = this.view;
setTimeout(function(){
v.headersDisabled = false;
}, 50);
}
});
// private
// This is a support class used internally by the Grid components
Ext.grid.HeaderDropZone = function(grid, hd, hd2){
this.grid = grid;
this.view = grid.getView();
// split the proxies so they don't interfere with mouse events
this.proxyTop = Ext.DomHelper.append(document.body, {
cls:"col-move-top", html:" "
}, true);
this.proxyBottom = Ext.DomHelper.append(document.body, {
cls:"col-move-bottom", html:" "
}, true);
this.proxyTop.hide = this.proxyBottom.hide = function(){
this.setLeftTop(-100,-100);
this.setStyle("visibility", "hidden");
};
this.ddGroup = "gridHeader" + this.grid.getGridEl().id;
// temporarily disabled
//Ext.dd.ScrollManager.register(this.view.scroller.dom);
Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom);
};
Ext.extend(Ext.grid.HeaderDropZone, Ext.dd.DropZone, {
proxyOffsets : [-4, -9],
fly: Ext.Element.fly,
getTargetFromEvent : function(e){
var t = Ext.lib.Event.getTarget(e);
var cindex = this.view.findCellIndex(t);
if(cindex !== false){
return this.view.getHeaderCell(cindex);
}
},
nextVisible : function(h){
var v = this.view, cm = this.grid.colModel;
h = h.nextSibling;
while(h){
if(!cm.isHidden(v.getCellIndex(h))){
return h;
}
h = h.nextSibling;
}
return null;
},
prevVisible : function(h){
var v = this.view, cm = this.grid.colModel;
h = h.prevSibling;
while(h){
if(!cm.isHidden(v.getCellIndex(h))){
return h;
}
h = h.prevSibling;
}
return null;
},
positionIndicator : function(h, n, e){
var x = Ext.lib.Event.getPageX(e);
var r = Ext.lib.Dom.getRegion(n.firstChild);
var px, pt, py = r.top + this.proxyOffsets[1];
if((r.right - x) <= (r.right-r.left)/2){
px = r.right+this.view.borderWidth;
pt = "after";
}else{
px = r.left;
pt = "before";
}
var oldIndex = this.view.getCellIndex(h);
var newIndex = this.view.getCellIndex(n);
if(this.grid.colModel.isFixed(newIndex)){
return false;
}
var locked = this.grid.colModel.isLocked(newIndex);
if(pt == "after"){
newIndex++;
}
if(oldIndex < newIndex){
newIndex--;
}
if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){
return false;
}
px += this.proxyOffsets[0];
this.proxyTop.setLeftTop(px, py);
this.proxyTop.show();
if(!this.bottomOffset){
this.bottomOffset = this.view.mainHd.getHeight();
}
this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset);
this.proxyBottom.show();
return pt;
},
onNodeEnter : function(n, dd, e, data){
if(data.header != n){
this.positionIndicator(data.header, n, e);
}
},
onNodeOver : function(n, dd, e, data){
var result = false;
if(data.header != n){
result = this.positionIndicator(data.header, n, e);
}
if(!result){
this.proxyTop.hide();
this.proxyBottom.hide();
}
return result ? this.dropAllowed : this.dropNotAllowed;
},
onNodeOut : function(n, dd, e, data){
this.proxyTop.hide();
this.proxyBottom.hide();
},
onNodeDrop : function(n, dd, e, data){
var h = data.header;
if(h != n){
var cm = this.grid.colModel;
var x = Ext.lib.Event.getPageX(e);
var r = Ext.lib.Dom.getRegion(n.firstChild);
var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before";
var oldIndex = this.view.getCellIndex(h);
var newIndex = this.view.getCellIndex(n);
var locked = cm.isLocked(newIndex);
if(pt == "after"){
newIndex++;
}
if(oldIndex < newIndex){
newIndex--;
}
if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){
return false;
}
cm.setLocked(oldIndex, locked, true);
cm.moveColumn(oldIndex, newIndex);
this.grid.fireEvent("columnmove", oldIndex, newIndex);
return true;
}
return false;
}
});
Ext.grid.GridView.ColumnDragZone = function(grid, hd){
Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
this.proxy.el.addClass('x-grid3-col-dd');
};
Ext.extend(Ext.grid.GridView.ColumnDragZone, Ext.grid.HeaderDragZone, {
handleMouseDown : function(e){
},
callHandleMouseDown : function(e){
Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
}
}); | JavaScript |
/*
* 项目地址: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.grid.CheckboxSelectionModel
* @extends Ext.grid.RowSelectionModel
* 通过checkbox选择或反选时触发选区轮换的一个制定选区模型。<br />
* A custom selection model that renders a column of checkboxes that can be toggled to select or deselect rows.
* @constructor
* @param {Object} config 配置项选项 The configuration options
*/
Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, {
/**
* @cfg {String} header
* 任何显示在checkbox列头部上有效的HTML片断(默认为 '<div class="x-grid3-hd-checker"> </div>')
* 默认的CSS样式类'x-grid3-hd-checker'负责头部的那个checkbox,以支持全局单击、反选的行为。
* 这个字符串可以替换为任何有效的HTML片断,包括几句的文本字符串(如'Select Rows'), 但是全局单击、反选行为的checkbox就只能带有“x-grid3-hd-checker”样式的元素才能工作。<br />
* Any valid text or HTML fragment to display in the header cell for the checkbox column
* (defaults to '<div class="x-grid3-hd-checker"> </div>'). The default CSS class of 'x-grid3-hd-checker'
* displays a checkbox in the header and provides support for automatic check all/none behavior on header click.
* This string can be replaced by any valid HTML fragment, including a simple text string (e.g., 'Select Rows'), but
* the automatic check all/none behavior will only work if the 'x-grid3-hd-checker' class is supplied.
*/
header: '<div class="x-grid3-hd-checker"> </div>',
/**
* @cfg {Number} width checkbox列默认的宽度(默认为20)。
* The default width in pixels of the checkbox column (defaults to 20).
*/
width: 20,
/**
* @cfg {Boolean} sortable True 表示为checkbox列可以被排序(默认为fasle)。
* if the checkbox column is sortable (defaults to false).
*/
sortable: false,
// private
menuDisabled:true,
fixed:true,
dataIndex: '',
id: 'checker',
constructor: function(){
Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this, arguments);
if(this.checkOnly){
this.handleMouseDown = Ext.emptyFn;
}
},
// private
initEvents : function(){
Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this);
this.grid.on('render', function(){
var view = this.grid.getView();
view.mainBody.on('mousedown', this.onMouseDown, this);
Ext.fly(view.innerHd).on('mousedown', this.onHdMouseDown, this);
}, this);
},
// private
onMouseDown : function(e, t){
if(e.button === 0 && t.className == 'x-grid3-row-checker'){ // Only fire if left-click
e.stopEvent();
var row = e.getTarget('.x-grid3-row');
if(row){
var index = row.rowIndex;
if(this.isSelected(index)){
this.deselectRow(index);
}else{
this.selectRow(index, true);
}
}
}
},
// private
onHdMouseDown : function(e, t){
if(t.className == 'x-grid3-hd-checker'){
e.stopEvent();
var hd = Ext.fly(t.parentNode);
var isChecked = hd.hasClass('x-grid3-hd-checker-on');
if(isChecked){
hd.removeClass('x-grid3-hd-checker-on');
this.clearSelections();
}else{
hd.addClass('x-grid3-hd-checker-on');
this.selectAll();
}
}
},
// private
renderer : function(v, p, record){
return '<div class="x-grid3-row-checker"> </div>';
}
}); | 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.grid.GridPanel
* @extends Ext.Panel
* <p>此类系基于Grid控件的一个面板组件,呈现了Grid的主要交互接口。<br />
* This class represents the primary interface of a component based grid control to represent data
* in a tabular format of rows and columns. The GridPanel is composed of the following:</p>
* <div class="mdetail-params"><ul>
* <li><b>{@link Ext.data.Store Store}</b> :数据记录的模型(行为单位 ) The Model holding the data records (rows)
* <div class="sub-desc"></div></li>
* <li><b>{@link Ext.grid.ColumnModel Column model}</b> : 列怎么显示 Column makeup
* <div class="sub-desc"></div></li>
* <li><b>{@link Ext.grid.GridView View}</b> : 封装了用户界面 Encapsulates the user interface
* <div class="sub-desc"></div></li>
* <li><b>{@link Ext.grid.AbstractSelectionModel selection model}</b> : 选择行为的模型 Selection behavior
* <div class="sub-desc"></div></li>
* </ul></div>
* <br><br>用法 Usage:
* <pre><code>var grid = new Ext.grid.GridPanel({
store: new Ext.data.Store({
reader: reader,
data: xg.dummyData
}),
columns: [
{id:'company', header: "Company", width: 200, sortable: true, dataIndex: 'company'},
{header: "Price", width: 120, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
{header: "Change", width: 120, sortable: true, dataIndex: 'change'},
{header: "% Change", width: 120, sortable: true, dataIndex: 'pctChange'},
{header: "Last Updated", width: 135, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
],
viewConfig: {
forceFit: true,
// Return CSS class to apply to rows depending upon data values
getRowClass: function(record, index) {
var c = record.get('change');
if (c < 0) {
return 'price-fall';
} else if (c > 0) {
return 'price-rise';
}
}
},
sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
width:600,
height:300,
frame:true,
title:'Framed with Checkbox Selection and Horizontal Scrolling',
iconCls:'icon-grid'
});</code></pre>
* <b>注意 Notes:</b><ul>
* <li>
* 尽管本类是由Panel类继承而得到的,但是不支持其基类的某些功能,不能都做到好像一般Panel类那样的方法,如autoScroll、autoWidth、layout、items等……
* Although this class inherits many configuration options from base classes, some of them
* (such as autoScroll, autoWidth,layout, items, etc) are not used by this class, and will have no effect.</li>
*
* <li>
* Grid<b>需要</b>一个宽度来显示其所有的列,也需要一个高度来滚动列出所有的行。这些尺寸都通过配置项<tt>{@link Ext.BoxComponent#height height}</tt>
* 和<tt>{@link Ext.BoxComponent#width width}</tt>来精确地指定,
* 又或者将Grid放置进入一个带有{@link Ext.Container#layout 某种布局风格}的{@link Ext.Container 容器}中去,让上层容器来管理子容器的尺寸大小。
* 例如指定{@link Ext.Container#layout layout}为“fit”的布局就可以很好地自适应容器的拉伸了。
*
* A grid <b>requires</b> a width in which to scroll its columns, and a height in which to
* scroll its rows. These dimensions can either be set explicitly through the
* <tt>{@link Ext.BoxComponent#height height}</tt> and <tt>{@link Ext.BoxComponent#width width}</tt>
* configuration options or implicitly set by using the grid as a child item of a
* {@link Ext.Container Container} which will have a {@link Ext.Container#layout layout manager}
* provide the sizing of its child items (for example the Container of the Grid may specify
* <tt>{@link Ext.Container#layout layout}:'fit'</tt>).</li>
*
*
* <li>要访问GRID中的数据,就必须通过由{@link #store Store}封装的数据模型。参与{@link #cellclick}事件。
* To access the data in a Grid, it is necessary to use the data model encapsulated
* by the {@link #store Store}. See the {@link #cellclick} event.</li>
* </ul>
* @constructor
* @param {Object} config 配置项对象 The config object
*/
Ext.grid.GridPanel = Ext.extend(Ext.Panel, {
/**
* @cfg {Ext.data.Store} store Grid应使用{@link Ext.data.Store}作为其数据源(必须的)。
* The {@link Ext.data.Store} the grid should use as its data source (required).
*/
/**
* @cfg {Object} cm {@link #colModel}的简写方式。
* Shorthand for {@link #colModel}.
*/
/**
* @cfg {Object} colModel 渲染Grid所使用的{@link Ext.grid.ColumnModel}(必须的)。
* The {@link Ext.grid.ColumnModel} to use when rendering the grid (required).
*/
/**
* @cfg {Object} sm {@link #selModel}的简写方式。
* Shorthand for {@link #selModel}.
*/
/**
* @cfg {Object} selModel AbstractSelectionModel的子类,以为Grid提供选区模型(selection model)。
* (如不指定则默认为{@link Ext.grid.RowSelectionModel})。
* Any subclass of {@link Ext.grid.AbstractSelectionModel} that will provide
* the selection model for the grid (defaults to {@link Ext.grid.RowSelectionModel} if not specified).
*/
/**
* @cfg {Array} columns 自动创建列模型(ColumnModel)的数组。
* An array of columns to auto create a ColumnModel
*/
/**
* @cfg {Number} maxHeight 设置Grid的高度最大值(若autoHeight关闭则忽略)。
* Sets the maximum height of the grid - ignored if autoHeight is not on.
*/
/**
* @cfg {Boolean} disableSelection True表示为禁止grid的选区功能(默认为false)——若指定了SelectionModel则忽略。
* True to disable selections in the grid (defaults to false). - ignored if a SelectionModel is specified
*/
/**
* @cfg {Boolean} enableColumnMove False表示为在列拖动时禁止排序(默认为true)。
* False to turn off column reordering via drag drop (defaults to true).
*/
/**
* @cfg {Boolean} enableColumnResize False 表示为关闭列的大小调节功能(默认为true)。
* False to turn off column resizing for the whole grid (defaults to true).
*/
/**
* @cfg {Object} viewConfig 作用在grid's UI试图上的配置项对象,
* 任何{@link Ext.grid.GridView}可用的配置选项都可在这里指定。若{@link #view}已指定则此项无效。
* A config object that will be applied to the grid's UI view. Any of
* the config options available for {@link Ext.grid.GridView} can be specified here. This option
* is ignored if {@link #view} is xpecified.
*/
/**
* @cfg {Boolean} hideHeaders True表示为隐藏Grid的头部(默认为false)。
* True to hide the grid's header (defaults to false).
*/
/**
* 配置拖动代理中的文本(缺省为"{0} selected row(s)")。选中行的行数会替换到{0}。
* Configures the text in the drag proxy (defaults to "{0} selected row(s)").
* {0} is replaced with the number of selected rows.
* @type String
*/
ddText : "{0} selected row{1}",
/**
* @cfg {Number} minColumnWidth 列的宽度的调整下限。默认为25。
* The minimum width a column can be resized to. Defaults to 25.
*/
minColumnWidth : 25,
/**
* @cfg {Boolean} trackMouseOver True表示为鼠标移动时高亮显示(默认为true)。
* True to highlight rows when the mouse is over. Default is true.
*/
trackMouseOver : true,
/**
* @cfg {Boolean} enableDragDrop <p>True表示为激活GridPanel行的拖动。
* True to enable dragging of the selected rows of the GridPanel.</p>
* <p>
* 设置该项为<b><tt>true</tt></b>那样{GridPanel@link #getView GridView}的将会创建一个{@link Ext.grid.GridDragZone}实例。
* 通过GridView的{@link Ext.grid.GridView#dragZone dragZone}属性可访问该实例(只在Grid渲染后的条件后)。
* Setting this to <b><tt>true</tt></b> causes this GridPanel's {@link #getView GridView} to create an instance of
* {@link Ext.grid.GridDragZone}. This is available <b>(only after the Grid has been rendered)</b> as the
* GridView's {@link Ext.grid.GridView#dragZone dragZone} property.
* </p>
* <p>
* 要让{@link Ext.dd.DropZone DropZone}运作起来必须一定要有{@link Ext.dd.DropZone#onNodeEnter onNodeEnter}、{@link Ext.dd.DropZone#onNodeOver onNodeOver},
* {@link Ext.dd.DropZone#onNodeOut onNodeOut}以及{@link Ext.dd.DropZone#onNodeDrop onNodeDrop}这些实现的定义,好让能够处理{@link Ext.grid.GridDragZone#getDragData data}。
* A cooperating {@link Ext.dd.DropZone DropZone} must be created who's implementations of
* {@link Ext.dd.DropZone#onNodeEnter onNodeEnter}, {@link Ext.dd.DropZone#onNodeOver onNodeOver},
* {@link Ext.dd.DropZone#onNodeOut onNodeOut} and {@link Ext.dd.DropZone#onNodeDrop onNodeDrop} are able
* to process the {@link Ext.grid.GridDragZone#getDragData data} which is provided. </p>
*/
enableDragDrop : false,
/**
* @cfg {Boolean} enableColumnMove True表示为激活列的拖动(默认为true)。
* True to enable drag and drop reorder of columns.
*/
enableColumnMove : true,
/**
* @cfg {Boolean} enableColumnHide True表示为隐藏每列头部的邮件菜单(默认为true)。
* True to enable hiding of columns with the header context menu.
*/
enableColumnHide : true,
/**
* @cfg {Boolean} enableHdMenu True表示为在头部出现下拉按钮,以激活头部菜单。
* True to enable the drop down button for menu in the headers.
*/
enableHdMenu : true,
/**
* @cfg {Boolean} stripeRows True表示为显示行的分隔符(默认为true)。
* True to stripe the rows. Default is false.
* <p>为Grid的隔行之处都会加上<tt><b>x-grid3-row-alt</b></tt>样式。
* 原理是利用加入背景色的CSS规则来实现,但你可以用有修饰符"!important"的<b>background-color</b>样式覆盖这个规则,或使用较高优先级的CSS选择符。
* This causes the CSS class <tt><b>x-grid3-row-alt</b></tt> to be added to alternate rows of
* the grid. A default CSS rule is provided which sets a background colour, but you can override this
* with a rule which either overrides the <b>background-color</b> style using the "!important"
* modifier, or which uses a CSS selector of higher specificity.
* </p>
*/
stripeRows : false,
/**
* @cfg {String} autoExpandColumn 指定某个列之id,grid就会在这一列自动扩展宽度,以填满空白的位置,该id不能为0。
* The id of a column in this grid that should expand to fill unused space. This id can not be 0.
*/
autoExpandColumn : false,
/**
* @cfg {Number} autoExpandMin autoExpandColumn可允许最小之宽度(有激活的话)。默认为50。
* The minimum width the autoExpandColumn can have (if enabled).
* defaults to 50.
*/
autoExpandMin : 50,
/**
* @cfg {Number} autoExpandMax autoExpandColumn可允许最大之宽度(有激活的话)。默认为 1000。
* The maximum width the autoExpandColumn can have (if enabled). Defaults to 1000.
*/
autoExpandMax : 1000,
/**
* @cfg {Object} view Grid所使用的{@link Ext.grid.GridView}。该项可在render()调用之前设置。
* The {@link Ext.grid.GridView} used by the grid. This can be set before a call to render().
*/
view : null,
/**
* @cfg {Object} loadMask True表示为当grid加载过程中,会有一个{@link Ext.LoadMask}的遮罩效果。默认为false。
* An {@link Ext.LoadMask} config or true to mask the grid while loading (defaults to false).
*/
loadMask : false,
/**
* @cfg {Boolean} columnLines True表示为在列分隔处显示分隔符。默认为false。
* True to add css for column separation lines. Default is false.
*/
columnLines : false,
/**
* @cfg {Boolean} deferRowRender True表示为延时激活行渲染。默认为true。
* True to enable deferred row rendering. Default is true.
*/
deferRowRender : true,
// private
rendered : false,
// private
viewReady: false,
/**
* @cfg {Array} stateEvents
* 事件名称组成的数组。这些事件触发时会导致该组件进行状态记忆(默认为["columnmove", "columnresize", "sortchange"])。
* 可支持该组件身上的任意事件类型,包括浏览器原生的或自定义的,如['click', 'customerchange']。
* An array of events that, when fired, should trigger this component to save its state (defaults to ["columnmove", "columnresize", "sortchange"]).
* These can be any types of events supported by this component, including browser or custom events (e.g.,['click', 'customerchange']).
* <p>请参阅{@link #stateful}有关Component状态的恢复与保存方面的解释。See {@link #stateful} for an explanation of saving and restoring Component state.</p>
*/
stateEvents: ["columnmove", "columnresize", "sortchange"],
// private
initComponent : function(){
Ext.grid.GridPanel.superclass.initComponent.call(this);
if(this.columnLines){
this.cls = (this.cls || '') + ' x-grid-with-col-lines';
}
// override any provided value since it isn't valid
// and is causing too many bug reports ;)
this.autoScroll = false;
this.autoWidth = false;
if(Ext.isArray(this.columns)){
this.colModel = new Ext.grid.ColumnModel(this.columns);
delete this.columns;
}
// check and correct shorthanded configs
if(this.ds){
this.store = this.ds;
delete this.ds;
}
if(this.cm){
this.colModel = this.cm;
delete this.cm;
}
if(this.sm){
this.selModel = this.sm;
delete this.sm;
}
this.store = Ext.StoreMgr.lookup(this.store);
this.addEvents(
// raw events
/**
* @event click
* 整个Grid被单击的原始事件。
* The raw click event for the entire grid.
* @param {Ext.EventObject} e
*/
"click",
/**
* @event dblclick
* 整个Grid被双击的原始事件。
* The raw dblclick event for the entire grid.
* @param {Ext.EventObject} e
*/
"dblclick",
/**
* @event contextmenu
* 整个Grid被右击的原始事件。
* The raw contextmenu event for the entire grid.
* @param {Ext.EventObject} e
*/
"contextmenu",
/**
* @event mousedown
* 整个Grid的mousedown的原始事件。
* The raw mousedown event for the entire grid.
* @param {Ext.EventObject} e
*/
"mousedown",
/**
* @event mouseup
* 整个Grid的mouseup的原始事件。
* The raw mouseup event for the entire grid.
* @param {Ext.EventObject} e
*/
"mouseup",
/**
* @event mouseover
* 整个Grid的mouseover的原始事件。
* The raw mouseover event for the entire grid.
* @param {Ext.EventObject} e
*/
"mouseover",
/**
* @event mouseout
* 整个Grid的mouseout的原始事件。
* The raw mouseout event for the entire grid.
* @param {Ext.EventObject} e
*/
"mouseout",
/**
* @event keypress
* 整个Grid的keypress的原始事件。
* The raw keypress event for the entire grid.
* @param {Ext.EventObject} e
*/
"keypress",
/**
* @event keydown
* 整个Grid的keydown的原始事件。
* The raw keydown event for the entire grid.
* @param {Ext.EventObject} e
*/
"keydown",
// custom events
/**
* @event cellmousedown
* 当单元格被单击之前触发。
* Fires before a cell is clicked
* @param {Grid} this
* @param {Number} rowIndex
* @param {Number} columnIndex
* @param {Ext.EventObject} e
*/
"cellmousedown",
/**
* @event rowmousedown
* 当行被单击之前触发。
* Fires before a row is clicked
* @param {Grid} this
* @param {Number} rowIndex
* @param {Ext.EventObject} e
*/
"rowmousedown",
/**
* @event headermousedown
* 当头部被单击之前触发。
* Fires before a header is clicked
* @param {Grid} this
* @param {Number} columnIndex
* @param {Ext.EventObject} e
*/
"headermousedown",
/**
* @event cellclick
* 当单元格被点击时触发。
* 单击格的数据保存在{@link Ext.data.Record Record}。要在侦听器函数内访问数据,可按照以下的办法:
* Fires when a cell is clicked.
* The data for the cell is drawn from the {@link Ext.data.Record Record}
* for this row. To access the data in the listener function use the
* following technique:
* <pre><code>
function(grid, rowIndex, columnIndex, e) {
var record = grid.getStore().getAt(rowIndex); // 返回Record对象 Get the Record
var fieldName = grid.getColumnModel().getDataIndex(columnIndex); // 返回字段名称 Get field name
var data = record.get(fieldName);
}
</code></pre>
* @param {Grid} this
* @param {Number} rowIndex 行索引。rowIndex
* @param {Number} columnIndex 列索引。columnIndex
* @param {Ext.EventObject} e
*/
"cellclick",
/**
* @event celldblclick
* 单元格(cell)被双击时触发。
* Fires when a cell is double clicked
* @param {Grid} this
* @param {Number} rowIndex 行索引。rowIndex
* @param {Number} columnIndex 列索引。columnIndex
* @param {Ext.EventObject} e
*/
"celldblclick",
/**
* @event rowclick
* 行(row)被单击时触发。
* Fires when a row is clicked
* @param {Grid} this
* @param {Number} rowIndex 行索引。rowIndex
* @param {Ext.EventObject} e
*/
"rowclick",
/**
* @event rowdblclick
* 行(row)被双击时触发。
* Fires when a row is double clicked
* @param {Grid} this
* @param {Number} rowIndex 行索引。rowIndex
* @param {Ext.EventObject} e
*/
"rowdblclick",
/**
* @event headerclick
* 头部(header)被单击时触发。
* Fires when a header is clicked
* @param {Grid} this
* @param {Number} columnIndex 列索引。columnIndex
* @param {Ext.EventObject} e
*/
"headerclick",
/**
* @event headerdblclick
* 头部(header)被双击时触发。
* Fires when a header cell is double clicked
* @param {Grid} this
* @param {Number} columnIndex 列索引。columnIndex
* @param {Ext.EventObject} e
*/
"headerdblclick",
/**
* @event rowcontextmenu
* 行(row)被右击时触发。
* Fires when a row is right clicked
* @param {Grid} this
* @param {Number} rowIndex 行索引。rowIndex
* @param {Ext.EventObject} e
*/
"rowcontextmenu",
/**
* @event cellcontextmenu
* 单元格(cell)被右击时触发。
* Fires when a cell is right clicked
* @param {Grid} this
* @param {Number} rowIndex 行索引。rowIndex
* @param {Number} cellIndex 单元格索引。cellIndex
* @param {Ext.EventObject} e
*/
"cellcontextmenu",
/**
* @event headercontextmenu
* 头部(header)被右击时触发。
* Fires when a header is right clicked
* @param {Grid} this
* @param {Number} columnIndex
* @param {Ext.EventObject} e
*/
"headercontextmenu",
/**
* @event bodyscroll
* 当body元素被滚动后触发。
* Fires when the body element is scrolled
* @param {Number} scrollLeft
* @param {Number} scrollTop
*/
"bodyscroll",
/**
* @event columnresize
* 当用户调整某个列(column)大小时触发。
* Fires when the user resizes a column
* @param {Number} columnIndex
* @param {Number} newSize
*/
"columnresize",
/**
* @event columnmove
* 当用户移动某个列(column)时触发。
* Fires when the user moves a column
* @param {Number} oldIndex
* @param {Number} newIndex
*/
"columnmove",
/**
* @event sortchange
* 当行(row)开始被拖动时触发。
* Fires when the grid's store sort changes
* @param {Grid} this
* @param {Object} sortInfo 包含键字段和方向的对象。An object with the keys field and direction
*/
"sortchange"
);
},
// private
onRender : function(ct, position){
Ext.grid.GridPanel.superclass.onRender.apply(this, arguments);
var c = this.body;
this.el.addClass('x-grid-panel');
var view = this.getView();
view.init(this);
this.mon(c, {
mousedown: this.onMouseDown,
click: this.onClick,
dblclick: this.onDblClick,
contextmenu: this.onContextMenu,
keydown: this.onKeyDown,
scope: this
})
this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
this.getSelectionModel().init(this);
this.view.render();
},
// private
initEvents : function(){
Ext.grid.GridPanel.superclass.initEvents.call(this);
if(this.loadMask){
this.loadMask = new Ext.LoadMask(this.bwrap,
Ext.apply({store:this.store}, this.loadMask));
}
},
initStateEvents : function(){
Ext.grid.GridPanel.superclass.initStateEvents.call(this);
this.mon(this.colModel, 'hiddenchange', this.saveState, this, {delay: 100});
},
applyState : function(state){
var cm = this.colModel;
var cs = state.columns;
if(cs){
for(var i = 0, len = cs.length; i < len; i++){
var s = cs[i];
var c = cm.getColumnById(s.id);
if(c){
c.hidden = s.hidden;
c.width = s.width;
var oldIndex = cm.getIndexById(s.id);
if(oldIndex != i){
cm.moveColumn(oldIndex, i);
}
}
}
}
if(state.sort && this.store){
this.store[this.store.remoteSort ? 'setDefaultSort' : 'sort'](state.sort.field, state.sort.direction);
}
},
getState : function(){
var o = {columns: []};
for(var i = 0, c; c = this.colModel.config[i]; i++){
o.columns[i] = {
id: c.id,
width: c.width
};
if(c.hidden){
o.columns[i].hidden = true;
}
}
if(this.store){
var ss = this.store.getSortState();
if(ss){
o.sort = ss;
}
}
return o;
},
// private
afterRender : function(){
Ext.grid.GridPanel.superclass.afterRender.call(this);
this.view.layout();
if(this.deferRowRender){
this.view.afterRender.defer(10, this.view);
}else{
this.view.afterRender();
}
this.viewReady = true;
},
/**
* <p>重新配置Grid的Store和Column Model(列模型)。视图会重新绑定对象并刷新。
* Reconfigures the grid to use a different Store and Column Model.
* The View will be bound to the new objects and refreshed.</p>
* <p>
* 要注意当重新配置这个GridPanel之后,某些现有的设置<i>可能会</i>变为无效。
* 比如配置项{@link #autoExpandColumn}的设置在新的ColumnModel作用后就不复存在;
* 再譬如,{@link Ext.PagingToolbar PagingToolbar}还是旧Store的,需要重新绑定之;
* 某些{@link #plugins}需要在新数据的配合下再配置配置。
* Be aware that upon reconfiguring a GridPanel, certain existing settings <i>may</i> become
* invalidated. For example the configured {@link #autoExpandColumn} may no longer exist in the
* new ColumnModel. Also, an existing {@link Ext.PagingToolbar PagingToolbar} will still be bound
* to the old Store, and will need rebinding. Any {@link #plugins} might also need reconfiguring
* with the new data.</p>
* @param {Ext.data.Store} store 另外一个{@link Ext.data.Store}对象。The new {@link Ext.data.Store} object
* @param {Ext.grid.ColumnModel} colModel 另外一个{@link Ext.grid.ColumnModel}对象。The new {@link Ext.grid.ColumnModel} object
*/
reconfigure : function(store, colModel){
if(this.loadMask){
this.loadMask.destroy();
this.loadMask = new Ext.LoadMask(this.bwrap,
Ext.apply({store:store}, this.initialConfig.loadMask));
}
this.view.bind(store, colModel);
this.store = store;
this.colModel = colModel;
if(this.rendered){
this.view.refresh(true);
}
},
// private
onKeyDown : function(e){
this.fireEvent("keydown", e);
},
// private
onDestroy : function(){
if(this.rendered){
if(this.loadMask){
this.loadMask.destroy();
}
var c = this.body;
c.removeAllListeners();
this.view.destroy();
c.update("");
}
this.colModel.purgeListeners();
Ext.grid.GridPanel.superclass.onDestroy.call(this);
},
// private
processEvent : function(name, e){
this.fireEvent(name, e);
var t = e.getTarget();
var v = this.view;
var header = v.findHeaderIndex(t);
if(header !== false){
this.fireEvent("header" + name, this, header, e);
}else{
var row = v.findRowIndex(t);
var cell = v.findCellIndex(t);
if(row !== false){
this.fireEvent("row" + name, this, row, e);
if(cell !== false){
this.fireEvent("cell" + name, this, row, cell, e);
}
}
}
},
// private
onClick : function(e){
this.processEvent("click", e);
},
// private
onMouseDown : function(e){
this.processEvent("mousedown", e);
},
// private
onContextMenu : function(e, t){
this.processEvent("contextmenu", e);
},
// private
onDblClick : function(e){
this.processEvent("dblclick", e);
},
// private
walkCells : function(row, col, step, fn, scope){
var cm = this.colModel, clen = cm.getColumnCount();
var ds = this.store, rlen = ds.getCount(), first = true;
if(step < 0){
if(col < 0){
row--;
first = false;
}
while(row >= 0){
if(!first){
col = clen-1;
}
first = false;
while(col >= 0){
if(fn.call(scope || this, row, col, cm) === true){
return [row, col];
}
col--;
}
row--;
}
} else {
if(col >= clen){
row++;
first = false;
}
while(row < rlen){
if(!first){
col = 0;
}
first = false;
while(col < clen){
if(fn.call(scope || this, row, col, cm) === true){
return [row, col];
}
col++;
}
row++;
}
}
return null;
},
// private
getSelections : function(){
return this.selModel.getSelections();
},
// private
onResize : function(){
Ext.grid.GridPanel.superclass.onResize.apply(this, arguments);
if(this.viewReady){
this.view.layout();
}
},
/**
* 返回Grid的元素。
* Returns the grid's underlying element.
* @return {Element} 元素。The element
*/
getGridEl : function(){
return this.body;
},
// private for compatibility, overridden by editor grid
stopEditing : Ext.emptyFn,
/**
* 返回grid的SelectionModel。
* Returns the grid's SelectionModel.
* @return 其实就是配置项的(@link #selModel}选区模型。它是{Ext.grid.AbstractSelectionModel}的子类,提供了单元格或行的选区。
* The selection model configured by the (@link #selModel} configuration option. This will be a subclass of {Ext.grid.AbstractSelectionModel}
* which provides either cell or row selectability.
*/
getSelectionModel : function(){
if(!this.selModel){
this.selModel = new Ext.grid.RowSelectionModel(
this.disableSelection ? {selectRow: Ext.emptyFn} : null);
}
return this.selModel;
},
/**
* 返回Grid的Data store。
* Returns the grid's data store.
* @return Store对象。The store
*/
getStore : function(){
return this.store;
},
/**
* 返回Grid的列模型(ColumnModel)。
* Returns the grid's ColumnModel.
* @return {Ext.grid.ColumnModel} 列模型。The column model
*/
getColumnModel : function(){
return this.colModel;
},
/**
* 返回Grid的GridView对象。
* Returns the grid's GridView object.
* @return {Ext.grid.GridView} GridView对象。The grid view
*/
getView : function(){
if(!this.view){
this.view = new Ext.grid.GridView(this.viewConfig);
}
return this.view;
},
/**
* 获取GRID拖动的代理文本(drag proxy text),默认返回this.ddText。
* Called to get grid's drag proxy text, by default returns this.ddText.
* @return {String} GRID拖动的代理文本。The text
*/
getDragDropText : function(){
var count = this.selModel.getCount();
return String.format(this.ddText, count, count == 1 ? '' : 's');
}
/**
* @cfg {String/Number} activeItem
* @hide
*/
/**
* @cfg {Boolean} autoDestroy
* @hide
*/
/**
* @cfg {Object/String/Function} autoLoad
* @hide
*/
/**
* @cfg {Boolean} autoWidth
* @hide
*/
/**
* @cfg {Boolean/Number} bufferResize
* @hide
*/
/**
* @cfg {String} defaultType
* @hide
*/
/**
* @cfg {Object} defaults
* @hide
*/
/**
* @cfg {Boolean} hideBorders
* @hide
*/
/**
* @cfg {Mixed} items
* @hide
*/
/**
* @cfg {String} layout
* @hide
*/
/**
* @cfg {Object} layoutConfig
* @hide
*/
/**
* @cfg {Boolean} monitorResize
* @hide
*/
/**
* @property items
* @hide
*/
/**
* @method add
* @hide
*/
/**
* @method cascade
* @hide
*/
/**
* @method doLayout
* @hide
*/
/**
* @method find
* @hide
*/
/**
* @method findBy
* @hide
*/
/**
* @method findById
* @hide
*/
/**
* @method findByType
* @hide
*/
/**
* @method getComponent
* @hide
*/
/**
* @method getLayout
* @hide
*/
/**
* @method getUpdater
* @hide
*/
/**
* @method insert
* @hide
*/
/**
* @method load
* @hide
*/
/**
* @method remove
* @hide
*/
/**
* @event add
* @hide
*/
/**
* @event afterLayout
* @hide
*/
/**
* @event beforeadd
* @hide
*/
/**
* @event beforeremove
* @hide
*/
/**
* @event remove
* @hide
*/
/**
* @cfg {String} allowDomMove @hide
*/
/**
* @cfg {String} autoEl @hide
*/
/**
* @cfg {String} applyTo @hide
*/
/**
* @cfg {String} autoScroll @hide
*/
/**
* @cfg {String} bodyBorder @hide
*/
/**
* @cfg {String} bodyStyle @hide
*/
/**
* @cfg {String} contentEl @hide
*/
/**
* @cfg {String} disabledClass @hide
*/
/**
* @cfg {String} elements @hide
*/
/**
* @cfg {String} html @hide
*/
/**
* @property disabled
* @hide
*/
/**
* @method applyToMarkup
* @hide
*/
/**
* @method enable
* @hide
*/
/**
* @method disable
* @hide
*/
/**
* @method setDisabled
* @hide
*/
});
Ext.reg('grid', Ext.grid.GridPanel); | 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.grid.AbstractSelectionModel
* @extends Ext.util.Observable
* Grid选区模型(SelectionModels)基本抽象类。本类提供了子类要实现的接口。该类不能被直接实例化。<br />
* Abstract base class for grid SelectionModels.
* It provides the interface that should be implemented by descendant classes.
* This class should not be directly instantiated.
* @constructor
*/
Ext.grid.AbstractSelectionModel = function(){
this.locked = false;
Ext.grid.AbstractSelectionModel.superclass.constructor.call(this);
};
Ext.extend(Ext.grid.AbstractSelectionModel, Ext.util.Observable, {
/** @ignore grid自动调用。勿直接调用 Called by the grid automatically. Do not call directly.*/
init : function(grid){
this.grid = grid;
this.initEvents();
},
/**
* 锁定多个选区。
* Locks the selections.
*/
lock : function(){
this.locked = true;
},
/**
* 解锁多个选区。
* Unlocks the selections.
*/
unlock : function(){
this.locked = false;
},
/**
* 返回true如果选区被锁。
* Returns true if the selections are locked.
* @return {Boolean}
*/
isLocked : function(){
return this.locked;
}
}); | 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.grid.RowNumberer
* 一个辅助类,用于传入到{@link Ext.grid.ColumnModel},作为自动列数字的生成。<br />
* This is a utility class that can be passed into a {@link Ext.grid.ColumnModel} as a column config that provides an automatic row numbering column.
* <br>用法 Usage:<br>
<pre><code>
// 这是一个典型的例子,第一行生成数字序号
// This is a typical column config with the first column providing row numbers
var colModel = new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
{header: "Name", width: 80, sortable: true},
{header: "Code", width: 50, sortable: true},
{header: "Description", width: 200, sortable: true}
]);
</code></pre>
* @constructor
* @param {Object} config 配置项选项 The configuration options
*/
Ext.grid.RowNumberer = function(config){
Ext.apply(this, config);
if(this.rowspan){
this.renderer = this.renderer.createDelegate(this);
}
};
Ext.grid.RowNumberer.prototype = {
/**
* @cfg {String} header 任何有效的HMTL片断,显示在单元格头部(缺省为'')。
* Any valid text or HTML fragment to display in the header cell for the row number column (defaults to '').
*/
header: "",
/**
* @cfg {Number} width 列的默认宽度(默认为23)。
* The default width in pixels of the row number column (defaults to 23).
*/
width: 23,
/**
* @cfg {Boolean} sortable True表示为数字列可以被排序(默认为fasle)。
* True if the row number column is sortable (defaults to false).
* @hide
*/
sortable: false,
// private
fixed:true,
menuDisabled:true,
dataIndex: '',
id: 'numberer',
rowspan: undefined,
// private
renderer : function(v, p, record, rowIndex){
if(this.rowspan){
p.cellAttr = 'rowspan="'+this.rowspan+'"';
}
return rowIndex+1;
}
}; | JavaScript |
/*
* 项目地址: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.grid.PropertyRecord
* {@link Ext.grid.PropertyGrid}的一种特定类型,用于表示一对“名称/值”的数据。数据的格式必须是{@link Ext.data.Record}类型。
* 典型状态下,属性记录(PropertyRecords)由于能够隐式生成而不需要直接创建,
* 只需要配置适当的数据配置,即通过 {@link Ext.grid.PropertyGrid#source}的配置属性或是调用{@link Ext.grid.PropertyGrid#setSource}的方法。
* 然而在如需要的情况下,这些记录也可以显式创建起来,例子如下:<br />
* A specific {@link Ext.data.Record} type that represents a name/value pair and is made to work with the
* {@link Ext.grid.PropertyGrid}. Typically, PropertyRecords do not need to be created directly as they can be
* created implicitly by simply using the appropriate data configs either via the {@link Ext.grid.PropertyGrid#source}
* config property or by calling {@link Ext.grid.PropertyGrid#setSource}. However, if the need arises, these records
* can also be created explicitly as shwon below. Example usage:
* <pre><code>
var rec = new Ext.grid.PropertyRecord({
name: 'Birthday',
value: new Date(Date.parse('05/26/1972'))
});
// 对当前的grid加入记录 Add record to an already populated grid
grid.store.addSorted(rec);
</code></pre>
* @constructor
* @param {Object} config 数据对象,格式如下:{name: [name], value: [value]}。
* Grid会自动读取指定值的格式以决定用哪种方式来显示。
* A data object in the format: {name: [name], value: [value]}. The specified value's type
* will be read automatically by the grid to determine the type of editor to use when displaying it.
*/
Ext.grid.PropertyRecord = Ext.data.Record.create([
{name:'name',type:'string'}, 'value'
]);
/**
* @class Ext.grid.PropertyStore
* @extends Ext.util.Observable
* 一个属于{@link Ext.grid.PropertyGrid}的{@link Ext.data.Store}的制定包裹器(custom wrapper)。
* 该类负责属于grid的自定义数据对象与这个类 {@link Ext.grid.PropertyRecord}本身格式所需store之间的映射,使得两者可兼容一起。
* 一般情况下不需要直接使用该类——应该通过属性{@link #store}从所属的store访问Grid的数据。
* A custom wrapper for the {@link Ext.grid.PropertyGrid}'s {@link Ext.data.Store}. This class handles the mapping
* between the custom data source objects supported by the grid and the {@link Ext.grid.PropertyRecord} format
* required for compatibility with the underlying store. Generally this class should not need to be used directly --
* the grid's data should be accessed from the underlying store via the {@link #store} property.
* @constructor
* @param {Ext.grid.Grid} grid stroe所绑定的grid。The grid this store will be bound to
* @param {Object} source 配置项对象数据源。The source data config object
*/
Ext.grid.PropertyStore = function(grid, source){
this.grid = grid;
this.store = new Ext.data.Store({
recordType : Ext.grid.PropertyRecord
});
this.store.on('update', this.onUpdate, this);
if(source){
this.setSource(source);
}
Ext.grid.PropertyStore.superclass.constructor.call(this);
};
Ext.extend(Ext.grid.PropertyStore, Ext.util.Observable, {
// protected - should only be called by the grid. Use grid.setSource instead.
setSource : function(o){
this.source = o;
this.store.removeAll();
var data = [];
for(var k in o){
if(this.isEditableValue(o[k])){
data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k));
}
}
this.store.loadRecords({records: data}, {}, true);
},
// private
onUpdate : function(ds, record, type){
if(type == Ext.data.Record.EDIT){
var v = record.data['value'];
var oldValue = record.modified['value'];
if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){
this.source[record.id] = v;
record.commit();
this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue);
}else{
record.reject();
}
}
},
// private
getProperty : function(row){
return this.store.getAt(row);
},
// private
isEditableValue: function(val){
if(Ext.isDate(val)){
return true;
}else if(typeof val == 'object' || typeof val == 'function'){
return false;
}
return true;
},
// private
setValue : function(prop, value){
this.source[prop] = value;
this.store.getById(prop).set('value', value);
},
// protected - should only be called by the grid. Use grid.getSource instead.
getSource : function(){
return this.source;
}
});
/**
* @class Ext.grid.PropertyColumnModel
* @extends Ext.grid.ColumnModel
* 为{@link Ext.grid.PropertyGrid}制定的列模型。一般情况下不需要直接使用该类。
* A custom column model for the {@link Ext.grid.PropertyGrid}.Generally it should not need to be used directly.
* @constructor
* @param {Ext.grid.Grid} grid stroe所绑定的grid。The grid this store will be bound to
* @param {Object} source 配置项对象数据源。The source data config object
*/
Ext.grid.PropertyColumnModel = function(grid, store){
this.grid = grid;
var g = Ext.grid;
g.PropertyColumnModel.superclass.constructor.call(this, [
{header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name', menuDisabled:true},
{header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value', menuDisabled:true}
]);
this.store = store;
this.bselect = Ext.DomHelper.append(document.body, {
tag: 'select', cls: 'x-grid-editor x-hide-display', children: [
{tag: 'option', value: 'true', html: 'true'},
{tag: 'option', value: 'false', html: 'false'}
]
});
var f = Ext.form;
var bfield = new f.Field({
el:this.bselect,
bselect : this.bselect,
autoShow: true,
getValue : function(){
return this.bselect.value == 'true';
}
});
this.editors = {
'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})),
'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})),
'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})),
'boolean' : new g.GridEditor(bfield)
};
this.renderCellDelegate = this.renderCell.createDelegate(this);
this.renderPropDelegate = this.renderProp.createDelegate(this);
};
Ext.extend(Ext.grid.PropertyColumnModel, Ext.grid.ColumnModel, {
// private - strings used for locale support
nameText : 'Name',
valueText : 'Value',
dateFormat : 'm/j/Y',
// private
renderDate : function(dateVal){
return dateVal.dateFormat(this.dateFormat);
},
// private
renderBool : function(bVal){
return bVal ? 'true' : 'false';
},
// private
isCellEditable : function(colIndex, rowIndex){
return colIndex == 1;
},
// private
getRenderer : function(col){
return col == 1 ?
this.renderCellDelegate : this.renderPropDelegate;
},
// private
renderProp : function(v){
return this.getPropertyName(v);
},
// private
renderCell : function(val){
var rv = val;
if(Ext.isDate(val)){
rv = this.renderDate(val);
}else if(typeof val == 'boolean'){
rv = this.renderBool(val);
}
return Ext.util.Format.htmlEncode(rv);
},
// private
getPropertyName : function(name){
var pn = this.grid.propertyNames;
return pn && pn[name] ? pn[name] : name;
},
// private
getCellEditor : function(colIndex, rowIndex){
var p = this.store.getProperty(rowIndex);
var n = p.data['name'], val = p.data['value'];
if(this.grid.customEditors[n]){
return this.grid.customEditors[n];
}
if(Ext.isDate(val)){
return this.editors['date'];
}else if(typeof val == 'number'){
return this.editors['number'];
}else if(typeof val == 'boolean'){
return this.editors['boolean'];
}else{
return this.editors['string'];
}
}
});
/**
* @class Ext.grid.PropertyGrid
* @extends Ext.grid.EditorGridPanel
* Grid的一种特殊形式的实现,大体情形类似于IDE开发环境中的属性grid。
* Grid中的每一行表示一些对象当中的属性、数据,以“名称/值”的形式保存在{@link Ext.grid.PropertyRecord}中。举例如下:
* A specialized grid implementation intended to mimic the traditional property grid as typically seen in
* development IDEs. Each row in the grid represents a property of some object, and the data is stored
* as a set of name/value pairs in {@link Ext.grid.PropertyRecord}s. Example usage:
* <pre><code>
var grid = new Ext.grid.PropertyGrid({
title: 'Properties Grid',
autoHeight: true,
width: 300,
renderTo: 'grid-ct',
source: {
"(name)": "My Object",
"Created": new Date(Date.parse('10/15/2006')),
"Available": false,
"Version": .01,
"Description": "A test object"
}
});
</pre></code>
* @constructor
* @param {Object} config Grid配置参数。The grid config object
*/
Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, {
/**
* @cfg {Object} propertyNames
* 包含“名称(键值)/显示名称”的结对对象。
* 如指定,将用“显示名称”以代替直接显示属性名称(即键值名称)。
* An object containing property name/display name pairs.
* If specified, the display name will be shown in the name column instead of the property name.
*/
/**
* @cfg {Object} source 数据对象,作为grid的数据源(参阅{@link #setSource})。
* A data object to use as the data source of the grid (see {@link #setSource} for details).
*/
/**
* @cfg {Object} customEditors 为了使grid能够支持一些可编辑字段,把这些编辑字段的类型的定义写在这个对象中,它以“名称/值”的形式出现。
* 缺省下,Grid内置的表单编辑器支持强类型的编辑,如字符串、日期、数字和布尔型,但亦可以将任意的input控件关联到特定的编辑器。
* 编辑器的名字应该与属性的名字相一致,例如:
* An object containing name/value pairs of custom editor type definitions that allow
* the grid to support additional types of editable fields. By default, the grid supports strongly-typed editing
* of strings, dates, numbers and booleans using built-in form editors, but any custom type can be supported and
* associated with a custom input control by specifying a custom editor. The name of the editor
* type should correspond with the name of the property that will use the editor. Example usage:
* <pre><code>
var grid = new Ext.grid.PropertyGrid({
...
customEditors: {
'Start Time': new Ext.grid.GridEditor(new Ext.form.TimeField({selectOnFocus:true}))
},
source: {
'Start Time': '10:00 AM'
}
});
</code></pre>
*/
// private config overrides
enableColumnMove:false,
stripeRows:false,
trackMouseOver: false,
clicksToEdit:1,
enableHdMenu : false,
viewConfig : {
forceFit:true
},
// private
initComponent : function(){
this.customEditors = this.customEditors || {};
this.lastEditRow = null;
var store = new Ext.grid.PropertyStore(this);
this.propStore = store;
var cm = new Ext.grid.PropertyColumnModel(this, store);
store.store.sort('name', 'ASC');
this.addEvents(
/**
* @event beforepropertychange
* 当属性值改变时触发。如要取消事件可在这个句柄中返回一个false值(同时会内置调用{@link Ext.data.Record#reject}方法在这个属性的记录上)。
* Fires before a property value changes. Handlers can return false to cancel the property change
* (this will internally call {@link Ext.data.Record#reject} on the property's record).
* @param {Object} source grid的数据源对象(与传入到配置属性的{@link #source}对象相一致)。
* The source data object for the grid (corresponds to the same object passed in
* as the {@link #source} config property).
* @param {String} recordId Data store里面的记录id。The record's id in the data store
* @param {Mixed} value 当前被编辑的属性值。The current edited property value
* @param {Mixed} oldValue 属性原始值。The original property value prior to editing
*/
'beforepropertychange',
/**
* @event propertychange
* 当属性改变之后触发的事件。
* Fires after a property value has changed.
* @param {Object} source grid的数据源对象(与传入到配置属性的{@link #source}对象相一致)。The source data object for the grid (corresponds to the same object passed in
* as the {@link #source} config property).
* @param {String} recordId Data store里面的记录id。 The record's id in the data store
* @param {Mixed} value 当前被编辑的属性值。The current edited property value
* @param {Mixed} oldValue 属性原始值。The original property value prior to editing
*/
'propertychange'
);
this.cm = cm;
this.ds = store.store;
Ext.grid.PropertyGrid.superclass.initComponent.call(this);
this.mon(this.selModel, 'beforecellselect', function(sm, rowIndex, colIndex){
if(colIndex === 0){
this.startEditing.defer(200, this, [rowIndex, 1]);
return false;
}
}, this);
},
// private
onRender : function(){
Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments);
this.getGridEl().addClass('x-props-grid');
},
// private
afterRender: function(){
Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments);
if(this.source){
this.setSource(this.source);
}
},
/**
* 设置包含属性的源数据对象。数据对象包含了一个或一个以上的“名称/值”格式的对象以显示在grid。
* 这些数据也会自动加载到grid的{@link #store}。
* 如果grid已经包含数据,该方法会替换原有Grid的数据。请参阅{@link #source}的配置值。举例:
* Sets the source data object containing the property data. The data object can contain one or more name/value
* pairs representing all of the properties of an object to display in the grid, and this data will automatically
* be loaded into the grid's {@link #store}. The values should be supplied in the proper data type if needed,
* otherwise string type will be assumed. If the grid already contains data, this method will replace any
* existing data. See also the {@link #source} config value. Example usage:
* <pre><code>
grid.setSource({
"(name)": "My Object",
"Created": new Date(Date.parse('10/15/2006')), // 日期类型 date type
"Available": false, // 布尔类型 boolean type
"Version": .01, // 小数类型 decimal type
"Description": "一个测试对象 A test object"
});
</code></pre>
* @param {Object} source 数据对象。The data object
*/
setSource : function(source){
this.propStore.setSource(source);
},
/**
* 返回包含属性的数据对象源。请参阅{@link #setSource}以了解数据对象的格式。
* Gets the source data object containing the property data. See {@link #setSource} for details regarding the
* format of the data object.
* @return {Object} 数据对象 The data object
*/
getSource : function(){
return this.propStore.getSource();
}
});
Ext.reg("propertygrid", Ext.grid.PropertyGrid);
| 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.grid.ColumnModel
* @extends Ext.util.Observable
* Grid的列模型(ColumnModel)的默认实现。该类由列配置组成的数组初始化。<br />
* This is the default implementation of a ColumnModel used by the Grid. This class is initialized with an Array of column config objects.
* <br>我们用配置对象来定义不同列是怎么显示的,
* 包括头部(header)的字符串、对当前列是否可排序、对齐方式等的一般设置、当然还有最重要的dataIndex,该配置指定了数据的来源(须配合{@link Ext.data.Record}字段的描述)
* 另外render也是我们开发者经常要特别设置的,它本质上就是一个自定义数据格式的渲染函数。
* 这里介绍一个小技巧,就是允许通过和配置选项{@link #id}相同名称的CSS样式类来指定某列的样式。<br />
* An individual column's config object defines the header string, the {@link Ext.data.Record}
* field the column draws its data from, an optional rendering function to provide customized
* data formatting, and the ability to apply a CSS class to all cells in a column through its
* {@link #id} config option.<br>
* <br>用法:Usage:<br>
<pre><code>
var colModel = new Ext.grid.ColumnModel([
{ header: "Ticker", width: 60, sortable: true},
{ header: "Company Name", width: 150, sortable: true},
{ header: "Market Cap.", width: 100, sortable: true},
{ header: "$ Sales", width: 100, sortable: true, renderer: money},
{ header: "Employees", width: 100, sortable: true, resizable: false}
]);
</code></pre>
* <p>
* 适用于该类的许多配置项参数也适用于每一个<b>列的定义</b>。
* 为了让父类能够使用更多的配置项参数,可以将列的参数指定在配置项<tt><b>columns<b><tt>的数组中,如:<br />
* The config options <b>defined by</b> this class are options which may appear in each
* individual column definition. In order to use configuration options from the superclass,
* specify the column configuration Array in the <tt><b>columns<b><tt> config property. eg:<pre><code>
var colModel = new Ext.grid.ColumnModel({
listeners: {
widthchange: function(cm, colIndex, width) {
saveConfig(colIndex, width);
}
},
columns: [
{ header: "Ticker", width: 60, sortable: true},
{ header: "Company Name", width: 150, sortable: true},
{ header: "Market Cap.", width: 100, sortable: true},
{ header: "$ Sales", width: 100, sortable: true, renderer: money},
{ header: "Employees", width: 100, sortable: true, resizable: false}
]
});
</code></pre>
* @constructor
* @param {Object} config 列配置组成的数组,参阅关于本类的配置对象的更多资料。An Array of column config objects. See this class's
* config objects for details.
*/
Ext.grid.ColumnModel = function(config){
/**
* 传入配置到构建函数。
* The config passed into the constructor
* @type {Array}
* @property config
*/
if(config.columns){
Ext.apply(this, config);
this.setConfig(config.columns, true);
}else{
this.setConfig(config, true);
}
this.addEvents(
/**
* @event widthchange
* 当列宽度变动时触发。
* Fires when the width of a column changes.
* @param {ColumnModel} this
* @param {Number} columnIndex 列索引。The column index
* @param {Number} newWidth 新宽度。The new width
*/
"widthchange",
/**
* @event headerchange
* 当头部文字改变时触发。
* Fires when the text of a header changes.
* @param {ColumnModel} this
* @param {Number} columnIndex 列索引。The column index
* @param {String} newText 新头部文字。The new header text
*/
"headerchange",
/**
* @event hiddenchange
* 当某一列隐藏或“反隐藏”时触发。
* Fires when a column is hidden or "unhidden".
* @param {ColumnModel} this
* @param {Number} columnIndex 列索引。The column index
* @param {Boolean} hidden 隐藏,false:“反隐藏”。true if hidden, false otherwise
*/
"hiddenchange",
/**
* @event columnmoved
* 当列被移动时触发。
* Fires when a column is moved.
* @param {ColumnModel} this
* @param {Number} oldIndex
* @param {Number} newIndex
*/
"columnmoved",
// deprecated - to be removed
"columnlockchange",
/**
* @event configchange
* 当列锁定状态被改变时触发。
* Fires when the configuration is changed
* @param {ColumnModel} this
*/
"configchange"
);
Ext.grid.ColumnModel.superclass.constructor.call(this);
};
Ext.extend(Ext.grid.ColumnModel, Ext.util.Observable, {
/**
* 列不指定宽度时的默认值(默认为100)。
* The width of columns which have no width specified (defaults to 100)
* @type Number
* @property defaultWidth
*/
defaultWidth: 100,
/**
* 是否默认排序(默认为false)。只对那些没有指定sortable的有效。
* Default sortable of columns which have no sortable specified (defaults to false)
* @type Boolean
* @property defaultSortable
*/
defaultSortable: false,
/**
* @cfg {String} id (可选的)默认值是按列出现的位置的序号。
* 这就是该列的标示。该列的所有单元格包括头部都是用这个值来创建CSS class属性。
* CSS Class产生的格式将是<pre>x-grid3-td-<b>id</b></pre>。
* (optional) Defaults to the column's initial ordinal position.
* A name which identifies this column. The id is used to create a CSS class name which
* is applied to all table cells (including headers) in that column. The class name
* takes the form of <pre>x-grid3-td-<b>id</b></pre>
* <br><br>
* 头部区域也有这个CSS类,但会多出<pr>x-grid3-hd</pre>,因此使用这样的<pre>.x-grid3-hd.x-grid3-td-<b>id</b></pre>
* CSS选择符就可以找到头部。
* {@link Ext.grid.GridPanel#autoExpandColumn}也是透过这个id来配置的。
* Header cells will also recieve this class name, but will also have the class <pr>x-grid3-hd</pre>,
* so to target header cells, use CSS selectors such as:<pre>.x-grid3-hd.x-grid3-td-<b>id</b></pre>
* The {@link Ext.grid.GridPanel#autoExpandColumn} grid config option references the column
* via this identifier.
*/
/**
* @cfg {String} header 在Grid头部视图中显示的文字。
* The header text to display in the Grid view.
*/
/**
* @cfg {String} dataIndex (可选的)数据索引,相当于Grid记录集({@link Ext.data.Store}里面的{@link Ext.data.Record} )中字段名称,字段的值用于展示列里面的值(column's value)。
* 如不指定,Record的数据列中的索引将作为列的索引。
* (optional) The name of the field in the grid's {@link Ext.data.Store}'s
* {@link Ext.data.Record} definition from which to draw the column's value. If not
* specified, the column's index is used as an index into the Record's data Array.
*/
/**
* @cfg {Number} width (可选的)列的初始宽度(像素)。如采用{@link Ext.grid.Grid#autoSizeColumns}性能较差。
* (optional) The initial width in pixels of the column. This is ignored if the
* Grid's {@link Ext.grid.GridView view} is configured with {@link Ext.grid.GridView#forceFit forceFit} true.
*/
/**
* @cfg {Boolean} sortable (可选的)True表示为可在该列上进行排列。
* 默认为{@link #defaultSortable}属性的值。
* 由{@link Ext.data.Store#remoteSort}指定本地排序抑或是远程排序。
* (optional) True if sorting is to be allowed on this column.
* Defaults to the value of the {@link #defaultSortable} property.
* Whether local/remote sorting is used is specified in {@link Ext.data.Store#remoteSort}.
*/
/**
* @cfg {Boolean} fixed (optional) True表示为列的宽度不能够改变。默认为fasle。
* True if the column width cannot be changed. Defaults to false.
*/
/**
* @cfg {Boolean} resizable (可选的)False禁止列可变动大小。默认为true。
* (optional) False to disable column resizing. Defaults to true.
*/
/**
* @cfg {Boolean} menuDisabled True表示禁止列菜单。默认为fasle。
* (optional) True to disable the column menu. Defaults to false.
*/
/**
* @cfg {Boolean} hidden (optional) (可选的)True表示隐藏列,默认为false。
* True to hide the column. Defaults to false.
*/
/**
* @cfg {String} tooltip (optional) (可选的)在列头部显示的提示文字。
* 如果Quicktips的功能有被打开,那么就会用Quicktps来显示,否则就会用HTML的title属性来显示。
* 默认为""。
* A text string to use as the column header's tooltip. If Quicktips are enabled, this
* value will be used as the text of the quick tip, otherwise it will be set as the header's HTML title attribute.
* Defaults to ''.
*/
/**
* @cfg {Function} renderer (可选的)该函数用于加工单元格的原始数据,转换成为HTML并返回给GridView进一步处理。
* 请参阅{@link #setRenderer}。如不指定,则对原始数据值进行默认地渲染。
* (optional) A function used to generate HTML markup for a cell
* given the cell's data value. See {@link #setRenderer}. If not specified, the
* default renderer uses the raw data value.
*/
/**
* @cfg {String} align (可选的)设置列的CSS text-align属性。默认为undefined。
* (optional) Set the CSS text-align property of the column. Defaults to undefined.
*/
/**
* @cfg {String} css (可选的)设置表格中全体单元格的CSS样式(包括头部)。默认为undefined。
* (optional) Set custom CSS for all table cells in the column (excluding headers). Defaults to undefined.
*/
/**
* @cfg {Boolean} hideable (可选的)指定<tt>false</tt>可禁止用户隐藏该列。默认为True。
* 要全局地禁止Grid中所有列的隐藏性,使用{@link Ext.grid.GridPanel#enableColumnHide}。
* (optional) Specify as <tt>false</tt> to prevent the user from hiding this column
* (defaults to true). To disallow column hiding globally for all columns in the grid, use
* {@link Ext.grid.GridPanel#enableColumnHide} instead.
*/
/**
* @cfg {Ext.form.Field} editor (可选的)如果Grid的编辑器支持被打开,这属性指定了用户编辑时所用的编辑器{@link Ext.form.Field}。
*(optional) The {@link Ext.form.Field} to use when editing values in this column if editing is supported by the grid.
*/
/**
* @cfg {Function} groupRenderer 如果Grid是通过{@link Ext.grid.GroupingView}负责渲染的,
* 那么该配置项将对格式化组字段的值有用,指定一个函数就是这个格式化的函数,告知Grid怎么显示头部的组。这函数应该返回字符串。
* If the grid is being rendered by an {@link Ext.grid.GroupingView}, this
* option may be used to specify the function used to format the grouping field value for
* display in the group header. Should return a string value.
* <p>
* 可以有以下的参数:
* This takes the following parameters:
* <div class="mdetail-params"><ul>
* <li><b>v</b> : Object<p class="sub-desc">组字段的新值。The new value of the group field.</p></li>
* <li><b>unused</b> : undefined<p class="sub-desc">未用的参数。Unused parameter.</p></li>
* <li><b>r</b> : Ext.data.Record<p class="sub-desc">引发组变动的Record对象。The Record providing the data
* for the row which caused group change.</p></li>
* <li><b>rowIndex</b> : Number<p class="sub-desc">引发组变动的Record行索引。The row index of the Record which caused group change.</p></li>
* <li><b>colIndex</b> : Number<p class="sub-desc">组字段的列索引。The column index of the group field.</p></li>
* <li><b>ds</b> : Ext.data.Store<p class="sub-desc">提高数据模型的Store对象。The Store which is providing the data Model.</p></li>
* </ul></div></p>
*/
/**
* 返回指定index列的Id。
* Returns the id of the column at the specified index.
* @param {Number} index 列索引。The column index
* @return {String} the id
*/
getColumnId : function(index){
return this.config[index].id;
},
getColumnAt : function(index){
return this.config[index];
},
/**
* <p>
* 重新配置列模型。传入一个数组,就是各个列的配置对象。
* 要了解各个列的配置说明,请参阅<a href="#Ext.grid.ColumnModel-configs">Config Options</a>。
* Reconfigures this column model according to the passed Array of column definition objects. For a description of
* the individual properties of a column definition object, see the <a href="#Ext.grid.ColumnModel-configs">Config Options</a>.</p>
* <p>
* 这会引起{@link #configchange}事件的触发。
* {@link Ext.grid.GridPanel GridPanel}就是靠这个事件来得知其所用的列有变化并自动刷新Grid的UI。
* Causes the {@link #configchange} event to be fired. A {@link Ext.grid.GridPanel GridPanel} using
* this ColumnModel will listen for this event and refresh its UI automatically.</p>
* @param {Array} config 列配置组成的数组。Array of Column definition objects.
*/
setConfig : function(config, initial){
if(!initial){ // cleanup
delete this.totalWidth;
for(var i = 0, len = this.config.length; i < len; i++){
var c = this.config[i];
if(c.editor){
c.editor.destroy();
}
}
}
this.config = config;
this.lookup = {};
// if no id, create one
for(var i = 0, len = config.length; i < len; i++){
var c = config[i];
if(!c.isColumn){
var cls = Ext.grid.Column.types[c.xtype || 'gridcolumn'];
c = new cls(c);
config[i] = c;
}
this.lookup[c.id] = c;
}
if(!initial){
this.fireEvent('configchange', this);
}
},
/**
* 返回指定id的列。
* Returns the column for a specified id.
* @param {String} id 列id。The column id
* @return {Object} 列。the column
*/
getColumnById : function(id){
return this.lookup[id];
},
/**
* 返回指定列id的索引。
* Returns the index for a specified column id.
* @param {String} id 列id The column id
* @return {Number} 索引,-1表示找不到。the index, or -1 if not found
*/
getIndexById : function(id){
for(var i = 0, len = this.config.length; i < len; i++){
if(this.config[i].id == id){
return i;
}
}
return -1;
},
/**
* 把列从一个位置移到别处。
* Moves a column from one position to another.
* @param {Number} oldIndex 移动之前的列索引。The index of the column to move.
* @param {Number} newIndex 移动之后的列索引。The position at which to reinsert the coolumn.
*/
moveColumn : function(oldIndex, newIndex){
var c = this.config[oldIndex];
this.config.splice(oldIndex, 1);
this.config.splice(newIndex, 0, c);
this.dataMap = null;
this.fireEvent("columnmoved", this, oldIndex, newIndex);
},
// deprecated - to be removed
isLocked : function(colIndex){
return this.config[colIndex].locked === true;
},
// deprecated - to be removed
setLocked : function(colIndex, value, suppressEvent){
if(this.isLocked(colIndex) == value){
return;
}
this.config[colIndex].locked = value;
if(!suppressEvent){
this.fireEvent("columnlockchange", this, colIndex, value);
}
},
// deprecated - to be removed
getTotalLockedWidth : function(){
var totalWidth = 0;
for(var i = 0; i < this.config.length; i++){
if(this.isLocked(i) && !this.isHidden(i)){
this.totalWidth += this.getColumnWidth(i);
}
}
return totalWidth;
},
// deprecated - to be removed
getLockedCount : function(){
for(var i = 0, len = this.config.length; i < len; i++){
if(!this.isLocked(i)){
return i;
}
}
},
/**
* 返回列数。
* Returns the number of columns.
* @param {Boolean} visibleOnly (可选的)传入true表示只是包含可见那些的列。Optional. Pass as true to only include visible columns.
* @return {Number}
*/
getColumnCount : function(visibleOnly){
if(visibleOnly === true){
var c = 0;
for(var i = 0, len = this.config.length; i < len; i++){
if(!this.isHidden(i)){
c++;
}
}
return c;
}
return this.config.length;
},
/**
* 传入一个function类型的参数,这个函数执行时会有(columnConfig, index)的参数送入其内,如函数返回true则加入到数组中保存并返回数组。
* Returns the column configs that return true by the passed function that is called with (columnConfig, index)
* @param {Function} fn
* @param {Object} scope (可选的)(optional)
* @return {Array} result
*/
getColumnsBy : function(fn, scope){
var r = [];
for(var i = 0, len = this.config.length; i < len; i++){
var c = this.config[i];
if(fn.call(scope||this, c, i) === true){
r[r.length] = c;
}
}
return r;
},
/**
* 返回指定的列可否排序。
* Returns true if the specified column is sortable.
* @param {Number} col 列索引。The column index
* @return {Boolean}
*/
isSortable : function(col){
if(typeof this.config[col].sortable == "undefined"){
return this.defaultSortable;
}
return this.config[col].sortable;
},
/**
* 如果列的菜单被禁用的话,返回true。
* Returns true if the specified column menu is disabled.
* @param {Number} col 列索引。The column index
* @return {Boolean}
*/
isMenuDisabled : function(col){
return !!this.config[col].menuDisabled;
},
/**
* 返回对某个列的渲染(格式化)函数。
* Returns the rendering (formatting) function defined for the column.
* @param {Number} col 列索引。The column index.
* @return {Function} 用于渲染单元格的那个函数。可参阅{@link #setRenderer}。 The function used to render the cell. See {@link #setRenderer}.
*/
getRenderer : function(col){
if(!this.config[col].renderer){
return Ext.grid.ColumnModel.defaultRenderer;
}
return this.config[col].renderer;
},
/**
* 设置对某个列的渲染(格式化formatting)函数
* Sets the rendering (formatting) function for a column. See {@link Ext.util.Format} for some
* default formatting functions.
* @param {Number} col 列索引。The column index
* @param {Function} fn 该函数用于加工单元格的原始数据,转换成为HTML并返回给GridView进一步处理。这个渲染函数调用时会有下列的参数:
* The function to use to process the cell's raw data
* to return HTML markup for the grid view. The render function is called with
* the following parameters:<ul>
* <li><b>value</b> : Object<p class="sub-desc">单元格的数据值。The data value for the cell.</p></li>
* <li><b>metadata</b> : Object<p class="sub-desc">单元格元数据(Cell metadata)对象。你也可以设置下列的属性:An object in which you may set the following attributes:<ul>
* <li><b>css</b> : String<p class="sub-desc">单元格CSS样式字符串,作用在td元素上。A CSS class name to add to the cell's TD element.</p></li>
* <li><b>attr</b> : String<p class="sub-desc">一段HTML属性的字符串,将作用于表格单元格<i>内的</i>数据容器元素(如'style="color:red;"')。An HTML attribute definition string to apply to the data container element <i>within</i> the table cell
* (e.g. 'style="color:red;"').</p></li></ul></p></li>
* <li><b>record</b> : Ext.data.record<p class="sub-desc">从数据中提取的{@link Ext.data.Record}。The {@link Ext.data.Record} from which the data was extracted.</p></li>
* <li><b>rowIndex</b> : Number<p class="sub-desc">行索引。Row index</p></li>
* <li><b>colIndex</b> : Number<p class="sub-desc">列索引。Column index</p></li>
* <li><b>store</b> : Ext.data.Store<p class="sub-desc">从Record中提取的{@link Ext.data.Store}对象。The {@link Ext.data.Store} object from which the Record was extracted.</p></li></ul>
*/
setRenderer : function(col, fn){
this.config[col].renderer = fn;
},
/**
* 返回某个列的宽度。
* Returns the width for the specified column.
* @param {Number} col 列索引。The column index
* @return {Number}
*/
getColumnWidth : function(col){
return this.config[col].width || this.defaultWidth;
},
/**
* 设置某个列的宽度。
* Sets the width for a column.
* @param {Number} col 列索引。The column index
* @param {Number} width 新宽度。The new width
*/
setColumnWidth : function(col, width, suppressEvent){
this.config[col].width = width;
this.totalWidth = null;
if(!suppressEvent){
this.fireEvent("widthchange", this, col, width);
}
},
/**
* 返回所有列宽度之和。
* Returns the total width of all columns.
* @param {Boolean} includeHidden True表示为包括隐藏的宽度。True to include hidden column widths
* @return {Number}
*/
getTotalWidth : function(includeHidden){
if(!this.totalWidth){
this.totalWidth = 0;
for(var i = 0, len = this.config.length; i < len; i++){
if(includeHidden || !this.isHidden(i)){
this.totalWidth += this.getColumnWidth(i);
}
}
}
return this.totalWidth;
},
/**
* 返回某个列的头部(header)。
* Returns the header for the specified column.
* @param {Number} col 列索引。The column index
* @return {String}
*/
getColumnHeader : function(col){
return this.config[col].header;
},
/**
* 设置某个列的头部(header)。
* Sets the header for a column.
* @param {Number} col 列索引。The column index
* @param {String} header 新头部。The new header
*/
setColumnHeader : function(col, header){
this.config[col].header = header;
this.fireEvent("headerchange", this, col, header);
},
/**
* 返回某个列的工具提示(tooltip)。
* Returns the tooltip for the specified column.
* @param {Number} col 列索引。The column index
* @return {String}
*/
getColumnTooltip : function(col){
return this.config[col].tooltip;
},
/**
* 设置某个列的提示文字(tooltip)。
* Sets the tooltip for a column.
* @param {Number} col 列索引。The column index
* @param {String} tooltip 新tooltip对象。The new tooltip
*/
setColumnTooltip : function(col, tooltip){
this.config[col].tooltip = tooltip;
},
/**
* 返回某个列的数据索引。
* Returns the dataIndex for the specified column.
* @param {Number} col 列索引。The column index
* @return {String} 列的数据索引。The column's dataIndex
*/
getDataIndex : function(col){
return this.config[col].dataIndex;
},
/**
* 设置某个列的数据索引。
* Sets the dataIndex for a column.
* @param {Number} col 列索引。The column index
* @param {String} dataIndex 新数据索引。The new dataIndex
*/
setDataIndex : function(col, dataIndex){
this.config[col].dataIndex = dataIndex;
},
/**
* 送入数据索引,找到第一个匹配的列。
* Finds the index of the first matching column for the given dataIndex.
* @param {String} col dataIndex结果。The dataIndex to find
* @return {Number} 列索引,如果是-1就表示没找到。The column index, or -1 if no match was found
*/
findColumnIndex : function(dataIndex){
var c = this.config;
for(var i = 0, len = c.length; i < len; i++){
if(c[i].dataIndex == dataIndex){
return i;
}
}
return -1;
},
/**
* 返回true如果列是隐藏的。
* Returns true if the cell is editable.
* @param {Number} colIndex 列索引。The column index
* @param {Number} rowIndex 行索引。The row index
* @return {Boolean}
*/
isCellEditable : function(colIndex, rowIndex){
return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false;
},
/**
* 返回单元格/列所定义的编辑器。
* Returns the editor defined for the cell/column.
* @param {Number} colIndex 列索引。The column index
* @param {Number} rowIndex 行索引。The row index
* @return {Ext.Editor} 创建一个{@link Ext.Editor Editor}用于{@link Ext.form.Field Field}编辑时所用。
* The {@link Ext.Editor Editor} that was created to wrap the {@link Ext.form.Field Field} used to edit the cell.
*/
getCellEditor : function(colIndex, rowIndex){
return this.config[colIndex].getCellEditor(rowIndex);
},
/**
* 设置列是否可编辑的。
* Sets if a column is editable.
* @param {Number} col 列索引。The column index
* @param {Boolean} editable True表示为列是可编辑的。True if the column is editable
*/
setEditable : function(col, editable){
this.config[col].editable = editable;
},
/**
* 如果列是隐藏的则返回true。
* Returns true if the column is hidden.
* @param {Number} colIndex 列索引。The column index
* @return {Boolean}
*/
isHidden : function(colIndex){
return this.config[colIndex].hidden;
},
/**
* 如果列是固定的则返回true。
* Returns true if the column width cannot be changed
*/
isFixed : function(colIndex){
return this.config[colIndex].fixed;
},
/**
* 如果列不能调整尺寸返回true。
* Returns true if the column can be resized
* @return {Boolean}
*/
isResizable : function(colIndex){
return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true;
},
/**
* 设置列隐藏。
* Sets if a column is hidden.
* @param {Number} colIndex 列索引。The column index
* @param {Boolean} hidden True表示为列是已隐藏的。True if the column is hidden
*/
setHidden : function(colIndex, hidden){
var c = this.config[colIndex];
if(c.hidden !== hidden){
c.hidden = hidden;
this.totalWidth = null;
this.fireEvent("hiddenchange", this, colIndex, hidden);
}
},
/**
* 为列设置编辑器。
* Sets the editor for a column.
* @param {Number} col 列索引。The column index
* @param {Object} editor 编辑器对象。The editor object
*/
setEditor : function(col, editor){
this.config[col].editor = editor;
}
});
// private
Ext.grid.ColumnModel.defaultRenderer = function(value){
if(typeof value == "string" && value.length < 1){
return " ";
}
return value;
}; | 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.grid.GroupingView
* @extends Ext.grid.GridView
* Adds the ability for single level grouping to the grid.
*<pre><code>var grid = new Ext.grid.GridPanel({
// A groupingStore is required for a GroupingView
store: new Ext.data.GroupingStore({
reader: reader,
data: xg.dummyData,
sortInfo:{field: 'company', direction: "ASC"},
groupField:'industry'
}),
columns: [
{id:'company',header: "Company", width: 60, sortable: true, dataIndex: 'company'},
{header: "Price", width: 20, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price'},
{header: "Change", width: 20, sortable: true, dataIndex: 'change', renderer: Ext.util.Format.usMoney},
{header: "Industry", width: 20, sortable: true, dataIndex: 'industry'},
{header: "Last Updated", width: 20, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
],
view: new Ext.grid.GroupingView({
forceFit:true,
// custom grouping text template to display the number of items per group
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
frame:true,
width: 700,
height: 450,
collapsible: true,
animCollapse: false,
title: 'Grouping Example',
iconCls: 'icon-grid',
renderTo: document.body
});</code></pre>
* @constructor
* @param {Object} config
*/
Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, {
/**
* @cfg {Boolean} hideGroupedColumn True to hide the column that is currently grouped
*/
hideGroupedColumn:false,
/**
* @cfg {Boolean} showGroupName True to display the name for each set of grouped rows (defaults to true)
*/
showGroupName:true,
/**
* @cfg {Boolean} startCollapsed True to start all groups collapsed
*/
startCollapsed:false,
/**
* @cfg {Boolean} enableGrouping False to disable grouping functionality (defaults to true)
*/
enableGrouping:true,
/**
* @cfg {Boolean} enableGroupingMenu True to enable the grouping control in the column menu
*/
enableGroupingMenu:true,
/**
* @cfg {Boolean} enableNoGroups True to allow the user to turn off grouping
*/
enableNoGroups:true,
/**
* @cfg {String} emptyGroupText The text to display when there is an empty group value
*/
emptyGroupText : '(None)',
/**
* @cfg {Boolean} ignoreAdd True to skip refreshing the view when new rows are added (defaults to false)
*/
ignoreAdd: false,
/**
* @cfg {String} groupTextTpl The template used to render the group header. This is used to
* format an object which contains the following properties:
* <div class="mdetail-params"><ul>
* <li><b>group</b> : String<p class="sub-desc">The <i>rendered</i> value of the group field.
* By default this is the unchanged value of the group field. If a {@link #groupRenderer}
* is specified, it is the result of a call to that.</p></li>
* <li><b>gvalue</b> : Object<p class="sub-desc">The <i>raw</i> value of the group field.</p></li>
* <li><b>text</b> : String<p class="sub-desc">The configured {@link #header} (If
* {@link #showGroupName} is true) plus the <i>rendered</i>group field value.</p></li>
* <li><b>groupId</b> : String<p class="sub-desc">A unique, generated ID which is applied to the
* View Element which contains the group.</p></li>
* <li><b>startRow</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li>
* <li><b>rs</b> : Array<p class="sub-desc">.Contains a single element: The Record providing the data
* for the row which caused group change.</p></li>
* <li><b>cls</b> : String<p class="sub-desc">The generated class name string to apply to the group header Element.</p></li>
* <li><b>style</b> : String<p class="sub-desc">The inline style rules to apply to the group header Element.</p></li>
* </ul></div></p>
* See {@link Ext.XTemplate} for information on how to format data using a template.
*/
groupTextTpl : '{text}',
/**
* @cfg {Function} groupRenderer The function used to format the grouping field value for
* display in the group header. Should return a string value. <b>This configuration object
* is in fact a configuration option of the column definition in the grid's
* {@link Ext.grid.ColumnModel#groupRenderer ColumnModel}, it is included here for ease of reference.</b>
* <p>This takes the following parameters:
* <div class="mdetail-params"><ul>
* <li><b>v</b> : Object<p class="sub-desc">The new value of the group field.</p></li>
* <li><b>unused</b> : undefined<p class="sub-desc">Unused parameter.</p></li>
* <li><b>r</b> : Ext.data.Record<p class="sub-desc">The Record providing the data
* for the row which caused group change.</p></li>
* <li><b>rowIndex</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li>
* <li><b>colIndex</b> : Number<p class="sub-desc">The column index of the group field.</p></li>
* <li><b>ds</b> : Ext.data.Store<p class="sub-desc">The Store which is providing the data Model.</p></li>
* </ul></div></p>
*/
/**
* @cfg {String} header The text with which to prefix the group field value in the group header line.
*/
// private
gidSeed : 1000,
// private
initTemplates : function(){
Ext.grid.GroupingView.superclass.initTemplates.call(this);
this.state = {};
var sm = this.grid.getSelectionModel();
sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect',
this.onBeforeRowSelect, this);
if(!this.startGroup){
this.startGroup = new Ext.XTemplate(
'<div id="{groupId}" class="x-grid-group {cls}">',
'<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div>', this.groupTextTpl ,'</div></div>',
'<div id="{groupId}-bd" class="x-grid-group-body">'
);
}
this.startGroup.compile();
this.endGroup = '</div></div>';
},
// private
findGroup : function(el){
return Ext.fly(el).up('.x-grid-group', this.mainBody.dom);
},
// private
getGroups : function(){
return this.hasRows() ? this.mainBody.dom.childNodes : [];
},
// private
onAdd : function(){
if(this.enableGrouping && !this.ignoreAdd){
var ss = this.getScrollState();
this.refresh();
this.restoreScroll(ss);
}else if(!this.enableGrouping){
Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments);
}
},
// private
onRemove : function(ds, record, index, isUpdate){
Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments);
var g = document.getElementById(record._groupId);
if(g && g.childNodes[1].childNodes.length < 1){
Ext.removeNode(g);
}
this.applyEmptyText();
},
// private
refreshRow : function(record){
if(this.ds.getCount()==1){
this.refresh();
}else{
this.isUpdating = true;
Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments);
this.isUpdating = false;
}
},
// private
beforeMenuShow : function(){
var field = this.getGroupField();
var g = this.hmenu.items.get('groupBy');
if(g){
g.setDisabled(this.cm.config[this.hdCtxIndex].groupable === false);
}
var s = this.hmenu.items.get('showGroups');
if(s){
s.setDisabled(!field && this.cm.config[this.hdCtxIndex].groupable === false);
s.setChecked(!!field, true);
}
},
// private
renderUI : function(){
Ext.grid.GroupingView.superclass.renderUI.call(this);
this.mainBody.on('mousedown', this.interceptMouse, this);
if(this.enableGroupingMenu && this.hmenu){
this.hmenu.add('-',{
id:'groupBy',
text: this.groupByText,
handler: this.onGroupByClick,
scope: this,
iconCls:'x-group-by-icon'
});
if(this.enableNoGroups){
this.hmenu.add({
id:'showGroups',
text: this.showGroupsText,
checked: true,
checkHandler: this.onShowGroupsClick,
scope: this
});
}
this.hmenu.on('beforeshow', this.beforeMenuShow, this);
}
},
// private
onGroupByClick : function(){
this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));
this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups
},
// private
onShowGroupsClick : function(mi, checked){
if(checked){
this.onGroupByClick();
}else{
this.grid.store.clearGrouping();
}
},
/**
* Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed.
* @param {String} groupId The groupId assigned to the group (see getGroupId)
* @param {Boolean} expanded (optional)
*/
toggleGroup : function(group, expanded){
this.grid.stopEditing(true);
group = Ext.getDom(group);
var gel = Ext.fly(group);
expanded = expanded !== undefined ?
expanded : gel.hasClass('x-grid-group-collapsed');
this.state[gel.dom.id] = expanded;
gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed');
},
/**
* Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed.
* @param {Boolean} expanded (optional)
*/
toggleAllGroups : function(expanded){
var groups = this.getGroups();
for(var i = 0, len = groups.length; i < len; i++){
this.toggleGroup(groups[i], expanded);
}
},
/**
* Expands all grouped rows.
*/
expandAllGroups : function(){
this.toggleAllGroups(true);
},
/**
* Collapses all grouped rows.
*/
collapseAllGroups : function(){
this.toggleAllGroups(false);
},
// private
interceptMouse : function(e){
var hd = e.getTarget('.x-grid-group-hd', this.mainBody);
if(hd){
e.stopEvent();
this.toggleGroup(hd.parentNode);
}
},
// private
getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){
var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v);
if(g === ''){
g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText;
}
return g;
},
// private
getGroupField : function(){
return this.grid.store.getGroupState();
},
// private
renderRows : function(){
var groupField = this.getGroupField();
var eg = !!groupField;
// if they turned off grouping and the last grouped field is hidden
if(this.hideGroupedColumn) {
var colIndex = this.cm.findColumnIndex(groupField);
if(!eg && this.lastGroupField !== undefined) {
this.mainBody.update('');
this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false);
delete this.lastGroupField;
}else if (eg && this.lastGroupField === undefined) {
this.lastGroupField = groupField;
this.cm.setHidden(colIndex, true);
}else if (eg && this.lastGroupField !== undefined && groupField !== this.lastGroupField) {
this.mainBody.update('');
var oldIndex = this.cm.findColumnIndex(this.lastGroupField);
this.cm.setHidden(oldIndex, false);
this.lastGroupField = groupField;
this.cm.setHidden(colIndex, true);
}
}
return Ext.grid.GroupingView.superclass.renderRows.apply(
this, arguments);
},
// private
doRender : function(cs, rs, ds, startRow, colCount, stripe){
if(rs.length < 1){
return '';
}
var groupField = this.getGroupField();
var colIndex = this.cm.findColumnIndex(groupField);
this.enableGrouping = !!groupField;
if(!this.enableGrouping || this.isUpdating){
return Ext.grid.GroupingView.superclass.doRender.apply(
this, arguments);
}
var gstyle = 'width:'+this.getTotalWidth()+';';
var gidPrefix = this.grid.getGridEl().id;
var cfg = this.cm.config[colIndex];
var groupRenderer = cfg.groupRenderer || cfg.renderer;
var prefix = this.showGroupName ?
(cfg.groupName || cfg.header)+': ' : '';
var groups = [], curGroup, i, len, gid;
for(i = 0, len = rs.length; i < len; i++){
var rowIndex = startRow + i;
var r = rs[i],
gvalue = r.data[groupField],
g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds);
if(!curGroup || curGroup.group != g){
gid = gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(g);
// if state is defined use it, however state is in terms of expanded
// so negate it, otherwise use the default.
var isCollapsed = typeof this.state[gid] !== 'undefined' ? !this.state[gid] : this.startCollapsed;
var gcls = isCollapsed ? 'x-grid-group-collapsed' : '';
curGroup = {
group: g,
gvalue: gvalue,
text: prefix + g,
groupId: gid,
startRow: rowIndex,
rs: [r],
cls: gcls,
style: gstyle
};
groups.push(curGroup);
}else{
curGroup.rs.push(r);
}
r._groupId = gid;
}
var buf = [];
for(i = 0, len = groups.length; i < len; i++){
var g = groups[i];
this.doGroupStart(buf, g, cs, ds, colCount);
buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call(
this, cs, g.rs, ds, g.startRow, colCount, stripe);
this.doGroupEnd(buf, g, cs, ds, colCount);
}
return buf.join('');
},
/**
* Dynamically tries to determine the groupId of a specific value
* @param {String} value
* @return {String} The group id
*/
getGroupId : function(value){
var gidPrefix = this.grid.getGridEl().id;
var groupField = this.getGroupField();
var colIndex = this.cm.findColumnIndex(groupField);
var cfg = this.cm.config[colIndex];
var groupRenderer = cfg.groupRenderer || cfg.renderer;
var gtext = this.getGroup(value, {data:{}}, groupRenderer, 0, colIndex, this.ds);
return gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(value);
},
// private
doGroupStart : function(buf, g, cs, ds, colCount){
buf[buf.length] = this.startGroup.apply(g);
},
// private
doGroupEnd : function(buf, g, cs, ds, colCount){
buf[buf.length] = this.endGroup;
},
// private
getRows : function(){
if(!this.enableGrouping){
return Ext.grid.GroupingView.superclass.getRows.call(this);
}
var r = [];
var g, gs = this.getGroups();
for(var i = 0, len = gs.length; i < len; i++){
g = gs[i].childNodes[1].childNodes;
for(var j = 0, jlen = g.length; j < jlen; j++){
r[r.length] = g[j];
}
}
return r;
},
// private
updateGroupWidths : function(){
if(!this.enableGrouping || !this.hasRows()){
return;
}
var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.scrollOffset) +'px';
var gs = this.getGroups();
for(var i = 0, len = gs.length; i < len; i++){
gs[i].firstChild.style.width = tw;
}
},
// private
onColumnWidthUpdated : function(col, w, tw){
Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this, col, w, tw);
this.updateGroupWidths();
},
// private
onAllColumnWidthsUpdated : function(ws, tw){
Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this, ws, tw);
this.updateGroupWidths();
},
// private
onColumnHiddenUpdated : function(col, hidden, tw){
Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this, col, hidden, tw);
this.updateGroupWidths();
},
// private
onLayout : function(){
this.updateGroupWidths();
},
// private
onBeforeRowSelect : function(sm, rowIndex){
if(!this.enableGrouping){
return;
}
var row = this.getRow(rowIndex);
if(row && !row.offsetParent){
var g = this.findGroup(row);
this.toggleGroup(g, true);
}
},
/**
* @cfg {String} groupByText Text displayed in the grid header menu for grouping by a column
* (defaults to 'Group By This Field').
*/
groupByText: 'Group By This Field',
/**
* @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping
* (defaults to 'Show in Groups').
*/
showGroupsText: 'Show in Groups'
});
// private
Ext.grid.GroupingView.GROUP_ID = 1000; | JavaScript |
/*
* 项目地址: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.grid.SplitDragZone
* private
* This is a support class used internally by the Grid components
*/
Ext.grid.SplitDragZone = function(grid, hd, hd2){
this.grid = grid;
this.view = grid.getView();
this.proxy = this.view.resizeProxy;
Ext.grid.SplitDragZone.superclass.constructor.call(this, hd,
"gridSplitters" + this.grid.getGridEl().id, {
dragElId : Ext.id(this.proxy.dom), resizeFrame:false
});
this.setHandleElId(Ext.id(hd));
this.setOuterHandleElId(Ext.id(hd2));
this.scroll = false;
};
Ext.extend(Ext.grid.SplitDragZone, Ext.dd.DDProxy, {
fly: Ext.Element.fly,
b4StartDrag : function(x, y){
this.view.headersDisabled = true;
this.proxy.setHeight(this.view.mainWrap.getHeight());
var w = this.cm.getColumnWidth(this.cellIndex);
var minw = Math.max(w-this.grid.minColumnWidth, 0);
this.resetConstraints();
this.setXConstraint(minw, 1000);
this.setYConstraint(0, 0);
this.minX = x - minw;
this.maxX = x + 1000;
this.startPos = x;
Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y);
},
handleMouseDown : function(e){
ev = Ext.EventObject.setEvent(e);
var t = this.fly(ev.getTarget());
if(t.hasClass("x-grid-split")){
this.cellIndex = this.view.getCellIndex(t.dom);
this.split = t.dom;
this.cm = this.grid.colModel;
if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){
Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments);
}
}
},
endDrag : function(e){
this.view.headersDisabled = false;
var endX = Math.max(this.minX, Ext.lib.Event.getPageX(e));
var diff = endX - this.startPos;
this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff);
},
autoOffset : function(){
this.setDelta(0,0);
}
}); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.grid.GridDragZone
* @extends Ext.dd.DragZone
* <p>A customized implementation of a {@link Ext.dd.DragZone DragZone} which provides default implementations of two of the
* template methods of DragZone to enable dragging of the selected rows of a GridPanel.</p>
* <p>A cooperating {@link Ext.dd.DropZone DropZone} must be created who's template method implementations of
* {@link Ext.dd.DropZone#onNodeEnter onNodeEnter}, {@link Ext.dd.DropZone#onNodeOver onNodeOver},
* {@link Ext.dd.DropZone#onNodeOut onNodeOut} and {@link Ext.dd.DropZone#onNodeDrop onNodeDrop}</p> are able
* to process the {@link #getDragData data} which is provided.
*/
Ext.grid.GridDragZone = function(grid, config){
this.view = grid.getView();
Ext.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config);
if(this.view.lockedBody){
this.setHandleElId(Ext.id(this.view.mainBody.dom));
this.setOuterHandleElId(Ext.id(this.view.lockedBody.dom));
}
this.scroll = false;
this.grid = grid;
this.ddel = document.createElement('div');
this.ddel.className = 'x-grid-dd-wrap';
};
Ext.extend(Ext.grid.GridDragZone, Ext.dd.DragZone, {
ddGroup : "GridDD",
/**
* <p>The provided implementation of the getDragData method which collects the data to be dragged from the GridPanel on mousedown.</p>
* <p>This data is available for processing in the {@link Ext.dd.DropZone#onNodeEnter onNodeEnter}, {@link Ext.dd.DropZone#onNodeOver onNodeOver},
* {@link Ext.dd.DropZone#onNodeOut onNodeOut} and {@link Ext.dd.DropZone#onNodeDrop onNodeDrop} methods of a cooperating {@link Ext.dd.DropZone DropZone}.</p>
* <p>The data object contains the following properties:<ul>
* <li><b>grid</b> : Ext.Grid.GridPanel<div class="sub-desc">The GridPanel from which the data is being dragged.</div></li>
* <li><b>ddel</b> : htmlElement<div class="sub-desc">An htmlElement which provides the "picture" of the data being dragged.</div></li>
* <li><b>rowIndex</b> : Number<div class="sub-desc">The index of the row which receieved the mousedown gesture which triggered the drag.</div></li>
* <li><b>selections</b> : Array<div class="sub-desc">An Array of the selected Records which are being dragged from the GridPanel.</div></li>
* </ul></p>
*/
getDragData : function(e){
var t = Ext.lib.Event.getTarget(e);
var rowIndex = this.view.findRowIndex(t);
if(rowIndex !== false){
var sm = this.grid.selModel;
if(!sm.isSelected(rowIndex) || e.hasModifier()){
sm.handleMouseDown(this.grid, rowIndex, e);
}
return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()};
}
return false;
},
/**
* <p>The provided implementation of the onInitDrag method. Sets the <tt>innerHTML</tt> of the drag proxy which provides the "picture"
* of the data being dragged.</p>
* <p>The <tt>innerHTML</tt> data is found by calling the owning GridPanel's {@link Ext.grid.GridPanel#getDragDropText getDragDropText}.</p>
*/
onInitDrag : function(e){
var data = this.dragData;
this.ddel.innerHTML = this.grid.getDragDropText();
this.proxy.update(this.ddel);
// fire start drag?
},
/**
* An empty immplementation. Implement this to provide behaviour after a repair of an invalid drop. An implementation might highlight
* the selected rows to show that they have not been dragged.
*/
afterRepair : function(){
this.dragging = false;
},
/**
* <p>An empty implementation. Implement this to provide coordinates for the drag proxy to slide back to after an invalid drop.</p>
* <p>Called before a repair of an invalid drop to get the XY to animate to.</p>
* @param {EventObject} e The mouse up event
* @return {Array} The xy location (e.g. [100, 200])
*/
getRepairXY : function(e, data){
return false;
},
onEndDrag : function(data, e){
// fire end drag?
},
onValidDrop : function(dd, e, id){
// fire drag drop?
this.hideProxy();
},
beforeInvalidDrop : function(e, id){
}
});
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.Viewport
* @extends Ext.Container
* 一个表示程序可视区域的特殊容器(浏览器可视区域)。<br />
* A specialized container representing the viewable application area (the browser viewport).
* <p>
* 视窗渲染在document的body标签上,并且根据浏览器可视区域的大小自动调整并且管理窗口的大小变化。一个页面上只允许存在一个viewport。
* 所有的{@link Ext.Panel 面板}增加到viewport,通过她的{@link #items},或者通过她的子面板(子面板也都可以拥有自己的layout)的items,子面板的{@link #add}方法,这种设计让内部布局的优势非常明显。<br />
* <br />
* The Viewport renders itself to the document body, and automatically sizes itself to the size of
* the browser viewport and manages window resizing. There may only be one Viewport created
* in a page. Inner layouts are available by virtue of the fact that all {@link Ext.Panel Panel}s
* added to the Viewport, either through its {@link #items}, or through the items, or the {@link #add}
* method of any of its child Panels may themselves have a layout.</p>
* <p>Viewport不支持滚动,所以如果子面板需要滚动支持可以使用{@link #autoScroll}配置。<br />
* The Viewport does not provide scrolling, so child Panels within the Viewport should provide
* for scrolling if needed using the {@link #autoScroll} config.</p>
* 展示一个经典的border布局的viewport程序示例:<br />Example showing a classic application border layout :<pre><code>
new Ext.Viewport({
layout: 'border',
items: [{
region: 'north',
html: '<h1 class="x-panel-header">Page Title</h1>',
autoHeight: true,
border: false,
margins: '0 0 5 0'
}, {
region: 'west',
collapsible: true,
title: 'Navigation',
xtype: 'treepanel',
width: 200,
autoScroll: true,
split: true,
loader: new Ext.tree.TreeLoader(),
root: new Ext.tree.AsyncTreeNode({
expanded: true,
children: [{
text: 'Menu Option 1',
leaf: true
}, {
text: 'Menu Option 2',
leaf: true
}, {
text: 'Menu Option 3',
leaf: true
}]
}),
rootVisible: false,
listeners: {
click: function(n) {
Ext.Msg.alert('Navigation Tree Click', 'You clicked: "' + n.attributes.text + '"');
}
}
}, {
region: 'center',
xtype: 'tabpanel',
items: {
title: 'Default Tab',
html: 'The first tab\'s content. Others may be added dynamically'
}
}, {
region: 'south',
title: 'Information',
collapsible: true,
html: 'Information goes here',
split: true,
height: 100,
minHeight: 100
}]
});
</code></pre>
* @constructor 创建一个新视区的对象。Create a new Viewport
* @param {Object} config 配置项对象。The config object
*/
Ext.Viewport = Ext.extend(Ext.Container, {
/*
* Privatize config options which, if used, would interfere with the
* correct operation of the Viewport as the sole manager of the
* layout of the document body.
*/
/**
* @cfg {Mixed} applyTo @hide
*/
/**
* @cfg {Boolean} allowDomMove @hide
*/
/**
* @cfg {Boolean} hideParent @hide
*/
/**
* @cfg {Mixed} renderTo @hide
*/
/**
* @cfg {Boolean} hideParent @hide
*/
/**
* @cfg {Number} height @hide
*/
/**
* @cfg {Number} width @hide
*/
/**
* @cfg {Boolean} autoHeight @hide
*/
/**
* @cfg {Boolean} autoWidth @hide
*/
/**
* @cfg {Boolean} deferHeight @hide
*/
/**
* @cfg {Boolean} monitorResize @hide
*/
initComponent : function() {
Ext.Viewport.superclass.initComponent.call(this);
document.getElementsByTagName('html')[0].className += ' x-viewport';
this.el = Ext.getBody();
this.el.setHeight = Ext.emptyFn;
this.el.setWidth = Ext.emptyFn;
this.el.setSize = Ext.emptyFn;
this.el.dom.scroll = 'no';
this.allowDomMove = false;
this.autoWidth = true;
this.autoHeight = true;
Ext.EventManager.onWindowResize(this.fireResize, this);
this.renderTo = this.el;
},
fireResize : function(w, h){
this.fireEvent('resize', this, w, h, w, h);
}
});
Ext.reg('viewport', Ext.Viewport); | JavaScript |
/*
* 项目地址: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.Panel
* @extends Ext.Container
* 面板是一种面向用户界面构建应用程序最佳的单元块,一种特定功能和结构化组件。面板包含有底部和顶部的工具条,连同单独的头部、底部和body部分。
* 它提供内建都得可展开和可闭合的行为,连同多个内建的可制定的行为的工具按钮。面板可简易地置入任意的容器或布局,而面板和渲染管线(rendering pipeline)则由框架完全控制。<br />
* Panel is a container that has specific functionality and structural components that make it the perfect building
* block for application-oriented user interfaces. The Panel contains bottom and top toolbars, along with separate
* header, footer and body sections. It also provides built-in expandable and collapsible behavior, along with a
* variety of prebuilt tool buttons that can be wired up to provide other customized behavior. Panels can be easily
* dropped into any Container or layout, and the layout and rendering pipeline is completely managed by the framework.
* @constructor
* @param {Object} config 配置项对象。The config object
*/
Ext.Panel = Ext.extend(Ext.Container, {
/**
* 面板的头部元素{@link Ext.Element Element}。只读的。
* The Panel's header {@link Ext.Element Element}. Read-only.
* <p>
* 此元素用于承载 {@link #title} 和 {@link #tools}。
* This Element is used to house the {@link #title} and {@link #tools}</p>
* @type Ext.Element
* @property header
*/
/**
* 面板的躯干元素{@link Ext.Element Element}用于承载HTML内容。
* 内容可由配置项{@link #html}指定,亦可通过配置{@link autoLoad}加载,通过面板的{@link #getUpdater Updater}亦是同样的原理。只读的。
* The Panel's body {@link Ext.Element Element} which may be used to contain HTML content.
* The content may be specified in the {@link #html} config, or it may be loaded using the
* {@link autoLoad} config, or through the Panel's {@link #getUpdater Updater}. Read-only.
* <p>注:若采用了上述的方法,那么面板则不能当作布局的容器嵌套子面板。
* If this is used to load visible HTML elements in either way, then
* the Panel may not be used as a Layout for hosting nested Panels.</p>
* <p>换句话说,若打算将面板用于布局的承载者,Body躯干元素就不能有任何加载或改动,它是由面板的局部(Panel's Layout)负责调控。
* If this Panel is intended to be used as the host of a Layout (See {@link #layout}
* then the body Element must not be loaded or changed - it is under the control
* of the Panel's Layout.</p>
* @type Ext.Element
* @property body
*/
/**
* @cfg {Object} bodyCfg
* <p>构成面板{@link #body}元素的{@link Ext.DomHelper DomHelper}配置对象。
* A {@link Ext.DomHelper DomHelper} configuration object specifying the element structure
* of this Panel's {@link #body} Element.</p>
* <p>
* 这可能会对body元素采用另外一套的结构。例如使用<center> 元素就代表将其中内容都居中显示。
* This may be used to force the body Element to use a different form of markup than
* is created automatically. An example of this might be to create a child Panel containing
* custom content, such as a header, or forcing centering of all Panel
* content by having the body be a <center> element:</p><code><pre>
new Ext.Panel({
title: 'New Message',
collapsible: true,
renderTo: Ext.getBody(),
width: 400,
bodyCfg: {
tag: 'center',
cls: 'x-panel-body'
},
items: [{
border: false,
header: false,
bodyCfg: {tag: 'h2', html: 'Message'}
}, {
xtype: 'textarea',
style: {
width: '95%',
marginBottom: '10px'
}
},
new Ext.Button({
text: 'Send',
minWidth: '100',
style: {
marginBottom: '10px'
}
})
]
});</pre></code>
* <p>By default, the Default element in the table below will be used for the html markup to
* create a child element with the commensurate Default class name (<tt>baseCls</tt> will be
* replaced by <tt>{@link #baseCls}</tt>):</p>
* <pre>
* Panel Default Default Custom Additional Additional
* Element element class element class style
* ======== ========================== ========= ============== ===========
* {@link #header} div {@link #baseCls}+'-header' {@link #headerCfg} headerCssClass headerStyle
* {@link #bwrap} div {@link #baseCls}+'-bwrap' {@link #bwrapCfg} bwrapCssClass bwrapStyle
* + tbar div {@link #baseCls}+'-tbar' {@link #tbarCfg} tbarCssClass tbarStyle
* + {@link #body} div {@link #baseCls}+'-body' {@link #bodyCfg} {@link #bodyCssClass} {@link #bodyStyle}
* + bbar div {@link #baseCls}+'-bbar' {@link #bbarCfg} bbarCssClass bbarStyle
* + {@link #footer} div {@link #baseCls}+'-footer' {@link #footerCfg} footerCssClass footerStyle
* </pre>
* <p>Configuring a Custom element may be used, for example, to force the {@link #body} Element
* to use a different form of markup than is created by default. An example of this might be
* to {@link Ext.Element#createChild create a child} Panel containing a custom content, such as
* a header, or forcing centering of all Panel content by having the body be a <center>
* element:</p>
* <pre><code>
new Ext.Panel({
title: 'Message Title',
renderTo: Ext.getBody(),
width: 200, height: 130,
<b>bodyCfg</b>: {
tag: 'center',
cls: 'x-panel-body', // Default class not applied if Custom element specified
html: 'Message'
},
footerCfg: {
tag: 'h2',
cls: 'x-panel-footer' // same as the Default class
html: 'footer html'
},
footerCssClass: 'custom-footer', // additional css class, see {@link Ext.element#addClass addClass}
footerStyle: 'background-color:red' // see {@link #bodyStyle}
});
* </code></pre>
* <p>The example above also explicitly creates a <tt>{@link #footer}</tt> with custom markup and
* styling applied.</p>
*/
/**
* @cfg {Object} headerCfg
* <p>
* 面板{@link #header}元素的结构,符合{@link Ext.DomHelper DomHelper}配置的格式。
* A {@link Ext.DomHelper DomHelper} configuration object specifying the element structure
* of this Panel's {@link #header} Element.</p>
*/
/**
* @cfg {Object} bwrapCfg
* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
* of this Panel's {@link #bwrap} Element. See <tt>{@link #bodyCfg}</tt> also.</p>
*/
/**
* @cfg {Object} tbarCfg
* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
* of this Panel's {@link #tbar} Element. See <tt>{@link #bodyCfg}</tt> also.</p>
*/
/**
* @cfg {Object} bbarCfg
* <p>A {@link Ext.DomHelper DomHelper} element specification object specifying the element structure
* of this Panel's {@link #bbar} Element. See <tt>{@link #bodyCfg}</tt> also.</p>
*/
/**
* @cfg {Object} footerCfg
* <p>
* 面板{@link #footer}元素的结构,符合{@link Ext.DomHelper DomHelper}配置的格式。
* A {@link Ext.DomHelper DomHelper} configuration object specifying the element structure
* of this Panel's {@link #footer} Element.</p>
*/
/**
* @cfg {Boolean} closable
* Panels themselves do not directly support being closed, but some Panel subclasses do (like
* {@link Ext.Window}) or a Panel Class within an {@link Ext.TabPanel}. Specify <tt>true</tt>
* to enable closing in such situations. Defaults to <tt>false</tt>.
*/
/**
* 面板的底部元素{@link Ext.Element Element}。只读的。
* The Panel's footer {@link Ext.Element Element}. Read-only.
* <p>
* 该元素用于承托面板的{@link #buttons}。
* This Element is used to house the Panel's {@link #buttons}.</p>
* The Panel's footer {@link Ext.Element Element}. Read-only.
* <p>This Element is used to house the Panel's <tt>{@link #buttons}</tt> or <tt>{@link #fbar}</tt>.</p>
* <br><p><b>Note</b>: see the Note for <tt>{@link Ext.Component#el el} also.</p>
* @type Ext.Element
* @property footer
*/
/**
* @cfg {Mixed} applyTo
* 即applyTo代表一个在页面上已经存在的元素或元素的id,
* 该元素通过markup的方式来表示欲生成的组件的某些结构化信息,
* Ext在创建一个组件时会首先考虑使用applyTo元素中的存在的元素,
* 你可以认为applyTo是组件在页面上的模板,与YUI中的markup模式很相似。
* The id of the node, a DOM node or an existing Element corresponding to a DIV that is already present in
* the document that specifies some panel-specific structural markup. When applyTo is used, constituent parts of
* the panel can be specified by CSS class name within the main element, and the panel will automatically create those
* components from that markup. Any required components not specified in the markup will be autogenerated if necessary.
* The following class names are supported (baseCls will be replaced by {@link #baseCls}):
* <ul><li>baseCls + '-header'</li>
* <li>baseCls + '-header-text'</li>
* <li>baseCls + '-bwrap'</li>
* <li>baseCls + '-tbar'</li>
* <li>baseCls + '-body'</li>
* <li>baseCls + '-bbar'</li>
* <li>baseCls + '-footer'</li></ul>
* 当你在config中配置了applyTo属性后,render()方法就不需要了。
* 有了applyTo之后,{@link #renderTo}属性则会被忽略,并且applyTo所指定元素的父元素,将自动是面板的容器元素。
* Using this config, a call to render() is not required. If applyTo is specified, any value passed for
* {@link #renderTo} will be ignored and the target element's parent node will automatically be used as the panel's container.
*/
/**
* @cfg {Object/Array} tbar
* 面板顶部的工具条。
* 此项可以是{@link Ext.Toolbar}的实例、工具条的配置对象,或由按钮配置项对象构成的数组,以加入到工具条中。
* 注意,此项属性渲染过后就不可用了,应使用{@link #getTopToolbar}的方法代替。
* The top toolbar of the panel. This can be a {@link Ext.Toolbar} object, a toolbar config, or an array of
* buttons/button configs to be added to the toolbar. Note that this is not available as a property after render.
* To access the top toolbar after render, use {@link #getTopToolbar}.
*/
/**
* @cfg {Object/Array} bbar
* 面板底部的工具条。
* 此项可以是{@link Ext.Toolbar}的实例、工具条的配置对象,或由按钮配置项对象构成的数组,以加入到工具条中。
* 注意,此项属性渲染过后就不可用了,应使用{@link #getBottomToolbar}的方法代替。
* The bottom toolbar of the panel. This can be a {@link Ext.Toolbar} object, a toolbar config, or an array of
* buttons/button configs to be added to the toolbar. Note that this is not available as a property after render.
* To access the bottom toolbar after render, use {@link #getBottomToolbar}.
*/
/** @cfg {Object/Array} fbar
* <p>A {@link Ext.Toolbar Toolbar} object, a Toolbar config, or an array of
* {@link Ext.Button Button}s/{@link Ext.Button Button} configs, describing a {@link Ext.Toolbar Toolbar} to be rendered into this Panel's footer element.</p>
* <p>After render, the <code>fbar</code> property will be an {@link Ext.Toolbar Toolbar} instance.</p>
* <p>If <tt>{@link #buttons}</tt> are specified, they will supersede the <tt>fbar</tt> configuration property.</p>
* The Panel's <tt>{@link #buttonAlign}</tt> configuration affects the layout of these items, for example:
* <pre><code>
var w = new Ext.Window({
height: 250,
width: 500,
bbar: new Ext.Toolbar({
items: [{
text: 'bbar Left'
},'->',{
text: 'bbar Right'
}]
}),
{@link #buttonAlign}: 'left', // anything but 'center' or 'right' and you can use "-", and "->"
// to control the alignment of fbar items
fbar: [{
text: 'fbar Left'
},'->',{
text: 'fbar Right'
}]
}).show();
* </code></pre>
* <p><b>Note:</b> Although a Toolbar may contain Field components, these will <b>not<b> be updated by a load
* of an ancestor FormPanel. A Panel's toolbars are not part of the standard Container->Component hierarchy, and
* so are not scanned to collect form items. However, the values <b>will</b> be submitted because form
* submission parameters are collected from the DOM tree.</p>
*/
/**
* @cfg {Boolean} header
* True表示为显式建立头部元素,false则是跳过创建。
* 缺省下,如不创建头部,将使用{@link #title}的内容设置到头部去,如没指定title则不会。
* 如果设置好title,但头部设置为false,那么头部亦不会生成。
* True to create the header element explicitly, false to skip creating it. By default, when header is not
* specified, if a {@link #title} is set the header will be created automatically, otherwise it will not. If
* a title is set but header is explicitly set to false, the header will not be rendered.
*/
/**
* @cfg {Boolean} footer
* True表示为显式建立底部元素,false则是跳过创建。
* 缺省下,就算不声明创建底部,若有一个或一个以上的按钮加入到面板的话,也创建底部,不指定按钮就不会生成。
* True to create the footer element explicitly, false to skip creating it. By default, when footer is not
* specified, if one or more buttons have been added to the panel the footer will be created automatically,
* otherwise it will not.
*/
/**
* @cfg {String} title
* 显示在面板头部的文本标题(默认为'')。
* 如有指定了titile那么头部元素<tt>{@link #header}</tt>会自动生成和显示,除非<tt>{@link #header}</tt>强制设为false。如果你不想在写配置时指定好title,
* 不过想在后面才加入的话,你必须先指定一个非空的标题(具体说是空白字符''亦可或header:true),这样才保证容器元素生成出来。
* The title text to be used as innerHTML (html tags are accepted) to display in the panel <tt>{@link #header}</tt>(defaults to '').
* When a title is specified the header element will automatically be created and displayed unless {@link #header}
* is explicitly set to false. If you do not want to specify a title at config time, but you may want one later,
* you must either specify a non-empty title (a blank space ' ' will do) or header:true so that the container
* element will get created.
*/
/**
* @cfg {Array} buttons
* 在面板底部加入按钮,{@link Ext.Button}配置的数组。
* An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this panel.
*/
/**
* @cfg {Object/String/Function} autoLoad
* 一个特定的url反馈到Updater的{@link Ext.Updater#update}方法。
* 若autoLoad非null,面板会尝试在渲染后立即加载内容。
* 同时该面板{@link #body}元素的默认URL属性就是这URL,所以可随时调用{@link Ext.Element#refresh refresh}的方法。
* A valid url spec according to the Updater {@link Ext.Updater#update} method.
* If autoLoad is not null, the panel will attempt to load its contents immediately upon render.<p>
* The URL will become the default URL for this panel's {@link #body} element,
* so it may be {@link Ext.Element#refresh refresh}ed at any time.</p>
*/
/**
* @cfg {Boolean} frame
* True表示为面板的边框外框可自定义的,false表示为边框可1px的点线(默认为false)。
* True to render the panel with custom rounded borders, false to render with plain 1px square borders (defaults to false).
*/
/**
* @cfg {Boolean} border
* True表示为显示出面板body元素的边框,false则隐藏(缺省为true),默认下,边框是一套2px宽的内边框,但可在{@link #bodyBorder}中进一步设置。
* True to display the borders of the panel's body element, false to hide them (defaults to true). By default,
* the border is a 2px wide inset border, but this can be further altered by setting {@link #bodyBorder} to false.
*/
/**
* @cfg {Boolean} bodyBorder
* True表示为显示出面板body元素的边框,false则隐藏(缺省为true),只有{@link #border} == true时有效。
* 若border == true and bodyBorder == false,边框则为1px宽,可指定整个body元素的内置外观。
* True to display an interior border on the body element of the panel, false to hide it (defaults to true).
* This only applies when {@link #border} == true. If border == true and bodyBorder == false, the border will display
* as a 1px wide inset border, giving the entire body element an inset appearance.
*/
/**
* @cfg {String/Object/Function} bodyStyle
* 制定body元素的CSS样式。格式形如{@link Ext.Element#applyStyles}(缺省为null)。
* Custom CSS styles to be applied to the body element in the format expected by {@link Ext.Element#applyStyles}
* (defaults to null).
*/
/**
* @cfg {String} iconCls
* 一个能提供背景图片的CSS样式类,用于面板头部的图标:(默认为'')。
* The CSS class selector that specifies a background image to be used as the header icon (defaults to '').
* <p>
* 自定义图标的样式的示例:
* An example of specifying a custom icon class would be something like:
* </p><code><pre>
// 在配置项中指定哪一个样式:specify the property in the config for the class:
...
iconCls: 'my-icon'
// 利用css背景图说明图标文件是哪一个。css class that specifies background image to be used as the icon image:
.my-icon { background-image: url(../images/my-icon.gif) 0 6px no-repeat !important; }
</pre></code>
*/
/**
* @cfg {Boolean} collapsible
* True表示为面板是可收缩的,并自动渲染一个展开/收缩的轮换按钮在头部工具条。
* false表示为保持面板为一个静止的尺寸(缺省为false)。
* True to make the panel collapsible and have the expand/collapse toggle button automatically rendered into
* the header tool button area, false to keep the panel statically sized with no button (defaults to false).
*/
/**
* @cfg {Array} tools
* 一个按钮配置组成的数组,加入到头部的工具条区域。
* 渲染过程中,每一项工具都保存为{@link Ext.Element Element}对象,都集中保存在属性<tt><b></b>tools.<i><tool-type></i></tt>之中。
* 每个工具配置可包含下列属性:
* An array of tool button configs to be added to the header tool area. When rendered, each tool is
* stored as an {@link Ext.Element Element} referenced by a public property called <tt><b></b>tools.<i><tool-type></i></tt>
* <p>Each tool config may contain the following properties:
* <div class="mdetail-params"><ul>
* <li><b>id</b> : String<div class="sub-desc"><b>必须的。 Required.</b> 创建tool其类型。默认下有<tt>x-tool-<i><tool-type></i></tt>样式分配的了就表示这是一个tool元素。
* The type of tool to create. By default, this assigns a CSS class of the form <tt>x-tool-<i><tool-type></i></tt> to the
* resulting tool Element.
* Ext自带一些css样式,吻合于各种tool的按钮样式需求。
* 开发人员也可以自己弄一些css样式和背景图来修改图标。
* Ext provides CSS rules, and an icon sprite containing images for the tool types listed below.
* The developer may implement custom tools by supplying alternate CSS rules and background images:<ul>
* <li><tt>toggle</tt> 当{@link #collapsible}为<tt>true</tt>时自动创建。(Created by default when {@link #collapsible} is <tt>true</tt>)</li>
* <li><tt>close</tt></li>
* <li><tt>minimize</tt></li>
* <li><tt>maximize</tt></li>
* <li><tt>restore</tt></li>
* <li><tt>gear</tt></li>
* <li><tt>pin</tt></li>
* <li><tt>unpin</tt></li>
* <li><tt>right</tt></li>
* <li><tt>left</tt></li>
* <li><tt>up</tt></li>
* <li><tt>down</tt></li>
* <li><tt>refresh</tt></li>
* <li><tt>minus</tt></li>
* <li><tt>plus</tt></li>
* <li><tt>help</tt></li>
* <li><tt>search</tt></li>
* <li><tt>save</tt></li>
* <li><tt>print</tt></li>
* </ul></div></li>
* <li><b>handler</b>: Function<div class="sub-desc"><b> 必须的。Required.</b> 点击后执行的函数。它传入的参数有:
* The function tocall when clicked. Arguments passed are:<ul>
* <li><b>event</b> : Ext.EventObject<div class="sub-desc">单击事件。The click event.</div></li>
* <li><b>toolEl</b> : Ext.Element<div class="sub-desc">工具元素(tool Element) The tool Element.</div></li>
* <li><b>panel</b> : Ext.Panel<div class="sub-desc">面板。The host Panel</div></li>
* <li><b>tc</b> : Ext.Panel<div class="sub-desc">The tool configuration object</div></li>
* </ul></div></li>
* <li><b>stopEvent</b> : Boolean<div class="sub-desc">默认为true。false的话表示点击事件停止衍生。
* Defaults to true. Specify as false to allow click event to propagate.</div></li>
* <li><b>scope</b> : Object<div class="sub-desc">调用处理函数的作用域。The scope in which to call the handler.</div></li>
* <li><b>qtip</b> : String/Object<div class="sub-desc">提示字符串,或{@link Ext.QuickTip#register}的配置参数。
* A tip string, or a config argument to {@link Ext.QuickTip#register}</div></li>
* <li><b>hidden</b> : Boolean<div class="sub-desc">True表示为渲染为隐藏。True to initially render hidden.</div></li>
* <li><b>on</b> : Object<div class="sub-desc">特定事件侦听器的配置对象,格式形如{@link #addListener}的参数。
* 侦听器的配置对象格式应如{@link #addListener}。A listener config object specifiying
* event listeners in the format of an argument to {@link #addListener}</div></li>
* </ul></div>
* 用法举例: Example usage:
* <pre><code>
tools:[{
id:'refresh',
qtip: 'Refresh form Data',
// hidden:true,
handler: function(event, toolEl, panel){
// refresh logic
}
},
{
id:'help',
qtip: 'Get Help',
handler: function(event, toolEl, panel){
// whatever
}
}]
</code></pre>
* 注意面板关闭时的轮换按钮(toggle tool)的实现是分离出去,这些工具按钮只提供视觉上的按钮。
* 所需的功能必须由事件处理器提供以实现相应的行为。
* Note that apart from the toggle tool which is provided when a panel is
* collapsible, these tools only provide the visual button. Any required
* functionality must be provided by adding handlers that implement the
* necessary behavior.
*/
/**
* @cfg {Ext.Template/Ext.XTemplate} toolTemplate
* <p>
* 位于{@link #header}中的tools其模板是什么。默认是:
* A Template used to create tools in the {@link #header} Element. Defaults to:</p><pre><code>
new Ext.Template('<div class="x-tool x-tool-{id}">&#160;</div>')</code></pre>
* <p>
* 重写时,或者这是一个复杂的XTemplate。模板数据就是一给单独的配置对象而不会是一个数组,这点要与{@link #tools}比较。
* This may may be overridden to provide a custom DOM structure for tools based upon a more
* complex XTemplate. The template's data is a single tool configuration object (Not the entire Array)
* as specified in {@link #tools} Example:</p><pre><code>
var win = new Ext.Window({
tools: [{
id: 'download',
href: '/MyPdfDoc.pdf'
}],
toolTemplate: new Ext.XTemplate(
'<tpl if="id==\'download\'">',
'<a class="x-tool x-tool-pdf" href="{href}"></a>',
'</tpl>',
'<tpl if="id!=\'download\'">',
'<div class="x-tool x-tool-{id}">&#160;</div>',
'</tpl>'
),
width:500,
height:300,
closeAction:'hide'
});</code></pre>
* <p>
* 注意"x-tool-pdf"样式必须要对应好样式的定义,提供合适背景图片。
* Note that the CSS class "x-tool-pdf" should have an associated style rule which provides an appropriate background image.</p>
*/
/**
* @cfg {Boolean} hideCollapseTool
* True表示为不出 展开/收缩的轮换按钮,当{@link #collapsible} = true,false就显示(默认为false)。
* True to hide the expand/collapse toggle button when {@link #collapsible} = true, false to display it (defaults to false).
*/
/**
* @cfg {Boolean} titleCollapse
* True表示为允许单击头部区域任何一个位置都可收缩面板(当{@link #collapsible} = true)反之只允许单击工具按钮(默认为false)。
* True to allow expanding and collapsing the panel (when {@link #collapsible} = true) by clicking anywhere in the
* header bar, false to allow it only by clicking to tool button (defaults to false).
*/
/**
* @cfg {Boolean} autoScroll
* True表示为在面板body元素上,设置overflow:'auto'和出现滚动条false表示为裁剪所有溢出的内容(默认为false)。
* True to use overflow:'auto' on the panel's body element and show scroll bars automatically when necessary,
* false to clip any overflowing content (defaults to false).
*/
/**
* @cfg {Boolean} floating
* <p>
* True表示为浮动此面板(带有自动填充和投影的绝对定位),false表示为在其渲染的位置"就近"显示(默认为false)。
* True to float this Panel (absolute position it with automatic shimming and shadow), false to display it inline
* where it is rendered (defaults to false).</p>
* <p>
* 设置floating为true,将会在面板元素的基础上创建一个{@link Ext.Layer}
* 同时让面板显示到非正数的坐标上去了,不能正确显示。因此面板必须精确地设置渲染后的位置,也就是使用绝对的定位方式。
* (如:myPanel.setPosition(100,100);)
* Setting floating to true will create an {@link Ext.Layer} encapsulating this Panel's Element and
* display the Panel at negative offsets so that it is hidden. The position must be set explicitly after render
* (e.g., myPanel.setPosition(100,100);).</p>
* <p>
* 若一个浮动面板是没有固定其宽度的,这导致面板会填满与视图右方的区域。
* When floating a panel you should always assign a fixed width, otherwise it will be auto width and will expand
* to fill to the right edge of the viewport.</p>
* <p>
* 该属性也可以是创建那个{@link Ext.Layer}对象所用的配置项对象。
* This property may also be specified as an object to be used as the configuration object for
* the {@link Ext.Layer} that will be created.
*/
/**
* @cfg {Boolean/String} shadow
* True 表示为(或一个有效{@link Ext.Shadow#mode}值)在面板后显示投影效果(默认为'sides'四边)。
* 注意此项只当floating = true时有效。
* True (or a valid Ext.Shadow {@link Ext.Shadow#mode} value) to display a shadow behind the panel, false to
* display no shadow (defaults to 'sides'). Note that this option only applies when floating = true.
*/
/**
* @cfg {Number} shadowOffset
* 投影偏移的象素值(默认为4)。注意此项只当floating = true时有效。
* The number of pixels to offset the shadow if displayed (defaults to 4). Note that this option only applies
* when floating = true.
*/
/**
* @cfg {Boolean} shim
* False表示为禁止用iframe填充,有些浏览器可能需要设置(默认为true)。
* 注意此项只当floating = true时有效。
* False to disable the iframe shim in browsers which need one (defaults to true). Note that this option
* only applies when floating = true.
*/
/**
* @cfg {String/Object} html
* 一段HTML片段,或{@link Ext.DomHelper DomHelper}配置项作为面板body内容(默认为 '')。
* 面板的afterRender方法负责HTML内容的加入这一过程,所以render事件触发的时刻document还没有所说的HTML内容。
* 该部分的内容又比{@link #contentEl}的显示位置而居前。
* An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use
* as the panel's body content (defaults to ''). The HTML content is added by the Panel's
* afterRender method, and so the document will not contain this HTML at the time the render
* event is fired. This content is inserted into the body <i>before</i> any configured
* {@link #contentEl} is appended.
*/
/**
* @cfg {String} contentEl
* 用现有HTML节点的内容作为面板body的内容(缺省为'')。
* 面板的afterRender方法负责了此HTML元素的加入到面板body中去。
* 该部分的内容又比{@link #html HTML}的显示位置而居后,所以render事件触发的时刻document还没有所说的HTML内容。
* The id of an existing HTML node to use as the panel's body content (defaults to '').
* specified Element is appended to the Panel's body Element by the Panel's afterRender method
* <i>after any configured {@link #html HTML} has been inserted</i>, and so the document will
* not contain this HTML at the time the render event is fired.
*/
/**
* @cfg {Object/Array} keys
* KeyMap的配置项对象(格式形如:{@link Ext.KeyMap#addBinding})。
* 可用于将key分配到此面板(缺省为null)。
* A KeyMap config object (in the format expected by {@link Ext.KeyMap#addBinding} used to assign custom key
* handling to this panel (defaults to null).
*/
/**
* @cfg {Boolean} draggable
* <p>True表示为激活此面板的拖动(默认为false)。
* True to enable dragging of this Panel (defaults to false).</p>
* <p>虽然Ext.Panel.DD是一个内部类并未归档的,但亦可自定义拖放(drag/drop)的实现,具体做法是传入一个Ext.Panel.DD的配置代替true值。
* 它是{@link Ext.dd.DragSource}的子类,所以可在实现{@link Ext.dd.DragDrop}的接口方法的过程中加入具体行为:
* For custom drag/drop implementations, an Ext.Panel.DD
* config could also be passed in this config instead of true. Ext.Panel.DD is an internal,
* undocumented class which moves a proxy Element around in place of the Panel's element, but
* provides no other behaviour during dragging or on drop. It is a subclass of
* {@link Ext.dd.DragSource}, so behaviour may be added by implementing the interface methods
* of {@link Ext.dd.DragDrop} eg:
* <pre><code>
new Ext.Panel({
title: 'Drag me',
x: 100,
y: 100,
renderTo: Ext.getBody(),
floating: true,
frame: true,
width: 400,
height: 200,
draggable: {
// 类Ext.Panel.DD的配置。Config option of Ext.Panel.DD class.
// 如果是浮动的面板, 原始位置上不显示容器的代理元素。It's a floating Panel, so do not show a placeholder proxy in the original position.
insertProxy: false,
// 当拖动DD对象时mousemove事件均会调用。Called for each mousemove event while dragging the DD object.
onDrag : function(e){
// 记录拖动代理的x、y位置,好让Panel最终能定位。 Record the x,y position of the drag proxy so that we can
// position the Panel at end of drag.
var pel = this.proxy.getEl();
this.x = pel.getLeft(true);
this.y = pel.getTop(true);
// 出现投影的话一定保证其对其。Keep the Shadow aligned if there is one.
var s = this.panel.getEl().shadow;
if (s) {
s.realign(this.x, this.y, pel.getWidth(), pel.getHeight());
}
},
// mouseup事件触发时发生。Called on the mouseup event.
endDrag : function(e){
this.panel.setPosition(this.x, this.y);
}
}
}).show();
</code></pre>
*/
/**
* @cfg {String} tabTip
* tooltip的innerHTML字符串(也可以html标签),当鼠标移至tab时会显示。
* 这时Ext.Panel充当的角色是 Ext.TabPanel某一子面板。记得Ext.QuickTips.init()必须初始化好。
* A string to be used as innerHTML (html tags are accepted) to show in a tooltip when mousing over the tab of
* a Ext.Panel which is an item of a Ext.TabPanel. Ext.QuickTips.init() must be called in order for the tips to
* render.
*/
/**
* @cfg {Boolean} disabled
* 渲染后就是禁用状态的(默认为false)。
* 重要的信息就是设面板为disabled的话,IE很可能会不能将其正确地施加disabled的蒙板元素。
* 如果你遇到这个问题,就要采用{@link afterlayout}事件来初始化disabled的状态:
* Render this panel disabled (default is false).
* An important note when using the disabled config on panels is
* that IE will often fail to initialize the disabled mask element correectly if the panel's layout has not yet
* completed by the time the Panel is disabled during the render process. If you experience this issue, you may
* need to instead use the {@link afterlayout} event to initialize the disabled state:
* <pre><code>
new Ext.Panel({
...
listeners: {
'afterlayout': {
fn: function(p){
p.disable();
},
single: true // 关键~事因布局还会来 important, as many layouts can occur
}
}
});
</code></pre>
*/
/**
* @cfg {Boolean} autoHeight
* True表示使用height:'auto',否则采用固定的高度(默认为false)。
* <b>注意</b>:设置autoHeight:true意味着面板自适应内容的高度,Ext就毫不施以管制。
* 当一些需要尺寸管控的场合,如处于布局之中,这样的设置就会引起滚动条不能正常地工作的问题,这是因为面板的高度是取决于内容而不是布局上的要求。
* True to use height:'auto', false to use fixed height (defaults to false). <b>Note</b>:
* Setting autoHeight:true means that the browser will manage the panel's height based on its contents, and that Ext will not manage it at
* all. If the panel is within a layout that manages dimensions (fit, border, etc.) then setting autoHeight:true
* can cause issues with scrolling and will not generally work as expected since the panel will take on the height
* of its contents rather than the height required by the Ext layout.
*/
/**
* @cfg {String} baseCls
* 作用在面板元素上的CSS样式类 (默认为 'x-panel')。
* The base CSS class to apply to this panel's element (defaults to 'x-panel').
*/
baseCls : 'x-panel',
/**
* @cfg {String} collapsedCls
* 当面板闭合时,面板元素的CSS样式类 (默认为 'x-panel-collapsed')。
* A CSS class to add to the panel's element after it has been collapsed (defaults to 'x-panel-collapsed').
*/
collapsedCls : 'x-panel-collapsed',
/**
* @cfg {Boolean} maskDisabled
* True表示为当面板不可用时进行遮罩(默认为true)。
* 当面板禁用时,总是会告知下面的元素亦要禁用,但遮罩是另外一种方式同样达到禁用的效果。
* True to mask the panel when it is disabled, false to not mask it (defaults to true). Either way, the panel
* will always tell its contained elements to disable themselves when it is disabled, but masking the panel
* can provide an additional visual cue that the panel is disabled.
*/
maskDisabled: true,
/**
* @cfg {Boolean} animCollapse
* True 表示为面板闭合过程附有动画效果(默认为true,在类 {@link Ext.Fx} 可用的情况下)。
* True to animate the transition when the panel is collapsed, false to skip the animation (defaults to true
* if the {@link Ext.Fx} class is available, otherwise false).
*/
animCollapse: Ext.enableFx,
/**
* @cfg {Boolean} headerAsText
* True表示为显示面板头部的标题(默认为 true)。
* True to display the panel title in the header, false to hide it (defaults to true).
*/
headerAsText: true,
/**
* @cfg {String} buttonAlign
* 在此面板上的按钮的对齐方式,有效值是'right,' 'left' and 'center'(默认为 'right')。 The alignment of any buttons added to this panel. Valid values are 'right,' 'left' and 'center' (defaults to 'right').
*/
buttonAlign: 'right',
/**
* @cfg {Boolean} collapsed
* True 表示为渲染面板后即闭合(默认为false)。
* True to render the panel collapsed, false to render it expanded (defaults to false).
*/
collapsed : false,
/**
* @cfg {Boolean} collapseFirst
* True 表示为展开/闭合的轮换按钮出现在面板头部的左方,false表示为在右方(默认为true)。
* True to make sure the collapse/expand toggle button always renders first (to the left of) any other tools
* in the panel's title bar, false to render it last (defaults to true).
*/
collapseFirst: true,
/**
* @cfg {Number} minButtonWidth
* 此面板上按钮的最小宽度(默认为75)。
* Minimum width in pixels of all buttons in this panel (defaults to 75)
*/
minButtonWidth:75,
/**
* @cfg {Boolean} unstyled
* 不带样式渲染面板。
* Renders the panel unstyled
*/
/**
* @cfg {String} elements
* 面板渲染后,要初始化面板元素的列表,用逗号分隔开。
* 正常情况下,该列表会在面板读取配置的时候就自动生成,假设没有进行配置,但结构元素有更新渲染的情况下,
* 就可根据指值得知结构元素是否已渲染的(例如,你打算在面板完成渲染后动态加入按钮或工具条)。
* 加入此列表中的这些元素后就在渲染好的面板中分配所需的载体(placeholders)。
* 有效值是:
* A comma-delimited list of panel elements to initialize when the panel is rendered. Normally, this list will be
* generated automatically based on the items added to the panel at config time, but sometimes it might be useful to
* make sure a structural element is rendered even if not specified at config time (for example, you may want
* to add a button or toolbar dynamically after the panel has been rendered). Adding those elements to this
* list will allocate the required placeholders in the panel when it is rendered. Valid values are<ul>
* <li><b>header</b></li>
* <li><b>tbar</b> (top bar)</li>
* <li><b>body</b></li>
* <li><b>bbar</b> (bottom bar)</li>
* <li><b>footer</b><li>
* </ul>
* 缺省为'body'. Defaults to 'body'.
*/
elements : 'body',
// protected - these could be used to customize the behavior of the window,
// but changing them would not be useful without further mofifications and
// could lead to unexpected or undesirable results.
toolTarget : 'header',
collapseEl : 'bwrap',
slideAnchor : 't',
disabledClass: '',
// private, notify box this class will handle heights
deferHeight: true,
// private
expandDefaults: {
duration:.25
},
// private
collapseDefaults: {
duration:.25
},
// private
initComponent : function(){
Ext.Panel.superclass.initComponent.call(this);
this.addEvents(
/**
* @event bodyresize
* 当面板的大小变化后触发。
* Fires after the Panel has been resized.
* @param {Ext.Panel} p 调节大小的面板。the Panel which has been resized.
* @param {Number} width 面板新宽度。The Panel's new width.
* @param {Number} height 面板新高度。The Panel's new height.
*/
'bodyresize',
/**
* @event titlechange
* 面板的标题有改动后触发。
* Fires after the Panel title has been set or changed.
* @param {Ext.Panel} p 标题被改动的那个面板。the Panel which has had its title changed.
* @param {String} t 新标题。The new title.
*/
'titlechange',
/**
* @event iconchange
* 当面板的图标类设置了或改变了触发。
* Fires after the Panel icon class has been set or changed.
* @param {Ext.Panel} p 图标类被改动的那个面板。the Panel which has had its icon class changed.
* @param {String} n 新图标类。The new icon class.
* @param {String} o 旧图标类。The old icon class.
*/
'iconchange',
/**
* @event collapse
* 当面板被闭合后触发。
* Fires after the Panel has been collapsed.
* @param {Ext.Panel} p 闭合的那个面板。the Panel that has been collapsed.
*/
'collapse',
/**
* @event expand
* 当面板被展开后触发。
* Fires after the Panel has been expanded.
* @param {Ext.Panel} p 展开的面板。The Panel that has been expanded.
*/
'expand',
/**
* @event beforecollapse
* 当面板被闭合之前触发。若句柄返回false则取消闭合的动作。
* Fires before the Panel is collapsed. A handler can return false to cancel the collapse.
* @param {Ext.Panel} p 正被闭合的面板。the Panel being collapsed.
* @param {Boolean} animate True表示闭合时带有动画效果。True if the collapse is animated, else false.
*/
'beforecollapse',
/**
* @event beforeexpand
* 当面板被展开之前触发。若句柄返回false则取消展开的动作。
* Fires before the Panel is expanded. A handler can return false to cancel the expand.
* @param {Ext.Panel} p 正被展开的面板。The Panel being expanded.
* @param {Boolean} animate True表示闭合时带有动画效果。True if the expand is animated, else false.
*/
'beforeexpand',
/**
* @event beforeclose
* 当面板被关闭之前触发。
* 注意面板不直接支持“关闭”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。
* 若句柄返回false则取消关闭的动作。
* Fires before the Panel is closed. Note that Panels do not directly support being closed, but some
* Panel subclasses do (like {@link Ext.Window}). This event only applies to such subclasses.
* A handler can return false to cancel the close.
* @param {Ext.Panel} p 正被关闭的面板。The Panel being closed.
*/
'beforeclose',
/**
* @event close
* 当面板被关闭后触发。
* 注意面板不直接支持“关闭”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。
* Fires after the Panel is closed. Note that Panels do not directly support being closed, but some
* Panel subclasses do (like {@link Ext.Window}).
* @param {Ext.Panel} p 已关闭的面板。The Panel that has been closed.
*/
'close',
/**
* @event activate
* 当面板视觉上取消活动后触发。
* 注意面板不直接支持“取消活动”,不过在面板的子类(如{@link Ext.Window})可支持即可调用该事件。
* 另外在TabPanel控制下子组件也会触发activate和deactivate事件。
* Fires after the Panel has been visually activated.
* Note that Panels do not directly support being activated, but some Panel subclasses
* do (like {@link Ext.Window}). Panels which are child Components of a TabPanel fire the
* activate and deactivate events under the control of the TabPanel.
* @param {Ext.Panel} p 激活的面板。The Panel that has been activated.
*/
'activate',
/**
* @event deactivate
* 当面板视觉上“反激活”过后触发。
* 注意面板不直接支持“反激活”,但面板某些子类就支持(如{@link Ext.Window})。
* TabPanel控制其子面板的激活与反激活事件。
* Fires after the Panel has been visually deactivated.
* Note that Panels do not directly support being deactivated, but some Panel subclasses
* do (like {@link Ext.Window}). Panels which are child Components of a TabPanel fire the
* activate and deactivate events under the control of the TabPanel.
* @param {Ext.Panel} p 已反激活的面板。The Panel that has been deactivated.
*/
'deactivate'
);
if(this.unstyled){
this.baseCls = 'x-plain';
}
// shortcuts
if(this.tbar){
this.elements += ',tbar';
if(typeof this.tbar == 'object'){
this.topToolbar = this.tbar;
}
delete this.tbar;
}
if(this.bbar){
this.elements += ',bbar';
if(typeof this.bbar == 'object'){
this.bottomToolbar = this.bbar;
}
delete this.bbar;
}
if(this.header === true){
this.elements += ',header';
delete this.header;
}else if(this.title && this.header !== false){
this.elements += ',header';
}
if(this.footer === true){
this.elements += ',footer';
delete this.footer;
}
if(this.buttons){
this.elements += ',footer';
var btns = this.buttons;
/**
* 面板的按钮组成的数组。只读的。
* This Panel's Array of buttons as created from the <tt>buttons</tt>
* config property. Read only.
* @type Array
* @property buttons
*/
this.buttons = [];
for(var i = 0, len = btns.length; i < len; i++) {
if(btns[i].render){ // button instance
this.buttons.push(btns[i]);
}else if(btns[i].xtype){
this.buttons.push(Ext.create(btns[i], 'button'));
}else{
this.addButton(btns[i]);
}
}
}
if(this.fbar){
this.elements += ',footer';
// if default button align and using fbar, align left by default
if(this.buttonAlign == 'right' && this.initialConfig.buttonAlign === undefined){
this.buttonAlign = 'left';
}
}
if(this.autoLoad){
this.on('render', this.doAutoLoad, this, {delay:10});
}
},
// private
createElement : function(name, pnode){
if(this[name]){
pnode.appendChild(this[name].dom);
return;
}
if(name === 'bwrap' || this.elements.indexOf(name) != -1){
if(this[name+'Cfg']){
this[name] = Ext.fly(pnode).createChild(this[name+'Cfg']);
}else{
var el = document.createElement('div');
el.className = this[name+'Cls'];
this[name] = Ext.get(pnode.appendChild(el));
}
if(this[name+'CssClass']){
this[name].addClass(this[name+'CssClass']);
}
if(this[name+'Style']){
this[name].applyStyles(this[name+'Style']);
}
}
},
// private
onRender : function(ct, position){
Ext.Panel.superclass.onRender.call(this, ct, position);
this.createClasses();
var el = this.el, d = el.dom;
el.addClass(this.baseCls);
if(d.firstChild){ // existing markup
this.header = el.down('.'+this.headerCls);
this.bwrap = el.down('.'+this.bwrapCls);
var cp = this.bwrap ? this.bwrap : el;
this.tbar = cp.down('.'+this.tbarCls);
this.body = cp.down('.'+this.bodyCls);
this.bbar = cp.down('.'+this.bbarCls);
this.footer = cp.down('.'+this.footerCls);
this.fromMarkup = true;
}
if(this.cls){
el.addClass(this.cls);
}
if(this.buttons){
this.elements += ',footer';
}
// This block allows for maximum flexibility and performance when using existing markup
// framing requires special markup
if(this.frame){
el.insertHtml('afterBegin', String.format(Ext.Element.boxMarkup, this.baseCls));
this.createElement('header', d.firstChild.firstChild.firstChild);
this.createElement('bwrap', d);
// append the mid and bottom frame to the bwrap
var bw = this.bwrap.dom;
var ml = d.childNodes[1], bl = d.childNodes[2];
bw.appendChild(ml);
bw.appendChild(bl);
var mc = bw.firstChild.firstChild.firstChild;
this.createElement('tbar', mc);
this.createElement('body', mc);
this.createElement('bbar', mc);
this.createElement('footer', bw.lastChild.firstChild.firstChild);
if(!this.footer){
this.bwrap.dom.lastChild.className += ' x-panel-nofooter';
}
}else{
this.createElement('header', d);
this.createElement('bwrap', d);
// append the mid and bottom frame to the bwrap
var bw = this.bwrap.dom;
this.createElement('tbar', bw);
this.createElement('body', bw);
this.createElement('bbar', bw);
this.createElement('footer', bw);
if(!this.header){
this.body.addClass(this.bodyCls + '-noheader');
if(this.tbar){
this.tbar.addClass(this.tbarCls + '-noheader');
}
}
}
if(this.padding !== undefined) {
this.body.setStyle('padding', this.body.addUnits(this.padding));
}
if(this.border === false){
this.el.addClass(this.baseCls + '-noborder');
this.body.addClass(this.bodyCls + '-noborder');
if(this.header){
this.header.addClass(this.headerCls + '-noborder');
}
if(this.footer){
this.footer.addClass(this.footerCls + '-noborder');
}
if(this.tbar){
this.tbar.addClass(this.tbarCls + '-noborder');
}
if(this.bbar){
this.bbar.addClass(this.bbarCls + '-noborder');
}
}
if(this.bodyBorder === false){
this.body.addClass(this.bodyCls + '-noborder');
}
this.bwrap.enableDisplayMode('block');
if(this.header){
this.header.unselectable();
// for tools, we need to wrap any existing header markup
if(this.headerAsText){
this.header.dom.innerHTML =
'<span class="' + this.headerTextCls + '">'+this.header.dom.innerHTML+'</span>';
if(this.iconCls){
this.setIconClass(this.iconCls);
}
}
}
if(this.floating){
this.makeFloating(this.floating);
}
if(this.collapsible){
this.tools = this.tools ? this.tools.slice(0) : [];
if(!this.hideCollapseTool){
this.tools[this.collapseFirst?'unshift':'push']({
id: 'toggle',
handler : this.toggleCollapse,
scope: this
});
}
if(this.titleCollapse && this.header){
this.mon(this.header, 'click', this.toggleCollapse, this);
this.header.setStyle('cursor', 'pointer');
}
}
if(this.tools){
var ts = this.tools;
this.tools = {};
this.addTool.apply(this, ts);
}else{
this.tools = {};
}
if(this.buttons && this.buttons.length > 0){
this.fbar = new Ext.Toolbar({
items: this.buttons,
toolbarCls: 'x-panel-fbar'
});
}
if(this.fbar){
this.fbar = Ext.create(this.fbar, 'toolbar');
this.fbar.enableOverflow = false;
if(this.fbar.items){
this.fbar.items.each(function(c){
c.minWidth = this.minButtonWidth;
}, this);
}
this.fbar.toolbarCls = 'x-panel-fbar';
var bct = this.footer.createChild({cls: 'x-panel-btns x-panel-btns-'+this.buttonAlign});
this.fbar.ownerCt = this;
this.fbar.render(bct);
bct.createChild({cls:'x-clear'});
}
if(this.tbar && this.topToolbar){
if(Ext.isArray(this.topToolbar)){
this.topToolbar = new Ext.Toolbar(this.topToolbar);
}else if(!this.topToolbar.events){
this.topToolbar = Ext.create(this.topToolbar, 'toolbar');
}
this.topToolbar.ownerCt = this;
this.topToolbar.render(this.tbar);
}
if(this.bbar && this.bottomToolbar){
if(Ext.isArray(this.bottomToolbar)){
this.bottomToolbar = new Ext.Toolbar(this.bottomToolbar);
}else if(!this.bottomToolbar.events){
this.bottomToolbar = Ext.create(this.bottomToolbar, 'toolbar');
}
this.bottomToolbar.ownerCt = this;
this.bottomToolbar.render(this.bbar);
}
},
/**
* 为该面板设置图标的样式类。此方法会覆盖当前现有的图标。
* Sets the CSS class that provides the icon image for this panel. This method will replace any existing
* icon class if one has already been set.
* @param {String} cls 新CSS样式类的名称。The new CSS class name
*/
setIconClass : function(cls){
var old = this.iconCls;
this.iconCls = cls;
if(this.rendered && this.header){
if(this.frame){
this.header.addClass('x-panel-icon');
this.header.replaceClass(old, this.iconCls);
}else{
var hd = this.header.dom;
var img = hd.firstChild && String(hd.firstChild.tagName).toLowerCase() == 'img' ? hd.firstChild : null;
if(img){
Ext.fly(img).replaceClass(old, this.iconCls);
}else{
Ext.DomHelper.insertBefore(hd.firstChild, {
tag:'img', src: Ext.BLANK_IMAGE_URL, cls:'x-panel-inline-icon '+this.iconCls
});
}
}
}
this.fireEvent('iconchange', this, cls, old);
},
// private
makeFloating : function(cfg){
this.floating = true;
this.el = new Ext.Layer(
typeof cfg == 'object' ? cfg : {
shadow: this.shadow !== undefined ? this.shadow : 'sides',
shadowOffset: this.shadowOffset,
constrain:false,
shim: this.shim === false ? false : undefined
}, this.el
);
},
/**
* 返回面板顶部区域的工具条。
* Returns the toolbar from the top (tbar) section of the panel.
* @return {Ext.Toolbar} The toolbar对象
*/
getTopToolbar : function(){
return this.topToolbar;
},
/**
* 返回面板底部区域的工具条。
* Returns the toolbar from the bottom (bbar) section of the panel.
* @return {Ext.Toolbar} The toolbar对象
*/
getBottomToolbar : function(){
return this.bottomToolbar;
},
/**
* 为面板添加按钮。注意必须在渲染之前才可以调用该方法。最佳的方法是通过{@link #buttons}的配置项添加按钮。
* Adds a button to this panel. Note that this method must be called prior to rendering. The preferred
* approach is to add buttons via the {@link #buttons} config.
* @param {String/Object} config 合法的{@link Ext.Button}配置项对象。若字符类型就表示这是按钮的提示文字。
* A valid {@link Ext.Button} config. A string will become the text for a default
* button config, an object will be treated as a button config object.
* @param {Function} handler 按钮被按下时执行的函数,等同{@link Ext.Button#click}。The function to be called on button {@link Ext.Button#click}
* @param {Object} scope 按钮触发时的事件处理函数所在作用域。The scope to use for the button handler function
* @return {Ext.Button} 已添加的按钮。The button that was added
*/
addButton : function(config, handler, scope){
var bc = {
handler: handler,
scope: scope,
minWidth: this.minButtonWidth,
hideParent:true
};
if(typeof config == "string"){
bc.text = config;
}else{
Ext.apply(bc, config);
}
var btn = new Ext.Button(bc);
if(!this.buttons){
this.buttons = [];
}
this.buttons.push(btn);
return btn;
},
// private
addTool : function(){
if(!this[this.toolTarget]) { // 没有渲染tools的地方!no where to render tools!
return;
}
if(!this.toolTemplate){
// 头一次执行时,就生成可供以后使用的tool模板(全局的,见Ext.Panel.prototype.toolTemplate = tt;这句)
// initialize the global tool template on first use
var tt = new Ext.Template(
'<div class="x-tool x-tool-{id}"> </div>'
);
tt.disableFormats = true;
tt.compile();
Ext.Panel.prototype.toolTemplate = tt;
}
for(var i = 0, a = arguments, len = a.length; i < len; i++) {
var tc = a[i];
if(!this.tools[tc.id]){
var overCls = 'x-tool-'+tc.id+'-over';
var t = this.toolTemplate.insertFirst((tc.align !== 'left') ? this[this.toolTarget] : this[this.toolTarget].child('span'), tc, true);
this.tools[tc.id] = t;
t.enableDisplayMode('block');
this.mon(t, 'click', this.createToolHandler(t, tc, overCls, this));
if(tc.on){
this.mon(t, tc.on);
}
if(tc.hidden){
t.hide();
}
if(tc.qtip){
if(typeof tc.qtip == 'object'){
Ext.QuickTips.register(Ext.apply({
target: t.id
}, tc.qtip));
} else {
t.dom.qtip = tc.qtip;
}
}
t.addClassOnOver(overCls);
}
}
},
doLayout : function(shallow){
Ext.Panel.superclass.doLayout.call(this, shallow);
if(this.topToolbar){
this.topToolbar.doLayout();
}
if(this.bottomToolbar){
this.bottomToolbar.doLayout();
}
if(this.fbar){
this.fbar.doLayout();
}
return this;
},
// private
onShow : function(){
if(this.floating){
return this.el.show();
}
Ext.Panel.superclass.onShow.call(this);
},
// private
onHide : function(){
if(this.floating){
return this.el.hide();
}
Ext.Panel.superclass.onHide.call(this);
},
// private
createToolHandler : function(t, tc, overCls, panel){
return function(e){
t.removeClass(overCls);
if(tc.stopEvent !== false){
e.stopEvent();
}
if(tc.handler){
tc.handler.call(tc.scope || t, e, t, panel, tc);
}
};
},
// private
afterRender : function(){
if(this.floating && !this.hidden && !this.initHidden){
this.el.show();
}
if(this.title){
this.setTitle(this.title);
}
this.setAutoScroll();
if(this.html){
this.body.update(typeof this.html == 'object' ?
Ext.DomHelper.markup(this.html) :
this.html);
delete this.html;
}
if(this.contentEl){
var ce = Ext.getDom(this.contentEl);
Ext.fly(ce).removeClass(['x-hidden', 'x-hide-display']);
this.body.dom.appendChild(ce);
}
if(this.collapsed){
this.collapsed = false;
this.collapse(false);
}
Ext.Panel.superclass.afterRender.call(this); // do sizing calcs last
this.initEvents();
},
// private
setAutoScroll : function(){
if(this.rendered && this.autoScroll){
var el = this.body || this.el;
if(el){
el.setOverflow('auto');
}
}
},
// private
getKeyMap : function(){
if(!this.keyMap){
this.keyMap = new Ext.KeyMap(this.el, this.keys);
}
return this.keyMap;
},
// private
initEvents : function(){
if(this.keys){
this.getKeyMap();
}
if(this.draggable){
this.initDraggable();
}
},
// private
initDraggable : function(){
/**
* <p>如果面板的{@link #draggable}的配置被打开,那么该属性的值就是一个{@link Ext.dd.DragSource}实例,代表着是谁负责拖动该面板。
* If this Panel is configured {@link #draggable}, this property will contain
* an instance of {@link Ext.dd.DragSource} which handles dragging the Panel.</p>
* 为了定位拖放过程中的每一个阶段,开发人员必须提供抽象方法{@link Ext.dd.DragSource}的一个实作。请参阅{@link #draggable}。
* The developer must provide implementations of the abstract methods of {@link Ext.dd.DragSource}
* in order to supply behaviour for each stage of the drag/drop process. See {@link #draggable}.
* @type Ext.dd.DragSource.
* @property dd
*/
this.dd = new Ext.Panel.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable);
},
// private
beforeEffect : function(){
if(this.floating){
this.el.beforeAction();
}
this.el.addClass('x-panel-animated');
},
// private
afterEffect : function(){
this.syncShadow();
this.el.removeClass('x-panel-animated');
},
// private - 封装一下动画效果 wraps up an animation param with internal callbacks
createEffect : function(a, cb, scope){
var o = {
scope:scope,
block:true
};
if(a === true){
o.callback = cb;
return o;
}else if(!a.callback){
o.callback = cb;
}else { // wrap it up
o.callback = function(){
cb.call(scope);
Ext.callback(a.callback, a.scope);
};
}
return Ext.applyIf(o, a);
},
/**
* 闭合面板body隐藏其内容。
* 触发{@link #beforecollapse}事件,如返回false则取消展开的动作。
* Collapses the panel body so that it becomes hidden. Fires the {@link #beforecollapse} event which will
* cancel the collapse action if it returns false.
* @param {Boolean} animate True表示为转换状态时出现动画,(默认为面板{@link #animCollapse}的配置值)。
* True to animate the transition, else false (defaults to the value of the
* {@link #animCollapse} panel config)
* @return {Ext.Panel} this
*/
collapse : function(animate){
if(this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforecollapse', this, animate) === false){
return;
}
var doAnim = animate === true || (animate !== false && this.animCollapse);
this.beforeEffect();
this.onCollapse(doAnim, animate);
return this;
},
// private
onCollapse : function(doAnim, animArg){
if(doAnim){
this[this.collapseEl].slideOut(this.slideAnchor,
Ext.apply(this.createEffect(animArg||true, this.afterCollapse, this),
this.collapseDefaults));
}else{
this[this.collapseEl].hide();
this.afterCollapse();
}
},
// private
afterCollapse : function(){
this.collapsed = true;
this.el.addClass(this.collapsedCls);
this.afterEffect();
this.fireEvent('collapse', this);
},
/**
* 展开面板的主体部分,显示全部。这会触发{@link #beforeexpand}的事件,若事件处理函数返回false那么这个方法将失效。
* Expands the panel body so that it becomes visible. Fires the {@link #beforeexpand} event which will
* cancel the expand action if it returns false.
* @param {Boolean} animate True 表示为转换状态时出现动画(默认为面板{@link #animCollapse}的配置值)。True to animate the transition, else false (defaults to the value of the
* {@link #animCollapse} panel config)
* @return {Ext.Panel} this
*/
expand : function(animate){
if(!this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforeexpand', this, animate) === false){
return;
}
var doAnim = animate === true || (animate !== false && this.animCollapse);
this.el.removeClass(this.collapsedCls);
this.beforeEffect();
this.onExpand(doAnim, animate);
return this;
},
// private
onExpand : function(doAnim, animArg){
if(doAnim){
this[this.collapseEl].slideIn(this.slideAnchor,
Ext.apply(this.createEffect(animArg||true, this.afterExpand, this),
this.expandDefaults));
}else{
this[this.collapseEl].show();
this.afterExpand();
}
},
// private
afterExpand : function(){
this.collapsed = false;
this.afterEffect();
this.fireEvent('expand', this);
},
/**
* 根据面板的当前状态,采取相应的{@link #expand}或{@link #collapse}。
* Shortcut for performing an {@link #expand} or {@link #collapse} based on the current state of the panel.
* @param {Boolean} animate True 表示为转换状态时出现动画(默认为面板{@link #animCollapse}的配置值)。True to animate the transition, else false (defaults to the value of the
* {@link #animCollapse} panel config)
* @return {Ext.Panel} this
*/
toggleCollapse : function(animate){
this[this.collapsed ? 'expand' : 'collapse'](animate);
return this;
},
// private
onDisable : function(){
if(this.rendered && this.maskDisabled){
this.el.mask();
}
Ext.Panel.superclass.onDisable.call(this);
},
// private
onEnable : function(){
if(this.rendered && this.maskDisabled){
this.el.unmask();
}
Ext.Panel.superclass.onEnable.call(this);
},
// private
onResize : function(w, h){
if(w !== undefined || h !== undefined){
if(!this.collapsed){
if(typeof w == 'number'){
w = this.adjustBodyWidth(w - this.getFrameWidth());
if(this.tbar){
this.tbar.setWidth(w);
if(this.topToolbar){
this.topToolbar.setSize(w);
}
}
if(this.bbar){
this.bbar.setWidth(w);
if(this.bottomToolbar){
this.bottomToolbar.setSize(w);
}
}
if(this.fbar && this.buttonAlign != 'center'){
this.fbar.setSize(w - this.fbar.container.getFrameWidth('lr'));
}
this.body.setWidth(w);
}else if(w == 'auto'){
this.body.setWidth(w);
}
if(typeof h == 'number'){
h = this.adjustBodyHeight(h - this.getFrameHeight());
this.body.setHeight(h);
}else if(h == 'auto'){
this.body.setHeight(h);
}
if(this.disabled && this.el._mask){
this.el._mask.setSize(this.el.dom.clientWidth, this.el.getHeight());
}
}else{
this.queuedBodySize = {width: w, height: h};
if(!this.queuedExpand && this.allowQueuedExpand !== false){
this.queuedExpand = true;
this.on('expand', function(){
delete this.queuedExpand;
this.onResize(this.queuedBodySize.width, this.queuedBodySize.height);
this.doLayout();
}, this, {single:true});
}
}
this.fireEvent('bodyresize', this, w, h);
}
this.syncShadow();
},
// private
adjustBodyHeight : function(h){
return h;
},
// private
adjustBodyWidth : function(w){
return w;
},
// private
onPosition : function(){
this.syncShadow();
},
/**
* 返回面板框架元素的宽度(不含body宽度)要取的body宽度参阅{@link #getInnerWidth}。
* Returns the width in pixels of the framing elements of this panel (not including the body width). To
* retrieve the body width see {@link #getInnerWidth}.
* @return {Number} 框架宽度。The frame width
*/
getFrameWidth : function(){
var w = this.el.getFrameWidth('lr')+this.bwrap.getFrameWidth('lr');
if(this.frame){
var l = this.bwrap.dom.firstChild;
w += (Ext.fly(l).getFrameWidth('l') + Ext.fly(l.firstChild).getFrameWidth('r'));
var mc = this.bwrap.dom.firstChild.firstChild.firstChild;
w += Ext.fly(mc).getFrameWidth('lr');
}
return w;
},
/**
* 返回面板框架元素的高度(包括顶部/底部工具条的高度)要取的body高度参阅{@link #getInnerHeight}。
* Returns the height in pixels of the framing elements of this panel (including any top and bottom bars and
* header and footer elements, but not including the body height). To retrieve the body height see {@link #getInnerHeight}.
* @return {Number} 框架高度。The frame height
*/
getFrameHeight : function(){
var h = this.el.getFrameWidth('tb')+this.bwrap.getFrameWidth('tb');
h += (this.tbar ? this.tbar.getHeight() : 0) +
(this.bbar ? this.bbar.getHeight() : 0);
if(this.frame){
var hd = this.el.dom.firstChild;
var ft = this.bwrap.dom.lastChild;
h += (hd.offsetHeight + ft.offsetHeight);
var mc = this.bwrap.dom.firstChild.firstChild.firstChild;
h += Ext.fly(mc).getFrameWidth('tb');
}else{
h += (this.header ? this.header.getHeight() : 0) +
(this.footer ? this.footer.getHeight() : 0);
}
return h;
},
/**
* 返回面板body元素的宽度(不含任何框架元素)要取的框架宽度参阅 {@link #getFrameWidth}。
* Returns the width in pixels of the body element (not including the width of any framing elements).
* For the frame width see {@link #getFrameWidth}.
* @return {Number} 宽度。The body width
*/
getInnerWidth : function(){
return this.getSize().width - this.getFrameWidth();
},
/**
* 返回面板body元素的高度(不包括任何框架元素的高度)要取的框架高度参阅{@link #getFrameHeight}。
* Returns the height in pixels of the body element (not including the height of any framing elements).
* For the frame height see {@link #getFrameHeight}.
* @return {Number} 高度。The body height
*/
getInnerHeight : function(){
return this.getSize().height - this.getFrameHeight();
},
// private
syncShadow : function(){
if(this.floating){
this.el.sync(true);
}
},
// private
getLayoutTarget : function(){
return this.body;
},
/**
* <p>
* 设置面板的标题文本,你也可以在这里指定面板的图片(透过CSS样式类)。
* Sets the title text for the panel and optionally the icon class.</p>
* <p>
* 为了确保标题能被设置,一个面板的头部元素必不可少。具体说,是要让面板的标题非空,或者设置<tt><b>{@link #header}: true</b></tt>即可。
* In order to be able to set the title, a header element must have been created
* for the Panel. This is triggered either by configuring the Panel with a non-blank title,
* or configuring it with <tt><b>{@link #header}: true</b></tt>.</p>
* @param {String} title 要设置的标题。The title text to set
* @param {String} iconCls (可选的)定义该面板用户自定义的图标,这是一个CSS样式类的字符串。(optional)A user-defined CSS class that provides the icon image for this panel
*/
setTitle : function(title, iconCls){
this.title = title;
if(this.header && this.headerAsText){
this.header.child('span').update(title);
}
if(iconCls){
this.setIconClass(iconCls);
}
this.fireEvent('titlechange', this, title);
return this;
},
/**
* 获取该面板的{@link Ext.Updater}。主要是为面板的主体部分(body)提过面向Ajax的内容更新。
* Get the {@link Ext.Updater} for this panel. Enables you to perform Ajax updates of this panel's body.
* @return {Ext.Updater}对象。The Updater
*/
getUpdater : function(){
return this.body.getUpdater();
},
/**
* 利用XHR的访问加载远程的内容,立即显示在面板中。
* Loads this content panel immediately with content returned from an XHR call.
* @param {Object/String/Function} config 特定的配置项对象,可包含以下选项: A config object containing any of the following options:
<pre><code>
panel.load({
url: "your-url.php",
params: {param1: "foo", param2: "bar"}, // 或URL字符串,要已编码的。or a URL encoded string
callback: yourFunction,
scope: yourObject, // 回调函数的可选作用域 optional scope for the callback
discardUrl: false,
nocache: false,
text: "Loading...",
timeout: 30,
scripts: false
});
</code></pre>
* 其中必填的属性是url。至于可选的属性有nocache、text与scripts,分别代表禁止缓存(disableCaching)、加载中的提示信息和是否对脚本敏感,都是关联到面板的Updater实例。
* The only required property is url. The optional properties nocache, text and scripts
* are shorthand for disableCaching, indicatorText and loadScripts and are used to set their
* associated property on this panel Updater instance.
* @return {Ext.Panel} this
*/
load : function(){
var um = this.body.getUpdater();
um.update.apply(um, arguments);
return this;
},
// private
beforeDestroy : function(){
if(this.header){
this.header.removeAllListeners();
if(this.headerAsText){
Ext.Element.uncache(this.header.child('span'));
}
}
Ext.Element.uncache(
this.header,
this.tbar,
this.bbar,
this.footer,
this.body,
this.bwrap
);
if(this.tools){
for(var k in this.tools){
Ext.destroy(this.tools[k]);
}
}
if(this.buttons){
for(var b in this.buttons){
Ext.destroy(this.buttons[b]);
}
}
Ext.destroy(
this.topToolbar,
this.bottomToolbar,
this.fbar
);
Ext.Panel.superclass.beforeDestroy.call(this);
},
// private
createClasses : function(){
this.headerCls = this.baseCls + '-header';
this.headerTextCls = this.baseCls + '-header-text';
this.bwrapCls = this.baseCls + '-bwrap';
this.tbarCls = this.baseCls + '-tbar';
this.bodyCls = this.baseCls + '-body';
this.bbarCls = this.baseCls + '-bbar';
this.footerCls = this.baseCls + '-footer';
},
// private
createGhost : function(cls, useShim, appendTo){
var el = document.createElement('div');
el.className = 'x-panel-ghost ' + (cls ? cls : '');
if(this.header){
el.appendChild(this.el.dom.firstChild.cloneNode(true));
}
Ext.fly(el.appendChild(document.createElement('ul'))).setHeight(this.bwrap.getHeight());
el.style.width = this.el.dom.offsetWidth + 'px';;
if(!appendTo){
this.container.dom.appendChild(el);
}else{
Ext.getDom(appendTo).appendChild(el);
}
if(useShim !== false && this.el.useShim !== false){
var layer = new Ext.Layer({shadow:false, useDisplay:true, constrain:false}, el);
layer.show();
return layer;
}else{
return new Ext.Element(el);
}
},
// private
doAutoLoad : function(){
var u = this.body.getUpdater();
if(this.renderer){
u.setRenderer(this.renderer);
}
u.update(typeof this.autoLoad == 'object' ? this.autoLoad : {url: this.autoLoad});
},
/**
* 获取某个工具项的id。
* Retrieve a tool by id.
* @param {String} id
* @return {Object} tool
*/
getTool: function(id) {
return this.tools[id];
}
/**
* @cfg {String} autoEl @hide
*/
});
Ext.reg('panel', Ext.Panel);
| 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.SplitBar
* @extends Ext.util.Observable
* 由DOM元素创建可拖拽的分割控件(可以拖拽和改变的大小的元素)。<br />
* Creates draggable splitter bar functionality from two elements (element to be dragged and element to be resized).
* <br><br>
* Usage:
* <pre><code>
var split = new Ext.SplitBar("elementToDrag", "elementToSize",
Ext.SplitBar.HORIZONTAL, Ext.SplitBar.LEFT);
split.setAdapter(new Ext.SplitBar.AbsoluteLayoutAdapter("container"));
split.minSize = 100;
split.maxSize = 600;
split.animate = true;
split.on('moved', splitterMoved);
</code></pre>
* @constructor 创建一个新的分割控件。Create a new SplitBar
* @param {Mixed} dragElement 拖拽到元素,作为分割控件被拖拽到元素。The element to be dragged and act as the SplitBar.
* @param {Mixed} resizingElement 根据SplitBar到拖拽缩放大小的元素。The element to be resized based on where the SplitBar element is dragged
* @param {Number} orientation (可选的)Ext.SplitBar.HORIZONTAL或者Ext.SplitBar.VERTICAL方向(默认为 HORIZONTAL)。(optional)Either Ext.SplitBar.HORIZONTAL or Ext.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
* @param {Number} placement (可选的)水平方向上,Ext.SplitBar.LEFT或者Ext.SplitBar.RIGHT垂直方向上,
* Ext.SplitBar.TOP或Ext.SplitBar.BOTTOM(默认的会根据SplitBar初始化的位置自己决定)。
* (optional)Either Ext.SplitBar.LEFT or Ext.SplitBar.RIGHT for horizontal or
Ext.SplitBar.TOP or Ext.SplitBar.BOTTOM for vertical. (By default, this is determined automatically by the initial
position of the SplitBar).
*/
Ext.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){
/** @private 私有的 */
this.el = Ext.get(dragElement, true);
this.el.dom.unselectable = "on";
/** @private 私有的 */
this.resizingEl = Ext.get(resizingElement, true);
/**
* @private
* 分割控件的方向。Ext.SplitBar.HORIZONTAL或者Ext.SplitBar.VERTICAL(默认为 HORIZONTAL)。
* 如果在分割控件被创建后修改该属性,placement属性必须要手动修改。
* The orientation of the split. Either Ext.SplitBar.HORIZONTAL or Ext.SplitBar.VERTICAL. (Defaults to HORIZONTAL)
* Note: If this is changed after creating the SplitBar, the placement property must be manually updated
* @type Number
*/
this.orientation = orientation || Ext.SplitBar.HORIZONTAL;
/**
* 移动该SplitBar的步长值,单位是像素。<i>undefined</i>的话,表示SplitBar移动的比较顺滑。
* The increment, in pixels by which to move this SplitBar. When <i>undefined</i>, the SplitBar moves smoothly.
* @type Number
* @property tickSize
*/
/**
* 可缩放元素的最小值(默认为0)。
* The minimum size of the resizing element. (Defaults to 0)
* @type Number
*/
this.minSize = 0;
/**
* 可缩放元素的最大值(默认为 2000)。
* The maximum size of the resizing element. (Defaults to 2000)
* @type Number
*/
this.maxSize = 2000;
/**
* 大小变化时是否产生动画效果。
* Whether to animate the transition to the new size
* @type Boolean
*/
this.animate = false;
/**
* 拖拽到时候是否在页面上生成透明层。允许跨iframes拖拽。
* Whether to create a transparent shim that overlays the page when dragging, enables dragging across iframes.
* @type Boolean
*/
this.useShim = false;
/** @private 私有的 */
this.shim = null;
if(!existingProxy){
/** @private 私有的*/
this.proxy = Ext.SplitBar.createProxy(this.orientation);
}else{
this.proxy = Ext.get(existingProxy).dom;
}
/** @private 私有的 */
this.dd = new Ext.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id});
/** @private 私有的 */
this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this);
/** @private 私有的 */
this.dd.endDrag = this.onEndProxyDrag.createDelegate(this);
/** @private 私有的 */
this.dragSpecs = {};
/**
* @private
* 放置和重置元素大小的适配器。
* The adapter to use to positon and resize elements
*/
this.adapter = new Ext.SplitBar.BasicLayoutAdapter();
this.adapter.init(this);
if(this.orientation == Ext.SplitBar.HORIZONTAL){
/** @private 私有的 */
this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Ext.SplitBar.LEFT : Ext.SplitBar.RIGHT);
this.el.addClass("x-splitbar-h");
}else{
/** @private 私有的 */
this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Ext.SplitBar.TOP : Ext.SplitBar.BOTTOM);
this.el.addClass("x-splitbar-v");
}
this.addEvents(
/**
* @event resize
* 当分割控件移动的时候激发({@link #event-moved}的别名)。
* Fires when the splitter is moved (alias for {@link #moved})
* @param {Ext.SplitBar} this
* @param {Number} newSize 新的高度或者宽度。the new width or height
*/
"resize",
/**
* @event moved
* 当分割控件移动的时候激发。
* Fires when the splitter is moved
* @param {Ext.SplitBar} this
* @param {Number} newSize 新的高度或者宽度。the new width or height
*/
"moved",
/**
* @event beforeresize
* 当分割控件被拖拽的时候激发。
* Fires before the splitter is dragged
* @param {Ext.SplitBar} this
*/
"beforeresize",
"beforeapply"
);
Ext.SplitBar.superclass.constructor.call(this);
};
Ext.extend(Ext.SplitBar, Ext.util.Observable, {
onStartProxyDrag : function(x, y){
this.fireEvent("beforeresize", this);
this.overlay = Ext.DomHelper.append(document.body, {cls: "x-drag-overlay", html: " "}, true);
this.overlay.unselectable();
this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
this.overlay.show();
Ext.get(this.proxy).setDisplayed("block");
var size = this.adapter.getElementSize(this);
this.activeMinSize = this.getMinimumSize();
this.activeMaxSize = this.getMaximumSize();
var c1 = size - this.activeMinSize;
var c2 = Math.max(this.activeMaxSize - size, 0);
if(this.orientation == Ext.SplitBar.HORIZONTAL){
this.dd.resetConstraints();
this.dd.setXConstraint(
this.placement == Ext.SplitBar.LEFT ? c1 : c2,
this.placement == Ext.SplitBar.LEFT ? c2 : c1,
this.tickSize
);
this.dd.setYConstraint(0, 0);
}else{
this.dd.resetConstraints();
this.dd.setXConstraint(0, 0);
this.dd.setYConstraint(
this.placement == Ext.SplitBar.TOP ? c1 : c2,
this.placement == Ext.SplitBar.TOP ? c2 : c1,
this.tickSize
);
}
this.dragSpecs.startSize = size;
this.dragSpecs.startPoint = [x, y];
Ext.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y);
},
/**
* @private 私有的
* 拖拽后由DDProxy调用。
* Called after the drag operation by the DDProxy
*/
onEndProxyDrag : function(e){
Ext.get(this.proxy).setDisplayed(false);
var endPoint = Ext.lib.Event.getXY(e);
if(this.overlay){
Ext.destroy(this.overlay);
delete this.overlay;
}
var newSize;
if(this.orientation == Ext.SplitBar.HORIZONTAL){
newSize = this.dragSpecs.startSize +
(this.placement == Ext.SplitBar.LEFT ?
endPoint[0] - this.dragSpecs.startPoint[0] :
this.dragSpecs.startPoint[0] - endPoint[0]
);
}else{
newSize = this.dragSpecs.startSize +
(this.placement == Ext.SplitBar.TOP ?
endPoint[1] - this.dragSpecs.startPoint[1] :
this.dragSpecs.startPoint[1] - endPoint[1]
);
}
newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize);
if(newSize != this.dragSpecs.startSize){
if(this.fireEvent('beforeapply', this, newSize) !== false){
this.adapter.setElementSize(this, newSize);
this.fireEvent("moved", this, newSize);
this.fireEvent("resize", this, newSize);
}
}
},
/**
* 获取分割控件的适配器。
* Get the adapter this SplitBar uses
* @return 适配器对象。The adapter object
*/
getAdapter : function(){
return this.adapter;
},
/**
* 设置分割控件的适配器。
* Set the adapter this SplitBar uses
* @param {Object} adapter SplitBar适配器对象。A SplitBar adapter object
*/
setAdapter : function(adapter){
this.adapter = adapter;
this.adapter.init(this);
},
/**
* 获取该元素可缩放的最小值。
* Gets the minimum size for the resizing element
* @return {Number} 最小尺寸。The minimum size
*/
getMinimumSize : function(){
return this.minSize;
},
/**
* 设置该元素可缩放的最小值。
* Sets the minimum size for the resizing element
* @param {Number} minSize 最小的尺寸值。The minimum size
*/
setMinimumSize : function(minSize){
this.minSize = minSize;
},
/**
* 获取该元素可缩放的最大值。
* Gets the maximum size for the resizing element
* @return {Number} 最大尺寸值。The maximum size
*/
getMaximumSize : function(){
return this.maxSize;
},
/**
* 设置该元素可缩放的最大值。
* Sets the maximum size for the resizing element
* @param {Number} maxSize 最大尺寸值。The maximum size
*/
setMaximumSize : function(maxSize){
this.maxSize = maxSize;
},
/**
* 设置该元素初始化可缩放值。
* Sets the initialize size for the resizing element
* @param {Number} size 初始化值。The initial size
*/
setCurrentSize : function(size){
var oldAnimate = this.animate;
this.animate = false;
this.adapter.setElementSize(this, size);
this.animate = oldAnimate;
},
/**
* 毁分割控件发。
* Destroy this splitbar.
* @param {Boolean} removeEl 一处分割控件。True to remove the element
*/
destroy : function(removeEl){
if(this.shim){
this.shim.remove();
}
this.dd.unreg();
Ext.destroy(Ext.get(this.proxy));
if(removeEl){
this.el.remove();
}
}
});
/**
* @private static
* 静态的
* 创建自己的代理元素,使得在不同的浏览器中,组件的大小都一致。使用背景色而不使用borders。
* Create our own proxy element element. So it will be the same same size on all browsers, we won't use borders. Instead we use a background color.
*/
Ext.SplitBar.createProxy = function(dir){
var proxy = new Ext.Element(document.createElement("div"));
proxy.unselectable();
var cls = 'x-splitbar-proxy';
proxy.addClass(cls + ' ' + (dir == Ext.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v'));
document.body.appendChild(proxy.dom);
return proxy.dom;
};
/**
* @class Ext.SplitBar.BasicLayoutAdapter
* 默认的适配器。假设分割组件和可伸缩组件没有被预先定位,并且只能获取/设置元素的宽度。一般用于基于table到布局。
* Default Adapter. It assumes the splitter and resizing element are not positioned
* elements and only gets/sets the width of the element. Generally used for table based layouts.
*/
Ext.SplitBar.BasicLayoutAdapter = function(){
};
Ext.SplitBar.BasicLayoutAdapter.prototype = {
// do nothing for now
init : function(s){
},
/**
* 在拖拽操作前调用,用于获取被缩放的元素的当前大小。
* Called before drag operations to get the current size of the resizing element.
* @param {Ext.SplitBar} s 使用该适配器的SplitBar对象。The SplitBar using this adapter
*/
getElementSize : function(s){
if(s.orientation == Ext.SplitBar.HORIZONTAL){
return s.resizingEl.getWidth();
}else{
return s.resizingEl.getHeight();
}
},
/**
* 在拖拽操作后调用,用于设置被缩放的元素的大小。
* Called after drag operations to set the size of the resizing element.
* @param {Ext.SplitBar} s 使用该适配器的SplitBar对象。The SplitBar using this adapter
* @param {Number} newSize 要设置的新尺寸。The new size to set
* @param {Function} onComplete 缩放完成后调用的函数。A function to be invoked when resizing is complete
*/
setElementSize : function(s, newSize, onComplete){
if(s.orientation == Ext.SplitBar.HORIZONTAL){
if(!s.animate){
s.resizingEl.setWidth(newSize);
if(onComplete){
onComplete(s, newSize);
}
}else{
s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut');
}
}else{
if(!s.animate){
s.resizingEl.setHeight(newSize);
if(onComplete){
onComplete(s, newSize);
}
}else{
s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut');
}
}
}
};
/**
*@class Ext.SplitBar.AbsoluteLayoutAdapter
* @extends Ext.SplitBar.BasicLayoutAdapter
* 是分割控件与缩放元素对其的适配器。使用绝对定位的分割控件的时候使用。
* Adapter that moves the splitter element to align with the resized sizing element.
* Used with an absolute positioned SplitBar.
* @param {Mixed} container 包围绝对定位的分割控件的容器。如果该容器是document.body一定要给该控件指定一个ID。
* The container that wraps around the absolute positioned content. If it's
* document.body, make sure you assign an id to the body element.
*/
Ext.SplitBar.AbsoluteLayoutAdapter = function(container){
this.basic = new Ext.SplitBar.BasicLayoutAdapter();
this.container = Ext.get(container);
};
Ext.SplitBar.AbsoluteLayoutAdapter.prototype = {
init : function(s){
this.basic.init(s);
},
getElementSize : function(s){
return this.basic.getElementSize(s);
},
setElementSize : function(s, newSize, onComplete){
this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s]));
},
moveSplitter : function(s){
var yes = Ext.SplitBar;
switch(s.placement){
case yes.LEFT:
s.el.setX(s.resizingEl.getRight());
break;
case yes.RIGHT:
s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px");
break;
case yes.TOP:
s.el.setY(s.resizingEl.getBottom());
break;
case yes.BOTTOM:
s.el.setY(s.resizingEl.getTop() - s.el.getHeight());
break;
}
}
};
/**
* 方向常量-创建一个垂直分割控件。
* Orientation constant - Create a vertical SplitBar
* @static
* @type Number
*/
Ext.SplitBar.VERTICAL = 1;
/**
* 方向常量-创建一个水平分割控件。
* Orientation constant - Create a horizontal SplitBar
* @static
* @type Number
*/
Ext.SplitBar.HORIZONTAL = 2;
/**
* 定位常量 - 缩放元素在分割控件的左边。
* Placement constant - The resizing element is to the left of the splitter element
* @static
* @type Number
*/
Ext.SplitBar.LEFT = 1;
/**
* 定位常量 - 缩放元素在分割控件的右边。
* Placement constant - The resizing element is to the right of the splitter element
* @static
* @type Number
*/
Ext.SplitBar.RIGHT = 2;
/**
* 定位常量 - 缩放元素在分割控件的上面。
* Placement constant - The resizing element is positioned above the splitter element
* @static
* @type Number
*/
Ext.SplitBar.TOP = 3;
/**
* 定位常量 - 缩放元素在分割控件的下面。
* Placement constant - The resizing element is positioned under splitter element
* @static
* @type Number
*/
Ext.SplitBar.BOTTOM = 4;
| JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.LoadMask
* 一个简单的工具类,用于在加载数据时为元素做出类似于遮罩的效果。
* 对于有可用的{@link Ext.data.Store},可将效果与Store的加载达到同步,而mask本身会被缓存以备复用。
* 而对于其他元素,这个遮照类会替换元素本身的UpdateManager加载指示器,并在初始化完毕后销毁。
* A simple utility class for generically masking elements while loading data. If the {@link #store}
* config option is specified, the masking will be automatically synchronized with the store's loading
* process and the mask element will be cached for reuse. For all other elements, this mask will replace the
* element's Updater load indicator and will be destroyed after the initial load.
* <p>用法举例:Example usage:</p>
*<pre><code>
// Basic mask:
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
</code></pre>
* @constructor 创建新的LoadMask对象。Create a new LoadMask
* @param {Mixed} el 元素、DOM节点或id。The element or DOM node, or its id
* @param {Object} config 配置项对象。The config object
*/
Ext.LoadMask = function(el, config){
this.el = Ext.get(el);
Ext.apply(this, config);
if(this.store){
this.store.on('beforeload', this.onBeforeLoad, this);
this.store.on('load', this.onLoad, this);
this.store.on('loadexception', this.onLoad, this);
this.removeMask = Ext.value(this.removeMask, false);
}else{
var um = this.el.getUpdater();
um.showLoadIndicator = false; // disable the default indicator
um.on('beforeupdate', this.onBeforeLoad, this);
um.on('update', this.onLoad, this);
um.on('failure', this.onLoad, this);
this.removeMask = Ext.value(this.removeMask, true);
}
};
Ext.LoadMask.prototype = {
/**
* @cfg {Ext.data.Store} store
* 可选地你可以为该蒙板绑定一个Store对象。当Store的load请求被发起就显示该蒙版,不论load成功或失败之后都隐藏该蒙板。
* Optional Store to which the mask is bound. The mask is displayed when a load request is issued, and
* hidden on either load sucess, or load fail.
*/
/**
* @cfg {Boolean} removeMask True表示为一次性使用,即加载之后自动销毁(页面加载时有用),false表示为多次使用模版效果,保留这个mask(例如,页面上数据的加载)。默认为false。
* True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
* False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
*/
/**
* @cfg {String} msg
* 加载信息中显示文字(默认为'Loading...')。
* The text to display in a centered loading message box (defaults to 'Loading...')
*/
msg : 'Loading...',
/**
* @cfg {String} msgCls
* 加载信息元素的样式(默认为"x-mask-loading")。
* The CSS class to apply to the loading message element (defaults to "x-mask-loading")
*/
msgCls : 'x-mask-loading',
/**
* 只读的。True表示为mask已被禁止,所以不会显示出来(默认为false)。
* Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
* @type Boolean
*/
disabled: false,
/**
* 禁用遮罩致使遮罩不会被显示。
* Disables the mask to prevent it from being displayed
*/
disable : function(){
this.disabled = true;
},
/**
* 启用遮罩以显示。
* Enables the mask so that it can be displayed
*/
enable : function(){
this.disabled = false;
},
// private
onLoad : function(){
this.el.unmask(this.removeMask);
},
// private
onBeforeLoad : function(){
if(!this.disabled){
this.el.mask(this.msg, this.msgCls);
}
},
/**
* 在已配置元素之前显示LoadMask。
* Show this LoadMask over the configured Element.
*/
show: function(){
this.onBeforeLoad();
},
/**
* 隐藏此LoadMask。
* Hide this LoadMask.
*/
hide: function(){
this.onLoad();
},
// private
destroy : function(){
if(this.store){
this.store.un('beforeload', this.onBeforeLoad, this);
this.store.un('load', this.onLoad, this);
this.store.un('loadexception', this.onLoad, this);
}else{
var um = this.el.getUpdater();
um.un('beforeupdate', this.onBeforeLoad, this);
um.un('update', this.onLoad, this);
um.un('failure', this.onLoad, this);
}
}
}; | JavaScript |
/*
* 项目地址: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.Component
* @extends Ext.util.Observable
* <p>
* 全体Ext组件的基类。Component下所有的子类均按照统一的Ext组件生命周期(lifeycle)执行运作,
* 即创建、渲染和销毁(creation、rendering和destruction),并具有隐藏/显示、启用/禁用的基本行为特性。
* Component下的子类可被延时渲染(lazy-rendered)成为{@link Ext.Container}的一种,同时自动登记到{@link Ext.ComponentMgr},这样便可在后面的代码使用{@link Ext#getCmp}获取组件的引用。
* 当需要以盒子模型(box model)的模式管理这些可视的器件(widgets),这些器件就必须从Component(或{@link Ext.BoxComponent})继承。<br />
* Base class for all Ext components.
* All subclasses of Component can automatically participate in the standard
* Ext component lifecycle of creation, rendering and destruction.
* They also have automatic support for basic hide/show
* and enable/disable behavior.
* Component allows any subclass to be lazy-rendered into any {@link Ext.Container} and
* to be automatically registered with the {@link Ext.ComponentMgr} so that it can be referenced at any time via
* {@link Ext#getCmp}.
* All visual widgets that require rendering into a layout should subclass Component (or
* {@link Ext.BoxComponent} if managed box model handling is required).</p>
* <p>
* 可参阅教程<a href="http://extjs.com/learn/Tutorial:Creating_new_UI_controls_(Chinese)">Creating new UI controls</a>创建自定义的组件。
* See the <a href="http://extjs.com/learn/Tutorial:Creating_new_UI_controls">Creating new UI controls</a> tutorial for details on how
* and to either extend or augment ExtJs base classes to create custom Components.</p>
* <p>
* 每种component都有特定的类型,是Ext自身设置的类型。
* 对xtype检查的相关方法如{@link #getXType}和{@link #isXType}。
* 这里是所有有效的xtypes列表:
* Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the
* xtype like {@link #getXType} and {@link #isXType}. This is the list of all valid xtypes:</p>
* <pre>
xtype 类 Class
------------- ------------------
box Ext.BoxComponent
button Ext.Button
colorpalette Ext.ColorPalette
component Ext.Component
container Ext.Container
cycle Ext.CycleButton
dataview Ext.DataView
datepicker Ext.DatePicker
editor Ext.Editor
editorgrid Ext.grid.EditorGridPanel
grid Ext.grid.GridPanel
paging Ext.PagingToolbar
panel Ext.Panel
progress Ext.ProgressBar
splitbutton Ext.SplitButton
tabpanel Ext.TabPanel
treepanel Ext.tree.TreePanel
viewport Ext.ViewPort
window Ext.Window
工具条组件 Toolbar components
---------------------------------------
toolbar Ext.Toolbar
tbbutton Ext.Toolbar.Button(已废弃,用button代替)
tbfill Ext.Toolbar.Fill
tbitem Ext.Toolbar.Item
tbseparator Ext.Toolbar.Separator
tbspacer Ext.Toolbar.Spacer
tbsplit Ext.Toolbar.SplitButton(已废弃,用splitbutton代替)
tbtext Ext.Toolbar.TextItem
表单组件 Form components
---------------------------------------
form Ext.FormPanel
checkbox Ext.form.Checkbox
combo Ext.form.ComboBox
datefield Ext.form.DateField
field Ext.form.Field
fieldset Ext.form.FieldSet
hidden Ext.form.Hidden
htmleditor Ext.form.HtmlEditor
label Ext.form.Label
numberfield Ext.form.NumberField
radio Ext.form.Radio
textarea Ext.form.TextArea
textfield Ext.form.TextField
timefield Ext.form.TimeField
trigger Ext.form.TriggerField
图表组件 Chart components
---------------------------------------
chart {@link Ext.chart.Chart}
barchart {@link Ext.chart.BarChart}
cartesianchart {@link Ext.chart.CartesianChart}
columnchart {@link Ext.chart.ColumnChart}
linechart {@link Ext.chart.LineChart}
piechart {@link Ext.chart.PieChart}
Store对象 Store xtypes
---------------------------------------
arraystore {@link Ext.data.ArrayStore}
directstore {@link Ext.data.DirectStore}
groupingstore {@link Ext.data.GroupingStore}
jsonstore {@link Ext.data.JsonStore}
simplestore {@link Ext.data.SimpleStore} (已废弃,用arraystore代替)
store {@link Ext.data.Store}
xmlstore {@link Ext.data.XmlStore}
</pre>
* @constructor
* @param {Ext.Element/String/Object} config 配置项。
* 如果传入的是一个元素,那么它将是内置的元素以及其id将用于组件的id。
* 如果传入的是一个字符串,那么就假设它是现有元素身上的id,也用于组件的id。
* 否则,那应该是一个标准的配置项对象,应用到组件身上。
* The configuration options. If an element is passed, it is set as the internal
* element and its id used as the component id. If a string is passed, it is assumed to be the id of an existing element
* and is used as the component id. Otherwise, it is assumed to be a standard config object and is applied to the component.
*/
Ext.Component = function(config){
config = config || {};
if(config.initialConfig){
if(config.isAction){ // actions
this.baseAction = config;
}
config = config.initialConfig; // component cloning / action set up
}else if(config.tagName || config.dom || typeof config == "string"){ // element object
config = {applyTo: config, id: config.id || config};
}
/**
* 组件初始化配置项。只读的。
* This Component's initial configuration specification. Read-only.
* @type Object
* @property initialConfig
*/
this.initialConfig = config;
Ext.apply(this, config);
this.addEvents(
/**
* @event disable
* 当组件禁用后触发。
* Fires after the component is disabled.
* @param {Ext.Component} this
*/
'disable',
/**
* @event enable
* 当组件被启用后触发。
* Fires after the component is enabled.
* @param {Ext.Component} this
*/
'enable',
/**
* @event beforeshow
* 当组件显示出来之前触发。如返回false则阻止显示。
* Fires before the component is shown. Return false to stop the show.
* @param {Ext.Component} this
*/
'beforeshow',
/**
* @event show
* 当组件显示后触发。
* Fires after the component is shown.
* @param {Ext.Component} this
*/
'show',
/**
* @event beforehide
* 当组件将要隐藏的时候触发。如返回false则阻止隐藏。
* Fires before the component is hidden. Return false to stop the hide.
* @param {Ext.Component} this
*/
'beforehide',
/**
* @event hide
* 当组件隐藏后触发。
* Fires after the component is hidden.
* @param {Ext.Component} this
*/
'hide',
/**
* @event beforerender
* 当组件渲染之前触发。如返回false则阻止渲染。
* Fires before the component is rendered. Return false to stop the render.
* @param {Ext.Component} this
*/
'beforerender',
/**
* @event render
* 组件渲染之后触发。
* Fires after the component markup is rendered.
* @param {Ext.Component} this
*/
'render',
/**
* @event afterrender
* 组件销毁之前触发。如返回false则停止销毁。
* Fires after the component rendering is finished.
* @param {Ext.Component} this
*/
'afterrender',
/**
* @event beforedestroy
* 组件销毁之前触发。如返回false则停止销毁。
* Fires before the component is destroyed. Return false to stop the destroy.
* @param {Ext.Component} this
*/
'beforedestroy',
/**
* @event destroy
* 组件销毁之后触发。
* Fires after the component is destroyed.
* @param {Ext.Component} this
*/
'destroy',
/**
* @event beforestaterestore
* 当组件的状态复原之前触发。如返回false则停止复原状态。
* Fires before the state of the component is restored. Return false to stop the restore.
* @param {Ext.Component} this
* @param {Object} state StateProvider返回状态的哈希表。如果事件被撤销,那么<b><tt>applyState</tt></b>会送入一个状态对象(state object)。
* 默认下状态对象的属性会复制到此组件身上。可以提供自定义的状态复原方法,重写便可。
* The hash of state values returned from the StateProvider. If this
* event is not vetoed, then the state object is passed to <b><tt>applyState</tt></b>. By default,
* that simply copies property values into this Component. The method maybe overriden to
* provide custom state restoration.
*/
'beforestaterestore',
/**
* @event staterestore
* 当组件的状态复原后触发。
* Fires after the state of the component is restored.
* @param {Ext.Component} this
* @param {Object} state StateProvider返回状态的哈希表。如果事件被撤销,那么<b><tt>applyState</tt></b>会送入一个状态对象(state object)。
* 默认下状态对象的属性会复制到此组件身上。可以提供自定义的状态复原方法,重写便可。
* The hash of state values returned from the StateProvider. This is passed
* to <b><tt>applyState</tt></b>. By default, that simply copies property values into this
* Component. The method maybe overriden to provide custom state restoration.
*/
'staterestore',
/**
* @event beforestatesave
* 当组件的状态被保存到state provider之前触发。如返回false则停止保存。
* Fires before the state of the component is saved to the configured state provider. Return false to stop the save.
* @param {Ext.Component} this this
* @param {Object} state 保存状态的哈希表。该项的值由Component的<b><tt>getState()</tt></b>方法执行后返回。
* 由于该方法是一个虚拟的方法,因此需由程序员所指定实作的方法,以便能够指定状态是怎么表征的。
* 缺省下Ext.Component提供一个null的实现(空的实现)。
* The hash of state values. This is determined by calling
* <b><tt>getState()</tt></b> on the Component. This method must be provided by the
* developer to return whetever representation of state is required, by default, Ext.Component
* has a null implementation.
*/
'beforestatesave',
/**
* @event statesave
* 当组件的状态被保存到state provider后触发。
* Fires after the state of the component is saved to the configured state provider.
* @param {Ext.Component} this this
* @param {Object} state 保存状态的哈希表。该项的值由Component的<b><tt>getState()</tt></b>方法执行后返回。
* 由于该方法是一个虚拟的方法,因此需由程序员所指定,以便能够指定状态是怎么表征的。
* 缺省下Ext.Component提供一个null的实现(空的实现)。
* The hash of state values. This is determined by calling
* <b><tt>getState()</tt></b> on the Component. This method must be provided by the
* developer to return whetever representation of state is required, by default, Ext.Component
* has a null implementation.
*/
'statesave'
);
this.getId();
Ext.ComponentMgr.register(this);
Ext.Component.superclass.constructor.call(this);
if(this.baseAction){
this.baseAction.addComponent(this);
}
this.initComponent();
if(this.plugins){
if(Ext.isArray(this.plugins)){
for(var i = 0, len = this.plugins.length; i < len; i++){
this.plugins[i] = this.initPlugin(this.plugins[i]);
}
}else{
this.plugins = this.initPlugin(this.plugins);
}
}
if(this.stateful !== false){
this.initState(config);
}
if(this.applyTo){
this.applyToMarkup(this.applyTo);
delete this.applyTo;
}else if(this.renderTo){
this.render(this.renderTo);
delete this.renderTo;
}
};
// private
Ext.Component.AUTO_ID = 1000;
Ext.extend(Ext.Component, Ext.util.Observable, {
// 下面的几个配置项都是关于FormLayout的组件
// Configs below are used for all Components when rendered by FormLayout.
/**
* @cfg {String} fieldLabel 在组件旁边那里显示的label文本(默认为'')。
* The label text to display next to this Component (defaults to '')
* <p><b>
* 此组件只有在{@link Ext.form.FormLayout FormLayout}布局管理器控制的容器下渲染才有用。
* This config is only used when this Component is rendered by a Container which has been
* configured to use the {@link Ext.form.FormLayout FormLayout} layout manager.</b></p>
* Example use:<pre><code>
new Ext.FormPanel({
height: 100,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
fieldLabel: 'Name'
}]
});
</code></pre>
*/
/**
* @cfg {String} labelStyle 关于表单字段的label提示文本的CSS样式的“完全表达式(CSS style specification)”。
* 默认为"",若容器的lableStyle有设置这样设置值。
* A CSS style specification to apply directly to this field's label (defaults to the
* container's labelStyle value if set, or '').
* <p><b>
* 此组件只有在{@link Ext.layout.FormLayout FormLayout}布局管理器控制的容器下渲染才有用。
* This config is only used when this Component is rendered by a Container which has been
* configured to use the {@link Ext.layout.FormLayout FormLayout} layout manager.</b></p>
* 演示实例:Example use:<pre><code>
new Ext.FormPanel({
height: 100,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
fieldLabel: 'Name',
labelStyle: 'font-weight:bold;'
}]
});
</code></pre>
*/
/**
* @cfg {String} labelSeparator
* 分隔符,就是每行表单中的label文本显示后面紧接着的那个分隔符(默认值是{@link Ext.layout.FormLayout#labelSeparator},即缺省是分号“:”)。
* 如果指定空白字符串""就表示不显示所谓的“分隔符”。
* The standard separator to display after the text of each form label (defaults
* to the value of {@link Ext.layout.FormLayout#labelSeparator}, which is a colon ':' by default). To display
* no separator for this field's label specify empty string ''.
* <p><b>
* 此组件只有在{@link Ext.form.FormLayout FormLayout}布局管理器控制的容器下渲染才有用。
* This config is only used when this Component is rendered by a Container which has been
* configured to use the {@link Ext.form.FormLayout FormLayout} layout manager.</b></p>
* Example use:<pre><code>
new Ext.FormPanel({
height: 100,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
fieldLabel: 'Name',
labelSeparator: '...'
}]
});
</code></pre>
*/
/**
* @cfg {Boolean} hideLabel
* True表示为完全隐藏label元素。默认下,即使你不指定{@link fieldLabel}都会有一个空白符插入,好让支撑field为一行。
* 设该值为true就不会有这个空白符了。
* True to completely hide the label element (defaults to false). By default, even if
* you do not specify a {@link fieldLabel} the space will still be reserved so that the field will line up with
* other fields that do have labels. Setting this to true will cause the field to not reserve that space.
* <p><b>
* 此组件只有在{@link Ext.form.FormLayout FormLayout}布局管理器控制的容器下渲染才有用。
* This config is only used when this Component is rendered by a Container which has been
* configured to use the {@link Ext.form.FormLayout FormLayout} layout manager.</b></p>
* Example use:<pre><code>
new Ext.FormPanel({
height: 100,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield'
hideLabel: true
}]
});
</code></pre>
*/
/**
* @cfg {String} clearCls
* 关于field的清除样式(默认为“x-form-clear-left”)。
* The CSS class used to provide field clearing (defaults to 'x-form-clear-left').
* <p><b>
* 此组件只有在{@link Ext.form.FormLayout FormLayout}布局管理器控制的容器下渲染才有用。
* This config is only used when this Component is rendered by a Container which has been
* configured to use the {@link Ext.form.FormLayout FormLayout} layout manager.</b></p>
*/
/**
* @cfg {String} itemCls
* 关于容器的表单项元素的额外的CSS样式(默认为"",如容器的itemCls有设置的话就用那个值)。
* 由于该样式是作用于整个条目容器的,这就会对在内的表单字段、label元素(若有指定)或其他元素只要属于条目内的元素都有效。
* An additional CSS class to apply to the wrapper's form item element of this field (defaults
* to the container's itemCls value if set, or ''). Since it is applied to the item wrapper, it allows you to write
* standard CSS rules that can apply to the field, the label (if specified) or any other element within the markup for
* the field.
* <p><b>
* 此组件只有在{@link Ext.form.FormLayout FormLayout}布局管理器控制的容器下渲染才有用。
* This config is only used when this Component is rendered by a Container which has been
* configured to use the {@link Ext.form.FormLayout FormLayout} layout manager.</b></p>
* Example use:<pre><code>
// 对表单字段的lable有效 Apply a style to the field's label:
<style>
.required .x-form-item-label {font-weight:bold;color:red;}
</style>
new Ext.FormPanel({
height: 100,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
fieldLabel: 'Name',
itemCls: 'required' //该label就会有效果 this label will be styled
},{
xtype: 'textfield',
fieldLabel: 'Favorite Color'
}]
});
</code></pre>
*/
/**
* @cfg {String} anchor <p><b>Note</b>: this config is only used when this Component is rendered
* by a Container which has been configured to use an <b>{@link Ext.layout.AnchorLayout AnchorLayout}</b>
* based layout manager, for example:<div class="mdetail-params"><ul>
* <li>{@link Ext.form.FormPanel}</li>
* <li>specifying <code>layout: 'anchor' // or 'form', or 'absolute'</code></li>
* </ul></div></p>
* <p>See {@link Ext.layout.AnchorLayout}.{@link Ext.layout.AnchorLayout#anchor anchor} also.</p>
*/
/**
* @cfg {String} id
* 唯一的组件id(默认为自动分配的id)。
* 出于你打算用id来获取组件引用这一目的(像使用{@link Ext.ComponentMgr#getCmp}的情形),你就会送入一个你写好的id到这个方法。
* 提示:容器的元素即HTML元素也会使用该id渲染在页面上。如此一来你就可以采用CSS id匹配的规则来定义该组件的样式。
* 换句话说,实例化该组件时,送入不同的Id,就有对应不同的样式效果。
* The unique id of this component (defaults to an auto-assigned id). You should assign an id if you need to
* be able to access the component later and you do not have an object reference available (e.g., using
* {@link Ext.ComponentMgr#getCmp}). Note that this id will also be used as the element id for the containing
* HTML element that is rendered to the page for this component. This allows you to write id-based CSS rules to
* style the specific instance of this component uniquely, and also to select sub-elements using this
* component's id as the parent.
*/
/**
* @cfg {String} itemId
* <p>
* 若没有为该组件分配到一个访问的应用(换言之是建立变量然后分配置),那么就可以用这个<tt>itemId</tt>的索引来获取这个组件,
* 另外一个方式就是<code>{@link #id}</code>,对应用{@link Ext}.{@link Ext#getCmp getCmp}获取;
* 而<code>itemId</code>就对应用{@link Ext.Container#getComponent getComponent}方法获取,
* 但范围更窄,在{@link Ext.Container}范围内。
* An <tt>itemId</tt> can be used as an alternative way to get a reference to a component
* when no object reference is available.
* Instead of using an <code>{@link #id}</code> with
* {@link Ext}.{@link Ext#getCmp getCmp}, use <code>itemId</code> with
* {@link Ext.Container}.
*
* {@link Ext.Container#getComponent getComponent} which will retrieve
* <code>itemId</code>'s or <tt>{@link #id}</tt>'s. Since <code>itemId</code>'s are an index to the
* container's internal MixedCollection, the <code>itemId</code> is scoped locally to the container --
* avoiding potential conflicts with {@link Ext.ComponentMgr} which requires a <b>unique</b>
* <code>{@link #id}</code>.</p>
* <pre><code>
var c = new Ext.Panel({ //
{@link Ext.BoxComponent#height height}: 300,
{@link #renderTo}: document.body,
{@link Ext.Container#layout layout}: 'auto',
{@link Ext.Container#items items}: [
{
itemId: 'p1',
{@link Ext.Panel#title title}: 'Panel 1',
{@link Ext.BoxComponent#height height}: 150
},
{
itemId: 'p2',
{@link Ext.Panel#title title}: 'Panel 2',
{@link Ext.BoxComponent#height height}: 150
}
]
})
p1 = c.{@link Ext.Container#getComponent getComponent}('p1'); // not the same as {@link Ext#getCmp Ext.getCmp()}
p2 = p1.{@link #ownerCt}.{@link Ext.Container#getComponent getComponent}('p2'); // reference via a sibling
* </code></pre>
* <p>Also see <tt>{@link #id}</tt> and <code>{@link #ref}</code>.</p>
* <p><b>Note</b>: to access the container of an item see <tt>{@link #ownerCt}</tt>.</p>
*/
/**
* @cfg {String} xtype
* 用于登记一个xtype。
* The registered xtype to create. This config option is not used when passing
* a config object into a constructor. This config option is used only when
* lazy instantiation is being used, and a child item of a Container is being
* specified not as a fully instantiated Component, but as a <i>Component config
* object</i>. The xtype will be looked up at render time up to determine what
* type of child Component to create.<br><br>
* The predefined xtypes are listed {@link Ext.Component here}.
* <br><br>
* If you subclass Components to create your own Components, you may register
* them using {@link Ext.ComponentMgr#registerType} in order to be able to
* take advantage of lazy instantiation and rendering.
*/
/**
* @cfg {String} ptype
* The registered <tt>ptype</tt> to create. This config option is not used when passing
* a config object into a constructor. This config option is used only when
* lazy instantiation is being used, and a Plugin is being
* specified not as a fully instantiated Component, but as a <i>Component config
* object</i>. The <tt>ptype</tt> will be looked up at render time up to determine what
* type of Plugin to create.<br><br>
* If you create your own Plugins, you may register them using
* {@link Ext.ComponentMgr#registerPlugin} in order to be able to
* take advantage of lazy instantiation and rendering.
*/
/**
* @cfg {String} cls
* 一个可选添加的CSS样式类,加入到组件的元素上(默认为'')。这为组件或组件的子节点加入标准CSS规则提供了方便。
* An optional extra CSS class that will be added to this component's Element (defaults to ''). This can be
* useful for adding customized styles to the component or any of its children using standard CSS rules.
*/
/**
* @cfg {String} overCls
* 关于鼠标上移至该组件元素的CSS样式类,移出时撤销该样式的效果(默认为'')。
* 该配置项在处理元素"active"或"hover"的时候很有用。
* An optional extra CSS class that will be added to this component's Element when the mouse moves
* over the Element, and removed when the mouse moves out. (defaults to ''). This can be
* useful for adding customized "active" or "hover" styles to the component or any of its children using standard CSS rules.
*/
/**
* @cfg {String} style
* 作用在组件元素上特定的样式。该值的有效格式应如{@link Ext.Element#applyStyles}。
* A custom style specification to be applied to this component's Element. Should be a valid argument to
* {@link Ext.Element#applyStyles}.
*/
/**
* @cfg {String} ctCls
* 一个可选添加的CSS样式类,加入到组件的容器上(默认为'')。这为容器或容器的子节点加入标准CSS规则提供了方便。
* An optional extra CSS class that will be added to this component's container (defaults to ''). This can be
* useful for adding customized styles to the container or any of its children using standard CSS rules.
*/
/**
* @cfg {Boolean} disabled
* 渲染该组件为禁用状态的(默认为false)。
* Render this component disabled (default is false).
*/
/**
* @cfg {Boolean} hidden
* 渲染该组件为隐藏状态的(默认为false)。
* Render this component hidden (default is false).
*/
/**
* @cfg {Object/Array} plugins
* 针对该组件自定义的功能,是对象或这些对象组成的数组。一个有效的插件须保证带有一个init的方法以便接收属于Ext.Component类型的引用。
* 当一个组件被创建后,若发现由插件可用,组件会调用每个插件上的init方法,传入一个应用到插件本身。这样,插件便能按照组件所提供的功能,调用到组件的方法或响应事件。
* An object or array of objects that will provide custom functionality for this component. The only
* requirement for a valid plugin is that it contain an init method that accepts a reference of type Ext.Component.
* When a component is created, if any plugins are available, the component will call the init method on each
* plugin, passing a reference to itself. Each plugin can then call methods or respond to events on the
* component as needed to provide its functionality.
*/
/**
* @cfg {Mixed} applyTo
* 节点的id,或是DOM节点,又或者是与DIV相当的现有元素,这些都是文档中已经存在的元素
* 当使用applyTo后,主元素所指定的id或CSS样式类将会作用于组件构成的部分,而被创建的组件将会尝试着根据这些markup构建它的子组件。
* 使用了这项配置后,不需要执行render()的方法。
* 若指定了applyTo,那么任何由{@link #renderTo}传入的值将会被忽略并使用目标元素的父级元素作为组件的容器。
* The id of the element, a DOM element or an existing Element corresponding to a DIV that is already present in
* the document that specifies some structural markup for this component. When applyTo is used, constituent parts of
* the component can also be specified by id or CSS class name within the main element, and the component being created
* may attempt to create its subcomponents from that markup if applicable. Using this config, a call to render() is
* not required. If applyTo is specified, any value passed for {@link #renderTo} will be ignored and the target
* element's parent node will automatically be used as the component's container.
*/
/**
* @cfg {Mixed} renderTo
* <p>
* 容器渲染的那个节点的id,或是DOM节点,又或者是与DIV相当的现有元素。
* 使用了这项配置后,不需要执行render()的方法。
* The id of the element, a DOM element or an existing Element that this component will be rendered into.
* When using this config, a call to render() is not required.<p>
* <p>If this Component needs to be managed by a {@link Ext.Container Container}'s
* {@link Ext.Component#layout layout manager}, do not use this option. It is the responsiblity
* of the Container's layout manager to perform rendering. See {@link #render}.</p>
*/
/**
* @cfg {Boolean} stateful
* <p>
* 组件记忆了一个状态信息,启动时候就根据这个标记获取状态信息。
* 组件必须设置其{@link #stateId}或{@link #id},较有保障性,
* 而自动生成的id在跨页面加载的时候则不能保证一定不出现相同的情形。
* A flag which causes the Component to attempt to restore the state of internal properties
* from a saved state on startup. The component must have either a {@link #stateId} or {@link #id}
* assigned for state to be managed. Auto-generated ids are not guaranteed to be stable across page
* loads and cannot be relied upon to save and restore the same state for a component.<p>
* <p>
* 为了能记忆状态,必须通过方法设置一个{@link Ext.state.Provider}的实例置于一个状态管理器之中,
* 然后才可以用{@link Ext.state.Provider#set set}与{@link Ext.state.Provider#get get}的方法,保存记忆和提取记忆。
* 可用内建的{@link Ext.state.CookieProvider}实现设置一个。
* For state saving to work, the state manager's provider must have been set to an implementation
* of {@link Ext.state.Provider} which overrides the {@link Ext.state.Provider#set set}
* and {@link Ext.state.Provider#get get} methods to save and recall name/value pairs.
* A built-in implementation, {@link Ext.state.CookieProvider} is available.</p>
* <p>
* 要设置页面的状态供应器:
* To set the state provider for the current page:
* </p>
* <pre><code>
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
</code></pre>
* <p>
* 接下来,具备状态记忆功能的组件就可以在相关的事件触发过程中保存记忆,事件例表在{@link #stateEvents}。
* A stateful Component attempts to save state when one of the events listed in the {@link #stateEvents}
* configuration fires.</p>
* <p>
* 要保存状态,该组件首先会调用b><tt>getState</tt></b>初始化状态。
* 默认下该方法是没有的,这就要让程序员提供针对性的实现,以返回一个该组件可复原状态的对象。
* To save state, A stateful Component first serializes its state by calling <b><tt>getState</tt></b>. By default,
* this function does nothing. The developer must provide an implementation which returns an object hash
* which represents the Component's restorable state.</p>
* <p>
* 所返回的对象会被送入到{@link Ext.state.Manager#set}配置项所指定{@link Ext.state.Provider}对象的方法,
* 还有组件的{@link stateId}作为键值,如果不指定,那{@link #id}代替之。
* The value yielded by getState is passed to {@link Ext.state.Manager#set} which uses the configured
* {@link Ext.state.Provider} to save the object keyed by the Component's {@link stateId}, or,
* if that is not specified, its {@link #id}.</p>
* <p>
* 构造过程中,状态化组件首先会尝试使用{@link Ext.state.Manager#get}根据(@link #stateId}<i>复原</i>其状态,
* 如不能,就用{@link #id}代替之,得到的结果对象就送入至<b><tt>applyState</tt></b>。
* 缺省的情况是简单的复制属性到对象,但程序员是可在重写该函数的过程添加更多的功能。
* During construction, a stateful Component attempts to <i>restore</i> its state by calling
* {@link Ext.state.Manager#get} passing the (@link #stateId}, or, if that is not specified, the {@link #id}.</p>
* <p>The resulting object is passed to <b><tt>applyState</tt></b>. The default implementation of applyState
* simply copies properties into the object, but a developer may override this to support more behaviour.</p>
* <p>
* 同样你可以加入更多额外的功能,如是者有{@link #beforestaterestore}事件、{@link #staterestore}事件、{@link #beforestatesave}事件、{@link #beforestatesave}事件和{@link #statesave}。
* You can perform extra processing on state save and restore by attaching handlers to the
* {@link #beforestaterestore}, {@link #staterestore}, {@link #beforestatesave} and {@link #statesave} events</p>
*/
/**
* @cfg {String} stateId
* 出于状态管理目的id,(默认是人为设置过的组件id,如果组件是自动生成的id那种那么该项是null。
* The unique id for this component to use for state management purposes (defaults to the component id if one was
* set, otherwise null if the component is using a generated id).
* <p>参阅{@link #stateful}了解记忆与复原的机制。See {@link #stateful} for an explanation of saving and restoring Component state.</p>
*/
/* //internal - to be set by subclasses
* @cfg {Array} stateEvents
* An array of events that, when fired, should trigger this component to save its state (defaults to none).
* These can be any types of events supported by this component, including browser or custom events (e.g.,
* ['click', 'customerchange']).
* <p>See {@link #stateful} for an explanation of saving and restoring Component state.</p>
*/
/**
* @cfg {Mixed} autoEl
* <p>
* 某种标签的字符串或者{@link Ext.DomHelper DomHelper}配置对象,用于创建承载此组件的元素。
* A tag name or {@link Ext.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will
* encapsulate this Component.</p>
* <p>
* 一般而言你无须对其设置。对于这些基础类而言,就会使用<b><tt>div</tt></b>作为其默认的元素。
* Ext类写得越复杂,组件的onRender方法产生的DOM结构就随之更为复杂。
* You do not normally need to specify this. For the base classes {@link Ext.Component}, {@link Ext.BoxComponent},
* and {@link Ext.Container}, this defaults to <b><tt>'div'</tt></b>. The more complex Ext classes use a more complex
* DOM structure created by their own onRender methods.</p>
* <p>
* 该项是为创建形形色色的DOM元素而准备的,开发者可根据程序的特定要求去制定,如:
* This is intended to allow the developer to create application-specific utility Components encapsulated by
* different DOM elements. Example usage:</p><pre><code>
{
xtype: 'box',
autoEl: {
tag: 'img',
src: 'http://www.example.com/example.jpg'
}
}, {
xtype: 'box',
autoEl: {
tag: 'blockquote',
html: 'autoEl is cool!'
}
}, {
xtype: 'container',
autoEl: 'ul',
cls: 'ux-unordered-list',
items: {
xtype: 'box',
autoEl: 'li',
html: 'First list item'
}
}
</code></pre>
*/
autoEl : 'div',
/**
* @cfg {String} disabledClass
* 当组件被禁用时作用的CSS样式类(默认为"x-item-disabled")。
* CSS class added to the component when it is disabled (defaults to "x-item-disabled").
*/
disabledClass : "x-item-disabled",
/**
* @cfg {Boolean} allowDomMove
* 当渲染进行时能否移动Dom节点上的组件(默认为true)。
* Whether the component can move the Dom node when rendering (defaults to true).
*/
allowDomMove : true,
/**
* @cfg {Boolean} autoShow
* True表示为在渲染的时候先检测一下有否关于隐藏的样式类(如:'x-hidden'或'x-hide-display'),有就移除隐藏的样式类(缺省为false)。
* True if the component should check for hidden classes (e.g. 'x-hidden' or 'x-hide-display') and remove
* them on render (defaults to false).
*/
autoShow : false,
/**
* @cfg {String} hideMode
* <p>
* 这个组件是怎么隐藏的。可支持的值有"visibility" (css中的visibility),"offsets"(负偏移位置)和"display"(css中的display)-默认为“display”。
* How this component should be hidden. Supported values are "visibility" (css visibility), "offsets" (negative
* offset position) and "display" (css display) - defaults to "display".</p>
* <p>
* 容器可能是{@link Ext.layout.CardLayout card layout}或{@link Ext.TabPanel TabPanel}中的一员,会有隐藏/显未的情形,这种情形下最好将其hideMode模式设为"offsets"。
* 这保证了计算布局时,组件仍有正确的高度和宽度,组件管理器才能顺利地测量。
* For Containers which may be hidden and shown as part of a {@link Ext.layout.CardLayout card layout} Container such as a
* {@link Ext.TabPanel TabPanel}, it is recommended that hideMode is configured as "offsets". This ensures
* that hidden Components still have height and width so that layout managers can perform measurements when
* calculating layouts.</p>
*/
hideMode: 'display',
/**
* @cfg {Boolean} hideParent
* True表示为当隐藏/显示组件时对组件的容器亦一同隐藏/显示,false就只会隐藏/显示组件本身(默认为false)。
* 例如,可设置一个hide:true的隐藏按钮在window,如果按下就通知其父容器一起隐藏,这样做起来比较快捷省事。
* True to hide and show the component's container when hide/show is called on the component, false to hide
* and show the component itself (defaults to false). For example, this can be used as a shortcut for a hide
* button on a window by setting hide:true on the button when adding it to its parent container.
*/
hideParent: false,
/**
* <p>该组件的{@link Ext.Element}元素对象。只读的。</p>
* <p>用<tt>{@link #getEl getEl}可返回该对象。</p>
* @type Ext.Element
* @property el
*/
/**
* 组件自身的{@link Ext.Container}(默认是undefined,只有在组件加入到容器时才会自动设置该属性)只读的。
* The component's owner {@link Ext.Container} (defaults to undefined, and is set automatically when
* the component is added to a container). Read-only.
* @type Ext.Container
* @property ownerCt
*/
/**
* True表示为组件是隐藏的。只读的。
* True if this component is hidden. Read-only.
* @type Boolean
* @property hidden
*/
hidden : false,
/**
* True表示为组件已被禁止。只读的。
* True if this component is disabled. Read-only.
* @type Boolean
* @property disabled
*/
disabled : false,
/**
* True表示为该组件已经渲染好了。只读的。
* True if this component has been rendered. Read-only.
* @type Boolean
* @property rendered
*/
rendered : false,
// private
ctype : "Ext.Component",
// private
actionMode : "el",
// private
getActionEl : function(){
return this[this.actionMode];
},
initPlugin : function(p){
if(p.ptype && typeof p.init != 'function'){
p = Ext.ComponentMgr.createPlugin(p);
}else if(typeof p == 'string'){
p = Ext.ComponentMgr.createPlugin({
ptype: p
});
}
p.init(this);
return p;
},
/* // protected
* Function to be implemented by Component subclasses to be part of standard component initialization flow (it is empty by default).
* <pre><code>
// Traditional constructor:
Ext.Foo = function(config){
// call superclass constructor:
Ext.Foo.superclass.constructor.call(this, config);
this.addEvents({
// add events
});
};
Ext.extend(Ext.Foo, Ext.Bar, {
// class body
}
// initComponent replaces the constructor:
Ext.Foo = Ext.extend(Ext.Bar, {
initComponent : function(){
// call superclass initComponent
Ext.Container.superclass.initComponent.call(this);
this.addEvents({
// add events
});
}
}
</code></pre>
*/
initComponent : Ext.emptyFn,
/**
* <p>执行容器的渲染,可以将渲染执行在送入的HTML元素上面。
* Render this Component into the passed HTML element.</p>
* <p><b>如果你在使用{@link Ext.Container Container}对象来存放该组件,那么就不要使用render方法。
* If you are using a {@link Ext.Container Container} object to house this Component, then
* do not use the render method.</b></p>
* <p>一个容器的子组件可以由容器其{@link Ext.Container#layout layout}属性在第一次渲染的时候来明确指定。
* A Container's child Components are rendered by that Container's
* {@link Ext.Container#layout layout} manager when the 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>
* 对于已渲染的组件加入新的子组件在内,就要调用{@link Ext.Container#doLayout doLayout}方法刷新视图,
* 并层引发未渲染的于组件进行渲染,如果加入多个子组件渲染一次就足够了。
* If the Container is already rendered when a new child Component is added, you may need to call
* the Container's {@link Ext.Container#doLayout 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>
* 对于复杂的而言,要请楚知道的是其子项的定位与大小调节的任务是归属于容器的{@link Ext.Container#layout layout}管理器的。
* When creating complex UIs, it is important to remember that sizing and positioning
* of child items is the responsibility of the Container's {@link Ext.Container#layout layout} manager.
* If you expect child items to be sized in response to user interactions, you must
* configure the Container with a layout manager which creates and manages the type of layout you
* have in mind.</p>
* <p><b>
* 省略不写容器的{@link Ext.Container#layout layout}配置项表示使用的最最简单的布局管理器,功能只有渲染子组件到容器中,没有大小调节和定位的功能,
* 不过你想实现这些功能就要为容器准备好一个你要调置的布局管理器。
* Omitting the Container's {@link Ext.Container#layout 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 {Element/HTMLElement/String} container (可选的)组件准备渲染到的元素,如果基于现有的元素,那该项就应有略。
* (optional) The element this Component should be
* rendered into. If it is being created from existing markup, this should be omitted.
* @param {String/Number} position (可选的)元素ID或Dom节点索引,说明该组件在容器中的哪一个子组件<b>之前</b>插入(默认加在容器中最后的位置)。
* (optional) The element ID or DOM node index within the container <b>before</b>
* which this component will be inserted (defaults to appending to the end of the container)
*/
render : function(container, position){
if(!this.rendered && this.fireEvent("beforerender", this) !== false){
if(!container && this.el){
this.el = Ext.get(this.el);
container = this.el.dom.parentNode;
this.allowDomMove = false;
}
this.container = Ext.get(container);
if(this.ctCls){
this.container.addClass(this.ctCls);
}
this.rendered = true;
if(position !== undefined){
if(typeof position == 'number'){
position = this.container.dom.childNodes[position];
}else{
position = Ext.getDom(position);
}
}
this.onRender(this.container, position || null);
if(this.autoShow){
this.el.removeClass(['x-hidden','x-hide-' + this.hideMode]);
}
if(this.cls){
this.el.addClass(this.cls);
delete this.cls;
}
if(this.style){
this.el.applyStyles(this.style);
delete this.style;
}
if(this.overCls){
this.el.addClassOnOver(this.overCls);
}
this.fireEvent("render", this);
this.afterRender(this.container);
if(this.hidden){
this.hide();
}
if(this.disabled){
this.disable();
}
if(this.stateful !== false){
this.initStateEvents();
}
this.initRef();
this.fireEvent("afterrender", this);
}
return this;
},
/**
* @cfg {String} ref
* <p>
* 一种路径的规范,可获取位于该容器下某一子组件的{@link #ownerCt}。该路径依靠此组件本身为引用根据。
* A path specification, relative to the Component's {@link #ownerCt} specifying into which
* ancestor Container to place a named reference to this Component.</p>
* <p>
* 父亲轴可以用'/'字符横切开来。例如在一个Panel面板中的工具栏上如此地引用按钮,会是这样:
* The ancestor axis can be traversed by using '/' characters in the path.
* For example, to put a reference to a Toolbar Button into <i>the Panel which owns the Toolbar</i>:</p><pre><code>
var myGrid = new Ext.grid.EditorGridPanel({
title: '我的EditorGridPanel',
store: myStore,
colModel: myColModel,
tbar: [{
text: '保存',
handler: saveChanges,
disabled: true,
ref: '../saveButton'
}],
listeners: {
afteredit: function() {
// GridPanel(myGrid)就有了这个savaButton的引用。The button reference is in the GridPanel
myGrid.saveButton.enable();
}
}
});
</code></pre>
* <p>
* 以上代码中,ref: '../saveButton'就是配置项的按钮其标识为saveButton,“../”相对为该组件,即目标组件的{@link #ownerCt}的上一层组件。
* In the code above, if the ref had been <code>'saveButton'</code> the reference would
* have been placed into the Toolbar. Each '/' in the ref moves up one level from the
* Component's {@link #ownerCt}.</p>
*/
initRef : function(){
if(this.ref){
var levels = this.ref.split('/');
var last = levels.length, i = 0;
var t = this;
while(i < last){
if(t.ownerCt){
t = t.ownerCt;
}
i++;
}
t[levels[--i]] = this;
}
},
// private
initState : function(config){
if(Ext.state.Manager){
var id = this.getStateId();
if(id){
var state = Ext.state.Manager.get(id);
if(state){
if(this.fireEvent('beforestaterestore', this, state) !== false){
this.applyState(state);
this.fireEvent('staterestore', this, state);
}
}
}
}
},
// private
getStateId : function(){
return this.stateId || ((this.id.indexOf('ext-comp-') == 0 || this.id.indexOf('ext-gen') == 0) ? null : this.id);
},
// private
initStateEvents : function(){
if(this.stateEvents){
for(var i = 0, e; e = this.stateEvents[i]; i++){
this.on(e, this.saveState, this, {delay:100});
}
}
},
// private
applyState : function(state, config){
if(state){
Ext.apply(this, state);
}
},
// private
getState : function(){
return null;
},
// private
saveState : function(){
if(Ext.state.Manager){
var id = this.getStateId();
if(id){
var state = this.getState();
if(this.fireEvent('beforestatesave', this, state) !== false){
Ext.state.Manager.set(id, state);
this.fireEvent('statesave', this, state);
}
}
}
},
/**
* 把这个组件应用到当前有效的markup。执行该函数后,无须调用render()。
* Apply this component to existing markup that is valid. With this function, no call to render() is required.
* @param {String/HTMLElement} el
*/
applyToMarkup : function(el){
this.allowDomMove = false;
this.el = Ext.get(el);
this.render(this.el.dom.parentNode);
},
/**
* 加入CSS样式类到组件所在的元素。
* Adds a CSS class to the component's underlying element.
* @param {string} cls 要加入的CSS样式类。The CSS class name to add
* @return {Ext.Component} this
*/
addClass : function(cls){
if(this.el){
this.el.addClass(cls);
}else{
this.cls = this.cls ? this.cls + ' ' + cls : cls;
}
return this;
},
/**
* 移除CSS样式类到组件所属的元素。
* Removes a CSS class from the component's underlying element.
* @param {string} cls 要移除的CSS样式类。The CSS class name to remove
* @return {Ext.Component} this
*/
removeClass : function(cls){
if(this.el){
this.el.removeClass(cls);
}else if(this.cls){
this.cls = this.cls.split(' ').remove(cls).join(' ');
}
return this;
},
// private
// default function is not really useful
onRender : function(ct, position){
if(!this.el && this.autoEl){
if(typeof this.autoEl == 'string'){
this.el = document.createElement(this.autoEl);
}else{
var div = document.createElement('div');
Ext.DomHelper.overwrite(div, this.autoEl);
this.el = div.firstChild;
}
if (!this.el.id) {
this.el.id = this.getId();
}
}
if(this.el){
this.el = Ext.get(this.el);
if(this.allowDomMove !== false){
ct.dom.insertBefore(this.el.dom, position);
}
}
},
// private
getAutoCreate : function(){
var cfg = typeof this.autoCreate == "object" ?
this.autoCreate : Ext.apply({}, this.defaultAutoCreate);
if(this.id && !cfg.id){
cfg.id = this.id;
}
return cfg;
},
// private
afterRender : Ext.emptyFn,
/**
* 清除任何的事件的句柄,在DOM中移除组件的元素,从容器{@link Ext.Container}中移除本身(如果适合的话)和在{@link Ext.ComponentMgr}注销
* 销毁的方法一般由框架自动执行,通常不需要直接执行。
* Destroys this component by purging any event listeners, removing the component's element from the DOM,
* removing the component from its {@link Ext.Container} (if applicable) and unregistering it from
* {@link Ext.ComponentMgr}. Destruction is generally handled automatically by the framework and this method
* should usually not need to be called directly.
*/
destroy : function(){
if(this.fireEvent("beforedestroy", this) !== false){
this.beforeDestroy();
if(this.rendered){
this.el.removeAllListeners();
this.el.remove();
if(this.actionMode == "container" || this.removeMode == "container"){
this.container.remove();
}
}
this.onDestroy();
Ext.ComponentMgr.unregister(this);
this.fireEvent("destroy", this);
this.purgeListeners();
}
},
// private
beforeDestroy : Ext.emptyFn,
// private
onDestroy : Ext.emptyFn,
/**
* <p>返回所属的{@link Ext.Element}。<i>通常</i>这是一个<DIV>元素,由onRender方法所创建,但也有可能是{@link #autoEl}配置项所制定的那个。
* Returns the {@link Ext.Element} which encapsulates this Component. This will <i>usually</i> be
* a <DIV> element created by the class's onRender method, but that may be overridden using the {@link #autoEl} config.</p>
* <p><b>
* 该组件若是未完全渲染完毕的话,这个元素是不存在的。
* The Element will not be available until this Component has been rendered.</b></p>
* <p>
* 要登记改组件的<b>DOM事件</b>(相当于组件本身的Observable事件而言),就要这样加入事件侦听器(如render事件):
* To add listeners for <b>DOM events</b> to this Component (as opposed to listeners for this Component's
* own Observable events), perform the adding of the listener in a render event listener:</p><pre><code>
new Ext.Panel({
title: 'The Clickable Panel',
listeners: {
render: function(p) {
// Append the Panel to the click handler's argument list.
p.getEl().on('click', handlePanelClick.createDelegate(null, [p], true));
}
}
});
</code></pre>
* @return {Ext.Element} 包含该组件的元素对象。The Element which encapsulates this Component.
*/
getEl : function(){
return this.el;
},
/**
* 返回该组件的id。
* Returns the id of this component.
* @return {String}
*/
getId : function(){
return this.id || (this.id = "ext-comp-" + (++Ext.Component.AUTO_ID));
},
/**
* 返回该组件的item id。
* Returns the item id of this component.
* @return {String}
*/
getItemId : function(){
return this.itemId || this.getId();
},
/**
* 试着将焦点放到此项。
* Try to focus this component.
* @param {Boolean} selectText (可选的)true的话同时亦选中组件中的文本(尽可能)。(optional)If applicable, true to also select the text in this component
* @param {Boolean/Number} delay (可选的)延时聚焦行为的毫秒数(true表示为10毫秒)。(optional) Delay the focus this number of milliseconds (true for 10 milliseconds)
* @return {Ext.Component} this
*/
focus : function(selectText, delay){
if(delay){
this.focus.defer(typeof delay == 'number' ? delay : 10, this, [selectText, false]);
return;
}
if(this.rendered){
this.el.focus();
if(selectText === true){
this.el.dom.select();
}
}
return this;
},
// private
blur : function(){
if(this.rendered){
this.el.blur();
}
return this;
},
/**
* 禁止该组件。
* Disable this component.
* @return {Ext.Component} this
*/
disable : function(){
if(this.rendered){
this.onDisable();
}
this.disabled = true;
this.fireEvent("disable", this);
return this;
},
// private
onDisable : function(){
this.getActionEl().addClass(this.disabledClass);
this.el.dom.disabled = true;
},
/**
* 启用该组件。
* Enable this component.
* @return {Ext.Component} this
*/
enable : function(){
if(this.rendered){
this.onEnable();
}
this.disabled = false;
this.fireEvent("enable", this);
return this;
},
// private
onEnable : function(){
this.getActionEl().removeClass(this.disabledClass);
this.el.dom.disabled = false;
},
/**
* 方便的函数用来控制组件禁用/可用。
* Convenience function for setting disabled/enabled by boolean.
* @param {Boolean} disabled
* @return {Ext.Component} this
*/
setDisabled : function(disabled){
return this[disabled ? "disable" : "enable"]();
},
/**
* 显示该组件。
* Show this component.
* @return {Ext.Component} this
*/
show: function(){
if(this.fireEvent("beforeshow", this) !== false){
this.hidden = false;
if(this.autoRender){
this.render(typeof this.autoRender == 'boolean' ? Ext.getBody() : this.autoRender);
}
if(this.rendered){
this.onShow();
}
this.fireEvent("show", this);
}
return this;
},
// private
onShow : function(){
if(this.hideParent){
this.container.removeClass('x-hide-' + this.hideMode);
}else{
this.getActionEl().removeClass('x-hide-' + this.hideMode);
}
},
/**
* 隐藏该组件。
* Hide this component.
* @return {Ext.Component} this
*/
hide: function(){
if(this.fireEvent("beforehide", this) !== false){
this.hidden = true;
if(this.rendered){
this.onHide();
}
this.fireEvent("hide", this);
}
return this;
},
// private
onHide : function(){
if(this.hideParent){
this.container.addClass('x-hide-' + this.hideMode);
}else{
this.getActionEl().addClass('x-hide-' + this.hideMode);
}
},
/**
* 方便的函数用来控制组件显示/隐藏。
* Convenience function to hide or show this component by boolean.
* @param {Boolean} visible 为True时显示/false时隐藏。True to show, false to hide
* @return {Ext.Component} this
*/
setVisible: function(visible){
return this[visible ? "show" : "hide"]();
},
/**
* 该组件可见时返回true。
* Returns true if this component is visible.
* @return {Boolean} 为True时显示/false时隐藏。True if this component is visible, false otherwise.
*/
isVisible : function(){
return this.rendered && this.getActionEl().isVisible();
},
/**
* 根据原始传入到该实例的配置项值,克隆一份组件。
* Clone the current component using the original config values passed into this instance by default.
* @param {Object} overrides 一个新配置项对象,用于对克隆版本的属性进行重写。属性id应要重写,避免重复生成一个。 A new config containing any properties to override in the cloned version.
* An id property can be passed on this object, otherwise one will be generated to avoid duplicates.
* @return {Ext.Component} clone 克隆该组件的copy。The cloned copy of this component
*/
cloneConfig : function(overrides){
overrides = overrides || {};
var id = overrides.id || Ext.id();
var cfg = Ext.applyIf(overrides, this.initialConfig);
cfg.id = id; // prevent dup id
return new this.constructor(cfg);
},
/**
* 获取{@link Ext.ComponentMgr}在已登记组件的xtypes。
* 全部可用的xtypes列表,可参考{@link Ext.Component}开头,用法举例:
* Gets the xtype for this component as registered with {@link Ext.ComponentMgr}. For a list of all
* available xtypes, see the {@link Ext.Component} header. Example usage:
* <pre><code>
var t = new Ext.form.TextField();
alert(t.getXType()); // 提示alerts 'textfield'
</code></pre>
* @return {String} The xtype
*/
getXType : function(){
return this.constructor.xtype;
},
/**
* <p>测试这个组件是否属于某个指定的xtype。
* 这个方法既可测试该组件是否为某个xtype的子类,或直接是这个xtype的实例(shallow = true)
* Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended
* from the xtype (default) or whether it is directly of the xtype specified (shallow = true).</p>
* <p><b>
* 如果你创建了子类,要注意必须登记一个新的xtype,让xtype的层次性发挥作用。
* If using your own subclasses, be aware that a Component must register its own xtype
* to participate in determination of inherited xtypes.</b></p>
* <p>全部可用的xtypes列表,可参考{@link Ext.Component}开头。
* For a list of all available xtypes, see the {@link Ext.Component} header.</p>
* <p>用法举例:Example usage:</p>
* <pre><code>
var t = new Ext.form.TextField();
var isText = t.isXType('textfield'); // true
var isBoxSubclass = t.isXType('box'); // true,textfield继承自BoxComponent true, descended from BoxComponent
var isBoxInstance = t.isXType('box', true); // false,非BoxComponent本身的实例 false, not a direct BoxComponent instance
</code></pre>
* @param {String} xtype 测试该组件的xtype。The xtype to check for this Component
* @param {Boolean} shallow (可选的)False表示为测试该组件是否为某个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 {Boolean} true就表示为测试该组件是否这个xtype本身的实例。True if this component descends from the specified xtype, false otherwise.
*/
isXType : function(xtype, shallow){
//assume a string by default
if (typeof xtype == 'function'){
xtype = xtype.xtype; //handle being passed the class, eg. Ext.Component
}else if (typeof xtype == 'object'){
xtype = xtype.constructor.xtype; //handle being passed an instance
}
return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype;
},
/**
* <p>
* 返回以斜杠分割的字符串,表示组件的xtype层次。
* 全部可用的xtypes列表,可参考{@link Ext.Component}开头。
* Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all
* available xtypes, see the {@link Ext.Component} header.</p>
* <p><b>
* 如果你创建了子类,要注意必须登记一个新的xtype,让xtype的层次性发挥作用。
* If using your own subclasses, be aware that a Component must register its own xtype
* to participate in determination of inherited xtypes.</b></p>
* <p>用法举例:Example usage:</p>
* <pre><code>
var t = new Ext.form.TextField();
alert(t.getXTypes()); // 提示alerts 'component/box/field/textfield'
</pre></code>
* @return {String} 层次的字符串。The xtype hierarchy string
*/
getXTypes : function(){
var tc = this.constructor;
if(!tc.xtypes){
var c = [], sc = this;
while(sc && sc.constructor.xtype){
c.unshift(sc.constructor.xtype);
sc = sc.constructor.superclass;
}
tc.xtypeChain = c;
tc.xtypes = c.join('/');
}
return tc.xtypes;
},
/**
* 在此组件之下由自定义的函数作搜索依据查找容器。
* 如函数返回true返回容器的结果。传入的函数会有(container, this component)的参数。
* Find a container above this component at any level by a custom function. If the passed function returns
* true, the container will be returned. The passed function is called with the arguments (container, this component).
* @param {Function} fcn
* @param {Object} scope (optional)(可选的)
* @return {Ext.Container} 首次匹配的容器。The first Container for which the custom function returns true
*/
findParentBy: function(fn) {
for (var p = this.ownerCt; (p != null) && !fn(p, this); p = p.ownerCt);
return p || null;
},
/**
* 根据xtype或class查找该容器下任意层次中某个容器。
* Find a container above this component 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
* @return {Ext.Container} 首次匹配的容器。The first Container which matches the given xtype or class
*/
findParentByType: function(xtype) {
return typeof xtype == 'function' ?
this.findParentBy(function(p){
return p.constructor === xtype;
}) :
this.findParentBy(function(p){
return p.constructor.xtype === xtype;
});
},
getDomPositionEl : function(){
return this.getPositionEl ? this.getPositionEl() : this.getEl();
},
// internal function for auto removal of assigned event handlers on destruction
mon : function(item, ename, fn, scope, opt){
if(!this.mons){
this.mons = [];
this.on('beforedestroy', function(){
for(var i= 0, len = this.mons.length; i < len; i++){
var m = this.mons[i];
m.item.un(m.ename, m.fn, m.scope);
}
}, this, {single: true});
}
if(typeof ename == "object"){
var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
var o = ename;
for(var e in o){
if(propRe.test(e)){
continue;
}
if(typeof o[e] == "function"){
// shared options
this.mons.push({
item: item, ename: e, fn: o[e], scope: o.scope
});
item.on(e, o[e], o.scope, o);
}else{
// individual options
this.mons.push({
item: item, ename: e, fn: o[e], scope: o.scope
});
item.on(e, o[e]);
}
}
return;
}
this.mons.push({
item: item, ename: ename, fn: fn, scope: scope
});
item.on(ename, fn, scope, opt);
},
/**
* 在所属的容器范围中范围旁边下一个的组件。
* Returns the next component in the owning container
* @return Ext.Component
*/
nextSibling : function(){
if(this.ownerCt){
var index = this.ownerCt.items.indexOf(this);
if(index != -1 && index+1 < this.ownerCt.items.getCount()){
return this.ownerCt.items.itemAt(index+1);
}
}
return null;
},
/**
* 在所属的容器范围中范围旁边上一个的组件。
* Returns the previous component in the owning container
* @return Ext.Component
*/
previousSibling : function(){
if(this.ownerCt){
var index = this.ownerCt.items.indexOf(this);
if(index > 0){
return this.ownerCt.items.itemAt(index-1);
}
}
return null;
},
/**
* 为Observable对象的fireEvent方法,方便对该组件的父级组件进行逐层上报。
* Provides the link for Observable's fireEvent method to bubble up the ownership hierarchy.
* @return 包含该组件的容器。the Container which owns this Component.
*/
getBubbleTarget : function(){
return this.ownerCt;
}
});
Ext.reg('component', Ext.Component);
| 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.Resizable
* @extends Ext.util.Observable
* <p>在元素上应用拖动柄以使其支持缩放。拖动柄是嵌入在元素内部的且采用了绝对定位。某些元素, 如文本域或图片, 不支持这种做法。为了克服这种情况, 你可以把文本域打包在一个 Div 内, 并把 "resizeChild" 属性设为 true(或者指向元素的 ID), <b>或者</b>在配置项中设置 wrap 属性为 true, 元素就会被自动打包了。</p>
* <p>下面是有效的拖动柄的值列表:</p>
* <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
* and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
* the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
* the element will be wrapped for you automatically.</p>
* <p>Here is the list of valid resize handles:</p>
* <pre>
Value Description
值 说明
------ -------------------
'n' 北(north)
's' 南(south)
'e' 东(east)
'w' 西(west)
'nw' 西北(northwest)
'sw' 西南(southwest)
'se' 东北(southeast)
'ne' 东南(northeast)
'all' 所有(all)
</pre>
* <p>下面是展示的是创建一个典型的 Resizable 对象的例子: Here's an example showing the creation of a typical Resizable:</p>
* <pre><code>
var resizer = new Ext.Resizable("element-id", {
handles: 'all',
minWidth: 200,
minHeight: 100,
maxWidth: 500,
maxHeight: 400,
pinned: true
});
resizer.on("resize", myHandler);
</code></pre>
* <p>想要隐藏某个缩放柄, 可以将它的CSS样式中的 display 属性设为 none, 或者通过脚本来实现: To hide a particular handle, set its display to none in CSS, or through script:<br>
* resizer.east.setDisplayed(false);</p>
* @cfg {Boolean/String/Element} resizeChild 值为 true 时缩放首个子对象, 或者值为 id/element 时缩放指定对象(默认为 false)。
* True to resize the first child, or id/element to resize (defaults to false)
* @cfg {Array/String} adjustments 可以是字串 "auto" 或者形如 [width, height] 的数组, 其值会在执行缩放操作的时候被<b>加入</b>。(默认为 [0, 0])。
* String "auto" or an array [width, height] with values to be <b>added</b> to the
* resize operation's new size (defaults to [0, 0])
* @cfg {Number} minWidth 元素允许的最小宽度(默认为 5)。
* The minimum width for the element (defaults to 5)
* @cfg {Number} minHeight 元素允许的最小高度(默认为 5)。
* The minimum height for the element (defaults to 5)
* @cfg {Number} maxWidth 元素允许的最大宽度(默认为 10000)。
* The maximum width for the element (defaults to 10000)
* @cfg {Number} maxHeight 元素允许的最大高度(默认为 10000)。
* The maximum height for the element (defaults to 10000)
* @cfg {Boolean} enabled 设为 false 可禁止缩放(默认为 true)。
* False to disable resizing (defaults to true)
* @cfg {Boolean} wrap 设为 true 则在需要的时候将元素用 div 打包(文本域和图片对象必须设置此属性, 默认为 false)。
* True to wrap an element with a div if needed (required for textareas and images, defaults to false)
* @cfg {Number} width 以像素表示的元素宽度(默认为 null)。
* The width of the element in pixels (defaults to null)
* @cfg {Number} height 以像素表示的元素高度(默认为 null)。
* The height of the element in pixels (defaults to null)
* @cfg {Boolean} animate 设为 true 则在缩放时展示动画效果(不可与 dynamic 同时使用, 默认为 false)。
* True to animate the resize (not compatible with dynamic sizing, defaults to false)
* @cfg {Number} duration 当 animate = true 时动画持续的时间(默认为 .35)。
* Animation duration if animate = true (defaults to .35)
* @cfg {Boolean} dynamic 设为 true 则对元素进行实时缩放而不使用代理(默认为 false)。True to resize the element while dragging instead of using a proxy (defaults to false)
* @cfg {String} handles 由要显示的缩放柄组成的字串(默认为 undefined) String consisting of the resize handles to display (defaults to undefined)
* @cfg {Boolean} multiDirectional <b>Deprecated</b>. 以前的添加多向缩放柄的方式,建议使用 handles 属性。(默认为 false) The old style of adding multi-direction resize handles, deprecated
* in favor of the handles config option (defaults to false)
* @cfg {Boolean} disableTrackOver 设为 true 则禁止鼠标跟踪。此属性仅在配置对象时可用。(默认为 false)。True to disable mouse tracking. This is only applied at config time. (defaults to false)
* @cfg {String} easing 指定当 animate = true 时的动画效果(默认为 'easingOutStrong')。Animation easing if animate = true (defaults to 'easingOutStrong')
* @cfg {Number} widthIncrement 以像素表示的宽度缩放增量(dynamic 属性必须为 true, 默认为 0)。The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
* @cfg {Number} heightIncrement 以像素表示的高度缩放增量(dynamic 属性必须为 true, 默认为 0)。The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
* @cfg {Boolean} pinned 设为 true 则保持缩放柄总是可见,false 则只在用户将鼠标经过 resizable 对象的边框时显示缩放柄。此属性仅在配置对象时可用。(默认为 false)。True to ensure that the resize handles are always visible, false to display them only when the
* user mouses over the resizable borders. This is only applied at config time. (defaults to false)
* @cfg {Boolean} preserveRatio 设为 true 则在缩放时保持对象的原始长宽比(默认为 false)。True to preserve the original ratio between height and width during resize (defaults to false)
* @cfg {Boolean} transparent 设为 true 则将缩放柄设为透明。此属性仅在配置对象时可用。(默认为 false)。True for transparent handles. This is only applied at config time. (defaults to false)
* @cfg {Number} minX The minimum allowed page X for the element (仅用于向左缩放时, 默认为 0) (only used for west resizing, defaults to 0)
* @cfg {Number} minY The minimum allowed page Y for the element (仅用于向上缩放时, 默认为 0) (only used for north resizing, defaults to 0)
* @cfg {Boolean} draggable 便利的初始化拖移的方法(默认为 false)。Convenience to initialize drag drop (defaults to false)
* @constructor
* 创建一个 resizable 对象。Create a new resizable component
* @param {Mixed} el 要缩放的对象的 id 或 element 对象。The id or element to resize
* @param {Object} config 配置项对象。configuration options
*/
Ext.Resizable = function(el, config){
this.el = Ext.get(el);
if(config && config.wrap){
config.resizeChild = this.el;
this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
this.el.setStyle("overflow", "hidden");
this.el.setPositioning(config.resizeChild.getPositioning());
config.resizeChild.clearPositioning();
if(!config.width || !config.height){
var csize = config.resizeChild.getSize();
this.el.setSize(csize.width, csize.height);
}
if(config.pinned && !config.adjustments){
config.adjustments = "auto";
}
}
/**
* 调节期间,代替真实元素的那个代理元素。
* 有时可能要{@link Ext.Element#getBox}方法提供相应的新区域。
* The proxy Element that is resized in place of the real Element during the resize operation.
* This may be queried using {@link Ext.Element#getBox} to provide the new area to resize to.
* Read only.
* @type Ext.Element.
* @property proxy
*/
this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"}, Ext.getBody());
this.proxy.unselectable();
this.proxy.enableDisplayMode('block');
Ext.apply(this, config);
if(this.pinned){
this.disableTrackOver = true;
this.el.addClass("x-resizable-pinned");
}
// if the element isn't positioned, make it relative
var position = this.el.getStyle("position");
if(position != "absolute" && position != "fixed"){
this.el.setStyle("position", "relative");
}
if(!this.handles){ // no handles passed, must be legacy style
this.handles = 's,e,se';
if(this.multiDirectional){
this.handles += ',n,w';
}
}
if(this.handles == "all"){
this.handles = "n s e w ne nw se sw";
}
var hs = this.handles.split(/\s*?[,;]\s*?| /);
var ps = Ext.Resizable.positions;
for(var i = 0, len = hs.length; i < len; i++){
if(hs[i] && ps[hs[i]]){
var pos = ps[hs[i]];
this[pos] = new Ext.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
}
}
// legacy
this.corner = this.southeast;
if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1){
this.updateBox = true;
}
this.activeHandle = null;
if(this.resizeChild){
if(typeof this.resizeChild == "boolean"){
this.resizeChild = Ext.get(this.el.dom.firstChild, true);
}else{
this.resizeChild = Ext.get(this.resizeChild, true);
}
}
if(this.adjustments == "auto"){
var rc = this.resizeChild;
var hw = this.west, he = this.east, hn = this.north, hs = this.south;
if(rc && (hw || hn)){
rc.position("relative");
rc.setLeft(hw ? hw.el.getWidth() : 0);
rc.setTop(hn ? hn.el.getHeight() : 0);
}
this.adjustments = [
(he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
(hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
];
}
if(this.draggable){
this.dd = this.dynamic ?
this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
}
// public events
this.addEvents(
"beforeresize",
"resize"
);
if(this.width !== null && this.height !== null){
this.resizeTo(this.width, this.height);
}else{
this.updateChildSize();
}
if(Ext.isIE){
this.el.dom.style.zoom = 1;
}
Ext.Resizable.superclass.constructor.call(this);
};
Ext.extend(Ext.Resizable, Ext.util.Observable, {
resizeChild : false,
adjustments : [0, 0],
minWidth : 5,
minHeight : 5,
maxWidth : 10000,
maxHeight : 10000,
enabled : true,
animate : false,
duration : .35,
dynamic : false,
handles : false,
multiDirectional : false,
disableTrackOver : false,
easing : 'easeOutStrong',
widthIncrement : 0,
heightIncrement : 0,
pinned : false,
width : null,
height : null,
preserveRatio : false,
transparent: false,
minX: 0,
minY: 0,
draggable: false,
/**
* @cfg {Mixed} constrainTo 强制缩放到一个指定的元素。
* Constrain the resize to a particular element
*/
/**
* @cfg {Ext.lib.Region} resizeRegion 强制缩放到一个指定区域。
* Constrain the resize to a particular region
*/
/**
* @event beforeresize
* 在缩放被实施之前触发。设置 enabled 为 false 可以取消缩放。
* Fired before resize is allowed. Set enabled to false to cancel resize.
* @param {Ext.Resizable} this
* @param {Ext.EventObject} e mousedown事件。The mousedown event
*/
/**
* @event resize
* 缩放之后触发。
* Fired after a resize.
* @param {Ext.Resizable} this
* @param {Number} width 新的宽度。The new width
* @param {Number} height 新的高度。The new height
* @param {Ext.EventObject} e mouseup事件。The mouseup event
*/
/**
* 执行手动缩放。
* Perform a manual resize
* @param {Number} width
* @param {Number} height
*/
resizeTo : function(width, height){
this.el.setSize(width, height);
this.updateChildSize();
this.fireEvent("resize", this, width, height, null);
},
// private
startSizing : function(e, handle){
this.fireEvent("beforeresize", this, e);
if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
if(!this.overlay){
this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: " "}, Ext.getBody());
this.overlay.unselectable();
this.overlay.enableDisplayMode("block");
this.overlay.on("mousemove", this.onMouseMove, this);
this.overlay.on("mouseup", this.onMouseUp, this);
}
this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
this.resizing = true;
this.startBox = this.el.getBox();
this.startPoint = e.getXY();
this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
(this.startBox.y + this.startBox.height) - this.startPoint[1]];
this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
this.overlay.show();
if(this.constrainTo) {
var ct = Ext.get(this.constrainTo);
this.resizeRegion = ct.getRegion().adjust(
ct.getFrameWidth('t'),
ct.getFrameWidth('l'),
-ct.getFrameWidth('b'),
-ct.getFrameWidth('r')
);
}
this.proxy.setStyle('visibility', 'hidden'); // workaround display none
this.proxy.show();
this.proxy.setBox(this.startBox);
if(!this.dynamic){
this.proxy.setStyle('visibility', 'visible');
}
}
},
// private
onMouseDown : function(handle, e){
if(this.enabled){
e.stopEvent();
this.activeHandle = handle;
this.startSizing(e, handle);
}
},
// private
onMouseUp : function(e){
var size = this.resizeElement();
this.resizing = false;
this.handleOut();
this.overlay.hide();
this.proxy.hide();
this.fireEvent("resize", this, size.width, size.height, e);
},
// private
updateChildSize : function(){
if(this.resizeChild){
var el = this.el;
var child = this.resizeChild;
var adj = this.adjustments;
if(el.dom.offsetWidth){
var b = el.getSize(true);
child.setSize(b.width+adj[0], b.height+adj[1]);
}
// Second call here for IE
// The first call enables instant resizing and
// the second call corrects scroll bars if they
// exist
if(Ext.isIE){
setTimeout(function(){
if(el.dom.offsetWidth){
var b = el.getSize(true);
child.setSize(b.width+adj[0], b.height+adj[1]);
}
}, 10);
}
}
},
// private
snap : function(value, inc, min){
if(!inc || !value) return value;
var newValue = value;
var m = value % inc;
if(m > 0){
if(m > (inc/2)){
newValue = value + (inc-m);
}else{
newValue = value - m;
}
}
return Math.max(min, newValue);
},
/**
* <p>
* 对相关的元素进行大小调节。该方法是类的内部方法,不该由用户的代码所调用。
* Performs resizing of the associated Element. This method is called internally by this
* class, and should not be called by user code.
* </p>
* <p>如果Resizable用于一个复杂的UI的组件之元素,如Panel,
* 那么该方法可能由实作来重写,以便在最后的mouseup事件有特殊的操作,例如对Panel面板的大小调节,就取决于Panel的内容。
* If a Resizable is being used to resize an Element which encapsulates a more complex UI
* component such as a Panel, this method may be overridden by specifying an implementation
* as a config option to provide appropriate behaviour at the end of the resize operation on
* mouseup, for example resizing the Panel, and relaying the Panel's content.</p>
* <p>
* 调节过后的新区域可以通过检查{@link #proxy}元素状态的情况而得知。例如:
* The new area to be resized to is available by examining the state of the {@link #proxy}
* Element. Example:
<pre><code>
new Ext.Panel({
title: 'Resize me',
x: 100,
y: 100,
renderTo: Ext.getBody(),
floating: true,
frame: true,
width: 400,
height: 200,
listeners: {
render: function(p) {
new Ext.Resizable(p.getEl(), {
handles: 'all',
pinned: true,
transparent: true,
resizeElement: function() {
var box = this.proxy.getBox();
p.updateBox(box);
if (p.layout) {
p.doLayout();
}
return box;
}
});
}
}
}).show();
</code></pre>
*/
resizeElement : function(){
var box = this.proxy.getBox();
if(this.updateBox){
this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
}else{
this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
}
this.updateChildSize();
if(!this.dynamic){
this.proxy.hide();
}
return box;
},
// private
constrain : function(v, diff, m, mx){
if(v - diff < m){
diff = v - m;
}else if(v - diff > mx){
diff = mx - v;
}
return diff;
},
// private
onMouseMove : function(e){
if(this.enabled){
try{// try catch so if something goes wrong the user doesn't get hung
if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
return;
}
//var curXY = this.startPoint;
var curSize = this.curSize || this.startBox;
var x = this.startBox.x, y = this.startBox.y;
var ox = x, oy = y;
var w = curSize.width, h = curSize.height;
var ow = w, oh = h;
var mw = this.minWidth, mh = this.minHeight;
var mxw = this.maxWidth, mxh = this.maxHeight;
var wi = this.widthIncrement;
var hi = this.heightIncrement;
var eventXY = e.getXY();
var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
var pos = this.activeHandle.position;
switch(pos){
case "east":
w += diffX;
w = Math.min(Math.max(mw, w), mxw);
break;
case "south":
h += diffY;
h = Math.min(Math.max(mh, h), mxh);
break;
case "southeast":
w += diffX;
h += diffY;
w = Math.min(Math.max(mw, w), mxw);
h = Math.min(Math.max(mh, h), mxh);
break;
case "north":
diffY = this.constrain(h, diffY, mh, mxh);
y += diffY;
h -= diffY;
break;
case "west":
diffX = this.constrain(w, diffX, mw, mxw);
x += diffX;
w -= diffX;
break;
case "northeast":
w += diffX;
w = Math.min(Math.max(mw, w), mxw);
diffY = this.constrain(h, diffY, mh, mxh);
y += diffY;
h -= diffY;
break;
case "northwest":
diffX = this.constrain(w, diffX, mw, mxw);
diffY = this.constrain(h, diffY, mh, mxh);
y += diffY;
h -= diffY;
x += diffX;
w -= diffX;
break;
case "southwest":
diffX = this.constrain(w, diffX, mw, mxw);
h += diffY;
h = Math.min(Math.max(mh, h), mxh);
x += diffX;
w -= diffX;
break;
}
var sw = this.snap(w, wi, mw);
var sh = this.snap(h, hi, mh);
if(sw != w || sh != h){
switch(pos){
case "northeast":
y -= sh - h;
break;
case "north":
y -= sh - h;
break;
case "southwest":
x -= sw - w;
break;
case "west":
x -= sw - w;
break;
case "northwest":
x -= sw - w;
y -= sh - h;
break;
}
w = sw;
h = sh;
}
if(this.preserveRatio){
switch(pos){
case "southeast":
case "east":
h = oh * (w/ow);
h = Math.min(Math.max(mh, h), mxh);
w = ow * (h/oh);
break;
case "south":
w = ow * (h/oh);
w = Math.min(Math.max(mw, w), mxw);
h = oh * (w/ow);
break;
case "northeast":
w = ow * (h/oh);
w = Math.min(Math.max(mw, w), mxw);
h = oh * (w/ow);
break;
case "north":
var tw = w;
w = ow * (h/oh);
w = Math.min(Math.max(mw, w), mxw);
h = oh * (w/ow);
x += (tw - w) / 2;
break;
case "southwest":
h = oh * (w/ow);
h = Math.min(Math.max(mh, h), mxh);
var tw = w;
w = ow * (h/oh);
x += tw - w;
break;
case "west":
var th = h;
h = oh * (w/ow);
h = Math.min(Math.max(mh, h), mxh);
y += (th - h) / 2;
var tw = w;
w = ow * (h/oh);
x += tw - w;
break;
case "northwest":
var tw = w;
var th = h;
h = oh * (w/ow);
h = Math.min(Math.max(mh, h), mxh);
w = ow * (h/oh);
y += th - h;
x += tw - w;
break;
}
}
this.proxy.setBounds(x, y, w, h);
if(this.dynamic){
this.resizeElement();
}
}catch(e){}
}
},
// private
handleOver : function(){
if(this.enabled){
this.el.addClass("x-resizable-over");
}
},
// private
handleOut : function(){
if(!this.resizing){
this.el.removeClass("x-resizable-over");
}
},
/**
* 返回此组件绑定的element对象。
* Returns the element this component is bound to.
* @return {Ext.Element}
*/
getEl : function(){
return this.el;
},
/**
* 返回resizeChild属性指定的element对象(如果没有则返回null)。
* Returns the resizeChild element (or null).
* @return {Ext.Element}
*/
getResizeChild : function(){
return this.resizeChild;
},
/**
* 销毁此resizable对象。如果元素被打包且 removeEl 属性不为 true 则元素会保留。
* Destroys this resizable. If the element was wrapped and removeEl is not true then the element remains.
* @param {Boolean} removeEl (可选的)设为 true 则从 DOM 中删除此元素。(optional) true to remove the element from the DOM
*/
destroy : function(removeEl){
if(this.dd){
this.dd.destroy();
}
if(this.overlay){
Ext.destroy(this.overlay);
this.overlay = null;
}
Ext.destroy(this.proxy);
this.proxy = null;
var ps = Ext.Resizable.positions;
for(var k in ps){
if(typeof ps[k] != "function" && this[ps[k]]){
this[ps[k]].destroy();
}
}
if(removeEl){
this.el.update("");
Ext.destroy(this.el);
this.el = null;
}
},
syncHandleHeight : function(){
var h = this.el.getHeight(true);
if(this.west){
this.west.el.setHeight(h);
}
if(this.east){
this.east.el.setHeight(h);
}
}
});
// private
// hash to map config positions to true positions
Ext.Resizable.positions = {
n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast"
};
// private
Ext.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
if(!this.tpl){
// only initialize the template if resizable is used
var tpl = Ext.DomHelper.createTemplate(
{tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
);
tpl.compile();
Ext.Resizable.Handle.prototype.tpl = tpl;
}
this.position = pos;
this.rz = rz;
this.el = this.tpl.append(rz.el.dom, [this.position], true);
this.el.unselectable();
if(transparent){
this.el.setOpacity(0);
}
this.el.on("mousedown", this.onMouseDown, this);
if(!disableTrackOver){
this.el.on("mouseover", this.onMouseOver, this);
this.el.on("mouseout", this.onMouseOut, this);
}
};
// private
Ext.Resizable.Handle.prototype = {
// private
afterResize : function(rz){
// do nothing
},
// private
onMouseDown : function(e){
this.rz.onMouseDown(this, e);
},
// private
onMouseOver : function(e){
this.rz.handleOver(this, e);
},
// private
onMouseOut : function(e){
this.rz.handleOut(this, e);
},
// private
destroy : function(){
Ext.destroy(this.el);
this.el = null;
}
};
| JavaScript |
/*!
* Ext JS Library 3.1.1
* Copyright(c) 2006-2010 Ext JS, LLC
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.FlashProxy
* @singleton
*/
Ext.FlashEventProxy = {
onEvent : function(id, e){
var fp = Ext.getCmp(id);
if(fp){
fp.onFlashEvent(e);
}else{
arguments.callee.defer(10, this, [id, e]);
}
}
} | JavaScript |
/*!
* Ext JS Library 3.1.1
* Copyright(c) 2006-2010 Ext JS, LLC
* licensing@extjs.com
* http://www.extjs.com/license
*/
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject = function() {
var UNDEF = "undefined",
OBJECT = "object",
SHOCKWAVE_FLASH = "Shockwave Flash",
SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
FLASH_MIME_TYPE = "application/x-shockwave-flash",
EXPRESS_INSTALL_ID = "SWFObjectExprInst",
ON_READY_STATE_CHANGE = "onreadystatechange",
win = window,
doc = document,
nav = navigator,
plugin = false,
domLoadFnArr = [main],
regObjArr = [],
objIdArr = [],
listenersArr = [],
storedAltContent,
storedAltContentId,
storedCallbackFn,
storedCallbackObj,
isDomLoaded = false,
isExpressInstallActive = false,
dynamicStylesheet,
dynamicStylesheetMedia,
autoHideShow = true,
/* Centralized function for browser feature detection
- User agent string detection is only used when no good alternative is possible
- Is executed directly for optimal performance
*/
ua = function() {
var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
u = nav.userAgent.toLowerCase(),
p = nav.platform.toLowerCase(),
windows = p ? /win/.test(p) : /win/.test(u),
mac = p ? /mac/.test(p) : /mac/.test(u),
webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
playerVersion = [0,0,0],
d = null;
if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
d = nav.plugins[SHOCKWAVE_FLASH].description;
if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
plugin = true;
ie = false; // cascaded feature detection for Internet Explorer
d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
}
}
else if (typeof win.ActiveXObject != UNDEF) {
try {
var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
if (a) { // a will return null when ActiveX is disabled
d = a.GetVariable("$version");
if (d) {
ie = true; // cascaded feature detection for Internet Explorer
d = d.split(" ")[1].split(",");
playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
}
catch(e) {}
}
return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
}(),
/* Cross-browser onDomLoad
- Will fire an event as soon as the DOM of a web page is loaded
- Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
- Regular onload serves as fallback
*/
onDomLoad = function() {
if (!ua.w3) { return; }
if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
callDomLoadFunctions();
}
if (!isDomLoaded) {
if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
}
if (ua.ie && ua.win) {
doc.attachEvent(ON_READY_STATE_CHANGE, function() {
if (doc.readyState == "complete") {
doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
callDomLoadFunctions();
}
});
if (win == top) { // if not inside an iframe
(function(){
if (isDomLoaded) { return; }
try {
doc.documentElement.doScroll("left");
}
catch(e) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
}
if (ua.wk) {
(function(){
if (isDomLoaded) { return; }
if (!/loaded|complete/.test(doc.readyState)) {
setTimeout(arguments.callee, 0);
return;
}
callDomLoadFunctions();
})();
}
addLoadEvent(callDomLoadFunctions);
}
}();
function callDomLoadFunctions() {
if (isDomLoaded) { return; }
try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
t.parentNode.removeChild(t);
}
catch (e) { return; }
isDomLoaded = true;
var dl = domLoadFnArr.length;
for (var i = 0; i < dl; i++) {
domLoadFnArr[i]();
}
}
function addDomLoadEvent(fn) {
if (isDomLoaded) {
fn();
}
else {
domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
}
}
/* Cross-browser onload
- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
- Will fire an event as soon as a web page including all of its assets are loaded
*/
function addLoadEvent(fn) {
if (typeof win.addEventListener != UNDEF) {
win.addEventListener("load", fn, false);
}
else if (typeof doc.addEventListener != UNDEF) {
doc.addEventListener("load", fn, false);
}
else if (typeof win.attachEvent != UNDEF) {
addListener(win, "onload", fn);
}
else if (typeof win.onload == "function") {
var fnOld = win.onload;
win.onload = function() {
fnOld();
fn();
};
}
else {
win.onload = fn;
}
}
/* Main function
- Will preferably execute onDomLoad, otherwise onload (as a fallback)
*/
function main() {
if (plugin) {
testPlayerVersion();
}
else {
matchVersions();
}
}
/* Detect the Flash Player version for non-Internet Explorer browsers
- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
a. Both release and build numbers can be detected
b. Avoid wrong descriptions by corrupt installers provided by Adobe
c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
*/
function testPlayerVersion() {
var b = doc.getElementsByTagName("body")[0];
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
var t = b.appendChild(o);
if (t) {
var counter = 0;
(function(){
if (typeof t.GetVariable != UNDEF) {
var d = t.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
}
else if (counter < 10) {
counter++;
setTimeout(arguments.callee, 10);
return;
}
b.removeChild(o);
t = null;
matchVersions();
})();
}
else {
matchVersions();
}
}
/* Perform Flash Player and SWF version matching; static publishing only
*/
function matchVersions() {
var rl = regObjArr.length;
if (rl > 0) {
for (var i = 0; i < rl; i++) { // for each registered object element
var id = regObjArr[i].id;
var cb = regObjArr[i].callbackFn;
var cbObj = {success:false, id:id};
if (ua.pv[0] > 0) {
var obj = getElementById(id);
if (obj) {
if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
setVisibility(id, true);
if (cb) {
cbObj.success = true;
cbObj.ref = getObjectById(id);
cb(cbObj);
}
}
else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
var att = {};
att.data = regObjArr[i].expressInstall;
att.width = obj.getAttribute("width") || "0";
att.height = obj.getAttribute("height") || "0";
if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
// parse HTML object param element's name-value pairs
var par = {};
var p = obj.getElementsByTagName("param");
var pl = p.length;
for (var j = 0; j < pl; j++) {
if (p[j].getAttribute("name").toLowerCase() != "movie") {
par[p[j].getAttribute("name")] = p[j].getAttribute("value");
}
}
showExpressInstall(att, par, id, cb);
}
else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
displayAltContent(obj);
if (cb) { cb(cbObj); }
}
}
}
else { // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
setVisibility(id, true);
if (cb) {
var o = getObjectById(id); // test whether there is an HTML object element or not
if (o && typeof o.SetVariable != UNDEF) {
cbObj.success = true;
cbObj.ref = o;
}
cb(cbObj);
}
}
}
}
}
function getObjectById(objectIdStr) {
var r = null;
var o = getElementById(objectIdStr);
if (o && o.nodeName == "OBJECT") {
if (typeof o.SetVariable != UNDEF) {
r = o;
}
else {
var n = o.getElementsByTagName(OBJECT)[0];
if (n) {
r = n;
}
}
}
return r;
}
/* Requirements for Adobe Express Install
- only one instance can be active at a time
- fp 6.0.65 or higher
- Win/Mac OS only
- no Webkit engines older than version 312
*/
function canExpressInstall() {
return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
}
/* Show the Adobe Express Install dialog
- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
*/
function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
isExpressInstallActive = true;
storedCallbackFn = callbackFn || null;
storedCallbackObj = {success:false, id:replaceElemIdStr};
var obj = getElementById(replaceElemIdStr);
if (obj) {
if (obj.nodeName == "OBJECT") { // static publishing
storedAltContent = abstractAltContent(obj);
storedAltContentId = null;
}
else { // dynamic publishing
storedAltContent = obj;
storedAltContentId = replaceElemIdStr;
}
att.id = EXPRESS_INSTALL_ID;
if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + fv;
}
else {
par.flashvars = fv;
}
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
if (ua.ie && ua.win && obj.readyState != 4) {
var newObj = createElement("div");
replaceElemIdStr += "SWFObjectNew";
newObj.setAttribute("id", replaceElemIdStr);
obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
createSWF(att, par, replaceElemIdStr);
}
}
/* Functions to abstract and display alternative content
*/
function displayAltContent(obj) {
if (ua.ie && ua.win && obj.readyState != 4) {
// IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
// because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
var el = createElement("div");
obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
el.parentNode.replaceChild(abstractAltContent(obj), el);
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
obj.parentNode.removeChild(obj);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.replaceChild(abstractAltContent(obj), obj);
}
}
function abstractAltContent(obj) {
var ac = createElement("div");
if (ua.win && ua.ie) {
ac.innerHTML = obj.innerHTML;
}
else {
var nestedObj = obj.getElementsByTagName(OBJECT)[0];
if (nestedObj) {
var c = nestedObj.childNodes;
if (c) {
var cl = c.length;
for (var i = 0; i < cl; i++) {
if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
ac.appendChild(c[i].cloneNode(true));
}
}
}
}
}
return ac;
}
/* Cross-browser dynamic SWF creation
*/
function createSWF(attObj, parObj, id) {
var r, el = getElementById(id);
if (ua.wk && ua.wk < 312) { return r; }
if (el) {
if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
attObj.id = id;
}
if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
var att = "";
for (var i in attObj) {
if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
if (i.toLowerCase() == "data") {
parObj.movie = attObj[i];
}
else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
att += ' class="' + attObj[i] + '"';
}
else if (i.toLowerCase() != "classid") {
att += ' ' + i + '="' + attObj[i] + '"';
}
}
}
var par = "";
for (var j in parObj) {
if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
par += '<param name="' + j + '" value="' + parObj[j] + '" />';
}
}
el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
r = getElementById(attObj.id);
}
else { // well-behaving browsers
var o = createElement(OBJECT);
o.setAttribute("type", FLASH_MIME_TYPE);
for (var m in attObj) {
if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
o.setAttribute("class", attObj[m]);
}
else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
o.setAttribute(m, attObj[m]);
}
}
}
for (var n in parObj) {
if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
createObjParam(o, n, parObj[n]);
}
}
el.parentNode.replaceChild(o, el);
r = o;
}
}
return r;
}
function createObjParam(el, pName, pValue) {
var p = createElement("param");
p.setAttribute("name", pName);
p.setAttribute("value", pValue);
el.appendChild(p);
}
/* Cross-browser SWF removal
- Especially needed to safely and completely remove a SWF in Internet Explorer
*/
function removeSWF(id) {
var obj = getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (ua.ie && ua.win) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
removeObjectInIE(id);
}
else {
setTimeout(arguments.callee, 10);
}
})();
}
else {
obj.parentNode.removeChild(obj);
}
}
}
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
/* Functions to optimize JavaScript compression
*/
function getElementById(id) {
var el = null;
try {
el = doc.getElementById(id);
}
catch (e) {}
return el;
}
function createElement(el) {
return doc.createElement(el);
}
/* Updated attachEvent function for Internet Explorer
- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
*/
function addListener(target, eventType, fn) {
target.attachEvent(eventType, fn);
listenersArr[listenersArr.length] = [target, eventType, fn];
}
/* Flash Player and SWF content version matching
*/
function hasPlayerVersion(rv) {
var pv = ua.pv, v = rv.split(".");
v[0] = parseInt(v[0], 10);
v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
v[2] = parseInt(v[2], 10) || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
}
/* Cross-browser dynamic CSS creation
- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
*/
function createCSS(sel, decl, media, newStyle) {
if (ua.ie && ua.mac) { return; }
var h = doc.getElementsByTagName("head")[0];
if (!h) { return; } // to also support badly authored HTML pages that lack a head element
var m = (media && typeof media == "string") ? media : "screen";
if (newStyle) {
dynamicStylesheet = null;
dynamicStylesheetMedia = null;
}
if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
// create dynamic stylesheet + get a global reference to it
var s = createElement("style");
s.setAttribute("type", "text/css");
s.setAttribute("media", m);
dynamicStylesheet = h.appendChild(s);
if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
}
dynamicStylesheetMedia = m;
}
// add style rule
if (ua.ie && ua.win) {
if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
dynamicStylesheet.addRule(sel, decl);
}
}
else {
if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
}
}
}
function setVisibility(id, isVisible) {
if (!autoHideShow) { return; }
var v = isVisible ? "visible" : "hidden";
if (isDomLoaded && getElementById(id)) {
getElementById(id).style.visibility = v;
}
else {
createCSS("#" + id, "visibility:" + v);
}
}
/* Filter to avoid XSS attacks
*/
function urlEncodeIfNecessary(s) {
var regex = /[\\\"<>\.;]/;
var hasBadChars = regex.exec(s) != null;
return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
}
/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
*/
var cleanup = function() {
if (ua.ie && ua.win) {
window.attachEvent("onunload", function() {
// remove listeners to avoid memory leaks
var ll = listenersArr.length;
for (var i = 0; i < ll; i++) {
listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
}
// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
var il = objIdArr.length;
for (var j = 0; j < il; j++) {
removeSWF(objIdArr[j]);
}
// cleanup library's main closures to avoid memory leaks
for (var k in ua) {
ua[k] = null;
}
ua = null;
for (var l in swfobject) {
swfobject[l] = null;
}
swfobject = null;
});
}
}();
return {
/* Public API
- Reference: http://code.google.com/p/swfobject/wiki/documentation
*/
registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
if (ua.w3 && objectIdStr && swfVersionStr) {
var regObj = {};
regObj.id = objectIdStr;
regObj.swfVersion = swfVersionStr;
regObj.expressInstall = xiSwfUrlStr;
regObj.callbackFn = callbackFn;
regObjArr[regObjArr.length] = regObj;
setVisibility(objectIdStr, false);
}
else if (callbackFn) {
callbackFn({success:false, id:objectIdStr});
}
},
getObjectById: function(objectIdStr) {
if (ua.w3) {
return getObjectById(objectIdStr);
}
},
embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
var callbackObj = {success:false, id:replaceElemIdStr};
if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
setVisibility(replaceElemIdStr, false);
addDomLoadEvent(function() {
widthStr += ""; // auto-convert to string
heightStr += "";
var att = {};
if (attObj && typeof attObj === OBJECT) {
for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
att[i] = attObj[i];
}
}
att.data = swfUrlStr;
att.width = widthStr;
att.height = heightStr;
var par = {};
if (parObj && typeof parObj === OBJECT) {
for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
par[j] = parObj[j];
}
}
if (flashvarsObj && typeof flashvarsObj === OBJECT) {
for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
if (typeof par.flashvars != UNDEF) {
par.flashvars += "&" + k + "=" + flashvarsObj[k];
}
else {
par.flashvars = k + "=" + flashvarsObj[k];
}
}
}
if (hasPlayerVersion(swfVersionStr)) { // create SWF
var obj = createSWF(att, par, replaceElemIdStr);
if (att.id == replaceElemIdStr) {
setVisibility(replaceElemIdStr, true);
}
callbackObj.success = true;
callbackObj.ref = obj;
}
else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
att.data = xiSwfUrlStr;
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
return;
}
else { // show alternative content
setVisibility(replaceElemIdStr, true);
}
if (callbackFn) { callbackFn(callbackObj); }
});
}
else if (callbackFn) { callbackFn(callbackObj); }
},
switchOffAutoHideShow: function() {
autoHideShow = false;
},
ua: ua,
getFlashPlayerVersion: function() {
return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
},
hasFlashPlayerVersion: hasPlayerVersion,
createSWF: function(attObj, parObj, replaceElemIdStr) {
if (ua.w3) {
return createSWF(attObj, parObj, replaceElemIdStr);
}
else {
return undefined;
}
},
showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
if (ua.w3 && canExpressInstall()) {
showExpressInstall(att, par, replaceElemIdStr, callbackFn);
}
},
removeSWF: function(objElemIdStr) {
if (ua.w3) {
removeSWF(objElemIdStr);
}
},
createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
if (ua.w3) {
createCSS(selStr, declStr, mediaStr, newStyleBoolean);
}
},
addDomLoadEvent: addDomLoadEvent,
addLoadEvent: addLoadEvent,
getQueryParamValue: function(param) {
var q = doc.location.search || doc.location.hash;
if (q) {
if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
if (param == null) {
return urlEncodeIfNecessary(q);
}
var pairs = q.split("&");
for (var i = 0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
}
}
}
return "";
},
// For internal usage only
expressInstallCallback: function() {
if (isExpressInstallActive) {
var obj = getElementById(EXPRESS_INSTALL_ID);
if (obj && storedAltContent) {
obj.parentNode.replaceChild(storedAltContent, obj);
if (storedAltContentId) {
setVisibility(storedAltContentId, true);
if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
}
if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
}
isExpressInstallActive = 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.DomHelper
* 处理DOM或模板(Templates)的实用类。
* 能以JavaScript较清晰地编写HTML片段(HTML fragments)或DOM。
* 这是一个范例,产生五个子元素的无须列表,追加到当前元素'my-div':<br>
<pre><code>
var list = dh.append('my-div', {
tag: 'ul', cls: 'my-list', children: [
{tag: 'li', id: 'item0', html: 'List Item 0'},
{tag: 'li', id: 'item1', html: 'List Item 1'},
{tag: 'li', id: 'item2', html: 'List Item 2'},
{tag: 'li', id: 'item3', html: 'List Item 3'},
{tag: 'li', id: 'item4', html: 'List Item 4'}
]
});
</code></pre>
* 更多资讯,请参阅 <a href="http://www.jackslocum.com/yui/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">BLOG和一些例子</a>.
* @singleton
*/
Ext.DomHelper = function(){
var tempTableEl = null;
var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
var tableRe = /^table|tbody|tr|td$/i;
// build as innerHTML where available
/** @ignore */
var createHtml = function(o){
if(typeof o == 'string'){
return o;
}
var b = "";
if(!o.tag){
o.tag = "div";
}
b += "<" + o.tag;
for(var attr in o){
if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;
if(attr == "style"){
var s = o["style"];
if(typeof s == "function"){
s = s.call();
}
if(typeof s == "string"){
b += ' style="' + s + '"';
}else if(typeof s == "object"){
b += ' style="';
for(var key in s){
if(typeof s[key] != "function"){
b += key + ":" + s[key] + ";";
}
}
b += '"';
}
}else{
if(attr == "cls"){
b += ' class="' + o["cls"] + '"';
}else if(attr == "htmlFor"){
b += ' for="' + o["htmlFor"] + '"';
}else{
b += " " + attr + '="' + o[attr] + '"';
}
}
}
if(emptyTags.test(o.tag)){
b += "/>";
}else{
b += ">";
var cn = o.children || o.cn;
if(cn){
if(cn instanceof Array){
for(var i = 0, len = cn.length; i < len; i++) {
b += createHtml(cn[i], b);
}
}else{
b += createHtml(cn, b);
}
}
if(o.html){
b += o.html;
}
b += "</" + o.tag + ">";
}
return b;
};
// build as dom
/** @ignore */
var createDom = function(o, parentNode){
var el = document.createElement(o.tag||'div');
var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
for(var attr in o){
if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || attr == "style" || typeof o[attr] == "function") continue;
if(attr=="cls"){
el.className = o["cls"];
}else{
if(useSet) el.setAttribute(attr, o[attr]);
else el[attr] = o[attr];
}
}
Ext.DomHelper.applyStyles(el, o.style);
var cn = o.children || o.cn;
if(cn){
if(cn instanceof Array){
for(var i = 0, len = cn.length; i < len; i++) {
createDom(cn[i], el);
}
}else{
createDom(cn, el);
}
}
if(o.html){
el.innerHTML = o.html;
}
if(parentNode){
parentNode.appendChild(el);
}
return el;
};
var ieTable = function(depth, s, h, e){
tempTableEl.innerHTML = [s, h, e].join('');
var i = -1, el = tempTableEl;
while(++i < depth){
el = el.firstChild;
}
return el;
};
// kill repeat to save bytes
var ts = '<table>',
te = '</table>',
tbs = ts+'<tbody>',
tbe = '</tbody>'+te,
trs = tbs + '<tr>',
tre = '</tr>'+tbe;
/**
* @ignore
* Nasty code for IE's broken table implementation
*/
var insertIntoTable = function(tag, where, el, html){
if(!tempTableEl){
tempTableEl = document.createElement('div');
}
var node;
var before = null;
if(tag == 'td'){
if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
return;
}
if(where == 'beforebegin'){
before = el;
el = el.parentNode;
} else{
before = el.nextSibling;
el = el.parentNode;
}
node = ieTable(4, trs, html, tre);
}
else if(tag == 'tr'){
if(where == 'beforebegin'){
before = el;
el = el.parentNode;
node = ieTable(3, tbs, html, tbe);
} else if(where == 'afterend'){
before = el.nextSibling;
el = el.parentNode;
node = ieTable(3, tbs, html, tbe);
} else{ // INTO a TR
if(where == 'afterbegin'){
before = el.firstChild;
}
node = ieTable(4, trs, html, tre);
}
} else if(tag == 'tbody'){
if(where == 'beforebegin'){
before = el;
el = el.parentNode;
node = ieTable(2, ts, html, te);
} else if(where == 'afterend'){
before = el.nextSibling;
el = el.parentNode;
node = ieTable(2, ts, html, te);
} else{
if(where == 'afterbegin'){
before = el.firstChild;
}
node = ieTable(3, tbs, html, tbe);
}
} else{ // TABLE
if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
return;
}
if(where == 'afterbegin'){
before = el.firstChild;
}
node = ieTable(2, ts, html, te);
}
el.insertBefore(node, before);
return node;
};
return {
/**
* True表示为强制使用DOM而非html片断
* @type Boolean
*/
useDom : false,
/**
* 返回元素的装饰(markup)
* @param {Object} o DOM对象(包含子孙)
* @return {String}
*/
markup : function(o){
return createHtml(o);
},
/**
* 把指定的样式应用到元素
* @param {String/HTMLElement} el 样式所应用的元素
* @param {String/Object/Function} styles 表示样式的特定格式字符串,如“width:100px”,或是对象的形式如{width:"100px"},或是能返回这些格式的函数
*/
applyStyles : function(el, styles){
if(styles){
el = Ext.fly(el);
if(typeof styles == "string"){
var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
var matches;
while ((matches = re.exec(styles)) != null){
el.setStyle(matches[1], matches[2]);
}
}else if (typeof styles == "object"){
for (var style in styles){
el.setStyle(style, styles[style]);
}
}else if (typeof styles == "function"){
Ext.DomHelper.applyStyles(el, styles.call());
}
}
},
/**
* 插入HTML片断到Dom
* @param {String} where 插入的html要放在元素的哪里 - beforeBegin, afterBegin, beforeEnd, afterEnd.
* @param {HTMLElement} el 元素内容
* @param {String} html HTML片断
* @return {HTMLElement} 新节点
*/
insertHtml : function(where, el, html){
where = where.toLowerCase();
if(el.insertAdjacentHTML){
if(tableRe.test(el.tagName)){
var rs;
if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
return rs;
}
}
switch(where){
case "beforebegin":
el.insertAdjacentHTML('BeforeBegin', html);
return el.previousSibling;
case "afterbegin":
el.insertAdjacentHTML('AfterBegin', html);
return el.firstChild;
case "beforeend":
el.insertAdjacentHTML('BeforeEnd', html);
return el.lastChild;
case "afterend":
el.insertAdjacentHTML('AfterEnd', html);
return el.nextSibling;
}
throw 'Illegal insertion point -> "' + where + '"';
}
var range = el.ownerDocument.createRange();
var frag;
switch(where){
case "beforebegin":
range.setStartBefore(el);
frag = range.createContextualFragment(html);
el.parentNode.insertBefore(frag, el);
return el.previousSibling;
case "afterbegin":
if(el.firstChild){
range.setStartBefore(el.firstChild);
frag = range.createContextualFragment(html);
el.insertBefore(frag, el.firstChild);
return el.firstChild;
}else{
el.innerHTML = html;
return el.firstChild;
}
case "beforeend":
if(el.lastChild){
range.setStartAfter(el.lastChild);
frag = range.createContextualFragment(html);
el.appendChild(frag);
return el.lastChild;
}else{
el.innerHTML = html;
return el.lastChild;
}
case "afterend":
range.setStartAfter(el);
frag = range.createContextualFragment(html);
el.parentNode.insertBefore(frag, el.nextSibling);
return el.nextSibling;
}
throw 'Illegal insertion point -> "' + where + '"';
},
/**
* 创建新的Dom元素并插入到el之前
* @param {String/HTMLElement/Element} el 元素内容
* @param {Object/String} o 指定的Dom对象(和子孙)或是裸HTML部分
* @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element
* @return {HTMLElement/Ext.Element} 新节点
*/
insertBefore : function(el, o, returnElement){
return this.doInsert(el, o, returnElement, "beforeBegin");
},
/**
* 创建新的Dom元素并插入到el之后
* @param {String/HTMLElement/Element} el 元素内容
* @param {Object/String} o 指定的Dom对象(和子孙)
* @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element
* @return {HTMLElement/Ext.Element} 新节点
*/
insertAfter : function(el, o, returnElement){
return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
},
/**
* 创建新的Dom元素并插入到el中,元素是第一个孩子。
* @param {String/HTMLElement/Element} el 元素内容
* @param {Object/String} o 指定的Dom对象(和子孙)或是原始的HTML部分
* @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element
* @return {HTMLElement/Ext.Element} 新节点
*/
insertFirst : function(el, o, returnElement){
return this.doInsert(el, o, returnElement, "afterBegin", "firstChild");
},
// private
doInsert : function(el, o, returnElement, pos, sibling){
el = Ext.getDom(el);
var newNode;
if(this.useDom){
newNode = createDom(o, null);
(sibling === "firstChild" ? el : el.parentNode).insertBefore(newNode, sibling ? el[sibling] : el);
}else{
var html = createHtml(o);
newNode = this.insertHtml(pos, el, html);
}
return returnElement ? Ext.get(newNode, true) : newNode;
},
/**
* 创建新的Dom元素并加入到el中
* @param {String/HTMLElement/Element} el 元素内容
* @param {Object/String} o 指定的Dom对象(和子孙)或是原始的HTML部分
* @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element
* @return {HTMLElement/Ext.Element} 新节点
*/
append : function(el, o, returnElement){
el = Ext.getDom(el);
var newNode;
if(this.useDom){
newNode = createDom(o, null);
el.appendChild(newNode);
}else{
var html = createHtml(o);
newNode = this.insertHtml("beforeEnd", el, html);
}
return returnElement ? Ext.get(newNode, true) : newNode;
},
/**
* 创建新的Dom元素并覆盖el的内容
* @param {String/HTMLElement/Element} el 元素内容
* @param {Object/String} o 指定的Dom对象(和子孙)或是原始的HTML部分
* @param {Boolean} returnElement (可选的) true表示返回一个Ext.Element
* @return {HTMLElement/Ext.Element} 新节点
*/
overwrite : function(el, o, returnElement){
el = Ext.getDom(el);
el.innerHTML = createHtml(o);
return returnElement ? Ext.get(el.firstChild, true) : el.firstChild;
},
/**
* 根据指定的Dom对象创建新的Ext.DomHelper.Template对象
* @param {Object} o 指定的Dom对象(连同子孙)
* @return {Ext.DomHelper.Template} 新模板
*/
createTemplate : function(o){
var html = createHtml(o);
return new Ext.Template(html);
}
};
}();
| JavaScript |
/*
* 项目地址: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.CompositeElement
* 标准的复合类(composite class)。为集合中每个元素创建一个Ext.Element。
* <br><br>
* <b>注意:尽管未全部罗列,该类支持全部Ext.Element的set/update方法。
* 集合里面的全部元素都会执行所有的Ext.Element动作。</b>
* <br><br>
* 所有的方法都返回<i>this</i>所以可写成链式的语法。
<pre><code>
var els = Ext.select("#some-el div.some-class", true);
//或者是从现有的元素直接选择
var el = Ext.get('some-el');
el.select('div.some-class', true);
els.setWidth(100); // 所有的元素变为宽度100
els.hide(true); // 所有的元素渐隐。
// 或
els.setWidth(100).hide(true);
</code></pre>
*/
Ext.CompositeElement = function(els){
this.elements = [];
this.addElements(els);
};
Ext.CompositeElement.prototype = {
isComposite: true,
addElements : function(els){
if(!els) return this;
if(typeof els == "string"){
els = Ext.Element.selectorFunction(els);
}
var yels = this.elements;
var index = yels.length-1;
for(var i = 0, len = els.length; i < len; i++) {
yels[++index] = Ext.get(els[i]);
}
return this;
},
/**
* 清除该composite,将传入一个选择符的元素加入到composite中。
* @param {String/Array} els CSS选择符,一个或多个元素组成的数组
* @return {CompositeElement} this
*/
fill : function(els){
this.elements = [];
this.add(els);
return this;
},
/**
* 传入一个选择符的参数,若匹配成功,则保存到该composite,其它的就会被过滤
* @param {String} selector CSS选择符字符串
* @return {CompositeElement} this
*/
filter : function(selector){
var els = [];
this.each(function(el){
if(el.is(selector)){
els[els.length] = el.dom;
}
});
this.fill(els);
return this;
},
invoke : function(fn, args){
var els = this.elements;
for(var i = 0, len = els.length; i < len; i++) {
Ext.Element.prototype[fn].apply(els[i], args);
}
return this;
},
/**
* 加入元素到这个composite.
* @param {String/Array} els CSS选择符,一个或多个元素组成的数组
* @return {CompositeElement} this
*/
add : function(els){
if(typeof els == "string"){
this.addElements(Ext.Element.selectorFunction(els));
}else if(els.length !== undefined){
this.addElements(els);
}else{
this.addElements([els]);
}
return this;
},
/**
* 传入一个Function类型的参数,在这个composite中每个元素中执行Function(带参数el, this, index)。
* @param {Function} fn 要调用的函数
* @param {Object} scope (可选的) <i>this</i> 指向的对象(默认为element)
* @return {CompositeElement} this
*/
each : function(fn, scope){
var els = this.elements;
for(var i = 0, len = els.length; i < len; i++){
if(fn.call(scope || els[i], els[i], this, i) === false) {
break;
}
}
return this;
},
/**
* 根据指定的索引返回元素对象
* @param {Number} index
* @return {Ext.Element}
*/
item : function(index){
return this.elements[index] || null;
},
/**
* 返回第一个元素
* @return {Ext.Element}
*/
first : function(){
return this.item(0);
},
/**
* 返回最后的元素
* @return {Ext.Element}
*/
last : function(){
return this.item(this.elements.length-1);
},
/**
* 返回该composite的元素的总数
* @return Number
*/
getCount : function(){
return this.elements.length;
},
/**
* 传入一个元素的参数,如果该composite里面有的话返回true
* @return Boolean
*/
contains : function(el){
return this.indexOf(el) !== -1;
},
/**
* 传入一个元素的参数,返回元素第一次出现的位置。
* @return Boolean
*/
indexOf : function(el){
return this.elements.indexOf(Ext.get(el));
},
/**
* 移除指定的元素。
* @param {Mixed} el 元素的ID,或是元素本身,也可以是该composite中的元素索引(Number类型),或是以上类型组成的数组。
* @param {Boolean} removeDom (可选的) True表示为DOM文档中的元素一并删除
* @return {CompositeElement} this
*/
removeElement : function(el, removeDom){
if(el instanceof Array){
for(var i = 0, len = el.length; i < len; i++){
this.removeElement(el[i]);
}
return this;
}
var index = typeof el == 'number' ? el : this.indexOf(el);
if(index !== -1 && this.elements[index]){
if(removeDom){
var d = this.elements[index];
if(d.dom){
d.remove();
}else{
Ext.removeNode(d);
}
}
this.elements.splice(index, 1);
}
return this;
},
/**
* 传入一个元素,替换指定的元素。
* @param {Mixed} el 元素的ID,或是元素本身,也可以是该composite中的元素索引(Number类型),或是以上类型组成的数组。
* @param {String/HTMLElement/Element} replacement 元素的ID,或是元素本身
* @param {Boolean} removeDom (可选的) True表示为DOM文档中的元素一并删除
* @return {CompositeElement} this
*/
replaceElement : function(el, replacement, domReplace){
var index = typeof el == 'number' ? el : this.indexOf(el);
if(index !== -1){
if(domReplace){
this.elements[index].replaceWith(replacement);
}else{
this.elements.splice(index, 1, Ext.get(replacement))
}
}
return this;
},
/**
* 移除所有元素。
*/
clear : function(){
this.elements = [];
}
};
(function(){
Ext.CompositeElement.createCall = function(proto, fnName){
if(!proto[fnName]){
proto[fnName] = function(){
return this.invoke(fnName, arguments);
};
}
};
for(var fnName in Ext.Element.prototype){
if(typeof Ext.Element.prototype[fnName] == "function"){
Ext.CompositeElement.createCall(Ext.CompositeElement.prototype, fnName);
}
};
})(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
//Notifies Element that fx methods are available
Ext.enableFx = true;
/**
* @class Ext.Fx
* <p>这是一个提供基础动画和视觉效果支持的类。<b>注意:</b>此类被引用后会自动应用于 {@link Ext.Element} 的接口,
* 因此所有的效果必须通过 Element 对象来实现。反过来说,既然 Element 对象实际上并没有定义这些效果,
* Ext.Fx 类<b>必须</b>被 Element 对象引用后才能使那些效果生效。</p><br/>
*
* <p>值得注意的是,虽然 Fx 的方法和许多非 Fx Element 对象的方法支持“方法链”,即他们返回 Element 对象本身作为方法的返回值,
* 但是并非每次都能将两个对象混合在一个方法链中。Fx 的方法使用一个内部的效果队列以使每个效果能够在适当的时候按次序展现。
* 另一方面,对于非 Fx 的方法则没有这样的一个内部队列,它们总是立即生效。正因为如此,虽然可以在一个单链中混合调用 Fx 和非 Fx 的方法,
* 但是并非总能得到预期的结果,而且必须小心处理类似的情况。</p><br/>
*
* <p>移动类的效果支持8个方向的定位锚,这意味着你可以选择 Element 对象所有8个不同的锚点中的任意一个来作为动画的起点或终点。
* 下面是所有支持的定位锚点位置:</p>
<pre>
值 说明
----- -----------------------------
tl 左上角
t 顶部中央
tr 右上角
l 左边中央
r 右边中央
bl 左下角
b 底部中央
br 右下角
</pre>
* <b>尽管某些 Fx 方法可以接受特殊的自定义配置参数,然而下面的配置选项区域内显示了可供所有 Fx 方法使用的公共选项。</b>
*/
Ext.Fx = {
/**
* 将元素滑入到视图中。作为可选参数传入的定位锚点将被设置为滑入特效的起始点。该函数会在需要的时候自动将元素与一个固定尺寸的容器封装起来。
* 有效的定位锚点可以参见 Fx 类的概述。
* 用法:
*<pre><code>
// 默认情况:将元素从顶部滑入
el.slideIn();
// 自定义:在2秒钟内将元素从右边滑入
el.slideIn('r', { duration: 2 });
// 常见的配置选项及默认值
el.slideIn('t', {
easing: 'easeOut',
duration: .5
});
</code></pre>
* @param {String} anchor (可选)有效的 Fx 定位锚点之一(默认为顶部:'t')
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
slideIn : function(anchor, o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
anchor = anchor || "t";
// fix display to visibility
this.fixDisplay();
// restore values after effect
var r = this.getFxRestore();
var b = this.getBox();
// fixed size for slide
this.setSize(b);
// wrap if needed
var wrap = this.fxWrap(r.pos, o, "hidden");
var st = this.dom.style;
st.visibility = "visible";
st.position = "absolute";
// clear out temp styles after slide and unwrap
var after = function(){
el.fxUnwrap(wrap, r.pos, o);
st.width = r.width;
st.height = r.height;
el.afterFx(o);
};
// time to calc the positions
var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height};
switch(anchor.toLowerCase()){
case "t":
wrap.setSize(b.width, 0);
st.left = st.bottom = "0";
a = {height: bh};
break;
case "l":
wrap.setSize(0, b.height);
st.right = st.top = "0";
a = {width: bw};
break;
case "r":
wrap.setSize(0, b.height);
wrap.setX(b.right);
st.left = st.top = "0";
a = {width: bw, points: pt};
break;
case "b":
wrap.setSize(b.width, 0);
wrap.setY(b.bottom);
st.left = st.top = "0";
a = {height: bh, points: pt};
break;
case "tl":
wrap.setSize(0, 0);
st.right = st.bottom = "0";
a = {width: bw, height: bh};
break;
case "bl":
wrap.setSize(0, 0);
wrap.setY(b.y+b.height);
st.right = st.top = "0";
a = {width: bw, height: bh, points: pt};
break;
case "br":
wrap.setSize(0, 0);
wrap.setXY([b.right, b.bottom]);
st.left = st.top = "0";
a = {width: bw, height: bh, points: pt};
break;
case "tr":
wrap.setSize(0, 0);
wrap.setX(b.x+b.width);
st.left = st.bottom = "0";
a = {width: bw, height: bh, points: pt};
break;
}
this.dom.style.visibility = "visible";
wrap.show();
arguments.callee.anim = wrap.fxanim(a,
o,
'motion',
.5,
'easeOut', after);
});
return this;
},
/**
* @cfg {Function} callback 指定当效果完成时调用的函数
*/
/**
* @cfg {Object} scope 特效函数的作用域
*/
/**
* @cfg {String} easing 指定特效函数使用的合法的 Easing 值
*/
/**
* @cfg {String} afterCls 特效完成后应用的CSS样式类
*/
/**
* @cfg {Number} duration 以秒为单位设置的特效持续时间
*/
/**
* @cfg {Boolean} remove 特效完成后是否从 DOM 树中完全删除 Element 对象
*/
/**
* @cfg {Boolean} useDisplay 隐藏 Element 对象时是否使用 <i>display</i> CSS样式属性替代 <i>visibility</i>属性(仅仅应用于那些结束后隐藏 Element 对象的等效,其他的等效无效)
*/
/**
* @cfg {String/Object/Function} afterStyle 特效完成后应用于 Element 对象的指定样式的字符串,例如:"width:100px",或者形如 {width:"100px"} 的对象,或者返回值为类似形式的函数
*/
/**
* @cfg {Boolean} block 当特效生效时是否阻塞队列中的其他特效
*/
/**
* @cfg {Boolean} concurrent 是否允许特效与队列中的下一个特效并行生效,或者确保他们在运行队列中
*/
/**
* @cfg {Boolean} stopFx 是否在当前特效完成后停止并删除先前(并发)的特效
*/
/**
* 将元素从视图中滑出。作为可选参数传入的定位锚点将被设置为滑出特效的结束点。特效结束后,元素会被隐藏(visibility = 'hidden'),
* 但是块元素仍然会在 document 对象中占据空间。如果需要将元素从 DOM 树删除,则使用'remove'配置选项。
* 该函数会在需要的时候自动将元素与一个固定尺寸的容器封装起来。有效的定位锚点可以参见 Fx 类的概述。
* 用法:
*<pre><code>
// 默认情况:将元素从顶部滑出
el.slideOut();
// 自定义:在2秒钟内将元素从右边滑出
el.slideOut('r', { duration: 2 });
// 常见的配置选项及默认值
el.slideOut('t', {
easing: 'easeOut',
duration: .5,
remove: false,
useDisplay: false
});
</code></pre>
* @param {String} anchor (可选)有效的 Fx 定位锚点之一(默认为顶部:'t')
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
slideOut : function(anchor, o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
anchor = anchor || "t";
// restore values after effect
var r = this.getFxRestore();
var b = this.getBox();
// fixed size for slide
this.setSize(b);
// wrap if needed
var wrap = this.fxWrap(r.pos, o, "visible");
var st = this.dom.style;
st.visibility = "visible";
st.position = "absolute";
wrap.setSize(b);
var after = function(){
if(o.useDisplay){
el.setDisplayed(false);
}else{
el.hide();
}
el.fxUnwrap(wrap, r.pos, o);
st.width = r.width;
st.height = r.height;
el.afterFx(o);
};
var a, zero = {to: 0};
switch(anchor.toLowerCase()){
case "t":
st.left = st.bottom = "0";
a = {height: zero};
break;
case "l":
st.right = st.top = "0";
a = {width: zero};
break;
case "r":
st.left = st.top = "0";
a = {width: zero, points: {to:[b.right, b.y]}};
break;
case "b":
st.left = st.top = "0";
a = {height: zero, points: {to:[b.x, b.bottom]}};
break;
case "tl":
st.right = st.bottom = "0";
a = {width: zero, height: zero};
break;
case "bl":
st.right = st.top = "0";
a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}};
break;
case "br":
st.left = st.top = "0";
a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}};
break;
case "tr":
st.left = st.bottom = "0";
a = {width: zero, height: zero, points: {to:[b.right, b.y]}};
break;
}
arguments.callee.anim = wrap.fxanim(a,
o,
'motion',
.5,
"easeOut", after);
});
return this;
},
/**
* 渐隐元素的同时还伴随着向各个方向缓慢地展开。特效结束后,元素会被隐藏(visibility = 'hidden'),
* 但是块元素仍然会在 document 对象中占据空间。如果需要将元素从 DOM 树删除,则使用'remove'配置选项。
* 用法:
*<pre><code>
// 默认
el.puff();
// 常见的配置选项及默认值
el.puff({
easing: 'easeOut',
duration: .5,
remove: false,
useDisplay: false
});
</code></pre>
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
puff : function(o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
this.clearOpacity();
this.show();
// restore values after effect
var r = this.getFxRestore();
var st = this.dom.style;
var after = function(){
if(o.useDisplay){
el.setDisplayed(false);
}else{
el.hide();
}
el.clearOpacity();
el.setPositioning(r.pos);
st.width = r.width;
st.height = r.height;
st.fontSize = '';
el.afterFx(o);
};
var width = this.getWidth();
var height = this.getHeight();
arguments.callee.anim = this.fxanim({
width : {to: this.adjustWidth(width * 2)},
height : {to: this.adjustHeight(height * 2)},
points : {by: [-(width * .5), -(height * .5)]},
opacity : {to: 0},
fontSize: {to:200, unit: "%"}
},
o,
'motion',
.5,
"easeOut", after);
});
return this;
},
/**
* 类似单击过后般地闪烁一下元素,然后从元素的中间开始收缩(类似于关闭电视机时的效果)。
* 特效结束后,元素会被隐藏(visibility = 'hidden'),但是块元素仍然会在 document 对象中占据空间。
* 如果需要将元素从 DOM 树删除,则使用'remove'配置选项。
* 用法:
*<pre><code>
// 默认
el.switchOff();
// 所有的配置选项及默认值
el.switchOff({
easing: 'easeIn',
duration: .3,
remove: false,
useDisplay: false
});
</code></pre>
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
switchOff : function(o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
this.clearOpacity();
this.clip();
// restore values after effect
var r = this.getFxRestore();
var st = this.dom.style;
var after = function(){
if(o.useDisplay){
el.setDisplayed(false);
}else{
el.hide();
}
el.clearOpacity();
el.setPositioning(r.pos);
st.width = r.width;
st.height = r.height;
el.afterFx(o);
};
this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){
this.clearOpacity();
(function(){
this.fxanim({
height:{to:1},
points:{by:[0, this.getHeight() * .5]}
}, o, 'motion', 0.3, 'easeIn', after);
}).defer(100, this);
});
});
return this;
},
/**
* 根据设置的颜色高亮显示 Element 对象(默认情况下应用于 background-color 属性,但是也可以通过"attr"配置选项来改变),
* 然后渐隐为原始颜色。如果原始颜色不可用,你应该设置"endColor"配置选项以免动画结束后被清除。
* 用法:
<pre><code>
// 默认情况:高亮显示的背景颜色为黄色
el.highlight();
// 自定义:高亮显示前景字符颜色为蓝色并持续2秒
el.highlight("0000ff", { attr: 'color', duration: 2 });
// 常见的配置选项及默认值
el.highlight("ffff9c", {
attr: "background-color", //可以是任何能够把值设置成颜色代码的 CSS 属性
endColor: (current color) or "ffffff",
easing: 'easeIn',
duration: 1
});
</code></pre>
* @param {String} color (可选)高亮颜色。必须为不以 # 开头的6位16进制字符(默认为黄色:'ffff9c')
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
highlight : function(color, o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
color = color || "ffff9c";
var attr = o.attr || "backgroundColor";
this.clearOpacity();
this.show();
var origColor = this.getColor(attr);
var restoreColor = this.dom.style[attr];
var endColor = (o.endColor || origColor) || "ffffff";
var after = function(){
el.dom.style[attr] = restoreColor;
el.afterFx(o);
};
var a = {};
a[attr] = {from: color, to: endColor};
arguments.callee.anim = this.fxanim(a,
o,
'color',
1,
'easeIn', after);
});
return this;
},
/**
* 展示一个展开的波纹,伴随着渐隐的边框以突出显示 Element 对象。
* 用法:
<pre><code>
// 默认情况:一个淡蓝色的波纹
el.frame();
// 自定义:三个红色的波纹并持续3秒
el.frame("ff0000", 3, { duration: 3 });
// 常见的配置选项及默认值
el.frame("C3DAF9", 1, {
duration: 1 //每个波纹持续的时间duration of each individual ripple.
// 注意:这里不能使用 Easing 选项在,即使被包含了也会被忽略
});
</code></pre>
* @param {String} color (可选)边框的颜色。必须为不以 # 开头的6位16进制字符(默认为淡蓝色色:'C3DAF9')
* @param {Number} count (可选)要显示的波纹的个数(默认为1)
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
frame : function(color, count, o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
color = color || "#C3DAF9";
if(color.length == 6){
color = "#" + color;
}
count = count || 1;
var duration = o.duration || 1;
this.show();
var b = this.getBox();
var animFn = function(){
var proxy = Ext.getBody().createChild({
style:{
visbility:"hidden",
position:"absolute",
"z-index":"35000", // yee haw
border:"0px solid " + color
}
});
var scale = Ext.isBorderBox ? 2 : 1;
proxy.animate({
top:{from:b.y, to:b.y - 20},
left:{from:b.x, to:b.x - 20},
borderWidth:{from:0, to:10},
opacity:{from:1, to:0},
height:{from:b.height, to:(b.height + (20*scale))},
width:{from:b.width, to:(b.width + (20*scale))}
}, duration, function(){
proxy.remove();
if(--count > 0){
animFn();
}else{
el.afterFx(o);
}
});
};
animFn.call(this);
});
return this;
},
/**
* 在任何后续的等效开始之前创建一次暂停。如果队列中没有后续特效则没有效果。
* 用法:
<pre><code>
el.pause(1);
</code></pre>
* @param {Number} seconds 以秒为单位的暂停时间
* @return {Ext.Element} Element 对象
*/
pause : function(seconds){
var el = this.getFxEl();
var o = {};
el.queueFx(o, function(){
setTimeout(function(){
el.afterFx(o);
}, seconds * 1000);
});
return this;
},
/**
* 将元素从透明渐变为不透明。结束时的透明度可以根据"endOpacity"选项来指定。
* 用法:
<pre><code>
// 默认情况:将可见度由 0 渐变到 100%
el.fadeIn();
// 自定义:在2秒钟之内将可见度由 0 渐变到 75%
el.fadeIn({ endOpacity: .75, duration: 2});
// 常见的配置选项及默认值
el.fadeIn({
endOpacity: 1, //可以是 0 到 1 之前的任意值(例如:.5)
easing: 'easeOut',
duration: .5
});
</code></pre>
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
fadeIn : function(o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
this.setOpacity(0);
this.fixDisplay();
this.dom.style.visibility = 'visible';
var to = o.endOpacity || 1;
arguments.callee.anim = this.fxanim({opacity:{to:to}},
o, null, .5, "easeOut", function(){
if(to == 1){
this.clearOpacity();
}
el.afterFx(o);
});
});
return this;
},
/**
* 将元素从不透明渐变为透明。结束时的透明度可以根据"endOpacity"选项来指定。
* 用法:
<pre><code>
// 默认情况:将元素的可见度由当前值渐变到 0
el.fadeOut();
// 自定义:在2秒钟内将元素的可见度由当前值渐变到 25%
el.fadeOut({ endOpacity: .25, duration: 2});
// 常见的配置选项及默认值
el.fadeOut({
endOpacity: 0, 可以是 0 到 1 之前的任意值(例如:.5)
easing: 'easeOut',
duration: .5
remove: false,
useDisplay: false
});
</code></pre>
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
fadeOut : function(o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
var to = o.endOpacity || 0;
arguments.callee.anim = this.fxanim({opacity:{to:to}},
o, null, .5, "easeOut", function(){
if(to === 0){
if(this.visibilityMode == Ext.Element.DISPLAY || o.useDisplay){
this.dom.style.display = "none";
}else{
this.dom.style.visibility = "hidden";
}
this.clearOpacity();
}
el.afterFx(o);
});
});
return this;
},
/**
* 以动画展示元素从开始的高度/宽度转换到结束的高度/宽度。
* 用法:
<pre><code>
// 将宽度和高度设置为 100x100 象素
el.scale(100, 100);
// 常见的配置选项及默认值。如果给定值为 null,则高度和宽度默认被设置为元素已有的值。
el.scale(
[element's width],
[element's height], {
easing: 'easeOut',
duration: .35
});
</code></pre>
* @param {Number} width 新的宽度(传递 undefined 则保持原始宽度)
* @param {Number} height 新的高度(传递 undefined 则保持原始高度)
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
scale : function(w, h, o){
this.shift(Ext.apply({}, o, {
width: w,
height: h
}));
return this;
},
/**
* 以动画展示元素任意组合属性的改变,如元素的尺寸、位置坐标和(或)透明度。
* 如果以上属性中的任意一个没有在配置选项对象中指定则该属性不会发生改变。
* 为了使该特效生效,则必须在配置选项对象中设置至少一个新的尺寸、位置坐标或透明度属性。
* 用法:
<pre><code>
// 将元素水平地滑动到X坐标值为200的位置,同时还伴随着高度和透明度的改变
el.shift({ x: 200, height: 50, opacity: .8 });
// 常见的配置选项及默认值。
el.shift({
width: [element's width],
height: [element's height],
x: [element's x position],
y: [element's y position],
opacity: [element's opacity],
easing: 'easeOut',
duration: .35
});
</code></pre>
* @param {Object} options 由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
shift : function(o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity;
if(w !== undefined){
a.width = {to: this.adjustWidth(w)};
}
if(h !== undefined){
a.height = {to: this.adjustHeight(h)};
}
if(x !== undefined || y !== undefined){
a.points = {to: [
x !== undefined ? x : this.getX(),
y !== undefined ? y : this.getY()
]};
}
if(op !== undefined){
a.opacity = {to: op};
}
if(o.xy !== undefined){
a.points = {to: o.xy};
}
arguments.callee.anim = this.fxanim(a,
o, 'motion', .35, "easeOut", function(){
el.afterFx(o);
});
});
return this;
},
/**
* 将元素从视图滑出并伴随着渐隐。作为可选参数传入的定位锚点将被设置为滑出特效的结束点。
* 用法:
*<pre><code>
// 默认情况:将元素向下方滑出并渐隐
el.ghost();
// 自定义:在2秒钟内将元素向右边滑出并渐隐
el.ghost('r', { duration: 2 });
// 常见的配置选项及默认值。
el.ghost('b', {
easing: 'easeOut',
duration: .5
remove: false,
useDisplay: false
});
</code></pre>
* @param {String} anchor (可选)有效的 Fx 定位锚点之一(默认为底部:'b')
* @param {Object} options (可选)由任何 Fx 的配置选项构成的对象
* @return {Ext.Element} Element 对象
*/
ghost : function(anchor, o){
var el = this.getFxEl();
o = o || {};
el.queueFx(o, function(){
anchor = anchor || "b";
// restore values after effect
var r = this.getFxRestore();
var w = this.getWidth(),
h = this.getHeight();
var st = this.dom.style;
var after = function(){
if(o.useDisplay){
el.setDisplayed(false);
}else{
el.hide();
}
el.clearOpacity();
el.setPositioning(r.pos);
st.width = r.width;
st.height = r.height;
el.afterFx(o);
};
var a = {opacity: {to: 0}, points: {}}, pt = a.points;
switch(anchor.toLowerCase()){
case "t":
pt.by = [0, -h];
break;
case "l":
pt.by = [-w, 0];
break;
case "r":
pt.by = [w, 0];
break;
case "b":
pt.by = [0, h];
break;
case "tl":
pt.by = [-w, -h];
break;
case "bl":
pt.by = [-w, h];
break;
case "br":
pt.by = [w, h];
break;
case "tr":
pt.by = [w, -h];
break;
}
arguments.callee.anim = this.fxanim(a,
o,
'motion',
.5,
"easeOut", after);
});
return this;
},
/**
* 确保元素调用 syncFx 方法之后所有队列中的特效并发运行。它与 {@link #sequenceFx} 的作用是相反的。
* @return {Ext.Element} Element 对象
*/
syncFx : function(){
this.fxDefaults = Ext.apply(this.fxDefaults || {}, {
block : false,
concurrent : true,
stopFx : false
});
return this;
},
/**
* 确保元素调用 sequenceFx 方法之后所有队列中的特效依次运行。它与 {@link #syncFx} 的作用是相反的。
* @return {Ext.Element} Element 对象
*/
sequenceFx : function(){
this.fxDefaults = Ext.apply(this.fxDefaults || {}, {
block : false,
concurrent : false,
stopFx : false
});
return this;
},
/* @private */
nextFx : function(){
var ef = this.fxQueue[0];
if(ef){
ef.call(this);
}
},
/**
* 当元素拥有任何活动的或队列中的特效时返回 true,否则返回 false。
* @return {Boolean} 如果元素拥有特效为 true,否则为 false。
*/
hasActiveFx : function(){
return this.fxQueue && this.fxQueue[0];
},
/**
* 停止运行中的任何特效,如果元素的内部特效队列中还包含其他尚未开始的特效也一并清除。
* @return {Ext.Element} Element 对象
*/
stopFx : function(){
if(this.hasActiveFx()){
var cur = this.fxQueue[0];
if(cur && cur.anim && cur.anim.isAnimated()){
this.fxQueue = [cur]; // clear out others
cur.anim.stop(true);
}
}
return this;
},
/* @private */
beforeFx : function(o){
if(this.hasActiveFx() && !o.concurrent){
if(o.stopFx){
this.stopFx();
return true;
}
return false;
}
return true;
},
/**
* 如果元素的当前特效阻塞了特效队列以致于在当前特效完成前其他特效无法排队,则返回 true。如果元素没有阻塞队列则返回 false。
* 此方法一般用于保证由用户动作启动的特效在相同的特效重新启动之前能够顺利完成(例如:即使用户点击了很多次也只触发一个效果)。
* @return {Boolean} 如果阻塞返回 true,否则返回 false。
*/
hasFxBlock : function(){
var q = this.fxQueue;
return q && q[0] && q[0].block;
},
/* @private */
queueFx : function(o, fn){
if(!this.fxQueue){
this.fxQueue = [];
}
if(!this.hasFxBlock()){
Ext.applyIf(o, this.fxDefaults);
if(!o.concurrent){
var run = this.beforeFx(o);
fn.block = o.block;
this.fxQueue.push(fn);
if(run){
this.nextFx();
}
}else{
fn.call(this);
}
}
return this;
},
/* @private */
fxWrap : function(pos, o, vis){
var wrap;
if(!o.wrap || !(wrap = Ext.get(o.wrap))){
var wrapXY;
if(o.fixPosition){
wrapXY = this.getXY();
}
var div = document.createElement("div");
div.style.visibility = vis;
wrap = Ext.get(this.dom.parentNode.insertBefore(div, this.dom));
wrap.setPositioning(pos);
if(wrap.getStyle("position") == "static"){
wrap.position("relative");
}
this.clearPositioning('auto');
wrap.clip();
wrap.dom.appendChild(this.dom);
if(wrapXY){
wrap.setXY(wrapXY);
}
}
return wrap;
},
/* @private */
fxUnwrap : function(wrap, pos, o){
this.clearPositioning();
this.setPositioning(pos);
if(!o.wrap){
wrap.dom.parentNode.insertBefore(this.dom, wrap.dom);
wrap.remove();
}
},
/* @private */
getFxRestore : function(){
var st = this.dom.style;
return {pos: this.getPositioning(), width: st.width, height : st.height};
},
/* @private */
afterFx : function(o){
if(o.afterStyle){
this.applyStyles(o.afterStyle);
}
if(o.afterCls){
this.addClass(o.afterCls);
}
if(o.remove === true){
this.remove();
}
Ext.callback(o.callback, o.scope, [this]);
if(!o.concurrent){
this.fxQueue.shift();
this.nextFx();
}
},
/* @private */
getFxEl : function(){ // support for composite element fx
return Ext.get(this.dom);
},
/* @private */
fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){
animType = animType || 'run';
opt = opt || {};
var anim = Ext.lib.Anim[animType](
this.dom, args,
(opt.duration || defaultDur) || .35,
(opt.easing || defaultEase) || 'easeOut',
function(){
Ext.callback(cb, this);
},
this
);
opt.anim = anim;
return anim;
}
};
//向后兼容
Ext.Fx.resize = Ext.Fx.scale;
//被引用后,Ext.Fx 自动应用到 Element 对象,以便所有基础特效可以通过 Element API 直接使用
Ext.apply(Ext.Element.prototype, Ext.Fx); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/*
* This is code is also distributed under MIT license for use
* with jQuery and prototype JavaScript libraries.
* 本代码与 jQuery、prototype JavaScript 类库同样遵循 MIT 授权协议发布与使用。
*/
/**
* @class Ext.DomQuery
根据编译请求提供高效的将选择符 / xpath 处理为可复用的函数的方法。可以添加新的伪类和匹配器。该类可以运行于 HTML 和 XML 文档之上(如果给出了一个内容节点)。
<p>
DomQuery 提供大多数的<a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/">CSS3 选择符</a>,同时也支持某些自定义选择符和基本的 XPath。</p>
<p>
下列所有的选择符、属性过滤器和伪类可以在任何命令中无限地组合使用。例如:“div.foo:nth-child(odd)[@foo=bar].bar:first”将是一个完全有效的选择符。命令中出现的节点过滤器将可以使你根据自己的文档结构对查询做出优化。
</p>
<h4>元素选择符:</h4>
<ul class="list">
<li> <b>*</b> 任意元素</li>
<li> <b>E</b> 一个标签为 E 的元素</li>
<li> <b>E F</b> 所有 E 元素的分支元素中含有标签为 F 的元素</li>
<li> <b>E > F</b> 或 <b>E/F</b> 所有 E 元素的直系子元素中含有标签为 F 的元素</li>
<li> <b>E + F</b> 所有标签为 F 并紧随着标签为 E 的元素之后的元素</li>
<li> <b>E ~ F</b> 所有标签为 F 并与标签为 E 的元素是侧边的元素</li>
</ul>
<h4>属性选择符:</h4>
<p>@ 与引号的使用是可选的。例如:div[@foo='bar'] 也是一个有效的属性选择符。</p>
<ul class="list">
<li> <b>E[foo]</b> 拥有一个名为 “foo” 的属性</li>
<li> <b>E[foo=bar]</b> 拥有一个名为 “foo” 且值为 “bar” 的属性</li>
<li> <b>E[foo^=bar]</b> 拥有一个名为 “foo” 且值以 “bar” 开头的属性</li>
<li> <b>E[foo$=bar]</b> 拥有一个名为 “foo” 且值以 “bar” 结尾的属性</li>
<li> <b>E[foo*=bar]</b> 拥有一个名为 “foo” 且值包含字串 “bar” 的属性</li>
<li> <b>E[foo%=2]</b> 拥有一个名为 “foo” 且值能够被2整除的属性</li>
<li> <b>E[foo!=bar]</b> 拥有一个名为 “foo” 且值不为 “bar” 的属性</li>
</ul>
<h4>Pseudo Classes:</h4>
<h4>伪类:</h4>
<ul class="list">
<li> <b>E:first-child</b> E 元素为其父元素的第一个子元素</li>
<li> <b>E:last-child</b> E 元素为其父元素的最后一个子元素</li>
<li> <b>E:nth-child(<i>n</i>)</b> E 元素为其父元素的第 <i>n</i> 个子元素(由1开始的个数)</li>
<li> <b>E:nth-child(odd)</b> E 元素为其父元素的奇数个数的子元素</li>
<li> <b>E:nth-child(even)</b> E 元素为其父元素的偶数个数的子元素</li>
<li> <b>E:only-child</b> E 元素为其父元素的唯一子元素</li>
<li> <b>E:checked</b> E 元素为拥有一个名为“checked”且值为“true”的元素(例如:单选框或复选框)</li>
<li> <b>E:first</b> 结果集中第一个 E 元素</li>
<li> <b>E:last</b> 结果集中最后一个 E 元素</li>
<li> <b>E:nth(<i>n</i>)</b> 结果集中第 <i>n</i> 个 E 元素(由1开始的个数)</li>
<li> <b>E:odd</b> :nth-child(odd) 的简写</li>
<li> <b>E:even</b> :nth-child(even) 的简写</li>
<li> <b>E:contains(foo)</b> E 元素的 innerHTML 属性中包含“foo”字串</li>
<li> <b>E:nodeValue(foo)</b> E 元素包含一个 textNode 节点且 nodeValue 等于“foo”</li>
<li> <b>E:not(S)</b> 一个与简单选择符 S 不匹配的 E 元素</li>
<li> <b>E:has(S)</b> 一个包含与简单选择符 S 相匹配的分支元素的 E 元素</li>
<li> <b>E:next(S)</b> 下一个侧边元素为与简单选择符 S 相匹配的 E 元素</li>
<li> <b>E:prev(S)</b> 上一个侧边元素为与简单选择符 S 相匹配的 E 元素</li>
</ul>
<h4>CSS 值选择符:</h4>
<ul class="list">
<li> <b>E{display=none}</b> css 的“display”属性等于“none”</li>
<li> <b>E{display^=none}</b> css 的“display”属性以“none”开始</li>
<li> <b>E{display$=none}</b> css 的“display”属性以“none”结尾</li>
<li> <b>E{display*=none}</b> css 的“display”属性包含字串“none”</li>
<li> <b>E{display%=2}</b> css 的“display”属性能够被2整除</li>
<li> <b>E{display!=none}</b> css 的“display”属性不等于“none”</li>
</ul>
* @singleton
*/
Ext.DomQuery = function(){
var cache = {}, simpleCache = {}, valueCache = {};
var nonSpace = /\S/;
var trimRe = /^\s+|\s+$/g;
var tplRe = /\{(\d+)\}/g;
var modeRe = /^(\s?[\/>+~]\s?|\s|$)/;
var tagTokenRe = /^(#)?([\w-\*]+)/;
var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/;
function child(p, index){
var i = 0;
var n = p.firstChild;
while(n){
if(n.nodeType == 1){
if(++i == index){
return n;
}
}
n = n.nextSibling;
}
return null;
};
function next(n){
while((n = n.nextSibling) && n.nodeType != 1);
return n;
};
function prev(n){
while((n = n.previousSibling) && n.nodeType != 1);
return n;
};
function children(d){
var n = d.firstChild, ni = -1;
while(n){
var nx = n.nextSibling;
if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){
d.removeChild(n);
}else{
n.nodeIndex = ++ni;
}
n = nx;
}
return this;
};
function byClassName(c, a, v){
if(!v){
return c;
}
var r = [], ri = -1, cn;
for(var i = 0, ci; ci = c[i]; i++){
if((' '+ci.className+' ').indexOf(v) != -1){
r[++ri] = ci;
}
}
return r;
};
function attrValue(n, attr){
if(!n.tagName && typeof n.length != "undefined"){
n = n[0];
}
if(!n){
return null;
}
if(attr == "for"){
return n.htmlFor;
}
if(attr == "class" || attr == "className"){
return n.className;
}
return n.getAttribute(attr) || n[attr];
};
function getNodes(ns, mode, tagName){
var result = [], ri = -1, cs;
if(!ns){
return result;
}
tagName = tagName || "*";
if(typeof ns.getElementsByTagName != "undefined"){
ns = [ns];
}
if(!mode){
for(var i = 0, ni; ni = ns[i]; i++){
cs = ni.getElementsByTagName(tagName);
for(var j = 0, ci; ci = cs[j]; j++){
result[++ri] = ci;
}
}
}else if(mode == "/" || mode == ">"){
var utag = tagName.toUpperCase();
for(var i = 0, ni, cn; ni = ns[i]; i++){
cn = ni.children || ni.childNodes;
for(var j = 0, cj; cj = cn[j]; j++){
if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){
result[++ri] = cj;
}
}
}
}else if(mode == "+"){
var utag = tagName.toUpperCase();
for(var i = 0, n; n = ns[i]; i++){
while((n = n.nextSibling) && n.nodeType != 1);
if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){
result[++ri] = n;
}
}
}else if(mode == "~"){
for(var i = 0, n; n = ns[i]; i++){
while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName)));
if(n){
result[++ri] = n;
}
}
}
return result;
};
function concat(a, b){
if(b.slice){
return a.concat(b);
}
for(var i = 0, l = b.length; i < l; i++){
a[a.length] = b[i];
}
return a;
}
function byTag(cs, tagName){
if(cs.tagName || cs == document){
cs = [cs];
}
if(!tagName){
return cs;
}
var r = [], ri = -1;
tagName = tagName.toLowerCase();
for(var i = 0, ci; ci = cs[i]; i++){
if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){
r[++ri] = ci;
}
}
return r;
};
function byId(cs, attr, id){
if(cs.tagName || cs == document){
cs = [cs];
}
if(!id){
return cs;
}
var r = [], ri = -1;
for(var i = 0,ci; ci = cs[i]; i++){
if(ci && ci.id == id){
r[++ri] = ci;
return r;
}
}
return r;
};
function byAttribute(cs, attr, value, op, custom){
var r = [], ri = -1, st = custom=="{";
var f = Ext.DomQuery.operators[op];
for(var i = 0, ci; ci = cs[i]; i++){
var a;
if(st){
a = Ext.DomQuery.getStyle(ci, attr);
}
else if(attr == "class" || attr == "className"){
a = ci.className;
}else if(attr == "for"){
a = ci.htmlFor;
}else if(attr == "href"){
a = ci.getAttribute("href", 2);
}else{
a = ci.getAttribute(attr);
}
if((f && f(a, value)) || (!f && a)){
r[++ri] = ci;
}
}
return r;
};
function byPseudo(cs, name, value){
return Ext.DomQuery.pseudos[name](cs, value);
};
// This is for IE MSXML which does not support expandos.
// 此处用于兼容不支持扩展的 IE MSXML。
// IE runs the same speed using setAttribute, however FF slows way down
// and Safari completely fails so they need to continue to use expandos.
// IE 在运行 setAttribute 方法时速度相同,可是 FF 则要慢一些,而 Safari
// 完全无法运行,所以他们只能继续使用扩展。
var isIE = window.ActiveXObject ? true : false;
// this eval is stop the compressor from
// renaming the variable to something shorter
// 此处的 eval 用来阻止压缩程序将变量名变得更短
eval("var batch = 30803;");
var key = 30803;
function nodupIEXml(cs){
var d = ++key;
cs[0].setAttribute("_nodup", d);
var r = [cs[0]];
for(var i = 1, len = cs.length; i < len; i++){
var c = cs[i];
if(!c.getAttribute("_nodup") != d){
c.setAttribute("_nodup", d);
r[r.length] = c;
}
}
for(var i = 0, len = cs.length; i < len; i++){
cs[i].removeAttribute("_nodup");
}
return r;
}
function nodup(cs){
if(!cs){
return [];
}
var len = cs.length, c, i, r = cs, cj, ri = -1;
if(!len || typeof cs.nodeType != "undefined" || len == 1){
return cs;
}
if(isIE && typeof cs[0].selectSingleNode != "undefined"){
return nodupIEXml(cs);
}
var d = ++key;
cs[0]._nodup = d;
for(i = 1; c = cs[i]; i++){
if(c._nodup != d){
c._nodup = d;
}else{
r = [];
for(var j = 0; j < i; j++){
r[++ri] = cs[j];
}
for(j = i+1; cj = cs[j]; j++){
if(cj._nodup != d){
cj._nodup = d;
r[++ri] = cj;
}
}
return r;
}
}
return r;
}
function quickDiffIEXml(c1, c2){
var d = ++key;
for(var i = 0, len = c1.length; i < len; i++){
c1[i].setAttribute("_qdiff", d);
}
var r = [];
for(var i = 0, len = c2.length; i < len; i++){
if(c2[i].getAttribute("_qdiff") != d){
r[r.length] = c2[i];
}
}
for(var i = 0, len = c1.length; i < len; i++){
c1[i].removeAttribute("_qdiff");
}
return r;
}
function quickDiff(c1, c2){
var len1 = c1.length;
if(!len1){
return c2;
}
if(isIE && c1[0].selectSingleNode){
return quickDiffIEXml(c1, c2);
}
var d = ++key;
for(var i = 0; i < len1; i++){
c1[i]._qdiff = d;
}
var r = [];
for(var i = 0, len = c2.length; i < len; i++){
if(c2[i]._qdiff != d){
r[r.length] = c2[i];
}
}
return r;
}
function quickId(ns, mode, root, id){
if(ns == root){
var d = root.ownerDocument || root;
return d.getElementById(id);
}
ns = getNodes(ns, mode, "*");
return byId(ns, null, id);
}
return {
getStyle : function(el, name){
return Ext.fly(el).getStyle(name);
},
/**
* 将一个 选择符 / xpath 查询编译为一个可利用的函数。返回的函数获得一个“root”参数(可选)作为查询的起点。
* @param {String} selector 选择符 / xpath 查询
* @param {String} type (可选)可以是“select”(默认)或“simple”以供简单选择符使用
* @return {Function}
*/
compile : function(path, type){
type = type || "select";
var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"];
var q = path, mode, lq;
var tk = Ext.DomQuery.matchers;
var tklen = tk.length;
var mm;
// accept leading mode switch
var lmode = q.match(modeRe);
if(lmode && lmode[1]){
fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";';
q = q.replace(lmode[1], "");
}
// strip leading slashes
while(path.substr(0, 1)=="/"){
path = path.substr(1);
}
while(q && lq != q){
lq = q;
var tm = q.match(tagTokenRe);
if(type == "select"){
if(tm){
if(tm[1] == "#"){
fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");';
}else{
fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");';
}
q = q.replace(tm[0], "");
}else if(q.substr(0, 1) != '@'){
fn[fn.length] = 'n = getNodes(n, mode, "*");';
}
}else{
if(tm){
if(tm[1] == "#"){
fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");';
}else{
fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");';
}
q = q.replace(tm[0], "");
}
}
while(!(mm = q.match(modeRe))){
var matched = false;
for(var j = 0; j < tklen; j++){
var t = tk[j];
var m = q.match(t.re);
if(m){
fn[fn.length] = t.select.replace(tplRe, function(x, i){
return m[i];
});
q = q.replace(m[0], "");
matched = true;
break;
}
}
// prevent infinite loop on bad selector
if(!matched){
throw 'Error parsing selector, parsing failed at "' + q + '"';
}
}
if(mm[1]){
fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";';
q = q.replace(mm[1], "");
}
}
fn[fn.length] = "return nodup(n);\n}";
eval(fn.join(""));
return f;
},
/**
* 选择一组元素。
* @param {String} selector 选择符 / xpath 查询(可以是以逗号分隔的选择符列表)
* @param {Node} root (可选)查询的起点(默认为:document)。
* @return {Array} 匹配选择符而形成的DOM元素数组,如果没有匹配的结果,返回一个空的数组An Array of DOM elements which match the selector. If there are
* no matches, and empty Array is returned.
*/
select : function(path, root, type){
if(!root || root == document){
root = document;
}
if(typeof root == "string"){
root = document.getElementById(root);
}
var paths = path.split(",");
var results = [];
for(var i = 0, len = paths.length; i < len; i++){
var p = paths[i].replace(trimRe, "");
if(!cache[p]){
cache[p] = Ext.DomQuery.compile(p);
if(!cache[p]){
throw p + " is not a valid selector";
}
}
var result = cache[p](root);
if(result && result != document){
results = results.concat(result);
}
}
if(paths.length > 1){
return nodup(results);
}
return results;
},
/**
* 选择单个元素。
* @param {String} selector 选择符 / xpath 查询
* @param {Node} root (可选)查询的起点(默认为:document)。
* @return {Element} 匹配的选择符的DOM元素The DOM element which matched the selector.
*/
selectNode : function(path, root){
return Ext.DomQuery.select(path, root)[0];
},
/**
* 选择一个节点的值,可选择使用 defaultValue 替换掉 null。
* @param {String} selector 选择符 / xpath 查询
* @param {Node} root (可选)查询的起点(默认为:document)。
* @param {String} defaultValue
*/
selectValue : function(path, root, defaultValue){
path = path.replace(trimRe, "");
if(!valueCache[path]){
valueCache[path] = Ext.DomQuery.compile(path, "select");
}
var n = valueCache[path](root);
n = n[0] ? n[0] : n;
var v = (n && n.firstChild ? n.firstChild.nodeValue : null);
return ((v === null||v === undefined||v==='') ? defaultValue : v);
},
/**
* 取得一个经过处理的整形或浮点型的节点值。
* @param {String} selector 查询时使用的 XPath 或选择符
* @param {Node} root (可选)查询的起点(默认为 document)。
* @param {Number} defaultValue
* @return {Number}
*/
selectNumber : function(path, root, defaultValue){
var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0);
return parseFloat(v);
},
/**
* 如果所给的元素与简易选择符相匹配,则返回 true(例如:div.some-class 或者 span:first-child)
* @param {String/HTMLElement/Array} el 元素 ID、元素本身、或元素数组
* @param {String} selector 测试用的简易选择符
* @return {Boolean}
*/
is : function(el, ss){
if(typeof el == "string"){
el = document.getElementById(el);
}
var isArray = (el instanceof Array);
var result = Ext.DomQuery.filter(isArray ? el : [el], ss);
return isArray ? (result.length == el.length) : (result.length > 0);
},
/**
* 将元素数组过滤成只包含匹配简易选择符的元素(例如:div.some-class 或者 span:first-child)
* @param {Array} el 要过滤的元素数组
* @param {String} selector 测试用的简易选择符
* @param {Boolean} nonMatches 如果值为 true,将返回与选择符不匹配的元素,而不是匹配的元素
* @return {Array} 匹配选择符而形成的DOM元素数组,如果没有匹配的结果,返回一个空的数组An Array of DOM elements which match the selector. If there are
* no matches, and empty Array is returned.
*/
filter : function(els, ss, nonMatches){
ss = ss.replace(trimRe, "");
if(!simpleCache[ss]){
simpleCache[ss] = Ext.DomQuery.compile(ss, "simple");
}
var result = simpleCache[ss](els);
return nonMatches ? quickDiff(result, els) : result;
},
/**
* 匹配的正则表达式和代码片断的集合。
*/
matchers : [{
re: /^\.([\w-]+)/,
select: 'n = byClassName(n, null, " {1} ");'
}, {
re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
select: 'n = byPseudo(n, "{1}", "{2}");'
},{
re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,
select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'
}, {
re: /^#([\w-]+)/,
select: 'n = byId(n, null, "{1}");'
},{
re: /^@([\w-]+)/,
select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'
}
],
/**
* 比较函数运算符集合。默认的运算符有:=、!=、^=、$=、*= 和 %=。
* 可以添加形如 <i>c</i>= 的运算符。其中 <i>c</i> 可以是除空格、>和<之外的任意字符。
*/
operators : {
"=" : function(a, v){
return a == v;
},
"!=" : function(a, v){
return a != v;
},
"^=" : function(a, v){
return a && a.substr(0, v.length) == v;
},
"$=" : function(a, v){
return a && a.substr(a.length-v.length) == v;
},
"*=" : function(a, v){
return a && a.indexOf(v) !== -1;
},
"%=" : function(a, v){
return (a % v) == 0;
},
"|=" : function(a, v){
return a && (a == v || a.substr(0, v.length+1) == v+'-');
},
"~=" : function(a, v){
return a && (' '+a+' ').indexOf(' '+v+' ') != -1;
}
},
/**
* "pseudo class" 处理器集合。每一个处理器将传递当前节点集(数组形式)和参数(如果有)以供选择符使用。
*/
pseudos : {
"first-child" : function(c){
var r = [], ri = -1, n;
for(var i = 0, ci; ci = n = c[i]; i++){
while((n = n.previousSibling) && n.nodeType != 1);
if(!n){
r[++ri] = ci;
}
}
return r;
},
"last-child" : function(c){
var r = [], ri = -1, n;
for(var i = 0, ci; ci = n = c[i]; i++){
while((n = n.nextSibling) && n.nodeType != 1);
if(!n){
r[++ri] = ci;
}
}
return r;
},
"nth-child" : function(c, a) {
var r = [], ri = -1;
var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a);
var f = (m[1] || 1) - 0, l = m[2] - 0;
for(var i = 0, n; n = c[i]; i++){
var pn = n.parentNode;
if (batch != pn._batch) {
var j = 0;
for(var cn = pn.firstChild; cn; cn = cn.nextSibling){
if(cn.nodeType == 1){
cn.nodeIndex = ++j;
}
}
pn._batch = batch;
}
if (f == 1) {
if (l == 0 || n.nodeIndex == l){
r[++ri] = n;
}
} else if ((n.nodeIndex + l) % f == 0){
r[++ri] = n;
}
}
return r;
},
"only-child" : function(c){
var r = [], ri = -1;;
for(var i = 0, ci; ci = c[i]; i++){
if(!prev(ci) && !next(ci)){
r[++ri] = ci;
}
}
return r;
},
"empty" : function(c){
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
var cns = ci.childNodes, j = 0, cn, empty = true;
while(cn = cns[j]){
++j;
if(cn.nodeType == 1 || cn.nodeType == 3){
empty = false;
break;
}
}
if(empty){
r[++ri] = ci;
}
}
return r;
},
"contains" : function(c, v){
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
if((ci.textContent||ci.innerText||'').indexOf(v) != -1){
r[++ri] = ci;
}
}
return r;
},
"nodeValue" : function(c, v){
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
if(ci.firstChild && ci.firstChild.nodeValue == v){
r[++ri] = ci;
}
}
return r;
},
"checked" : function(c){
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
if(ci.checked == true){
r[++ri] = ci;
}
}
return r;
},
"not" : function(c, ss){
return Ext.DomQuery.filter(c, ss, true);
},
"any" : function(c, selectors){
var ss = selectors.split('|');
var r = [], ri = -1, s;
for(var i = 0, ci; ci = c[i]; i++){
for(var j = 0; s = ss[j]; j++){
if(Ext.DomQuery.is(ci, s)){
r[++ri] = ci;
break;
}
}
}
return r;
},
"odd" : function(c){
return this["nth-child"](c, "odd");
},
"even" : function(c){
return this["nth-child"](c, "even");
},
"nth" : function(c, a){
return c[a-1] || [];
},
"first" : function(c){
return c[0] || [];
},
"last" : function(c){
return c[c.length-1] || [];
},
"has" : function(c, ss){
var s = Ext.DomQuery.select;
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
if(s(ss, ci).length > 0){
r[++ri] = ci;
}
}
return r;
},
"next" : function(c, ss){
var is = Ext.DomQuery.is;
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
var n = next(ci);
if(n && is(n, ss)){
r[++ri] = ci;
}
}
return r;
},
"prev" : function(c, ss){
var is = Ext.DomQuery.is;
var r = [], ri = -1;
for(var i = 0, ci; ci = c[i]; i++){
var n = prev(ci);
if(n && is(n, ss)){
r[++ri] = ci;
}
}
return r;
}
}
};
}();
/**
* 选定一个通过CSS/XPath选择符获取的DOM节点组成的数组。{@link Ext.DomQuery#select}的简写方式。
* @param {String} path 查询时使用的 XPath 或选择符
* @param {Node} root (可选)查询的起点(默认为 document)。
* @return {Array}
* @member Ext
* @method query
*/
Ext.query = Ext.DomQuery.select; | JavaScript |
/*
* 项目地址: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.Template
* 将一段Html片段呈现为模板。可将模板编译以获取更高的性能。
* 针对格式化的函数的可用列表,请参阅{@link Ext.util.Format}.<br />
* 用法:
<pre><code>
var t = new Ext.Template(
'<div name="{id}">',
'<span class="{cls}">{name:trim} {value:ellipsis(10)}</span>',
'</div>'
);
t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
</code></pre>
* @constructor
* @param {String/Array} html HTML片断或是片断的数组(用于join(''))或多个参数(会执行join(''))。
*/
Ext.Template = function(html){
var a = arguments;
if(html instanceof Array){
html = html.join("");
}else if(a.length > 1){
var buf = [];
for(var i = 0, len = a.length; i < len; i++){
if(typeof a[i] == 'object'){
Ext.apply(this, a[i]);
}else{
buf[buf.length] = a[i];
}
}
html = buf.join('');
}
/**@private*/
this.html = html;
if(this.compiled){
this.compile();
}
};
Ext.Template.prototype = {
/**
* 返回HTML片段,这块片断是由数据填充模板之后而成的。
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @return {String} HTML片段
*/
applyTemplate : function(values){
if(this.compiled){
return this.compiled(values);
}
var useF = this.disableFormats !== true;
var fm = Ext.util.Format, tpl = this;
var fn = function(m, name, format, args){
if(format && useF){
if(format.substr(0, 5) == "this."){
return tpl.call(format.substr(5), values[name], values);
}else{
if(args){
// quoted values are required for strings in compiled templates,
// but for non compiled we need to strip them
// quoted reversed for jsmin
var re = /^\s*['"](.*)["']\s*$/;
args = args.split(',');
for(var i = 0, len = args.length; i < len; i++){
args[i] = args[i].replace(re, "$1");
}
args = [values[name]].concat(args);
}else{
args = [values[name]];
}
return fm[format].apply(fm, args);
}
}else{
return values[name] !== undefined ? values[name] : "";
}
};
return this.html.replace(this.re, fn);
},
/**
* 使得某段HTML可作用模板使用,也可将其编译
* @param {String} html
* @param {Boolean} compile (可选的) ture表示为编译模板(默认为undefined)
* @return {Ext.Template} this
*/
set : function(html, compile){
this.html = html;
this.compiled = null;
if(compile){
this.compile();
}
return this;
},
/**
* Ture表示为禁止格式化功能(默认为false)
* @type Boolean
*/
disableFormats : false,
/**
* 匹配模板变量的正则表达式。
* @type RegExp
* @property re
*/
re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
/**
* 将模板编译成内置调用函数,消除刚才的正则表达式
* @return {Ext.Template} this
*/
compile : function(){
var fm = Ext.util.Format;
var useF = this.disableFormats !== true;
var sep = Ext.isGecko ? "+" : ",";
var fn = function(m, name, format, args){
if(format && useF){
args = args ? ',' + args : "";
if(format.substr(0, 5) != "this."){
format = "fm." + format + '(';
}else{
format = 'this.call("'+ format.substr(5) + '", ';
args = ", values";
}
}else{
args= ''; format = "(values['" + name + "'] == undefined ? '' : ";
}
return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'";
};
var body;
// branched to use + in gecko and [].join() in others
if(Ext.isGecko){
body = "this.compiled = function(values){ return '" +
this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) +
"';};";
}else{
body = ["this.compiled = function(values){ return ['"];
body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn));
body.push("'].join('');};");
body = body.join('');
}
eval(body);
return this;
},
// private function used to call members
call : function(fnName, value, allValues){
return this[fnName](value, allValues);
},
/**
* 填充模板的数据,形成为一个或多个新节点,作为首个子节点插入到e1。
* @param {Mixed} el 上下文的元素
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined)
* @return {HTMLElement/Ext.Element} 新节点或元素
*/
insertFirst: function(el, values, returnElement){
return this.doInsert('afterBegin', el, values, returnElement);
},
/**
* 填充模板的数据,形成为一个或多个新节点,并位于el之前的位置插入。
* @param {Mixed} el 上下文的元素
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined)
* @return {HTMLElement/Ext.Element} 新节点或元素
*/
insertBefore: function(el, values, returnElement){
return this.doInsert('beforeBegin', el, values, returnElement);
},
/**
* 填充模板的数据,形成为一个或多个新节点,并位于el之后的位置插入。
* @param {Mixed} el 上下文的元素
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined)
* @return {HTMLElement/Ext.Element} 新节点或元素
*/
insertAfter : function(el, values, returnElement){
return this.doInsert('afterEnd', el, values, returnElement);
},
/**
* 填充模板的数据,形成为一个或多个新节点,并追加到e1。
* @param {Mixed} el 上下文的元素
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined)
* @return {HTMLElement/Ext.Element} 新节点或元素
*/
append : function(el, values, returnElement){
return this.doInsert('beforeEnd', el, values, returnElement);
},
doInsert : function(where, el, values, returnEl){
el = Ext.getDom(el);
var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values));
return returnEl ? Ext.get(newNode, true) : newNode;
},
/**
* 填充模板的数据,形成为一个或多个新节点,对el的内容进行覆盖。
* @param {Mixed} el 正文元素
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element(默认为undefined)
* @return {HTMLElement/Ext.Element} 新节点或元素
*/
overwrite : function(el, values, returnElement){
el = Ext.getDom(el);
el.innerHTML = this.applyTemplate(values);
return returnElement ? Ext.get(el.firstChild, true) : el.firstChild;
}
};
/**
* {@link #applyTemplate}的简写方式
* @method
*/
Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate;
/**
* 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML.
* @param {String/HTMLElement} DOM元素或某id
* @param {Object} config 一个配置项对象
* @returns {Ext.Template} 创建好的模板
* @static
*/
Ext.Template.from = function(el, config){
el = Ext.getDom(el);
return new Ext.Template(el.value || el.innerHTML, config || '');
}; | JavaScript |
/*
* 项目地址: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.Updater
* @extends Ext.util.Observable
* 为元素对象提供Ajax式更新。<br><br>
* 用法:<br>
* <pre><code>
* // 从Ext.Element对象上获取Updater
* var el = Ext.get("foo");
* var mgr = el.getUpdater();
* mgr.update({
* url: "http://myserver.com/index.php",
* params: {
* param1: "foo",
* param2: "bar"
* }
* });
* ...
* mgr.formUpdate("myFormId", "http://myserver.com/index.php");
* <br>
* // 或直接声明(返回相同的UpdateManager实例)
* var mgr = new Ext.Updater("myElementId");
* mgr.startAutoRefresh(60, "http://myserver.com/index.php");
* mgr.on("update", myFcnNeedsToKnow);
* <br>
// 用快捷的方法在元素上直接访问
Ext.get("foo").load({
url: "bar.php",
scripts: true,
params: "param1=foo&param2=bar",
text: "Loading Foo..."
});
* </code></pre>
* @constructor
* 直接创建新UpdateManager。
* @param {Mixed} el 被更新的元素
* @param {Boolean} forceNew (可选的) 默认下,构造器会检查传入之元素是否有UpdateManager,如果有的话它返回该实例,也会跳过检查(继承类时有用)。
*/
Ext.Updater = function(el, forceNew){
el = Ext.get(el);
if(!forceNew && el.updateManager){
return el.updateManager;
}
/**
* 元素对象
* @type Ext.Element
*/
this.el = el;
/**
* 用于刷新的缓存url,如参数设置为false,每次调用update()都会重写该值。
* @type String
*/
this.defaultUrl = null;
this.addEvents(
/**
* @event beforeupdate
* 在一个更新开始之前触发,如在事件句柄中返回false即意味着取消这次更新。
* @param {Ext.Element} el
* @param {String/Object/Function} url
* @param {String/Object} params
*/
"beforeupdate",
/**
* @event update
* 当更新成功后触发
* @param {Ext.Element} el
* @param {Object} oResponseObject response对象
*/
"update",
/**
* @event failure
* 当更新失败后触发
* @param {Ext.Element} el
* @param {Object} oResponseObject response对象
*/
"failure"
);
Ext.apply(this, Ext.Updater.defaults);
/**
* Blank page URL to use with SSL file uploads (defaults to {@link Ext.Updater.defaults#sslBlankUrl}).
* @property sslBlankUrl
* @type String
*/
/**
* Whether to append unique parameter on get request to disable caching (defaults to {@link Ext.Updater.defaults#disableCaching}).
* @property disableCaching
* @type Boolean
*/
/**
* Text for loading indicator (defaults to {@link Ext.Updater.defaults#indicatorText}).
* @property indicatorText
* @type String
*/
/**
* Whether to show indicatorText when loading (defaults to {@link Ext.Updater.defaults#showLoadIndicator}).
* @property showLoadIndicator
* @type String
*/
/**
* Timeout for requests or form posts in seconds (defaults to {@link Ext.Updater.defaults#timeout}).
* @property timeout
* @type Number
*/
/**
* True to process scripts in the output (defaults to {@link Ext.Updater.defaults#loadScripts}).
* @property loadScripts
* @type Boolean
*/
/**
* Transaction object of current executing transaction
*/
this.transaction = null;
/**
* @private
*/
this.autoRefreshProcId = null;
/**
* Delegate for refresh() prebound to "this", use myUpdater.refreshDelegate.createCallback(arg1, arg2) to bind arguments
* @type Function
*/
this.refreshDelegate = this.refresh.createDelegate(this);
/**
* Delegate for update() prebound to "this", use myUpdater.updateDelegate.createCallback(arg1, arg2) to bind arguments
* @type Function
*/
this.updateDelegate = this.update.createDelegate(this);
/**
* Delegate for formUpdate() prebound to "this", use myUpdater.formUpdateDelegate.createCallback(arg1, arg2) to bind arguments
* @type Function
*/
this.formUpdateDelegate = this.formUpdate.createDelegate(this);
if(!this.renderer){
/**
* The renderer for this Updater. Defaults to {@link Ext.Updater.BasicRenderer}.
*/
this.renderer = new Ext.Updater.BasicRenderer();
}
Ext.Updater.superclass.constructor.call(this);
};
Ext.extend(Ext.Updater, Ext.util.Observable, {
/**
* 获取当前UpdateManager所绑定的元素
* @return {Ext.Element} 元素
*/
getEl : function(){
return this.el;
},
/**
* 发起一个的<b>异步</b>请求,然后根据响应的response更新元素。
* 如不指定使用GET,否则POST。
* @param {Object/String/Function} url (可选的)请求的url或是能够返回url的函数(默认为最后使用的url),也可以是一个对象,包含下列可选项:
<pre><code>
um.update({<br/>
url: "your-url.php",<br/>
params: {param1: "foo", param2: "bar"}, // 或是可URL编码的字符串<br/>
callback: yourFunction,<br/>
scope: yourObject, //(作用域可选) <br/>
discardUrl: false, <br/>
nocache: false,<br/>
text: "加载中...",<br/>
timeout: 30,<br/>
scripts: false<br/>
});
</code></pre>
* 只有url的属性是必须的。
* 可选属性有nocache, text and scripts,分别是disableCaching,indicatorText和loadScripts的简写方式
* 它们用于设置UpdateManager实例相关的属性。
* @param {String/Object} params (可选的) 提交的参数,为可url编码的字符串"¶m1=1¶m2=2",也可以是对象的形式{param1: 1, param2: 2}
* @param {Function} callback (可选的) Callback 事务完成后执行的回调(带参数oElement, bSuccess)
* @param {Boolean} discardUrl (可选的) 默认情况下,完成更新后,最后一次使用的url会保存到defaultUrl属性
* 该参数为true的话,就不会保存。
*/
/**
* 发起一个的<b>异步</b>请求,然后根据响应的response更新元素。
* 如不指定使用GET,否则POST。<br><br>
* <b>NB:</b> 根据异步请求远端服务器的特性,此函数执行后元素不会立即被更新。要处理返回的数据,使用回调选项,或指定<b><tt>update</tt></b>事件句柄
* @param {Object} options 一个配置项对象可以包含下列属性:<ul>
* <li>url : <b>String/Function</b><p class="sub-desc">The URL to
* request or a function which <i>returns</i> the URL.</p></li>
* <li>method : <b>String</b><p class="sub-desc">The HTTP method to
* use. Defaults to POST if params are present, or GET if not.</p></li>
* <li>params : <b>String/Object/Function</b><p class="sub-desc">The
* parameters to pass to the server. 传到服务器的参数。这可以字符串(未urlencoded亦可),或代表参数的对象,或返回对象的函数。</p></li>
* <li><b>scripts</b> : Boolean<p class="sub-desc">If <tt>true</tt>
* any <script> tags embedded in the response text will be extracted
* and executed. If this option is specified, the callback will be
* called <i>after</i> the execution of the scripts.</p></li>
*
* <li><b>callback</b> : Function<p class="sub-desc">
* 接收到服务器的响应后,执行的回调函数。该函数带下列的参数:
* <ul>
* <li><b>el</b> : Ext.Element<p class="sub-desc">被更新的元素</p></li>
* <li><b>success</b> : Boolean<p class="sub-desc">True表示成功,false表示失败。</p></li>
* <li><b>response</b> : XMLHttpRequest<p class="sub-desc">进行更新的那个XMLHttpRequest对象</p></li>
* </ul>
* </p>
* </li>
*
* <li><b>scope</b> : Object<p class="sub-desc">The scope in which
* to execute the callback 回调函数所在的作用域(<tt>this<tt>所指向的引用)。如果
* <tt>params</tt> 选项是一个函数,那么这个作用域也用于该函数。</p></li>
*
* <li><b>discardUrl</b> : Boolean<p class="sub-desc">If not passed
* as <tt>false</tt> the URL of this request becomes the default URL for
* this Updater object, and will be subsequently used in {@link #refresh}
* calls.(可选的) 默认情况下,完成更新后,最后一次使用的url会保存到defaultUrl属性
* 该参数为true的话,就不会保存。</p></li>
* <li><b>timeout</b> : Number<p class="sub-desc">The timeout to use
* when waiting for a response.</p></li>
* <li><b>nocache</b> : Boolean<p class="sub-desc">Only needed for GET
* requests, this option causes an extra, generated parameter to be passed
* to defeat caching.</p></li></ul>
* <p>
* For example:
<pre><code>
um.update({
url: "your-url.php",
params: {param1: "foo", param2: "bar"}, // or a URL encoded string
callback: yourFunction,
scope: yourObject, //(optional scope)
discardUrl: false,
nocache: false,
text: "Loading...",
timeout: 30,
scripts: false // Save time by avoiding RegExp execution.
});
</code></pre>
*/
update : function(url, params, callback, discardUrl){
if(this.fireEvent("beforeupdate", this.el, url, params) !== false){
var method = this.method, cfg, callerScope;
if(typeof url == "object"){ // must be config object
cfg = url;
url = cfg.url;
params = params || cfg.params;
callback = callback || cfg.callback;
discardUrl = discardUrl || cfg.discardUrl;
callerScope = cfg.scope;
if(typeof cfg.method != "undefined"){method = cfg.method;};
if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;};
if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";};
if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;};
if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;};
}
this.showLoading();
if(!discardUrl){
this.defaultUrl = url;
}
if(typeof url == "function"){
url = url.call(this);
}
method = method || (params ? "POST" : "GET");
if(method == "GET"){
url = this.prepareUrl(url);
}
var o = Ext.apply(cfg ||{}, {
url : url,
params: (typeof params == "function" && callerScope) ? params.createDelegate(callerScope) : params,
success: this.processSuccess,
failure: this.processFailure,
scope: this,
callback: undefined,
timeout: (this.timeout*1000),
argument: {
"options": cfg,
"url": url,
"form": null,
"callback": callback,
"scope": callerScope || window,
"params": params
}
});
this.transaction = Ext.Ajax.request(o);
}
},
/**
* <p>执行表单的异步请求,然后根据响应response更新元素。Performs an async form post, updating this element with the response.
* 表单若有enctype="<a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</a>"的属性,即被认为是文件上传。
* If the form has the attribute
* enctype="<a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</a>", it assumes it's a file upload.
* SSL文件上传应使用this.sslBlankUrl以阻止IE的安全警告。
* Uses this.sslBlankUrl for SSL file uploads to prevent IE security warning.</p>
*
* <p>不能通过常规的“Ajax”方法来上传文件,XMLHttpRequests是不能为处理二进制文件服务的。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>Be aware that file upload packets, sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form-data</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>
* @param {String/HTMLElement} form 表单元素或表单idThe form Id or form element
* @param {String} url (可选的) 表单提交的url。如忽略则采用表单的action属性(optional) The url to pass the form to. If omitted the action attribute on the form will be used.
* @param {Boolean} reset (可选的) 完成更新后是否试着将表单复位(optional) Whether to try to reset the form after the update
* @param {Function} callback (可选的) 事务完成后执行的回调,回调带下列参数:(optional) Callback when transaction is complete. The following
* parameters are passed:<ul>
* <li><b>el</b> : Ext.Element<p class="sub-desc">被更新的元素The Element being updated.</p></li>
* <li><b>success</b> : Boolean<p class="sub-desc">True表示成功,false表示失败True for success, false for failure.</p></li>
* <li><b>response</b> : XMLHttpRequest<p class="sub-desc">进行更新的那个XMLHttpRequest对象The XMLHttpRequest which processed the update.</p></li></ul>
*/
formUpdate : function(form, url, reset, callback){
if(this.fireEvent("beforeupdate", this.el, form, url) !== false){
if(typeof url == "function"){
url = url.call(this);
}
form = Ext.getDom(form)
this.transaction = Ext.Ajax.request({
form: form,
url:url,
success: this.processSuccess,
failure: this.processFailure,
scope: this,
timeout: (this.timeout*1000),
argument: {
"url": url,
"form": form,
"callback": callback,
"reset": reset
}
});
this.showLoading.defer(1, this);
}
},
/**
* 根据最后一次使用的url,或属性defaultUrl,刷新元素。
* 如果未发现url,则立即返回。
* @param {Function} callback (可选的) Callback 事务完成后,执行的回调(带参数oElement, bSuccess)
*/
refresh : function(callback){
if(this.defaultUrl == null){
return;
}
this.update(this.defaultUrl, null, callback, true);
},
/**
* 设置该元素自动刷新。
* @param {Number} interval 更新频率(单位:秒)
* @param {String/Function} url (可选的) 请求的url或是能够返回url的函数(默认为最后使用那个的url)
* @param {String/Object} params (可选的) 提交的参数,为可url编码的字符串"¶m1=1¶m2=2",也可是对象的形式{param1: 1, param2: 2}
* @param {Function} callback (可选的) Callback 事务完成后执行的回调(带参数oElement, bSuccess)
* @param {Boolean} refreshNow (可选的) 是否立即执行更新,或等待下一次更新
*/
startAutoRefresh : function(interval, url, params, callback, refreshNow){
if(refreshNow){
this.update(url || this.defaultUrl, params, callback, true);
}
if(this.autoRefreshProcId){
clearInterval(this.autoRefreshProcId);
}
this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000);
},
/**
* 停止该元素的自动刷新
*/
stopAutoRefresh : function(){
if(this.autoRefreshProcId){
clearInterval(this.autoRefreshProcId);
delete this.autoRefreshProcId;
}
},
isAutoRefreshing : function(){
return this.autoRefreshProcId ? true : false;
},
/**
* 把元素换成“加载中”的状态,可重写该方法执行自定义的动作。
*/
showLoading : function(){
if(this.showLoadIndicator){
this.el.update(this.indicatorText);
}
},
/**
* 加入查询字符串的唯一的参数,前提是disableCaching = true。
* @private
*/
prepareUrl : function(url){
if(this.disableCaching){
var append = "_dc=" + (new Date().getTime());
if(url.indexOf("?") !== -1){
url += "&" + append;
}else{
url += "?" + append;
}
}
return url;
},
/**
* @private
*/
processSuccess : function(response){
this.transaction = null;
if(response.argument.form && response.argument.reset){
try{ // put in try/catch since some older FF releases had problems with this
response.argument.form.reset();
}catch(e){}
}
if(this.loadScripts){
this.renderer.render(this.el, response, this,
this.updateComplete.createDelegate(this, [response]));
}else{
this.renderer.render(this.el, response, this);
this.updateComplete(response);
}
},
updateComplete : function(response){
this.fireEvent("update", this.el, response);
if(typeof response.argument.callback == "function"){
response.argument.callback.call(response.argument.scope, this.el, true, response, response.argument.options);
}
},
/**
* @private
*/
processFailure : function(response){
this.transaction = null;
this.fireEvent("failure", this.el, response);
if(typeof response.argument.callback == "function"){
response.argument.callback.call(response.argument.scope, this.el, false, response, response.argument.options);
}
},
/**
* 为这次更新设置内容渲染器。参阅{@link Ext.Updater.BasicRenderer#render}的更多资料。
* @param {Object} renderer 实现render()的对象
*/
setRenderer : function(renderer){
this.renderer = renderer;
},
/**
* 返回Updater当前的内容渲染器。参阅{@link Ext.Updater.BasicRenderer#render}以了解更多。
* Returns the current content renderer for this Updater. See {@link Ext.Updater.BasicRenderer#render} for more details.
* @return {Object}
*/
getRenderer : function(){
return this.renderer;
},
/**
* 为这次更新设置defaultUrl
* @param {String/Function} defaultUrl URL或是能返回的URL的函数
*/
setDefaultUrl : function(defaultUrl){
this.defaultUrl = defaultUrl;
},
/**
* 取消执行事务
*/
abort : function(){
if(this.transaction){
Ext.Ajax.abort(this.transaction);
}
},
/**
* 当更新进行时返回true。
* @return {Boolean}
*/
isUpdating : function(){
if(this.transaction){
return Ext.Ajax.isLoading(this.transaction);
}
return false;
}
});
/**
* @class Ext.Updater.defaults
* UpdateManager组件中可定制的属性,这里是默认值集合。
*/
Ext.Updater.defaults = {
/**
* 以秒为单位的请求超时时限(默认为30秒)。
* @type Number
*/
timeout : 30,
/**
* True表示为执行脚本(默认为false)。
* @type Boolean
*/
loadScripts : false,
/**
* 空白页的URL,通过SSL链接上传文件时使用(默认为“javascript:false”)。
* @type String
*/
sslBlankUrl : (Ext.SSL_SECURE_URL || "javascript:false"),
/**
* 是否添加一个唯一的参数以使接到请求时禁止缓存(默认为 false)。
* @type Boolean
*/
disableCaching : false,
/**
* 加载时是否显示“indicatorText”(默认为 true)。
* @type Boolean
*/
showLoadIndicator : true,
/**
* 加载指示器显示的内容(默认为'<div class="loading-indicator">Loading...</div>')
* @type String
*/
indicatorText : '<div class="loading-indicator">Loading...</div>'
};
/**
* 静态的快捷方法。这个方法已经是过时的,推荐使用el.load({url:'foo.php', ...})。
*Usage:
* <pre><code>Ext.Updater.updateElement("my-div", "stuff.php");</code></pre>
* @param {Mixed} el The element to update
* @param {String} url The url
* @param {String/Object} params (optional) Url encoded param string or an object of name/value pairs
* @param {Object} options (optional) A config object with any of the Updater properties you want to set - for example: {disableCaching:true, indicatorText: "Loading data..."}
* @static
* @deprecated
* @member Ext.Updater
*/
Ext.Updater.updateElement = function(el, url, params, options){
var um = Ext.get(el).getUpdater();
Ext.apply(um, options);
um.update(url, params, options ? options.callback : null);
};
// alias for backwards compat
Ext.Updater.update = Ext.Updater.updateElement;
/**
* @class Ext.Updater.BasicRenderer
* 默认的内容渲染器。使用responseText更新元素的innerHTML属性。
*/
Ext.Updater.BasicRenderer = function(){};
Ext.Updater.BasicRenderer.prototype = {
/**
* 当事务完成并准备更新元素的时候调用此方法。
* BasicRenderer 使用 responseText 更新元素的 innerHTML 属性。
* 如想要指定一个定制的渲染器(如:XML 或 JSON),使用“render(el, response)”方法创建一个对象,
* 并通过setRenderer方法传递给UpdateManager。
* @param {Ext.Element} el 所渲染的元素
* @param {Object} response XMLHttpRequest对象
* @param {Updater} updateManager 调用的UpdateManager对象
* @param {Function} callback 如果loadScripts属性为true时,UpdateManager对象需要指定一个回调函数
*/
render : function(el, response, updateManager, callback){
el.update(response.responseText, updateManager.loadScripts, callback);
}
};
Ext.UpdateManager = Ext.Updater;
| JavaScript |
/*
* 项目地址: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.EventManager
* 对于登记的事件处理器(Event handlers),能够接受一个常规化的(已作跨浏览器处理的)EventObject的参数,而非浏览器的标准事件,并直接提供一些有用的事件。
* 更多“已常规化的事件对象(normalized event objects)”的信息,请参阅{@link Ext.EventObject}。
* Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
* several useful events directly.
* See {@link Ext.EventObject} for more details on normalized event objects.
* @singleton
*/
Ext.EventManager = function(){
var docReadyEvent, docReadyProcId, docReadyState = false;
var resizeEvent, resizeTask, textEvent, textSize;
var E = Ext.lib.Event;
var D = Ext.lib.Dom;
// fix parser confusion
var xname = 'Ex' + 't';
var elHash = {};
var addListener = function(el, ename, fn, wrap, scope){
var id = Ext.id(el);
if(!elHash[id]){
elHash[id] = {};
}
var es = elHash[id];
if(!es[ename]){
es[ename] = [];
}
var ls = es[ename];
ls.push({
id: id,
ename: ename,
fn: fn,
wrap: wrap,
scope: scope
});
E.on(el, ename, wrap);
if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
el.addEventListener("DOMMouseScroll", wrap, false);
E.on(window, 'unload', function(){
el.removeEventListener("DOMMouseScroll", wrap, false);
});
}
if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
}
}
var removeListener = function(el, ename, fn, scope){
el = Ext.getDom(el);
var id = Ext.id(el), es = elHash[id], wrap;
if(es){
var ls = es[ename], l;
if(ls){
for(var i = 0, len = ls.length; i < len; i++){
l = ls[i];
if(l.fn == fn && (!scope || l.scope == scope)){
wrap = l.wrap;
E.un(el, ename, wrap);
ls.splice(i, 1);
break;
}
}
}
}
if(ename == "mousewheel" && el.addEventListener && wrap){
el.removeEventListener("DOMMouseScroll", wrap, false);
}
if(ename == "mousedown" && el == document && wrap){ // fix stopped mousedowns on the document
Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
}
}
var removeAll = function(el){
el = Ext.getDom(el);
var id = Ext.id(el), es = elHash[id], ls;
if(es){
for(var ename in es){
if(es.hasOwnProperty(ename)){
ls = es[ename];
for(var i = 0, len = ls.length; i < len; i++){
E.un(el, ename, ls[i].wrap);
ls[i] = null;
}
}
es[ename] = null;
}
delete elHash[id];
}
}
var fireDocReady = function(){
if(!docReadyState){
docReadyState = true;
Ext.isReady = true;
if(docReadyProcId){
clearInterval(docReadyProcId);
}
if(Ext.isGecko || Ext.isOpera) {
document.removeEventListener("DOMContentLoaded", fireDocReady, false);
}
if(Ext.isIE){
var defer = document.getElementById("ie-deferred-loader");
if(defer){
defer.onreadystatechange = null;
defer.parentNode.removeChild(defer);
}
}
if(docReadyEvent){
docReadyEvent.fire();
docReadyEvent.clearListeners();
}
}
};
var initDocReady = function(){
docReadyEvent = new Ext.util.Event();
if(Ext.isGecko || Ext.isOpera) {
document.addEventListener("DOMContentLoaded", fireDocReady, false);
}else if(Ext.isIE){
document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
var defer = document.getElementById("ie-deferred-loader");
defer.onreadystatechange = function(){
if(this.readyState == "complete"){
fireDocReady();
}
};
}else if(Ext.isSafari){
docReadyProcId = setInterval(function(){
var rs = document.readyState;
if(rs == "complete") {
fireDocReady();
}
}, 10);
}
// 无论怎么样,保证on load时触发。no matter what, make sure it fires on load
E.on(window, "load", fireDocReady);
};
var createBuffered = function(h, o){
var task = new Ext.util.DelayedTask(h);
return function(e){
// 创建新的impl事件对象,这样新的事件就不会消灭掉(wipe out)属性(译注,js都是by refenerce)。
// create new event object impl so new events don't wipe out properties
e = new Ext.EventObjectImpl(e);
task.delay(o.buffer, h, null, [e]);
};
};
var createSingle = function(h, el, ename, fn, scope){
return function(e){
Ext.EventManager.removeListener(el, ename, fn, scope);
h(e);
};
};
var createDelayed = function(h, o){
return function(e){
// create new event object impl so new events don't wipe out properties
e = new Ext.EventObjectImpl(e);
setTimeout(function(){
h(e);
}, o.delay || 10);
};
};
var createTargeted = function(h, o){
return function(){
if(o.target == Ext.EventObject.setEvent(arguments[0]).target){
h.apply(this, Array.prototype.slice.call(arguments, 0));
}
};
};
var listen = function(element, ename, opt, fn, scope){
var o = (!opt || typeof opt == "boolean") ? {} : opt;
fn = fn || o.fn; scope = scope || o.scope;
var el = Ext.getDom(element);
if(!el){
throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
}
var h = function(e){
// prevent errors while unload occurring
if(!window[xname]){
return;
}
e = Ext.EventObject.setEvent(e);
var t;
if(o.delegate){
t = e.getTarget(o.delegate, el);
if(!t){
return;
}
}else{
t = e.target;
}
if(o.stopEvent === true){
e.stopEvent();
}
if(o.preventDefault === true){
e.preventDefault();
}
if(o.stopPropagation === true){
e.stopPropagation();
}
if(o.normalized === false){
e = e.browserEvent;
}
fn.call(scope || el, e, t, o);
};
if(o.target){
h = createTargeted(h, o);
}
if(o.delay){
h = createDelayed(h, o);
}
if(o.single){
h = createSingle(h, el, ename, fn, scope);
}
if(o.buffer){
h = createBuffered(h, o);
}
addListener(el, ename, fn, h, scope);
return h;
};
var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
var pub = {
/**
* 加入一个事件处理函数,方法{@link #on}是其简写方式。
* Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will
* use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
* @param {String/HTMLElement} el 要分配的html元素或者其id。The html element or id to assign the event handler to
* @param {String} eventName 事件处理函数的名称。The type of event to listen for
* @param {Function} handler 事件处理函数。该函数会送入以下的参数:The handler function the event invokes This function is passed
* the following parameters:<ul>
* <li>evt : EventObject<div class="sub-desc">
* 用于描述这次事件{@link Ext.EventObject EventObject}的事件对象。
* The {@link Ext.EventObject EventObject} describing the event.</div></li>
* <li>t : Element<div class="sub-desc">
* 事件源对象,类型为{@link Ext.Element Element}。
* 注意该项可能会因<tt>delegate</tt>选项的筛选而发生变化。
* The {@link Ext.Element Element} which was the target of the event.
* Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
* <li>o : Object<div class="sub-desc">
* 调用addListener时送入的选项对象。
* The options object from the addListener call.</div></li>
* </ul>
* @param {Object} scope (可选的)事件处理函数执行时所在的作用域。处理函数“this”的上下文。(optional) The scope in which to execute the handler
* function (the handler function's "this" context)
* @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会下来的属性:(optional) An object containing handler configuration properties.
* This may contain any of the following properties:<ul>
* <li>scope {Object} : 事件处理函数执行时所在的作用域。处理函数“this”的上下文环境。The scope in which to execute the handler function. The handler function's "this" context.</li>
* <li>delegate {String} : 一个简易选择符,用于过滤目标,或是查找目标的子孙。A simple selector to filter the target or look for a descendant of the target</li>
* <li>stopEvent {Boolean} : true表示为阻止事件。即停止传播、阻止默认动作。True to stop the event. That is stop propagation, and prevent the default action.</li>
* <li>preventDefault {Boolean} : true表示为阻止默认动作。True to prevent the default action</li>
* <li>stopPropagation {Boolean} : true表示为阻止事件传播。True to prevent event propagation</li>
* <li>normalized {Boolean} : false表示对处理函数送入一个原始、未封装过的浏览器对象而非标准的Ext.EventObject。False to pass a browser event to the handler function instead of an Ext.EventObject</li>
* <li>delay {Number} : 触发事件后处理函数延时执行的时间。The number of milliseconds to delay the invocation of the handler after te event fires.</li>
* <li>single {Boolean} : true代表为下次事件触发加入一个要处理的函数,然后再移除本身。True to add a handler to handle just the next firing of the event, and then remove itself.</li>
* <li>buffer {Number} : 若指定一个毫秒数会把该处理函数安排到{@link Ext.util.DelayedTask}延时之后才执行。
* 如果事件在那个事件再次触发,则原句柄将<em>不会</em> 被启用,但是新句柄会安排在其位置。
* Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
* by the specified number of milliseconds. If the event fires again within that time, the original
* handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
* <li>target {Element} :
* 只在目标元素触发的事件才有在这句柄上,事件上报中的子元素就<i>没有</i>。
* Only call the handler if the event was fired on the target Element, <i>not</i>
* if the event was bubbled up from a child node.</li>
* </ul><br>
* <p>
* 请参阅{@link Ext.Element#addListener}其中的例子以了解这些选项更多的用法。
* See {@link Ext.Element#addListener} for examples of how to use these options.</p>
*/
addListener : function(element, eventName, fn, scope, options){
if(typeof eventName == "object"){
var o = eventName;
for(var e in o){
if(propRe.test(e)){
continue;
}
if(typeof o[e] == "function"){
// shared options
listen(element, e, o, o[e], o.scope);
}else{
// individual options
listen(element, e, o[e]);
}
}
return;
}
return listen(element, eventName, options, fn, scope);
},
/**
* 移除事件处理器(event handler),跟简写方式{@link #un}是一样的。
* 通常你会更多的使用元素本身{@link Ext.Element#removeListener}的方法。
* Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
* you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
* @param {String/HTMLElement} el 欲移除事件的html元素或id。The id or html element from which to remove the event
* @param {String} eventName 事件的类型。The type of event
* @param {Function} fn 事件的执行那个函数。The handler function to remove
*/
removeListener : function(element, eventName, fn, scope){
return removeListener(element, eventName, fn, scope);
},
/**
* 移除某个元素所有的事件处理器。一般而言你直接在元素身上调用{@link Ext.Element#removeAllListeners}方法即可。
* Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
* directly on an Element in favor of calling this version.
* @param {String/HTMLElement} el HTML元素或其id。The id or html element from which to remove the event
*/
removeAll : function(element){
return removeAll(element);
},
/**
* 当Document准备好的时候触发(在onload之前和在图片加载之前)。可以简写为Ext.onReady()。
* Fires when the document is ready (before onload and before images are loaded). Can be
* accessed shorthanded as Ext.onReady().
* @param {Function} fn 执行的函数。The method the event invokes
* @param {Object} scope (可选的)函数的作用域。(optional) An object that becomes the scope of the handler
* @param {boolean} options (可选的)标准{@link #addListener}的选项对象。(optional) An object containing standard {@link #addListener} options
*/
onDocumentReady : function(fn, scope, options){
if(docReadyState){ // if it already fired
docReadyEvent.addListener(fn, scope, options);
docReadyEvent.fire();
docReadyEvent.clearListeners();
return;
}
if(!docReadyEvent){
initDocReady();
}
options = options || {};
if(!options.delay){
options.delay = 1;
}
docReadyEvent.addListener(fn, scope, options);
},
// private
doResizeEvent: function(){
resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
},
/**
* 当window改变大小后触发,并有随改变大小的缓冲(50毫秒),对回调函数传入新视图的高度、宽度的参数。
* Fires when the window is resized and provides resize event buffering (50 milliseconds), passes new viewport width and height to handlers.
* @param {Function} fn 事件执行的函数。The method the event invokes
* @param {Object} scope 函数的作用域。An object that becomes the scope of the handler
* @param {boolean} options
*/
onWindowResize : function(fn, scope, options){
if(!resizeEvent){
resizeEvent = new Ext.util.Event();
resizeTask = new Ext.util.DelayedTask(this.doResizeEvent);
E.on(window, "resize", this.fireWindowResize, this);
}
resizeEvent.addListener(fn, scope, options);
},
// exposed only to allow manual firing
fireWindowResize : function(){
if(resizeEvent){
if((Ext.isIE||Ext.isAir) && resizeTask){
resizeTask.delay(50);
}else{
resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
}
}
},
/**
* 当激活的文本尺寸被用户改变时触发该事件。对回调函数传入旧尺寸、新尺寸的参数。
* Fires when the user changes the active text size. Handler gets called with 2 params, the old size and the new size.
* @param {Function} fn 事件执行的函数。The method the event invokes
* @param {Object} scope 函数的作用域。An object that becomes the scope of the handler
* @param {boolean} options
*/
onTextResize : function(fn, scope, options){
if(!textEvent){
textEvent = new Ext.util.Event();
var textEl = new Ext.Element(document.createElement('div'));
textEl.dom.className = 'x-text-resize';
textEl.dom.innerHTML = 'X';
textEl.appendTo(document.body);
textSize = textEl.dom.offsetHeight;
setInterval(function(){
if(textEl.dom.offsetHeight != textSize){
textEvent.fire(textSize, textSize = textEl.dom.offsetHeight);
}
}, this.textResizeInterval);
}
textEvent.addListener(fn, scope, options);
},
/**
* 移除传入的window resize侦听器。
* Removes the passed window resize listener.
* @param {Function} fn 事件执行的函数。The method the event invokes
* @param {Object} scope 函数的作用域。The scope of handler
*/
removeResizeListener : function(fn, scope){
if(resizeEvent){
resizeEvent.removeListener(fn, scope);
}
},
// private
fireResize : function(){
if(resizeEvent){
resizeEvent.fire(D.getViewWidth(), D.getViewHeight());
}
},
/**
* 配合SSL为onDocumentReady使用的Url(默认为Ext.SSL_SECURE_URL)。
* Url used for onDocumentReady with using SSL (defaults to Ext.SSL_SECURE_URL)
*/
ieDeferSrc : false,
/**
* 检查resize事件的频率,单位是毫秒数(默认为50)。
* The frequency, in milliseconds, to check for text resize events (defaults to 50)
*/
textResizeInterval : 50
};
/**
* Appends an event handler to an element. Shorthand for {@link #addListener}.
* @param {String/HTMLElement} el The html element or id to assign the event handler to
* @param {String} eventName The type of event to listen for
* @param {Function} handler The handler function the event invokes
* @param {Object} scope (optional) The scope in which to execute the handler
* function (the handler function's "this" context)
* @param {Object} options (optional) An object containing standard {@link #addListener} options
* @member Ext.EventManager
* @method on
*/
pub.on = pub.addListener;
/**
* Removes an event handler from an element. Shorthand for {@link #removeListener}.
* @param {String/HTMLElement} el The id or html element from which to remove the event
* @param {String} eventName The type of event
* @param {Function} fn The handler function to remove
* @return {Boolean} True if a listener was actually removed, else false
* @member Ext.EventManager
* @method un
*/
pub.un = pub.removeListener;
pub.stoppedMouseDownEvent = new Ext.util.Event();
return pub;
}();
/**
* 当文档准备好的时候触发(在onload之前和在图片加载之前)。系{@link Ext.EventManager#onDocumentReady}的简写方式。
* Fires when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
* @param {Function} fn The method the event invokes
* @param {Object} scope An object that becomes the scope of the handler
* @param {boolean} options (optional) An object containing standard {@link #addListener} options
* @member Ext
* @method onReady
*/
Ext.onReady = Ext.EventManager.onDocumentReady;
// Initialize doc classes
(function(){
var initExtCss = function(){
// find the body element
var bd = document.body || document.getElementsByTagName('body')[0];
if(!bd){ return false; }
var cls = [' ',
Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
: Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
: Ext.isOpera ? "ext-opera"
: Ext.isSafari ? "ext-safari"
: Ext.isChrome ? "ext-chrome" : ""];
if(Ext.isMac){
cls.push("ext-mac");
}
if(Ext.isLinux){
cls.push("ext-linux");
}
if(Ext.isBorderBox){
cls.push('ext-border-box');
}
if(Ext.isStrict){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
var p = bd.parentNode;
if(p){
p.className += ' ext-strict';
}
}
bd.className += cls.join(' ');
return true;
}
if(!initExtCss()){
Ext.onReady(initExtCss);
}
})();
/**
* @class Ext.EventObject
* 为方便操作,在你定义的事件句柄上传入事件对象(Event Object),这个对象直接呈现了Yahoo! UI事件功能。
* 同时也解决了自动null检查的不便。<br />
* EventObject exposes the Yahoo! UI Event functionality directly on the object
* passed to your event handler. It exists mostly for convenience. It also fixes the annoying null checks automatically to cleanup your code
* 举例:Example:
* <pre><code>
function handleClick(e){ // e它不是一个标准的事件对象,而是Ext.EventObject。e is not a standard event object, it is a Ext.EventObject
e.preventDefault();
var target = e.getTarget();
...
}
var myDiv = Ext.get("myDiv");
myDiv.on("click", handleClick);
// 或者or
Ext.EventManager.on("myDiv", 'click', handleClick);
Ext.EventManager.addListener("myDiv", 'click', handleClick);
</code></pre>
* @singleton
*/
Ext.EventObject = function(){
var E = Ext.lib.Event;
// safari keypress events for special keys return bad keycodes
var safariKeys = {
3 : 13, // enter
63234 : 37, // left
63235 : 39, // right
63232 : 38, // up
63233 : 40, // down
63276 : 33, // page up
63277 : 34, // page down
63272 : 46, // delete
63273 : 36, // home
63275 : 35 // end
};
// normalize button clicks
var btnMap = Ext.isIE ? {1:0,4:1,2:2} :
(Ext.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
Ext.EventObjectImpl = function(e){
if(e){
this.setEvent(e.browserEvent || e);
}
};
Ext.EventObjectImpl.prototype = {
/** 一般浏览器事件。The normal browser event */
browserEvent : null,
/** 鼠标世界有按钮按下。The button pressed in a mouse event */
button : -1,
/** True表示事件触发时是有按下shift键的。True if the shift key was down during the event */
shiftKey : false,
/** True表示事件触发时是有按下ctrl键的。True if the control key was down during the event */
ctrlKey : false,
/** True表示事件触发时是有按下alt键的。True if the alt key was down during the event */
altKey : false,
/** 键码常量。Key constant @type Number */
BACKSPACE: 8,
/** 键码常量。Key constant @type Number */
TAB: 9,
/** 键码常量。Key constant @type Number */
NUM_CENTER: 12,
/** 键码常量。Key constant @type Number */
ENTER: 13,
/** 键码常量。Key constant @type Number */
RETURN: 13,
/** 键码常量。Key constant @type Number */
SHIFT: 16,
/** 键码常量。Key constant @type Number */
CTRL: 17,
CONTROL : 17, // legacy
/** 键码常量。Key constant @type Number */
ALT: 18,
/** 键码常量。Key constant @type Number */
PAUSE: 19,
/** 键码常量。Key constant @type Number */
CAPS_LOCK: 20,
/** 键码常量。Key constant @type Number */
ESC: 27,
/** 键码常量。Key constant @type Number */
SPACE: 32,
/** 键码常量。Key constant @type Number */
PAGE_UP: 33,
PAGEUP : 33, // legacy
/** 键码常量。Key constant @type Number */
PAGE_DOWN: 34,
PAGEDOWN : 34, // legacy
/** 键码常量。Key constant @type Number */
END: 35,
/** 键码常量。Key constant @type Number */
HOME: 36,
/** 键码常量。Key constant @type Number */
LEFT: 37,
/** 键码常量。Key constant @type Number */
UP: 38,
/** 键码常量。Key constant @type Number */
RIGHT: 39,
/** 键码常量。Key constant @type Number */
DOWN: 40,
/** 键码常量。Key constant @type Number */
PRINT_SCREEN: 44,
/** 键码常量。Key constant @type Number */
INSERT: 45,
/** 键码常量。Key constant @type Number */
DELETE: 46,
/** 键码常量。Key constant @type Number */
ZERO: 48,
/** 键码常量。Key constant @type Number */
ONE: 49,
/** 键码常量。Key constant @type Number */
TWO: 50,
/** 键码常量。Key constant @type Number */
THREE: 51,
/** 键码常量。Key constant @type Number */
FOUR: 52,
/** 键码常量。Key constant @type Number */
FIVE: 53,
/** 键码常量。Key constant @type Number */
SIX: 54,
/** 键码常量。Key constant @type Number */
SEVEN: 55,
/** 键码常量。Key constant @type Number */
EIGHT: 56,
/** 键码常量。Key constant @type Number */
NINE: 57,
/** 键码常量。Key constant @type Number */
A: 65,
/** 键码常量。Key constant @type Number */
B: 66,
/** 键码常量。Key constant @type Number */
C: 67,
/** 键码常量。Key constant @type Number */
D: 68,
/** 键码常量。Key constant @type Number */
E: 69,
/** 键码常量。Key constant @type Number */
F: 70,
/** 键码常量。Key constant @type Number */
G: 71,
/** 键码常量。Key constant @type Number */
H: 72,
/** 键码常量。Key constant @type Number */
I: 73,
/** 键码常量。Key constant @type Number */
J: 74,
/** 键码常量。Key constant @type Number */
K: 75,
/** 键码常量。Key constant @type Number */
L: 76,
/** 键码常量。Key constant @type Number */
M: 77,
/** 键码常量。Key constant @type Number */
N: 78,
/** 键码常量。Key constant @type Number */
O: 79,
/** 键码常量。Key constant @type Number */
P: 80,
/** 键码常量。Key constant @type Number */
Q: 81,
/** 键码常量。Key constant @type Number */
R: 82,
/** 键码常量。Key constant @type Number */
S: 83,
/** 键码常量。Key constant @type Number */
T: 84,
/** 键码常量。Key constant @type Number */
U: 85,
/** 键码常量。Key constant @type Number */
V: 86,
/** 键码常量。Key constant @type Number */
W: 87,
/** 键码常量。Key constant @type Number */
X: 88,
/** 键码常量。Key constant @type Number */
Y: 89,
/** 键码常量。Key constant @type Number */
Z: 90,
/** 键码常量。Key constant @type Number */
CONTEXT_MENU: 93,
/** 键码常量。Key constant @type Number */
NUM_ZERO: 96,
/** 键码常量。Key constant @type Number */
NUM_ONE: 97,
/** 键码常量。Key constant @type Number */
NUM_TWO: 98,
/** 键码常量。Key constant @type Number */
NUM_THREE: 99,
/** 键码常量。Key constant @type Number */
NUM_FOUR: 100,
/** 键码常量。Key constant @type Number */
NUM_FIVE: 101,
/** 键码常量。Key constant @type Number */
NUM_SIX: 102,
/** 键码常量。Key constant @type Number */
NUM_SEVEN: 103,
/** 键码常量。Key constant @type Number */
NUM_EIGHT: 104,
/** 键码常量。Key constant @type Number */
NUM_NINE: 105,
/** 键码常量。Key constant @type Number */
NUM_MULTIPLY: 106,
/** 键码常量。Key constant @type Number */
NUM_PLUS: 107,
/** 键码常量。Key constant @type Number */
NUM_MINUS: 109,
/** 键码常量。Key constant @type Number */
NUM_PERIOD: 110,
/** 键码常量。Key constant @type Number */
NUM_DIVISION: 111,
/** 键码常量。Key constant @type Number */
F1: 112,
/** 键码常量。Key constant @type Number */
F2: 113,
/** 键码常量。Key constant @type Number */
F3: 114,
/** 键码常量。Key constant @type Number */
F4: 115,
/** 键码常量。Key constant @type Number */
F5: 116,
/** 键码常量。Key constant @type Number */
F6: 117,
/** 键码常量。Key constant @type Number */
F7: 118,
/** 键码常量。Key constant @type Number */
F8: 119,
/** 键码常量。Key constant @type Number */
F9: 120,
/** 键码常量。Key constant @type Number */
F10: 121,
/** 键码常量。Key constant @type Number */
F11: 122,
/** 键码常量。Key constant @type Number */
F12: 123,
/** @private */
setEvent : function(e){
if(e == this || (e && e.browserEvent)){ // already wrapped
return e;
}
this.browserEvent = e;
if(e){
// normalize buttons
this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1);
if(e.type == 'click' && this.button == -1){
this.button = 0;
}
this.type = e.type;
this.shiftKey = e.shiftKey;
// mac metaKey behaves like ctrlKey
this.ctrlKey = e.ctrlKey || e.metaKey;
this.altKey = e.altKey;
// in getKey these will be normalized for the mac
this.keyCode = e.keyCode;
this.charCode = e.charCode;
// cache the target for the delayed and or buffered events
this.target = E.getTarget(e);
// same for XY
this.xy = E.getXY(e);
}else{
this.button = -1;
this.shiftKey = false;
this.ctrlKey = false;
this.altKey = false;
this.keyCode = 0;
this.charCode = 0;
this.target = null;
this.xy = [0, 0];
}
return this;
},
/**
* 停止事件(preventDefault和stopPropagation)。
* Stop the event (preventDefault and stopPropagation)
*/
stopEvent : function(){
if(this.browserEvent){
if(this.browserEvent.type == 'mousedown'){
Ext.EventManager.stoppedMouseDownEvent.fire(this);
}
E.stopEvent(this.browserEvent);
}
},
/**
* 阻止浏览器默认行为处理事件。
* Prevents the browsers default handling of the event.
*/
preventDefault : function(){
if(this.browserEvent){
E.preventDefault(this.browserEvent);
}
},
/** @private */
isNavKeyPress : function(){
var k = this.keyCode;
k = Ext.isSafari ? (safariKeys[k] || k) : k;
return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC;
},
isSpecialKey : function(){
var k = this.keyCode;
return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 ||
(k == 16) || (k == 17) ||
(k >= 18 && k <= 20) ||
(k >= 33 && k <= 35) ||
(k >= 36 && k <= 39) ||
(k >= 44 && k <= 45);
},
/**
* 获取事件的键盘代码。
* Cancels bubbling of the event.
*/
stopPropagation : function(){
if(this.browserEvent){
if(this.browserEvent.type == 'mousedown'){
Ext.EventManager.stoppedMouseDownEvent.fire(this);
}
E.stopPropagation(this.browserEvent);
}
},
/**
* 返回一个常规化的事件键盘代码
* Gets the character code for the event.
* @return {Number} 键盘代码
*/
getCharCode : function(){
return this.charCode || this.keyCode;
},
/**
* Returns a normalized keyCode for the event.
* @return {Number} The key code
*/
getKey : function(){
var k = this.keyCode || this.charCode;
return Ext.isSafari ? (safariKeys[k] || k) : k;
},
/**
* 获取事件X坐标。
* Gets the x coordinate of the event.
* @return {Number}
*/
getPageX : function(){
return this.xy[0];
},
/**
* 获取事件Y坐标。
* Gets the y coordinate of the event.
* @return {Number}
*/
getPageY : function(){
return this.xy[1];
},
/**
* 获取事件的时间。
* Gets the time of the event.
* @return {Number}
*/
getTime : function(){
if(this.browserEvent){
return E.getTime(this.browserEvent);
}
return null;
},
/**
* 获取事件的页面坐标。
* Gets the page coordinates of the event.
* @return {Array} xy值,格式[x, y]。The xy values like [x, y]
*/
getXY : function(){
return this.xy;
},
/**
* 获取事件的目标对象。
* Gets the target for the event.
* @param {String} selector (可选的) 一个简易的选择符,用于筛选目标或查找目标的父级元素。(optional) A simple selector to filter the target or look for an ancestor of the target
* @param {Number/Mixed} maxDepth (可选的)搜索的最大深度(数字或是元素,默认为10||document.body)。(optional) The max depth to search as a number or element (defaults to 10 || document.body)
* @param {Boolean} returnEl (可选的) True表示为返回Ext.Element的对象而非DOM节点。(optional) True to return a Ext.Element object instead of DOM node
* @return {HTMLelement}
*/
getTarget : function(selector, maxDepth, returnEl){
return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
},
/**
* 获取相关的目标对象。
* Gets the related target.
* @return {HTMLElement}
*/
getRelatedTarget : function(){
if(this.browserEvent){
return E.getRelatedTarget(this.browserEvent);
}
return null;
},
/**
* 常规化鼠标滚轮的有限增量(跨浏览器)。
* Normalizes mouse wheel delta across browsers
* @return {Number} 有限增量。The delta
*/
getWheelDelta : function(){
var e = this.browserEvent;
var delta = 0;
if(e.wheelDelta){ /* IE/Opera. */
delta = e.wheelDelta/120;
}else if(e.detail){ /* Mozilla case. */
delta = -e.detail/3;
}
return delta;
},
/**
* 返回一个布尔值,表示当该事件执行的过程中,ctrl、alt、shift有否被按下。
* Returns true if the control, meta, shift or alt key was pressed during this event.
* @return {Boolean}
*/
hasModifier : function(){
return ((this.ctrlKey || this.altKey) || this.shiftKey) ? true : false;
},
/**
* 返回true表示如果该事件的目标对象等于el,或是el的子元素。
* Returns true if the target of this event is a child of el. Unless the allowEl parameter is set, it will return false if if the target is el.
* Example usage:<pre><code>
// Handle click on any child of an element
Ext.getBody().on('click', function(e){
if(e.within('some-el')){
alert('Clicked on a child of some-el!');
}
});
// Handle click directly on an element, ignoring clicks on child nodes
Ext.getBody().on('click', function(e,t){
if((t.id == 'some-el') && !e.within(t, true)){
alert('Clicked directly on some-el!');
}
});
</code></pre>
* @param {Mixed} el The id, DOM element or Ext.Element to check
* @param {Boolean} related (可选的)如果相关的target就是el而非target本身,返回true。(optional) true to test if the related target is within el instead of the target
* @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
* @return {Boolean}
*/
within : function(el, related, allowEl){
var t = this[related ? "getRelatedTarget" : "getTarget"]();
return t && ((allowEl ? (t === Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
},
getPoint : function(){
return new Ext.lib.Point(this.xy[0], this.xy[1]);
}
};
return new Ext.EventObjectImpl();
}(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
Ext = {version: '3.0'};
// 为老版本浏览器提供,老版本没有undefined……——但这样会占据多个全局变量?
window["undefined"] = window["undefined"];
/**
* @class Ext
* Ext核心工具与函数
* @singleton
*/
/**
* 复制config对象的所有属性到obj(第一个参数为obj,第二个参数为config)。
* Copies all the properties of config to obj.
* @param {Object} obj 属性接受方对象。The receiver of the properties
* @param {Object} config 属性源对象。The source of the properties
* @param {Object} defaults 默认对象,如果该参数存在,obj将会得到那些defaults有而config没有的属性。
* A different object that will also be applied for default values
* @return {Object} returns obj
* @member Ext apply
*/
Ext.apply = function(o, c, defaults){
if(defaults){
// no "this" reference for friendly out of scope calls
Ext.apply(o, defaults);
}
if(o && c && typeof c == 'object'){
for(var p in c){
o[p] = c[p];
}
}
return o;
};
(function(){
var idSeed = 0;
var ua = navigator.userAgent.toLowerCase();
var scrollWidth;
var isStrict = document.compatMode == "CSS1Compat",
isOpera = ua.indexOf("opera") > -1,
isChrome = ua.indexOf("chrome") > -1,
isSafari = !isChrome && (/webkit|khtml/).test(ua),
isSafari3 = isSafari && ua.indexOf('webkit/5') != -1,
isIE = !isOpera && ua.indexOf("msie") > -1,
isIE7 = !isOpera && ua.indexOf("msie 7") > -1,
isIE8 = !isOpera && ua.indexOf("msie 8") > -1,
isGecko = !isSafari && !isChrome && ua.indexOf("gecko") > -1,
isGecko3 = isGecko && ua.indexOf("rv:1.9") > -1,
isBorderBox = isIE && !isStrict,
isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
isAir = (ua.indexOf("adobeair") != -1),
isLinux = (ua.indexOf("linux") != -1),
isSecure = window.location.href.toLowerCase().indexOf("https") === 0;
// remove css image flicker
if(isIE && !isIE7){
try{
document.execCommand("BackgroundImageCache", false, true);
}catch(e){}
}
Ext.apply(Ext, {
/**
* 判断浏览器是否是精确(Strict)模式,以相对于怪癖模式(quirks mode)。
* True if the browser is in strict (standards-compliant) mode, as opposed to quirks mode
* @type Boolean
*/
isStrict : isStrict,
/**
* 判断页面是否运行在SSL状态。
* True if the page is running over SSL
* @type Boolean
*/
isSecure : isSecure,
/**
* 页面是否完全被初始化,并可供使用。
* True when the document is fully initialized and ready for action
* @type Boolean
*/
isReady : false,
/**
* 是否自动定时清除孤立的Ext.Elements缓存(默认为是)。
* True to automatically uncache orphaned Ext.Elements periodically (defaults to true)
* @type Boolean
*/
enableGarbageCollector : true,
/**
* 是否在清除缓存后自动清除事件监听器(默认为否)。
* 注意:仅当enableGarbageCollector为true时该项的设置才有效。
* True to automatically purge event listeners after uncaching an element (defaults to false).
* Note: this only happens if enableGarbageCollector is true.
* @type Boolean
*/
enableListenerCollection:false,
/**
* 在非安全模式下,Ext要一个空白文件的链接,链接是为了iframe与onReady所指向的连接(src),以便能够组织IE不安全内容的警告(默认为javascript:fasle)
* URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent
* the IE insecure content warning (defaults to javascript:false).
* @type String
*/
SSL_SECURE_URL : "javascript:false",
/**
* 一个1*1的透明gif图片连接,用于内置图标和css背景。
* 默认地址为"http://extjs.com/s.gif",应用时应该设为自己的服务器连接。
* URL to a 1x1 transparent gif image used by Ext to create inline icons with CSS background images. (Defaults to
* "http://extjs.com/s.gif" and you should change this to a URL on your server).
* @type String
*/
BLANK_IMAGE_URL : "http:/"+"/extjs.com/s.gif",
/**
* 可复用的空函数。
* A reusable empty function
* @property emptyFn
* @type Function
*/
emptyFn : function(){},
/**
* 复制所有config的属性至obj,如果obj已有该属性,则不复制(第一个参数为obj,第二个参数为config)。
* Copies all the properties of config to obj if they don't already exist.
* @param {Object} obj 接受方对象。The receiver of the properties
* @param {Object} config 源对象。The source of the properties
* @return {Object} returns obj
*/
applyIf : function(o, c){
if(o && c){
for(var p in c){
if(typeof o[p] == "undefined"){ o[p] = c[p]; }
}
}
return o;
},
/**
* 页面被初始化完毕后,在元素上绑定事件监听。事件名在'@'符号后。
* Applies event listeners to elements by selectors when the document is ready.
* The event name is specified with an @ suffix.
<pre><code>
Ext.addBehaviors({
// 为id为foo的锚点元素增加onclick事件监听。
// add a listener for click on all anchors in element with id foo
'#foo a@click' : function(e, t){
// do something
},
// 为多个元素增加mouseover事件监听(在'@'前用逗号(,)分隔)。
// add the same listener to multiple selectors (separated by comma BEFORE the @)
'#foo a, #bar span.some-class@mouseover' : function(){
// do something
}
});
</code></pre>
* @param {Object} obj 所绑定的事件及其行为。The list of behaviors to apply
*/
addBehaviors : function(o){
if(!Ext.isReady){
Ext.onReady(function(){
Ext.addBehaviors(o);
});
return;
}
var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
for(var b in o){
var parts = b.split('@');
if(parts[1]){ // for Object prototype breakers
var s = parts[0];
if(!cache[s]){
cache[s] = Ext.select(s);
}
cache[s].on(parts[1], o[b]);
}
}
cache = null;
},
/**
* 对页面元素生成唯一id,如果该元素已存在id,则不会再生成。
* Generates unique ids. If the element already has an id, it is unchanged
* @param {Mixed} el (可选的) 将要生成id的元素。(optional)The element to generate an id for
* @param {String} prefix (可选的) 该id的前缀(默认为 "ext-gen")。(optional) Id prefix (defaults "ext-gen")
* @return {String} 生成的Id。The generated Id.
*/
id : function(el, prefix){
prefix = prefix || "ext-gen";
el = Ext.getDom(el);
var id = prefix + (++idSeed);
return el ? (el.id ? el.id : (el.id = id)) : id;
},
/**
* OO继承,并由传递的值决定是否覆盖原对象的属性。
* 返回的类对象中也增加了“override()”函数,用于覆盖实例的成员。
* Extends one class with another class and optionally overrides members with the passed literal. This class
* also adds the function "override()" to the class that can be used to override
* members on an instance.
* <p>
* 另外一种用法是,第一个参数不是父类(严格说是父类构造器)的话那么将会发生如下的变化(这是使用2个参数的方式):
* This function also supports a 2-argument call in which the subclass's constructor is
* not passed as an argument. In this form, the parameters are as follows:</p><p>
* <div class="mdetail-params"><ul>
* <li><code>superclass</code>
* <div class="sub-desc">被继承的类。The class being extended</div></li>
* <li><code>overrides</code>
* <div class="sub-desc">
* 成员列表,就是将会复制到子类的prototype对象身上,——这便会让该新类的实例可共享这些成员。
* A literal with members which are copied into the subclass's
* prototype, and are therefore shared among all instances of the new class.<p>
* 注意其中可以包含一个元素为属于子类的构造器,叫<tt><b>constructor</b></tt>的成员。
* 如果该项<i>不</i>指定,就意味引用父类的构造器,父类构造器就会直接接收所有的参数。
* This may contain a special member named <tt><b>constructor</b></tt>. This is used
* to define the constructor of the new class, and is returned. If this property is
* <i>not</i> specified, a constructor is generated and returned which just calls the
* superclass's constructor passing on its parameters.</p></div></li>
* </ul></div></p><p>
* 例如,这样创建Ext GridPanel的子类。
* For example, to create a subclass of the Ext GridPanel:
* <pre><code>
MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
constructor: function(config) {
// 你先这样调用……(就是调用父类的构造函数)
MyGridPanel.superclass.constructor.apply(this, arguments);
// 然后接着是子类的代码……
},
yourMethod: function() {
// ……
}
});
</code></pre>
* </p>
* @param {Function} subclass 子类,用于继承(该类继承了父类所有属性,并最终返回该对象)。The class inheriting the functionality
* @param {Function} superclass 父类,被继承。The class being extended
* @param {Object} overrides (可选的)一个对象,将它本身携带的属性对子类进行覆盖。(optional) A literal with members which are copied into the subclass's
* prototype, and are therefore shared between all instances of the new class.
* @return {Function} 子类的构造器。The subclass constructor.
* @method extend
*/
extend : function(){
// inline overrides
var io = function(o){
for(var m in o){
this[m] = o[m];
}
};
var oc = Object.prototype.constructor;
return function(sb, sp, overrides){
if(typeof sp == 'object'){
overrides = sp;
sp = sb;
sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);};
}
var F = function(){}, sbp, spp = sp.prototype;
F.prototype = spp;
sbp = sb.prototype = new F();
sbp.constructor=sb;
sb.superclass=spp;
if(spp.constructor == oc){
spp.constructor=sp;
}
sb.override = function(o){
Ext.override(sb, o);
};
sbp.superclass = sbp.supr = (function(){
return spp;
});
sbp.override = io;
Ext.override(sb, overrides);
sb.extend = function(o){Ext.extend(sb, o);};
return sb;
};
}(),
extendX : function(supr, fn){
return Ext.extend(supr, fn(supr.prototype));
},
/**
* 在类上添加overrides指定的方法(多个方法),同名则覆盖,例如:
* Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
* Usage:<pre><code>
Ext.override(MyClass, {
newMethod1: function(){
// etc.
},
newMethod2: function(foo){
// etc.
}
});
</code></pre>
* @param {Object} origclass 要override的类。The class to override
* @param {Object} overrides 加入到origClass的函数列表。这应该是一个包含一个或多个方法的对象。The list of functions to add to origClass. This should be specified as an object literal
* containing one or more methods.
* @method override
*/
override : function(origclass, overrides){
if(overrides){
var p = origclass.prototype;
for(var method in overrides){
p[method] = overrides[method];
}
if(Ext.isIE && overrides.toString != origclass.toString){
p.toString = overrides.toString;
}
}
},
/**
* 为变量创建其命名空间,这样类就有了“安身之所”,不是飘荡四处的“全局变量”。例如:
* Creates namespaces to be used for scoping variables and classes so that they are not global. Usage:
* <pre><code>
Ext.namespace('Company', 'Company.data');
Company.Widget = function() { ... }
Company.data.CustomStore = function(config) { ... }
</code></pre>
* @param {String} namespace1 命名空间一
* @param {String} namespace2 命名空间二
* @param {String} etc
* @method namespace
*/
namespace : function(){
var a=arguments, o=null, i, j, d, rt;
for (i=0; i<a.length; ++i) {
d=a[i].split(".");
rt = d[0];
eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
for (j=1; j<d.length; ++j) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
},
/**
* 把一个对象转换为一串以编码的URL字符。例如Ext.urlEncode({foo: 1, bar: 2});变为"foo=1&bar=2"。
* 可选地,如果遇到属性的类型是数组的话,那么该属性对应的key就是每个数组元素的key,逐一进行“结对的”编码。
* Takes an object and converts it to an encoded URL. e.g. Ext.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2".
* Optionally, property values can be arrays,
* instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
* @param {Object} o
* @return {String}
*/
urlEncode : function(o){
if(!o){
return "";
}
var buf = [];
for(var key in o){
var ov = o[key], k = encodeURIComponent(key);
var type = typeof ov;
if(type == 'undefined'){
buf.push(k, "=&");
}else if(type != "function" && type != "object"){
buf.push(k, "=", encodeURIComponent(ov), "&");
}else if(Ext.isArray(ov)){
if (ov.length) {
for(var i = 0, len = ov.length; i < len; i++) {
buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
}
} else {
buf.push(k, "=&");
}
}
}
buf.pop();
return buf.join("");
},
/**
* 把一个已经encoded的URL字符串转换为对象。如Ext.urlDecode("foo=1&bar=2"); 就是{foo: "1", bar: "2"};
* Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false);就是{foo: "1", bar: ["2", "3", "4"]}。
* Takes an encoded URL and and converts it to an object. e.g. Ext.urlDecode("foo=1&bar=2"); would return {foo: "1", bar: "2"}
* or Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false); would return {foo: "1", bar: ["2", "3", "4"]}.
* @param {String} string URL字符串
* @param {Boolean} overwrite (可选的)重复名称的就当作为数组,如果该项为true就禁止该功能(默认为false)。(optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
* @return {Object} 成员实体。A literal with members
*/
urlDecode : function(string, overwrite){
if(!string || !string.length){
return {};
}
var obj = {};
var pairs = string.split('&');
var pair, name, value;
for(var i = 0, len = pairs.length; i < len; i++){
pair = pairs[i].split('=');
name = decodeURIComponent(pair[0]);
value = decodeURIComponent(pair[1]);
if(overwrite !== true){
if(typeof obj[name] == "undefined"){
obj[name] = value;
}else if(typeof obj[name] == "string"){
obj[name] = [obj[name]];
obj[name].push(value);
}else{
obj[name].push(value);
}
}else{
obj[name] = value;
}
}
return obj;
},
/**
* 迭代一个数组,数组中每个成员都将调用一次所传函数,直到函数返回false才停止执行。
* 如果传递的数组并非一个真正的数组,所传递的函数只调用它一次。
* (译注:如果不是数组,就将该“数组”放入一个[]中,而且会返回一个隐藏的int参数,代表为该array调用function的次数。)
* Iterates an array calling the passed function with each item, stopping if your function returns false. If the
* passed array is not really an array, your function is called once with it.
* The supplied function is called with (Object item, Number index, Array allItems).
* @param {Array/NodeList/Mixed} array 数组
* @param {Function} fn 函数
* @param {Object} scope 作用域
*/
each : function(array, fn, scope){
if(typeof array.length == "undefined" || typeof array == "string"){
array = [array];
}
for(var i = 0, len = array.length; i < len; i++){
if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
}
},
// deprecated
combine : function(){
var as = arguments, l = as.length, r = [];
for(var i = 0; i < l; i++){
var a = as[i];
if(Ext.isArray(a)){
r = r.concat(a);
}else if(a.length !== undefined && !a.substr){
r = r.concat(Array.prototype.slice.call(a, 0));
}else{
r.push(a);
}
}
return r;
},
/**
* 避免传递的字符串参数被正则表达式读取。
* Escapes the passed string for use in a regular expression
* @param {String} str
* @return {String}
*/
escapeRe : function(s) {
return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
},
/**
* 计算浏览器滚动体实际的物理宽度。该值根据OS的不同有所变化,例如主题、字体大小的影响。Utility method for getting the width of the browser scrollbar. This can differ depending on
* operating system settings, such as the theme or font size.
* @param {Boolean} force (可选的)True表示为计算一次实际的值。(optional) true to force a recalculation of the value.
* @return {Number} 滚动体的宽度。The width of the scrollbar.
*/
getScrollBarWidth: function(force){
if(!Ext.isReady){
return 0;
}
if(force === true || scrollWidth === null){
// 供测试用的div,临时的,用完删除掉。Append our div, do our calculation and then remove it
var div = Ext.getBody().createChild('<div class="x-hide-offsets" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),
child = div.child('div', true);
var w1 = child.offsetWidth;
div.setStyle('overflow', (Ext.isWebKit || Ext.isGecko) ? 'auto' : 'scroll');
var w2 = child.offsetWidth;
div.remove();
// 补上2才够位置。Need to add 2 to ensure we leave enough space
scrollWidth = w1 - w2 + 2;
}
return scrollWidth;
},
/**
* 是否使用浏览器的原生JSON解析方法,一些新型的浏览器会提供该方法。Indicates whether to use native browser parsing for JSON methods.
* This option is ignored if the browser does not support native JSON methods.
* <b>需要注意的是,原生JSON方法对于那些携带函数的对象没作用,而且属性名称(即key)必须是要引号套着的,否则将不能被解析(严格很多)(默认为false)。Note: Native JSON methods will not work with objects that have functions.
* Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false)
* @type Boolean
*/
USE_NATIVE_JSON : false,
// internal
callback : function(cb, scope, args, delay){
if(typeof cb == "function"){
if(delay){
cb.defer(delay, scope, args || []);
}else{
cb.apply(scope, args || []);
}
}
},
/**
* 返回dom对象,参数可以是string(id),dom node,或Ext.Element。
* Return the dom node for the passed string (id), dom node, or Ext.Element
* @param {Mixed} el
* @return HTMLElement
*/
getDom : function(el){
if(!el || !document){
return null;
}
return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
},
/**
* 返回当前HTML文档的{@link Ext.Element}类型。
* Returns the current HTML document object as an {@link Ext.Element}.
* @return Ext.Element document对象。The document
*/
getDoc : function(){
return Ext.get(document);
},
/**
* 返回当前document.body的{@link Ext.Element}类型。
* Returns the current document body as an {@link Ext.Element}.
* @return Ext.Element document对象。The document body
*/
getBody : function(){
return Ext.get(document.body || document.documentElement);
},
/**
* {@link Ext.ComponentMgr#get}的简写方式。
* Shorthand for {@link Ext.ComponentMgr#get}
* @param {String} id
* @return Ext.Component
*/
getCmp : function(id){
return Ext.ComponentMgr.get(id);
},
/**
* 验证某个值是否数字的一个辅助方法,若不是,返回指定的缺省值。
* Utility method for validating that a value is numeric, returning the specified default value if it is not.
* @param {Mixed} value 应该是一个数字,但其它的类型的值亦可适当地处理。Should be a number, but any type will be handled appropriately
* @param {Number} defaultValue 若传入的值是非数字,则返回缺省值。The value to return if the original value is non-numeric
* @return {Number} 数字或缺省值Value。if numeric, else defaultValue
*/
num : function(v, defaultValue){
if(typeof v != 'number' || isNaN(v)){
return defaultValue;
}
return v;
},
/**
* 尝试去移除每个传入的对象,包括DOM,事件侦听者,并呼叫他们的destroy方法(如果存在)。
* 该方法主要接纳{@link Ext.Element}与{@link Ext.Component}类型的参数。
* 但理论上任何继承自Ext.util.Observable的子类都可以做为参数传入(支持传入多参)。
* Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
* DOM (if applicable) and calling their destroy functions (if available).
* This method is primarily intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
* {@link Ext.util.Observable} can be passed in.
* Any number of elements and/or components can be passed into this function in a single call as separate arguments.
* @param {Mixed} arg1 任意要销毁的{@link Ext.Element}或{@link Ext.Component}。An {@link Ext.Element} or {@link Ext.Component} to destroy
* @param {Mixed} arg2 (可选的)
* @param {Mixed} etc... (可选的)
*/
destroy : function(){
for(var i = 0, a = arguments, len = a.length; i < len; i++) {
var as = a[i];
if(as){
if(typeof as.destroy == 'function'){
as.destroy();
}
else if(as.dom){
as.removeAllListeners();
as.remove();
}
}
}
},
/**
* 删除对象的指定属性(支持传入多参,同时删除多个属性)。
* Attempts to destroy and then remove a set of named properties of the passed object.
* @param {Object} o 打算删除的对象(通常是Component类型的对象)。The object (most likely a Component) who's properties you wish to destroy.
* @param {Mixed} arg1 打算删除的属性名称。The name of the property to destroy and remove from the object.
* @param {Mixed} etc... 其他更多要删除的属性名称。More property names to destroy and remove.
*/
destroyMembers : function(o, arg1, arg2, etc){
for(var i = 1, a = arguments, len = a.length; i < len; i++) {
Ext.destroy(o[a[i]]);
delete o[a[i]];
}
},
/**
* 移除document的DOM节点。如果是body节点的话会被忽略。
* Removes a DOM node from the document. The body node will be ignored if passed in.
* @param {HTMLElement} node 要移除的节点。The node to remove
*/
removeNode : isIE ? function(){
var d;
return function(n){
if(n && n.tagName != 'BODY'){
d = d || document.createElement('div');
d.appendChild(n);
d.innerHTML = '';
}
}
}() : function(n){
if(n && n.parentNode && n.tagName != 'BODY'){
n.parentNode.removeChild(n);
}
},
// inpired by a similar function in mootools library
/**
* 返回参数类型的详细信息。如果送入的对象是null或undefined那么返回false,又或是以下类型:
* Returns the type of object that is passed in. If the object passed in is null or undefined it
* return false otherwise it returns one of the following values:<ul>
* <li><b>string</b>: 如果传入的是字符串。If the object passed is a string</li>
* <li><b>number</b>: 如果输入的是数字。If the object passed is a number</li>
* <li><b>boolean</b>: 如果传入的是布尔值。If the object passed is a boolean value</li>
* <li><b>date</b>: 如果传入的是日期。If the object passed is a Date object</li>
* <li><b>function</b>: 如果传入的是函数。If the object passed is a function reference</li>
* <li><b>object</b>: 如果传入的是对象。If the object passed is an object</li>
* <li><b>array</b>: 如果传入的是数组。If the object passed is an array</li>
* <li><b>regexp</b>: 如果传入的是正则表达式。If the object passed is a regular expression</li>
* <li><b>element</b>: 如果传入的是DOM Element。If the object passed is a DOM Element</li>
* <li><b>nodelist</b>: 如果传入的是DOM NodeList。If the object passed is a DOM NodeList</li>
* <li><b>textnode</b>: 如果传入的是DOM Text,且非空或空格。If the object passed is a DOM text node and contains something other than whitespace</li>
* <li><b>whitespace</b>: 如果传入的是DOM Text,且是空格。If the object passed is a DOM text node and contains only whitespace</li>
* @param {Mixed} object
* @return {String}
*/
type : function(o){
if(o === undefined || o === null){
return false;
}
if(o.htmlElement){
return 'element';
}
var t = typeof o;
if(t == 'object' && o.nodeName) {
switch(o.nodeType) {
case 1: return 'element';
case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
}
}
if(t == 'object' || t == 'function') {
switch(o.constructor) {
case Array: return 'array';
case RegExp: return 'regexp';
case Date: return 'date';
}
if(typeof o.length == 'number' && typeof o.item == 'function') {
return 'nodelist';
}
}
return t;
},
/**
* 如果传入的值是null、undefined或空字符串,则返回true。(可选的)
* Returns true if the passed value is null, undefined or an empty string.
* @param {Mixed} value 要验证的值。The value to test
* @param {Boolean} allowBlank (可选的) 如果该值为true,则空字符串不会当作空而返回true。(optional) true to allow empty strings (defaults to false)
* @return {Boolean}
*/
isEmpty : function(v, allowBlank){
return v === null || v === undefined || (!allowBlank ? v === '' : false);
},
/**
* 验证值是否非空、非null、非undefined、非空白字符的便捷方法。如指定了默认值还会返回默认值。
* Utility method for validating that a value is non-empty (i.e. i) not null, ii) not undefined, and iii) not an empty string),
* returning the specified default value if it is.
* @param {Mixed} value 要测试的值。The value to test
* @param {Mixed} defaultValue 如果原值是空的所返回的值。The value to return if the original value is empty
* @param {Boolean} allowBlank (可选的)true表示为允许空白的字符串(默认为false)。(optional) true to allow empty strings (defaults to false)
* @return {Mixed} 值,若果是非空,就是defalutValue。value, if non-empty, else defaultValue
*/
value : function(v, defaultValue, allowBlank){
return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
},
/**
* 返回true表名送入的对象是JavaScript的array类型对象,否则为false。
* Returns true if the passed object is a JavaScript array, otherwise false.
* @param {Object} v 要测试的对象。The object to test
* @return {Boolean}
*/
isArray : function(v){
return v && typeof v.length == 'number' && typeof v.splice == 'function';
},
/**
* 返回true表名送入的对象是JavaScript的date类型对象,否则为false。
* Returns true if the passed object is a JavaScript date object, otherwise false.
* @param {Object} v 要测试的对象。The object to test
* @return {Boolean}
*/
isDate : function(v){
return v && typeof v.getFullYear == 'function';
},
/**
* 复制源对象身上指定的属性到目标对象。
* Copies a set of named properties fom the source object to the destination object.
* @param {Object} dest 目标对象。The destination object.
* @param {Object} source 源对象。The source object.
* @param {Array/String} names 可以是属性名称构成的数组,也可以是属性名称构成的字符串,用逗号、分号隔开。Either an Array of property names, or a comma-delimited list
* of property names to copy.
* @return {Object} 以修改的对象。The modified object.
* <p>例子:example:<pre><code>
ImageComponent = Ext.extend(Ext.BoxComponent, {
initComponent: function() {
this.autoEl = { tag: 'img' };
MyComponent.superclass.initComponent.apply(this, arguments);
this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
}
});
</code></pre>
*/
copyTo: function(dest, source, names){
if(typeof names == 'string'){
names = names.split(/[,;\s]/);
}
for(var i = 0, len = names.length; i< len; i++){
var n = names[i];
if(source.hasOwnProperty(n)){
dest[n] = source[n];
}
}
return dest;
},
intercept : function(o, name, fn, scope){
o[name] = o[name].createInterceptor(fn, scope);
},
sequence : function(o, name, fn, scope){
o[name] = o[name].createSequence(fn, scope);
},
/**
* True表示为浏览器是True表示为浏览器是Opera。
* True if the detected browser is Opera.
* @type Boolean
*/
isOpera : isOpera,
/**
* True表示为浏览器是Chrome。
* True if the detected browser is Chrome.
* @type Boolean
*/
isChrome : isChrome,
/**
* True表示为浏览器是Safari。
* True if the detected browser is Chrome.
* @type Boolean
*/
isSafari : isSafari,
/**
* True表示为浏览器是Safari 3.x。
* True if the detected browser is Safari 3.x.
* @type Boolean
*/
isSafari3 : isSafari3,
/**
* True表示为浏览器是Safari 2.x。
* True if the detected browser is Safari 2.x.
* @type Boolean
*/
isSafari2 : isSafari && !isSafari3,
/**
* True表示为浏览器是Internet Explorer。
* True if the detected browser is Internet Explorer.
* @type Boolean
*/
isIE : isIE,
/**
* True表示为浏览器是Internet Explorer6。
* True if the detected browser is Internet Explorer 6.x.
* @type Boolean
*/
isIE6 : isIE && !isIE7 && !isIE8,
/**
* True表示为浏览器是Internet Explorer7。
* True if the detected browser is Internet Explorer 7.x.
* @type Boolean
*/
isIE7 : isIE7,
/**
* True表示为浏览器是Internet Explorer8。
* True if the detected browser is Internet Explorer 8.x.
* @type Boolean
*/
isIE8 : isIE8,
/**
* True表示为浏览器是Gecko。
* True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
* @type Boolean
*/
isGecko : isGecko,
/**
* True表示为浏览器是pre-Gecko 1.9。
* True if the detected browser uses a pre-Gecko 1.9 layout engine (e.g. Firefox 2.x).
* @type Boolean
*/
isGecko2 : isGecko && !isGecko3,
/**
* True表示为浏览器是Gecko 1.9+引擎的(如Firefox 3.X)。
* True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
* @type Boolean
*/
isGecko3 : isGecko3,
/**
* True表示为浏览器是非strict模式状态下的Internet Explorer。
* True if the detected browser is Internet Explorer running in non-strict mode.
* @type Boolean
*/
isBorderBox : isBorderBox,
/**
* True表示为Linux平台的系统。
* True if the detected platform is Linux.
* @type Boolean
*/
isLinux : isLinux,
/**
* True表示为Windows平台的系统。
* True if the detected platform is Windows.
* @type Boolean
*/
isWindows : isWindows,
/**
* True表示为Mac OS平台的系统。
* True if the detected platform is Mac OS.
* @type Boolean
*/
isMac : isMac,
/**
* True表示为Adobe Air平台的系统。
* True if the detected platform is Adobe Air.
* @type Boolean
*/
isAir : isAir,
/**
* 默认下,Ext会自动决定浮动元素是否应该被填充。如果你在用Flash那么该值很可能要设置为True。
* By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
* you may want to set this to true.
* @type Boolean
*/
useShims : ((isIE && !isIE7) || (isMac && isGecko && !isGecko3))
});
// in intellij using keyword "namespace" causes parsing errors
Ext.ns = Ext.namespace;
})();
Ext.ns("Ext", "Ext.util", "Ext.grid", "Ext.dd", "Ext.tree", "Ext.data",
"Ext.form", "Ext.menu", "Ext.state", "Ext.lib", "Ext.layout", "Ext.app", "Ext.ux", "Ext.chart", "Ext.direct");
/**
* @class Function
* 这些函数在所有Function对象上均可用的(随便一个JavaScript函数)。
* These functions are available on every Function object (any JavaScript function).
*/
Ext.apply(Function.prototype, {
/**
* 创建一个回调函数,该回调传递参数的形式为:arguments[0], arguments[1], arguments[2], ...
* 对于任何函数来说都是可以直接调用的,例如<code>myFunction.createCallback(arg1, arg2)</code>。
* 这样就会为这个函数绑定它两个参数。<b>如果需要指定这个函数的作用域,就应使用{@link #createDelegate}。</b>
* 如果这个函数需要作用域,请使用#createDelegate。
* 本方法仅使用于Window作用域。
* 在回调方法的参数引用中,如果是一个没有任何参数的方法,那么直接指明其引用即可,并不需要本方法,如(如callback:myFn)。
* 然而,如果想指定带有参数的方法, 就应该使用该方法了。
* 因为callback: myFn(arg1, arg2)会引起myFn的方法调用,而得到结果却不是函数引用而是这个函数的返回值。
* 要得到一个加参的方法引用就需要使用本方法了,达到对函数“加壳”的目的,如下例:
* Creates a callback that passes arguments[0], arguments[1], arguments[2], ...
* Call directly on any function. Example: <code>myFunction.createCallback(arg1, arg2)</code>
* Will create a function that is bound to those 2 args. <b>If a specific scope is required in the
* callback, use {@link #createDelegate} instead.</b> The function returned by createCallback always
* executes in the window scope.
* This method is required when you want to pass arguments to a callback function. If no arguments
* are needed, you can simply pass a reference to the function as a callback (e.g., callback: myFn).
* However, if you tried to pass a function with arguments (e.g., callback: myFn(arg1, arg2)) the function
* would simply execute immediately when the code is parsed. Example usage:
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
// 点击按钮就提示“Hi, Fred”。clicking the button alerts "Hi, Fred"
new Ext.Button({
text: 'Say Hi',
renderTo: Ext.getBody(),
handler: sayHi.createCallback('Fred')
});
</code></pre>
* @return {Function} 新产生的函数。The new function
*/
createCallback : function(/*args...*/){
// make args available, in function below
var args = arguments;
var method = this;
return function() {
return method.apply(window, args);
};
},
/**
* 创建一个委派对象(就是回调),该对象的作用域指向obj。
* 对于任何函数来说都是可以直接调用的。例如:<code>this.myFunction.createDelegate(this)</code>
* 将创建一个函数,该函数的作用域会自动指向<tt>this</tt>。
* Creates a delegate (callback) that sets the scope to obj.
* Call directly on any function. Example: <code>this.myFunction.createDelegate(this, [arg1, arg2])</code>
* Will create a function that is automatically scoped to obj so that the <tt>this</tt> variable inside the
* callback points to obj. Example usage:
* <pre><code>
var sayHi = function(name){
// Note this use of "this.text" here. This function expects to
// execute within a scope that contains a text property. In this
// example, the "this" variable is pointing to the btn object that
// was passed in createDelegate below.
alert('Hi, ' + name + '. You clicked the "' + this.text + '" button.');
}
var btn = new Ext.Button({
text: 'Say Hi',
renderTo: Ext.getBody()
});
// This callback will execute in the scope of the
// button instance. Clicking the button alerts
// "Hi, Fred. You clicked the "Say Hi" button."
btn.on('click', sayHi.createDelegate(btn, ['Fred']));
</code></pre>
* @param {Object} obj (可选的) 自定义的作用域对象。
* (optional) The object for which the scope is set
* @param {Array} args (可选的) 覆盖该次调用的参数列表。(默认为该函数的arguments)。
* (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
* @param {Boolean/Number} appendArgs (可选的) 如果该参数为true,将args加载到该函数的后面,如果该参数为数字类型,则args将插入到所指定的位置。
* (optional) if True args are appended to call args instead of overriding,
* if a number the args are inserted at the specified position
* @return {Function} 新产生的函数。The new function
*/
createDelegate : function(obj, args, appendArgs){
var method = this;
return function() {
var callArgs = args || arguments;
if(appendArgs === true){
callArgs = Array.prototype.slice.call(arguments, 0);
callArgs = callArgs.concat(args);
}else if(typeof appendArgs == "number"){
callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
var applyArgs = [appendArgs, 0].concat(args); // create method call params
Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
}
return method.apply(obj || window, callArgs);
};
},
/**
* 延迟调用该函数。你可以加入一个作用域的参数,例如:
* Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
//即刻执行的:
sayHi('Fred');
// 两秒过后执行的:
sayHi.defer(2000, this, ['Fred']);
// 有时候加上一个匿名函数也是很方便的:this syntax is sometimes useful for deferring
// execution of an anonymous function:
(function(){
alert('Anonymous');
}).defer(100);
</code></pre>
* @param {Number} millis 延迟时间,以毫秒为单位(如果是0则立即执行)。The number of milliseconds for the setTimeout call (if 0 the function is executed immediately)
* @param {Object} obj (可选的) fcn的作用域(默认指向原函数或window)。(optional) The object for which the scope is set
* @param {Array} args (可选的) 覆盖原函数的参数列表(默认为该函数的arguments)。(optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
* @param {Boolean/Number} appendArgs (可选的)如果该参数为true,将args加载到该函数的后面,如果该参数为数字类型,则args将插入到所指定的位置。
* (optional) if True args are appended to call args instead of overriding,if a number the args are inserted at the specified position
* @return {Number} 可被clearTimeout所使用的timeout id。The timeout id that can be used with clearTimeout
*/
defer : function(millis, obj, args, appendArgs){
var fn = this.createDelegate(obj, args, appendArgs);
if(millis){
return setTimeout(fn, millis);
}
fn();
return 0;
},
/**
* 创建一个组合函数,调用次序为:原函数 + 参数中的函数。
* 该函数返回了原函数执行的结果(也就是返回了原函数的返回值)。
* 在参数中传递的函数fcn,它的参数也是原函数的参数。
* Create a combined function call sequence of the original function + the passed function.
* The resulting function returns the results of the original function.
* The passed fcn is called with the parameters of the original function. 举例:Example usage:
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
sayHi('Fred'); // 提示 "Hi, Fred"
var sayGoodbye = sayHi.createSequence(function(name){
alert('Bye, ' + name);
});
sayGoodbye('Fred'); // both alerts show
</code></pre>
* @param {Function} fcn 将要进行组合的函数。The function to sequence
* @param {Object} scope (可选的)fcn的作用域(默认指向原函数或window)。(optional) The scope of the passed fcn (Defaults to scope of original function or window)
* @return {Function} 新产生的函数。The new function
*/
createSequence : function(fcn, scope){
if(typeof fcn != "function"){
return this;
}
var method = this;
return function() {
var retval = method.apply(this || window, arguments);
fcn.apply(scope || this || window, arguments);
return retval;
};
},
/**
* 创建一个拦截器函数。
* 传递的参数fcn被原函数之前调用。如果fcn的返回值为false,则原函数不会被调用。
* 在返回函数中,将返回原函数的返回值。
* 参数fcn会被调用,fcn被调用时会被传入原函数的参数。
* Creates an interceptor function.
* The passed fcn is called before the original one. If it returns false, the original one is not called.
* The resulting function returns the results of the original function.
* The passed fcn is called with the parameters of the original function.
* 例如:Example usage:
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
sayHi('Fred'); // 提示"Hi, Fred"
// 不修改原函数的前提下创建新验证的函数。
// create a new function that validates input without
// directly modifying the original function:
var sayHiToFriend = sayHi.createInterceptor(function(name){
return name == 'Brian';
});
sayHiToFriend('Fred'); // 没提示
sayHiToFriend('Brian'); // 提示 "Hi, Brian"
</code></pre>
* @param {Function} fcn 在原函数被调用前调用的函数。The function to call before the original
* @param {Object} scope (可选的)fcn的作用域(默认指向原函数或window)。(optional) The scope of the passed fcn (Defaults to scope of original function or window)
* @return {Function} 新产生的函数。The new function
*/
createInterceptor : function(fcn, scope){
if(typeof fcn != "function"){
return this;
}
var method = this;
return function() {
fcn.target = this;
fcn.method = method;
if(fcn.apply(scope || this || window, arguments) === false){
return;
}
return method.apply(this || window, arguments);
};
}
});
/**
* @class String
* 为JavaScript的String对象添加静态方法。
* These functions are available as static methods on the JavaScript String object.
*/
Ext.applyIf(String, {
/**
* 把输入的' 与 \字符转义。
* Escapes the passed string for ' and \
* @param {String} string 要转义的字符。
* @return {String} 已转义的字符。The escaped string
* @static
*/
escape : function(string) {
return string.replace(/('|\\)/g, "\\$1");
},
/**
* 在字符串左边填充指定字符。这对于统一字符或日期标准格式非常有用。
* Pads the left side of a string with a specified character. This is especially useful
* for normalizing number and date strings. 例如:Example usage:
* <pre><code>
var s = String.leftPad('123', 5, '0');
// s 现在是:'00123's now contains the string: '00123'
</code></pre>
* @param {String} string 源字符串。The original string
* @param {Number} size 源+填充字符串的总长度。The total length of the output string
* @param {String} char (可选的) 填充字符串(默认是" ")。(optional) The character with which to pad the original string (defaults to empty string " ")
* @return {String} 填充后的字符串。The padded string
* @static
*/
leftPad : function (val, size, ch) {
var result = new String(val);
if(!ch) {
ch = " ";
}
while (result.length < size) {
result = ch + result;
}
return result.toString();
},
/**
* 定义带标记的字符串,并用传入的字符替换标记。每个标记必须是唯一的,而且必须要像{0},{1}...{n}这样地自增长。
* Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
* token must be unique, and must increment in the format {0}, {1}, etc.
* 例如:Example usage:
* <pre><code>
var cls = 'my-class', text = 'Some text';
var s = String.format('<div class="{0}">{1}</div>', cls, text);
//s现在是字符串:s now contains the string: '<div class="my-class">Some text</div>'
</code></pre>
* @param {String} string 带标记的字符串。The tokenized string to be formatted
* @param {String} value1 第一个值,替换{0}。The value to replace token {0}
* @param {String} value2 第二个值,替换{1}...等等(可以有任意多个)。Etc...
* @return {String} 转化过的字符串。The formatted string
* @static
*/
format : function(format){
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/\{(\d+)\}/g, function(m, i){
return args[i];
});
}
});
/**
* 比较并交换字符串的值。
* 参数中的第一个值与当前字符串对象比较,如果相等则返回传入的第一个参数,否则返回第二个参数。
* Utility function that allows you to easily switch a string between two alternating values. The passed value
* is compared to the current string, and if they are equal, the other value that was passed in is returned. If
* they are already different, the first value passed in is returned.
* 注意:这个方法返回新值,但并不改变现有字符串。
* Note that this method returns the new value
* but does not change the current string.
* <pre><code>
// 可供选择的排序方向。alternate sort directions
sort = sort.toggle('ASC', 'DESC');
// 等价判断语句:instead of conditional logic:
sort = (sort == 'ASC' ? 'DESC' : 'ASC');
</code></pre>
* @param {String} value 第一个参数,与函数相等则返回。The value to compare to the current string
* @param {String} other 传入的第二个参数,不等返回。The new value to use if the string already equals the first value passed in
* @return {String} 新值。The new value
*/
String.prototype.toggle = function(value, other){
return this == value ? other : value;
};
/**
* 裁剪字符串两旁的空白符,保留中间空白符,例如:
* Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
* <pre><code>
var s = ' foo bar ';
alert('-' + s + '-'); //alerts "- foo bar -"
alert('-' + s.trim() + '-'); //alerts "-foo bar-"
</code></pre>
* @return {String} 已裁剪的字符串。The trimmed string
*/
String.prototype.trim = function(){
var re = /^\s+|\s+$/g;
return function(){ return this.replace(re, ""); };
}();
/**
* @class Number
*/
Ext.applyIf(Number.prototype, {
/**
* 检查当前数字是否属于某个期望的范围内。
* 若数字是在范围内的就返回数字,否则最小或最大的极限值,那个极限值取决于数字是倾向那一面(最大、最小)。
* 注意返回的极限值并不会影响当前的值。
* Checks whether or not the current number is within a desired range. If the number is already within the
* range it is returned, otherwise the min or max value is returned depending on which side of the range is
* exceeded. Note that this method returns the constrained value but does not change the current number.
* @param {Number} min 范围中最小的极限值。The minimum number in the range
* @param {Number} max 范围中最大的极限值。The maximum number in the range
* @return {Number} 若在范围内,返回原值,否则返回超出那个范围边界的值。The constrained value if outside the range, otherwise the current value
*/
constrain : function(min, max){
return Math.min(Math.max(this, min), max);
}
});
/**
* @class Array
*/
Ext.applyIf(Array.prototype, {
/**
* 检查对象是否存在于当前数组中。
* Checks whether or not the specified object exists in the array.
* @param {Object} o 要检查的对象。The object to check for
* @return {Number} 返回该对象在数组中的位置(不存在则返回-1)。The index of o in the array (or -1 if it is not found)
*/
indexOf : function(o){
for (var i = 0, len = this.length; i < len; i++){
if(this[i] == o) return i;
}
return -1;
},
/**
* 删除数组中指定对象。如果该对象不在数组中,则不进行操作。
* Removes the specified object from the array. If the object is not found nothing happens.
* @param {Object} o 要移除的对象。The object to remove
* @return {Array} 当前数组。this array
*/
remove : function(o){
var index = this.indexOf(o);
if(index != -1){
this.splice(index, 1);
}
return this;
}
});
// 写在这里就不用依赖Date.js
/**
* 返回date对象创建时间与现在时间的时间差,单位为毫秒。
* Returns the number of milliseconds between this date and date
* (译注:)例:var date = new Date();
* var x=0;
* while(x<2){
* alert('x');
* x++;
* }
*
* var theTime = date.getElapsed();
* alert(theTime); //将显示间隔的时间,单位是毫秒
*
* @param {Date} date (可选的)默认时间是now。(optional) Defaults to now
* @return {Number} 间隔毫秒数。The diff in milliseconds
* @member Date getElapsed
*/
Date.prototype.getElapsed = function(date) {
return Math.abs((date || new Date()).getTime()-this.getTime());
};
Ext.Element.addMethods({
/**
* 返回元素的坐标,这个坐标是依据元素某一个方位(anchor position)所确定的坐标。
* Gets the x,y coordinates specified by the anchor position on the element.
* @param {String} anchor (可选的) 指定的方位位置点(默认为 "c",正中)。参阅 {@link #alignTo}可了解有什么支持的方位位置点。(optional) The specified anchor position (defaults to "c"). See {@link #alignTo}
* for details on supported anchor positions.
* @param {Boolean} local (optional) (可选的) true表示为获取元素局部的(相对于元素左上角位置)的坐标而非页面坐标。True to get the local (element top/left-relative) anchor position instead
* of page coordinates
* @param {Object} size (optional) (可选的) 用于计算方位位置点大小的对象(默认为元素当前大小)。An object containing the size to use for calculating anchor position
* {width: (target width), height: (target height)} (defaults to the element's current size)
* @return {Array} [x, y] 包含元素X、Y坐标的数组。An array containing the element's x and y coordinates
*/
getAnchorXY : function(anchor, local, s){
//Passing a different size is useful for pre-calculating anchors,
//especially for anchored animations that change the el size.
var w, h, vp = false;
if(!s){
var d = this.dom;
if(d == document.body || d == document){
vp = true;
w = Ext.lib.Dom.getViewWidth(); h = Ext.lib.Dom.getViewHeight();
}else{
w = this.getWidth(); h = this.getHeight();
}
}else{
w = s.width; h = s.height;
}
var x = 0, y = 0, r = Math.round;
switch((anchor || "tl").toLowerCase()){
case "c":
x = r(w*.5);
y = r(h*.5);
break;
case "t":
x = r(w*.5);
y = 0;
break;
case "l":
x = 0;
y = r(h*.5);
break;
case "r":
x = w;
y = r(h*.5);
break;
case "b":
x = r(w*.5);
y = h;
break;
case "tl":
x = 0;
y = 0;
break;
case "bl":
x = 0;
y = h;
break;
case "br":
x = w;
y = h;
break;
case "tr":
x = w;
y = 0;
break;
}
if(local === true){
return [x, y];
}
if(vp){
var sc = this.getScroll();
return [x + sc.left, y + sc.top];
}
//Add the element's offset xy
var o = this.getXY();
return [x+o[0], y+o[1]];
},
/**
* 当window大小变化时,让当前的元素向送入的元素看齐(Anchors & realigns)。
* Anchors an element to another element and realigns it when the window is resized.
* @param {Mixed} element 对齐的元素对齐的元素。The element to align to.
* @param {String} position 对齐的位置。The position to align to.
* @param {Array} offsets (可选的) 偏移位置 [x, y]。(optional) Offset the positioning by [x, y]
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional)。True for the default animation or a standard Element animation config object
* @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).
* @param {Function} callback 动画执行完毕的函数。The function to call after the animation finishes
* @return {Ext.Element} this
*/
anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
var action = function(){
this.alignTo(el, alignment, offsets, animate);
Ext.callback(callback, this);
};
Ext.EventManager.onWindowResize(action, this);
var tm = typeof monitorScroll;
if(tm != 'undefined'){
Ext.EventManager.on(window, 'scroll', action, this,
{buffer: tm == 'number' ? monitorScroll : 50});
}
action.call(this); // align immediately
return this;
},
/**
* 获取当前元素相对于另一个元素时候的x,y坐标,这时当前元素的坐标是[0,0]。关于可支持的位置,可参阅{@link #alignTo}。
* Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
* supported position values.
* @param {Mixed} element 对齐的元素。The element to align to.
* @param {String} position 对齐的位置,如“tl-bl”。The position to align to.
* @param {Array} offsets (可选的) 偏移位置 [x, y]。(optional) Offset the positioning by [x, y]
* @return {Array} [x, y]
*/
getAlignToXY : function(el, p, o){
el = Ext.get(el);
if(!el || !el.dom){
throw "Element.alignToXY with an element that doesn't exist";
}
var d = this.dom;
var c = false; //constrain to viewport
var p1 = "", p2 = "";
o = o || [0,0];
if(!p){
p = "tl-bl";
}else if(p == "?"){
p = "tl-bl?";
}else if(p.indexOf("-") == -1){
p = "tl-" + p;
}
p = p.toLowerCase();
var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
if(!m){
throw "Element.alignTo with an invalid alignment " + p;
}
p1 = m[1]; p2 = m[2]; c = !!m[3];
//Subtract the aligned el's internal xy from the target's offset xy
//plus custom offset to get the aligned el's new offset xy
var a1 = this.getAnchorXY(p1, true);
var a2 = el.getAnchorXY(p2, false);
var x = a2[0] - a1[0] + o[0];
var y = a2[1] - a1[1] + o[1];
if(c){
//constrain the aligned el to viewport if necessary
var w = this.getWidth(), h = this.getHeight(), r = el.getRegion();
// 10px of margin for ie
var dw = Ext.lib.Dom.getViewWidth()-10, dh = Ext.lib.Dom.getViewHeight()-10;
//If we are at a viewport boundary and the aligned el is anchored on a target border that is
//perpendicular to the vp border, allow the aligned el to slide on that border,
//otherwise swap the aligned el to the opposite border of the target.
var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1);
var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1);
var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
var doc = document;
var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5;
var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5;
if((x+w) > dw + scrollX){
x = swapX ? r.left-w : dw+scrollX-w;
}
if(x < scrollX){
x = swapX ? r.right : scrollX;
}
if((y+h) > dh + scrollY){
y = swapY ? r.top-h : dh+scrollY-h;
}
if (y < scrollY){
y = swapY ? r.bottom : scrollY;
}
}
return [x,y];
},
/**
* 以另外一个元素为基准,根据任意的方位位置点对齐当前元素(送入的元素“不动”,当前元素“动”)。如果这个元素是document,则对齐到视图。
* Aligns this element with another element relative to the specified anchor points. If the other element is the
* document it aligns it to the viewport.
* 位置参数是可选的,可指定为下列任意的格式:The position parameter is optional, and can be specified in any one of the following formats:
* <ul>
* <li><b>空白Blank</b>: 默认对齐元素的左上角(即"tl-bl")。Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
* <li><b>有一个锚点(已弃置的,不翻译了)One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
* The element being aligned will position its top-left corner (tl) to that point. <i>This method has been
* deprecated in favor of the newer two anchor syntax below</i>.</li>
* <li><b>有两个锚点Two anchors</b>: 如果有如下表的两个值被传入,以“-”分隔开,那么第一个值是要往那个看齐元素的方位位置点,第二个值是当前目标元素的。If two values from the table below are passed separated by a dash, the first value is used as the
* element's anchor point, and the second value is used as the target's anchor point.</li>
* </ul>
* 除了罗列的方位位置点外,位置(position)参数还支持“?”字符。如果送入一“?”字符在方位位置点后面,那元素首先会正确地对齐然后看情况需要调整在视图的范围内显示。(are you sure?)
* In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of
* the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
* the viewport if necessary.
* 注意这一过程中,元素可能会被不断地以各种方向调整位置,以适合视图显示的要求。
* Note that the element being aligned might be swapped to align to a different position than
* that specified in order to enforce the viewport constraints.
* 支持的锚点位置如下列Following are all of the supported anchor positions:
<pre>
值Value 描述Description
----- -----------------------------
tl 左上角(缺省值)。The top left corner (default)
t 顶部中央。The center of the top edge
tr 右上角。The top right corner
l 左边中央。The center of the left edge
c 元素正中。In the center of the element
r 右边中央。The center of the right edge
bl 左下角。The bottom left corner
b 底部中央。The center of the bottom edge
br 右下角。The bottom right corner
</pre>
使用范例:Example Usage:
<pre><code>
// 这是默认值("tl-bl")对齐到other-e。align el to other-el using the default positioning ("tl-bl", non-constrained)
el.alignTo("other-el");
// align the top left corner of el with the top right corner of other-el (constrained to viewport)
el.alignTo("other-el", "tr?");
// align the bottom right corner of el with the center left edge of other-el
el.alignTo("other-el", "br-l?");
// align the center of el with the bottom left corner of other-el and
// adjust the x position by -6 pixels (and the y position by 0)
el.alignTo("other-el", "c-bl", [-6, 0]);
</code></pre>
* @param {Mixed} element 对齐的元素。The element to align to.
* @param {String} position 对齐的位置。The position to align to.
* @param {Array} offsets (可选的) 偏移位置 [x, y]。(optional) Offset the positioning by [x, y]
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
alignTo : function(element, position, offsets, animate){
var xy = this.getAlignToXY(element, position, offsets);
this.setXY(xy, this.preanim(arguments, 3));
return this;
},
// private
getConstrainToXY : function(){
var os = {top:0, left:0, bottom:0, right: 0};
return function(el, local, offsets, proposedXY){
el = Ext.get(el);
offsets = offsets ? Ext.applyIf(offsets, os) : os;
var vw, vh, vx = 0, vy = 0;
if(el.dom == document.body || el.dom == document){
vw =Ext.lib.Dom.getViewWidth();
vh = Ext.lib.Dom.getViewHeight();
}else{
vw = el.dom.clientWidth;
vh = el.dom.clientHeight;
if(!local){
var vxy = el.getXY();
vx = vxy[0];
vy = vxy[1];
}
}
var s = el.getScroll();
vx += offsets.left + s.left;
vy += offsets.top + s.top;
vw -= offsets.right;
vh -= offsets.bottom;
var vr = vx+vw;
var vb = vy+vh;
var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
var x = xy[0], y = xy[1];
var w = this.dom.offsetWidth, h = this.dom.offsetHeight;
// only move it if it needs it
var moved = false;
// first validate right/bottom
if((x + w) > vr){
x = vr - w;
moved = true;
}
if((y + h) > vb){
y = vb - h;
moved = true;
}
// then make sure top/left isn't negative
if(x < vx){
x = vx;
moved = true;
}
if(y < vy){
y = vy;
moved = true;
}
return moved ? [x, y] : false;
};
}()
});
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
Ext.Element.addMethods({
/**
* 为当前元素初始化{@link Ext.dd.DD}对象。
* Initializes a {@link Ext.dd.DD} drag drop object for this element.
* @param {String} group DD对象隶属于的那个组(Group)。The group the DD object is member of
* @param {Object} config DD之配置对象。The DD config object
* @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象。An object containing methods to override/implement on the DD object
* @return {Ext.dd.DD} DD对象。The DD object
*/
initDD : function(group, config, overrides){
var dd = new Ext.dd.DD(Ext.id(this.dom), group, config);
return Ext.apply(dd, overrides);
},
/**
* 为当前元素初始化{@link Ext.dd.DDProxy}对象。
* Initializes a {@link Ext.dd.DDProxy} drag drop object for this element.
* @param {String} group DD对象隶属于的那个组。(Group)The group the DD object is member of
* @param {Object} config DD之配置对象。The DD config object
* @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象。An object containing methods to override/implement on the DD object
* @return {Ext.dd.DD} DD对象。The DD object
*/
initDDProxy : function(group, config, overrides){
var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config);
return Ext.apply(dd, overrides);
},
/**
* 为当前元素初始化{@link Ext.dd.DDTarget}对象。
* Initializes a {@link Ext.dd.DDTarget} drag drop object for this element.
* @param {String} group DD对象隶属于的那个组(Group)。The group the DD object is member of
* @param {Object} config DD之配置对象。The DD config object
* @param {Object} overrides 包含一些方法的对象,用于重写或实现(override/implement)DDTarget对象。An object containing methods to override/implement on the DD object
* @return {Ext.dd.DD} DD对象。The DD object
*/
initDDTarget : function(group, config, overrides){
var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config);
return Ext.apply(dd, overrides);
}
});
Ext.Element.addMethods({
/**
* 把送入的元素归为这个元素的子元素。
* Appends the passed element(s) to this element
* @param {String/HTMLElement/Array/Element/CompositeElement} el
* @return {Ext.Element} this
*/
appendChild: function(el){
el = Ext.get(el);
el.appendTo(this);
return this;
},
/**
* 把这个元素添加到送入的元素里面。
* Appends this element to the passed element
* @param {Mixed} el 新父元素。The new parent element
* @return {Ext.Element} this
*/
appendTo: function(el){
el = Ext.getDom(el);
el.appendChild(this.dom);
return this;
},
/**
* 传入一个元素的参数,将其放置在当前元素之前的位置。
* Inserts this element before the passed element in the DOM
* @param {Mixed} el 要插入在当前元素之前的元素。The element before which this element will be inserted
* @return {Ext.Element} this
*/
insertBefore: function(el){
el = Ext.getDom(el);
el.parentNode.insertBefore(this.dom, el);
return this;
},
/**
* 传入一个元素的参数,将其放置在当前元素之后的位置。
* Inserts this element after the passed element in the DOM
* @param {Mixed} el 要插入在当前元素之后的元素。The element to insert after
* @return {Ext.Element} this
*/
insertAfter: function(el){
el = Ext.getDom(el);
el.parentNode.insertBefore(this.dom, el.nextSibling);
return this;
},
/**
* 可以是插入一个元素,也可以是创建一个元素(要创建的话请使用“DomHelper配置项对象”作为参数传入),
* 总之,这个元素作为当前元素的第一个子元素出现。
* Inserts (or creates) an element (or DomHelper config) as the first child of this element
* @param {Mixed/Object} el 可以是元素的id,或是插入的元素本身,或是要创建的“DomHelper配置项”对象。The id or element to insert or a DomHelper config to create and insert
* @return {Ext.Element} 新子元素。The new child
*/
insertFirst: function(el, returnDom){
el = el || {};
if(typeof el == 'object' && !el.nodeType && !el.dom){ // dh config
return this.createChild(el, this.dom.firstChild, returnDom);
}else{
el = Ext.getDom(el);
this.dom.insertBefore(el, this.dom.firstChild);
return !returnDom ? Ext.get(el) : el;
}
},
/**
* 可以是插入一个元素,也可以是创建一个元素(要创建的话请使用“DomHelper配置项对象”作为参数传入),总之,这个元素作为当前元素的相邻元素出现。
* Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element
* @param {Mixed/Object/Array} el 可以是元素的id,或是插入的元素本身,或是要创建的“DomHelper配置项”对象。The id, element to insert or a DomHelper config to create and insert *or* an array of any of those.
* @param {String} where (optional) 在当前元素之前还是之后默认为'before'。'before' or 'after' defaults to before
* @param {Boolean} returnDom (可选的)True表示为返回原始的DOM类型对象而非Ext标准对象。(optional) True to return the raw DOM element instead of Ext.Element
* @return {Ext.Element} 插入的元素。the inserted Element
*/
insertSibling: function(el, where, returnDom){
var rt;
if(Ext.isArray(el)){
for(var i = 0, len = el.length; i < len; i++){
rt = this.insertSibling(el[i], where, returnDom);
}
return rt;
}
where = where ? where.toLowerCase() : 'before';
el = el || {};
var refNode = where == 'before' ? this.dom : this.dom.nextSibling;
if(typeof el == 'object' && !el.nodeType && !el.dom){ // dh config
if(where == 'after' && !this.dom.nextSibling){
rt = Ext.DomHelper.append(this.dom.parentNode, el, !returnDom);
}else{
rt = Ext.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom);
}
}else{
rt = this.dom.parentNode.insertBefore(Ext.getDom(el), refNode);
if(!returnDom){
rt = Ext.get(rt);
}
}
return rt;
},
/**
* 用于当前这个元素替换传入的元素。
* Replaces the passed element with this element
* @param {Mixed} el 要替换的元素。The element to replace
* @return {Ext.Element} this
*/
replace: function(el){
el = Ext.get(el);
this.insertBefore(el);
el.remove();
return this;
},
/**
* 用传入的元素替换这个元素。
* Replaces this element with the passed element
* @param {Mixed/Object} el 新元素或是要创建的DomHelper配置项对象。The new element or a DomHelper config of an element to create
* @return {Ext.Element} this
*/
replaceWith: function(el){
if(typeof el == 'object' && !el.nodeType && !el.dom){ // dh config
el = this.insertSibling(el, 'before', true);
}else{
el = Ext.getDom(el);
this.dom.parentNode.insertBefore(el, this.dom);
}
Ext.Element.uncache(this.id);
Ext.removeNode(this.dom);
this.dom = el;
this.id = Ext.id(el);
Ext.Element.cache[this.id] = this;
return this;
}
});
Ext.Element.addMethods({
/**
* 构建KeyMap的快捷方式Convenience method for constructing a KeyMap
* @param {Number/Array/Object/String} key 可侦听key代码的数值、key代码的数组的字串符,或者是像这样的object:Either a string with the keys to listen for, the numeric key code, array of key codes or an object with the following options:
* {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
* @param {Function} fn 按下键后调用的函数。The function to call
* @param {Object} scope (可选的) 函数的作用域。(optional) The scope of the function
* @return {Ext.KeyMap} 创建好的KeyMap。The KeyMap created
*/
addKeyListener : function(key, fn, scope){
var config;
if(typeof key != "object" || Ext.isArray(key)){
config = {
key: key,
fn: fn,
scope: scope
};
}else{
config = {
key : key.key,
shift : key.shift,
ctrl : key.ctrl,
alt : key.alt,
fn: fn,
scope: scope
};
}
return new Ext.KeyMap(this, config);
},
/**
* 为该元素创建一个KeyMap。
* Creates a KeyMap for this element
* @param {Object} config KeyMap配置项。请参阅{@link Ext.KeyMap}。The KeyMap config. See {@link Ext.KeyMap} for more details
* @return {Ext.KeyMap} 创建好的KeyMap。The KeyMap created
*/
addKeyMap : function(config){
return new Ext.KeyMap(this, config);
}
});
Ext.Element.addMethods({
/**
* Measures the element's content height and updates height to match. Note: this function uses setTimeout so
* the new height may not be available immediately.
* @param {Boolean} animate (optional) Animate the transition (defaults to false)
* @param {Float} duration (optional) Length of the animation in seconds (defaults to .35)
* @param {Function} onComplete (optional) Function to call when animation completes
* @param {String} easing (optional) Easing method to use (defaults to easeOut)
* @return {Ext.Element} this
*/
autoHeight : function(animate, duration, onComplete, easing){
var oldHeight = this.getHeight();
this.clip();
this.setHeight(1); // force clipping
setTimeout(function(){
var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
if(!animate){
this.setHeight(height);
this.unclip();
if(typeof onComplete == "function"){
onComplete();
}
}else{
this.setHeight(oldHeight); // restore original height
this.setHeight(height, animate, duration, function(){
this.unclip();
if(typeof onComplete == "function") onComplete();
}.createDelegate(this), easing);
}
}.createDelegate(this), 0);
return this;
}
});
Ext.Element.addMethods({
/**
* 测量元素其内容的实际高度,使元素之高度适合。
* 注:改函数使用setTimeout所以新高度或者不会立即有效。
* Measures the element's content height and updates height to match. Note: this function uses setTimeout so
* the new height may not be available immediately.
* @param {Boolean} animate (可选的)是否要动画(默认 false)。(optional) Animate the transition (defaults to false)
* @param {Float} duration (可选的)动画持续时间(默认为0.35秒)。(optional) Length of the animation in seconds (defaults to .35)
* @param {Function} onComplete (可选的)动画完成后执行的函数。(optional) Function to call when animation completes
* @param {String} easing (可选的)采用清除的方法(默认为easeOut)。(optional) Easing method to use (defaults to easeOut)
* @return {Ext.Element} this
*/
autoHeight : function(animate, duration, onComplete, easing){
var oldHeight = this.getHeight();
this.clip();
this.setHeight(1); // force clipping
setTimeout(function(){
var height = parseInt(this.dom.scrollHeight, 10); // parseInt for Safari
if(!animate){
this.setHeight(height);
this.unclip();
if(typeof onComplete == "function"){
onComplete();
}
}else{
this.setHeight(oldHeight); // restore original height
this.setHeight(height, animate, duration, function(){
this.unclip();
if(typeof onComplete == "function") onComplete();
}.createDelegate(this), easing);
}
}.createDelegate(this), 0);
return this;
}
});
Ext.Element.addMethods({
/**
* 传入一个容器(container)参数,把元素滚动到容器视图的范围内(View)。
* Scrolls this element into view within the passed container.
* @param {Mixed} container (可选的)滚动容器的元素(默认为document.body)该值应该是字符串id,dom节点或Ext.Element。(optional) The container element to scroll (defaults to document.body). Should be a
* string (id), dom node, or Ext.Element.
* @param {Boolean} hscroll (可选的)false表示为禁止水平滚动(默认为true)。(optional) False to disable horizontal scroll (defaults to true)
* @return {Ext.Element} this
*/
scrollIntoView : function(container, hscroll){
var c = Ext.getDom(container) || Ext.getBody().dom;
var el = this.dom;
var o = this.getOffsetsTo(c),
l = o[0] + c.scrollLeft,
t = o[1] + c.scrollTop,
b = t+el.offsetHeight,
r = l+el.offsetWidth;
var ch = c.clientHeight;
var ct = parseInt(c.scrollTop, 10);
var cl = parseInt(c.scrollLeft, 10);
var cb = ct + ch;
var cr = cl + c.clientWidth;
if(el.offsetHeight > ch || t < ct){
c.scrollTop = t;
}else if(b > cb){
c.scrollTop = b-ch;
}
c.scrollTop = c.scrollTop; // corrects IE, other browsers will ignore
if(hscroll !== false){
if(el.offsetWidth > c.clientWidth || l < cl){
c.scrollLeft = l;
}else if(r > cr){
c.scrollLeft = r-c.clientWidth;
}
c.scrollLeft = c.scrollLeft;
}
return this;
},
// private
scrollChildIntoView : function(child, hscroll){
Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll);
},
/**
* 返回true表示为该元素是允许滚动的。
* Returns true if this element is scrollable.
* @return {Boolean}
*/
isScrollable : function(){
var dom = this.dom;
return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
},
/**
* 滚动该元素到指定的点(scroll point)。
* 它不会做边界检查所以若果你滚动到一个不合理的值时它也会试着去这么做。
* 要自动检查边界,请使用scroll()。
* Scrolls this element the specified scroll point.
* It does NOT do bounds checking so if you scroll to a weird value it will try to do it. For auto bounds checking, use scroll().
* @param {String} side 即可是对应于scrollLeft"left"值,也可以是scrollTop对应于的"top"值。Either "left" for scrollLeft values or "top" for scrollTop values.
* @param {Number} value 新滚动值。The new scroll value
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。(optional) true for the default animation or a standard Element animation config object
* @return {Element} this
*/
scrollTo : function(side, value, animate){
var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop";
if(!animate){
this.dom[prop] = value;
}else{
var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value];
this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll');
}
return this;
},
/**
* 按照指定的方向滚动该当前元素。须确认元素可滚动的范围,以免滚动超出元素可滚动的范围(溢出)。
* Scrolls this element the specified direction. Does bounds checking to make sure the scroll is
* within this element's scrollable range.
* @param {String} direction 允许值: "l","left" - "r","right" - "t","top","up" - "b","bottom","down"。Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
* @param {Number} distance 元素滚动有多远(像素)。How far to scroll the element in pixels
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。(optional) true for the default animation or a standard Element animation config object
* @return {Boolean} true表示为滚动是轮换的;false表示为元素能滚动其最远的。Returns true if a scroll was triggered or false if the element
* was scrolled as far as it could go.
*/
scroll : function(direction, distance, animate){
if(!this.isScrollable()){
return;
}
var el = this.dom;
var l = el.scrollLeft, t = el.scrollTop;
var w = el.scrollWidth, h = el.scrollHeight;
var cw = el.clientWidth, ch = el.clientHeight;
direction = direction.toLowerCase();
var scrolled = false;
var a = this.preanim(arguments, 2);
switch(direction){
case "l":
case "left":
if(w - l > cw){
var v = Math.min(l + distance, w-cw);
this.scrollTo("left", v, a);
scrolled = true;
}
break;
case "r":
case "right":
if(l > 0){
var v = Math.max(l - distance, 0);
this.scrollTo("left", v, a);
scrolled = true;
}
break;
case "t":
case "top":
case "up":
if(t > 0){
var v = Math.max(t - distance, 0);
this.scrollTo("top", v, a);
scrolled = true;
}
break;
case "b":
case "bottom":
case "down":
if(h - t > ch){
var v = Math.min(t + distance, h-ch);
this.scrollTo("top", v, a);
scrolled = true;
}
break;
}
return scrolled;
}
}); | 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.Element
* 表示着DOM里面的一个元素。Represents an Element in the DOM.<br><br>
* 用法:Usage:<br>
<pre><code>
// 通过id获取
var el = Ext.get("my-div");
// 通过DOM元素引用by DOM element reference
var el = Ext.get(myDivElement);
</code></pre>
* <b>动画Animations</b><br />
* 操作DOM元素,很多情况下会用一些到动画效果(可选的)。
* 动画选项应该是布尔值(true)或是动画的配置项对象(以Object Literal形式)。
* 注意要产生动画效果必须依赖{@link Ext.Fx}的包方可正确调用功能。动画的可选项有:
* Many of the functions for manipulating an element have an optional "animate" parameter. The animate parameter
* should either be a boolean (true) or an object literal with animation options. Note that the supported Element animation
* options are a subset of the {@link Ext.Fx} animation options specific to Fx effects. The Element animation options are:
<pre>
可选项Option默认值Default 描述Description
--------- -------- ---------------------------------------------
duration .35 动画持续的时间(单位:秒)。The duration of the animation in seconds
easing easeOut 退却(收尾)的方法。The easing method
callback none 动画完成之后执行的函数。A function to execute when the anim completes
scope this 回调函数的作用域。The scope (this) of the callback function
</pre>
* 另外,可通过配置项中的“anim”来获取动画对象,这样便可停止或操控这个动画效果。例子如下:
* Also, the Anim object being used for the animation will be set on your options object as "anim", which allows you to stop or
* manipulate the animation. Here's an example:
<pre><code>
var el = Ext.get("my-div");
// 没有动画no animation
el.setWidth(100);
// 默认动画default animation
el.setWidth(100, true);
// 对动画的一些设置animation with some options set
el.setWidth(100, {
duration: 1,
callback: this.foo,
scope: this
});
// 使用属性“anim”来获取动画对象using the "anim" property to get the Anim object
var opt = {
duration: 1,
callback: this.foo,
scope: this
};
el.setWidth(100, opt);
...
if(opt.anim.isAnimated()){
opt.anim.stop();
}
</code></pre>
* <b>组合(集合的)元素Composite (Collections of) Elements</b><br />
* 要处理一组的元素,请参阅{@link Ext.CompositeElement}。
* For working with collections of Elements, see {@link Ext.CompositeElement}
* @constructor 直接创建新元素对象。Create a new Element directly.
* @param {String/HTMLElement} element
* @param {Boolean} forceNew (可选的) 构建函数默认会检查在Cache中是否已经有这个element实例。如果有,则返回缓存中的对象。如果设置为否,则跳过缓存的验查。
* 设置这个布尔值会中止检查(扩展这个类时较有用)。
* (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class).
*/
(function(){
var D = Ext.lib.Dom;
var E = Ext.lib.Event;
var A = Ext.lib.Anim;
// local style camelizing for speed
var propCache = {};
var camelRe = /(-[a-z])/gi;
var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
var view = document.defaultView;
Ext.Element = function(element, forceNew){
var dom = typeof element == "string" ?
document.getElementById(element) : element;
if(!dom){ // invalid id/element
return null;
}
var id = dom.id;
if(forceNew !== true && id && Ext.Element.cache[id]){ // element object already exists
return Ext.Element.cache[id];
}
/**
* DOM元素。The DOM element
* @type HTMLElement
*/
this.dom = dom;
/**
* DOM元素之ID。The DOM element ID
* @type String
*/
this.id = id || Ext.id(dom);
};
var El = Ext.Element;
El.prototype = {
/**
* 元素默认的显示模式(默认为"")。
* The element's default display mode (defaults to "")
* @type String
*/
originalDisplay : "",
visibilityMode : 1,
/**
* CSS值的单位。如不指定则默认为px。
* The default unit to append to CSS values where a unit isn't provided (defaults to px).
* @type String
*/
defaultUnit : "px",
/**
* 设置元素的可见模式。
* 当通过调用setVisible()方法确定,可见模式(visibility mode)究竟是“可见性visibility”的还是“显示display”的。
* Sets the element's visibility mode. When setVisible() is called it
* will use this to determine whether to set the visibility or the display property.
* @param {String} visMode Element.VISIBILITY或Element.DISPLAY Element.VISIBILITY or Element.DISPLAY
* @return {Ext.Element} this
*/
setVisibilityMode : function(visMode){
this.visibilityMode = visMode;
return this;
},
/**
* 调用setVisibilityMode(Element.DISPLAY)的快捷方式。
* Convenience method for setVisibilityMode(Element.DISPLAY)
* @param {String} display (可选的) 当可见时显示的内容。(optional) What to set display to when visible
* @return {Ext.Element} this
*/
enableDisplayMode : function(display){
this.setVisibilityMode(El.DISPLAY);
if(typeof display != "undefined") this.originalDisplay = display;
return this;
},
/**
* 定位于此节点,以此节点为起点,向外围搜索外层的父节点,搜索条件必须符合并匹配传入的简易选择符(简易选择符形如div.some-class、span:first-child)。
* Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
* @param {String} selector 要进行测试的简易选择符。The simple selector to test
* @param {Number/Mixed} maxDepth (可选的) 搜索深度,可以为数字或元素(默认是10||document.body)。(optional) The max depth to
search as a number or element (defaults to 10 || document.body)
* @param {Boolean} returnEl (可选的) True表示为返回Ext.Element类型的对象,false的话返回标准DOM类型的节点(optional) True to return a Ext.Element object instead of DOM node
* @return {HTMLElement} 匹配的DOM节点(null的话表示没有找到匹配结果)。The matching DOM node (or null if no match was found)
*/
findParent : function(simpleSelector, maxDepth, returnEl){
var p = this.dom, b = document.body, depth = 0, dq = Ext.DomQuery, stopEl;
maxDepth = maxDepth || 50;
if(typeof maxDepth != "number"){
stopEl = Ext.getDom(maxDepth);
maxDepth = 10;
}
while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
if(dq.is(p, simpleSelector)){
return returnEl ? Ext.get(p) : p;
}
depth++;
p = p.parentNode;
}
return null;
},
/**
* 定位于此节点的“父节点”,以此节点的“父节点”为起点,向外围搜索外层的“父父”节点,搜索条件必须符合并匹配传入的简易选择符,简易选择符形如div.some-class、span:first-child)。
* Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
* @param {String} selector 要进行测试的简易选择符。The simple selector to test
* @param {Number/Mixed} maxDepth (可选的) 搜索深度,可以为数字或元素(默认是10||document.body)。(optional) The max depth to
search as a number or element (defaults to 10 || document.body)
* @param {Boolean} returnEl (可选的) True表示为返回Ext.Element类型的对象,false的话返回标准DOM类型的节点(optional) True to return a Ext.Element object instead of DOM node
* @return {HTMLElement} 匹配的DOM节点(null的话表示没有找到匹配结果)。The matching DOM node (or null if no match was found)
*/
findParentNode : function(simpleSelector, maxDepth, returnEl){
var p = Ext.fly(this.dom.parentNode, '_internal');
return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null;
},
/**
* 沿着DOM,向外围搜索外层的“父父”节点,搜索条件必须符合并匹配传入的简易选择符,简易选择符形如div.some-class、span:first-child)。
* Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child).
* 这是一个便捷方法因此总是返回Ext.Element类型的节点。
* This is a shortcut for findParentNode() that always returns an Ext.Element.
* @param {String} selector 要进行测试的简易选择符。The simple selector to test
* @param {Number/Mixed} maxDepth (可选的) 搜索深度,可以为数字或元素(默认是10||document.body)。(optional) The max depth to
search as a number or element (defaults to 10 || document.body)
* @return {Ext.Element} 匹配的DOM节点(null的话表示没有找到匹配结果)。The matching DOM node (or null if no match was found)
*/
up : function(simpleSelector, maxDepth){
return this.findParentNode(simpleSelector, maxDepth, true);
},
/**
* 如果这个元素符合传入的简易选择符的条件就返回true,简易选择符形如div.some-class或span:first-child。
* Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child)
* @param {String} selector 要进行测试的简易选择符。The simple selector to test
* @return {Boolean} true表示元素匹配选择符成功,否则返回false。True if this element matches the selector, else false
*/
is : function(simpleSelector){
return Ext.DomQuery.is(this.dom, simpleSelector);
},
/**
* 在元素上执行动画
* Perform animation on this element.
* @param {Object} args 动画配置项参数。The animation control args
* @param {Float} duration (可选的) 动画持续多久(默认为 .35 秒)。(optional) How long the animation lasts in seconds (defaults to .35)
* @param {Function} onComplete (可选的) 动画完成后调用的函数。(optional) Function to call when animation completes
* @param {String} easing (optional) (可选的) 指定“收尾”的方法(默认为 'easeOut')。Easing method to use (defaults to 'easeOut')
* @param {String} animType (可选的) 默认为'run',可以是'color','motion',或'scroll'。(optional) 'run' is the default. Can also be 'color', 'motion', or 'scroll'
* @return {Ext.Element} this
*/
animate : function(args, duration, onComplete, easing, animType){
this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType);
return this;
},
/*
* @private 内置动画调用Internal animation call
*/
anim : function(args, opt, animType, defaultDur, defaultEase, cb){
animType = animType || 'run';
opt = opt || {};
var anim = Ext.lib.Anim[animType](
this.dom, args,
(opt.duration || defaultDur) || .35,
(opt.easing || defaultEase) || 'easeOut',
function(){
Ext.callback(cb, this);
Ext.callback(opt.callback, opt.scope || this, [this, opt]);
},
this
);
opt.anim = anim;
return anim;
},
// private legacy anim prep 预设的动画配置参数
preanim : function(a, i){
return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]});
},
/**
* 移除无用的文本节点。
* Removes worthless text nodes
* @param {Boolean} forceReclean (可选的)缺省地,
* 元素会追踪自己是否已被清除了,所以你可以不断地调用这个方法。
* 然而,如果你需要更新元素而且需要强制清除,你可以传入true的参数。(optional) By default the element
* keeps track if it has been cleaned already so
* you can call this over and over. However, if you update the element and
* need to force a reclean, you can pass true.
*/
clean : function(forceReclean){
if(this.isCleaned && forceReclean !== true){
return this;
}
var ns = /\S/;
var d = this.dom, n = d.firstChild, ni = -1;
while(n){
var nx = n.nextSibling;
if(n.nodeType == 3 && !ns.test(n.nodeValue)){
d.removeChild(n);
}else{
n.nodeIndex = ++ni;
}
n = nx;
}
this.isCleaned = true;
return this;
},
/**
* 如果当前元素是传入元素的父辈级元素(ancestor)返回true。
* Returns true if this element is an ancestor of the passed element
* @param {HTMLElement/String} el 要检查的元素。The element to check
* @return {Boolean} true表示这个元素是传入元素的父级元素,否则返回false。True if this element is an ancestor of el, else false
*/
contains : function(el){
if(!el){return false;}
return D.isAncestor(this.dom, el.dom ? el.dom : el);
},
/**
* 检查当前该元素是否都使用属性visibility和属性display来显示。
* Checks whether the element is currently visible using both visibility and display properties.
* @param {Boolean} deep (可选的)True表示为沿着DOM一路看父元素是否隐藏的。(optional) True to walk the dom and see if parent elements are hidden (defaults to false)
* @return {Boolean} true表示该元素当前是可见的,否则返回false。True if the element is currently visible, else false
*/
isVisible : function(deep) {
var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none");
if(deep !== true || !vis){
return vis;
}
var p = this.dom.parentNode;
while(p && p.tagName.toLowerCase() != "body"){
if(!Ext.fly(p, '_isVisible').isVisible()){
return false;
}
p = p.parentNode;
}
return true;
},
/**
* 传入一个CSS选择符的参数,然后依据该CSS选择符从当前元素下面,形成期待匹配子节点的集合,也就是“选择”的操作,最后以一个{@link Ext.CompositeElement}类型的组合元素的形式返回(因为id的元素唯一的,所以选择符不应是id的选择符)。
* Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id).
* @param {String} selector CSS选择符。The CSS selector
* @param {Boolean} unique (可选的)true表示为为每个子元素创建唯一的Ext.Element(默认为false享元的普通对象flyweight object)。
* (optional) True to create a unique Ext.Element for each child (defaults to false, which creates a single shared flyweight object)
* @return {CompositeElement/CompositeElementLite} 组合元素。The composite element
*/
select : function(selector, unique){
return El.select(selector, unique, this.dom);
},
/**
* 传入一个CSS选择符的参数,然后基于该选择符选取其子节点(因为id的元素唯一的,所以选择符不应是id的选择符)。
* Selects child nodes based on the passed CSS selector (the selector should not contain an id).
* @param {String} selector CSS选择符。The CSS selector
* @return {Array} 匹配节点之数组。An array of the matched nodes
*/
query : function(selector, unique){
return Ext.DomQuery.select(selector, this.dom);
},
/**
* 传入一个CSS选择符的参数,然后基于该选择符,不限定深度进行搜索,符合的话选取单个子节点(选择符不应有id)。
* Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id).
* @param {String} selector CSS选择符。The CSS selector
* @param {Boolean} returnDom (可选的) True表示为返回Ext.Element类型的对象,false的话返回标准DOM类型的节点。
* (optional) True to return the DOM node instead of Ext.Element (defaults to false)
* @return {HTMLElement/Ext.Element} 子节点,Ext.Element类型(如returnDom = true则为DOM节点)。The child Ext.Element (or DOM node if returnDom = true)
*/
child : function(selector, returnDom){
var n = Ext.DomQuery.selectNode(selector, this.dom);
return returnDom ? n : Ext.get(n);
},
/**
* 传入一个CSS选择符的参数,然后基于该选择符,"直接"选取单个子节点(选择符不应有id)。
* Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id).
* @param {String} selector The CSS selector
* @param {Boolean} returnDom (可选的) True表示为返回Ext.Element类型的对象,false的话返回标准DOM类型的节点。
* (optional) True to return the DOM node instead of Ext.Element (defaults to false)
* @return {HTMLElement/Ext.Element} 子节点,Ext.Element类型。The child Ext.Element (or DOM node if returnDom = true)
*/
down : function(selector, returnDom){
var n = Ext.DomQuery.selectNode(" > " + selector, this.dom);
return returnDom ? n : Ext.get(n);
},
/**
* 设置元素可见性(请参阅细节)。
* 如果visibilityMode被设置成常量Element.DISPLAY,
* 那么它会使用display属性来隐藏元素,否则它会使用visibility。默认是使用visibility属性。
* Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
* the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
* @param {Boolean} visible 元素是否可见的。Whether the element is visible
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。
* (optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
setVisible : function(visible, animate){
if(!animate || !A){
if(this.visibilityMode == El.DISPLAY){
this.setDisplayed(visible);
}else{
this.fixDisplay();
this.dom.style.visibility = visible ? "visible" : "hidden";
}
}else{
// closure for composites
var dom = this.dom;
var visMode = this.visibilityMode;
if(visible){
this.setOpacity(.01);
this.setVisible(true);
}
this.anim({opacity: { to: (visible?1:0) }},
this.preanim(arguments, 1),
null, .35, 'easeIn', function(){
if(!visible){
if(visMode == El.DISPLAY){
dom.style.display = "none";
}else{
dom.style.visibility = "hidden";
}
Ext.get(dom).setOpacity(1);
}
});
}
return this;
},
/**
* 如果属性display不是"none"就返回true。
* Returns true if display is not "none"
* @return {Boolean}
*/
isDisplayed : function() {
return this.getStyle("display") != "none";
},
/**
* 轮换(两种状态中转换到一个状态)元素的visibility或display,取决于visibility mode。
* Toggles the element's visibility or display, depending on visibility mode.
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。
* (optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
toggle : function(animate){
this.setVisible(!this.isVisible(), this.preanim(arguments, 0));
return this;
},
/**
* 设置元素在样式中的display属性。如果value为true,则使用originalDisplay。
* Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
* @param {Mixed} value 如果value为true,则使用originalDisplay。否则直接设置显示的字符串。
* Boolean value to display the element using its default display, or a string to set the display directly.
* @return {Ext.Element} this
*/
setDisplayed : function(value) {
if(typeof value == "boolean"){
value = value ? this.originalDisplay : "none";
}
this.setStyle("display", value);
return this;
},
/**
* 使这个元素得到焦点。忽略任何已捕获的异常。
* Tries to focus the element. Any exceptions are caught and ignored.
* @param {Number} defer (可选的) 延时执行focus的毫秒数。(optional) Milliseconds to defer the focus
* @return {Ext.Element} this
*/
focus : function(defer) {
try{
if(typeof defer == 'number'){
this.focus.defer(defer, this);
}else{
this.dom.focus();
}
}catch(e){}
return this;
},
/**
* 使这个元素失去焦点。忽略任何已捕获的异常。
* Tries to blur the element. Any exceptions are caught and ignored.
* @return {Ext.Element} this
*/
blur : function() {
try{
this.dom.blur();
}catch(e){}
return this;
},
/**
* 为元素添加设置CSS类(CSS Class)。重复出来的类会被忽略。
* Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out.
* @param {String/Array} className 要加入的CSS类或者由各类组成的数组。The CSS class to add, or an array of classes
* @return {Ext.Element} this
*/
addClass : function(className){
if(Ext.isArray(className)){
for(var i = 0, len = className.length; i < len; i++) {
this.addClass(className[i]);
}
}else{
if(className && !this.hasClass(className)){
this.dom.className = this.dom.className + " " + className;
}
}
return this;
},
/**
* 添加一个或多个className到这个元素,并移除其所有侧边(siblings)节点上的同名样式。
* Adds one or more CSS classes to this element and removes the same class(es) from all siblings.
* @param {String/Array} className 要加入的className,或者是由类组成的数组。The CSS class to add, or an array of classes
* @return {Ext.Element} this
*/
radioClass : function(className){
var siblings = this.dom.parentNode.childNodes;
for(var i = 0; i < siblings.length; i++) {
var s = siblings[i];
if(s.nodeType == 1){
Ext.get(s).removeClass(className);
}
}
this.addClass(className);
return this;
},
/**
* 移除元素身上一个或多个的CSS类。
* Removes one or more CSS classes from the element.
* @param {String/Array} className 要加入的className,或者是由类组成的数组。The CSS class to remove, or an array of classes
* @return {Ext.Element} this
*/
removeClass : function(className){
if(!className || !this.dom.className){
return this;
}
if(Ext.isArray(className)){
for(var i = 0, len = className.length; i < len; i++) {
this.removeClass(className[i]);
}
}else{
if(this.hasClass(className)){
var re = this.classReCache[className];
if (!re) {
re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
this.classReCache[className] = re;
}
this.dom.className =
this.dom.className.replace(re, " ");
}
}
return this;
},
// private
classReCache: {},
/**
* 轮换(Toggles,两种状态中转换到一个状态)--添加或移除指定的CSS类(如果已经存在的话便删除,否则就是新增加)。
* Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it).
* @param {String} className 轮换的CSS类The CSS class to toggle
* @return {Ext.Element} this
*/
toggleClass : function(className){
if(this.hasClass(className)){
this.removeClass(className);
}else{
this.addClass(className);
}
return this;
},
/**
* 检查某个CSS类是否作用于这个元素身上。
* Checks if the specified CSS class exists on this element's DOM node.
* @param {String} className 要检查CSS类The CSS class to check for
* @return {Boolean} true表示为类是有的,否则为falseTrue if the class exists, else false
*/
hasClass : function(className){
return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1;
},
/**
* 在这个元素身上替换CSS类。如果旧的CSS名称不存在,新的就会加入。
* Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added.
* @param {String} oldClassName 要被替换之CSS类,旧的CSS类The CSS class to replace
* @param {String} newClassName 新CSS类The replacement CSS class
* @return {Ext.Element} this
*/
replaceClass : function(oldClassName, newClassName){
this.removeClass(oldClassName);
this.addClass(newClassName);
return this;
},
/**
* 给出一些CSS属性名,得到其值。
* 如el.getStyles('color', 'font-size', 'width')会返回
* {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}。
* Returns an object with properties matching the styles requested.
* For example, el.getStyles('color', 'font-size', 'width') might return
* {'color': '#FFFFFF', 'font-size': '13px', 'width': '100px'}.
* @param {String} style1 样式一A style name
* @param {String} style2 样式二A style name
* @param {String} etc.
* @return {Object} 样式对象The style object
*/
getStyles : function(){
var a = arguments, len = a.length, r = {};
for(var i = 0; i < len; i++){
r[a[i]] = this.getStyle(a[i]);
}
return r;
},
/**
* 统一化当前样式和计算样式。
* Normalizes currentStyle and computedStyle.
* @param {String} property 返回值的那个样式属性The style property whose value is returned.
* @return {String} 该元素样式属性的当前值The current value of the style property for this element.
*/
getStyle : function(){
return view && view.getComputedStyle ?
function(prop){
var el = this.dom, v, cs, camel;
if(prop == 'float'){
prop = "cssFloat";
}
if(v = el.style[prop]){
return v;
}
if(cs = view.getComputedStyle(el, "")){
if(!(camel = propCache[prop])){
camel = propCache[prop] = prop.replace(camelRe, camelFn);
}
return cs[camel];
}
return null;
} :
function(prop){
var el = this.dom, v, cs, camel;
if(prop == 'opacity'){
if(typeof el.style.filter == 'string'){
var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
if(m){
var fv = parseFloat(m[1]);
if(!isNaN(fv)){
return fv ? fv / 100 : 0;
}
}
}
return 1;
}else if(prop == 'float'){
prop = "styleFloat";
}
if(!(camel = propCache[prop])){
camel = propCache[prop] = prop.replace(camelRe, camelFn);
}
if(v = el.style[camel]){
return v;
}
if(cs = el.currentStyle){
return cs[camel];
}
return null;
};
}(),
/**
* 设置元素的样式,也可以用一个对象参数包含多个样式。
* Wrapper for setting style properties, also takes single object parameter of multiple styles.
* @param {String/Object} property 要设置的样式属性,或是包含多个样式的对象The style property to be set, or an object of multiple styles.
* @param {String} value (可选的)样式属性的值,如果第一个参数是对象,则这个参数为null(不需要了)(optional) The value to apply to the given property, or null if an object was passed.
* @return {Ext.Element} this
*/
setStyle : function(prop, value){
if(typeof prop == "string"){
var camel;
if(!(camel = propCache[prop])){
camel = propCache[prop] = prop.replace(camelRe, camelFn);
}
if(camel == 'opacity') {
this.setOpacity(value);
}else{
this.dom.style[camel] = value;
}
}else{
for(var style in prop){
if(typeof prop[style] != "function"){
this.setStyle(style, prop[style]);
}
}
}
return this;
},
/**
* {@link #setStyle}的另一个版本,更能灵活地设置样式属性。
* More flexible version of {@link #setStyle} for setting style properties.
* @param {String/Object/Function} styles 表示样式的特定格式字符串,如“width:100px”,或是对象的形式如{width:"100px"},或是能返回这些格式的函数。
* A style specification string, e.g. "width:100px", or object in the form {width:"100px"}, or
* a function which returns such a specification.
* @return {Ext.Element} this
*/
applyStyles : function(style){
Ext.DomHelper.applyStyles(this.dom, style);
return this;
},
/**
* 返回元素相对于页面坐标的X位置。
* 元素必须是属于DOM树中的一部分才拥有正确的页面坐标(display:none或未加入的elements返回false)。
* Gets the current X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @return {Number} 元素的X位置。The X position of the element
*/
getX : function(){
return D.getX(this.dom);
},
/**
* 返回元素相对于页面坐标的Y位置。
* 元素必须是属于DOM树中的一部分才拥有正确的页面坐标(display:none或未加入的elements返回false)。
* Gets the current Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @return {Number} 元素的Y位置。The Y position of the element
*/
getY : function(){
return D.getY(this.dom);
},
/**
* 返回元素当前页面坐标的位置。
* 元素必须是属于DOM树中的一部分才拥有正确的页面坐标(display:none或未加入的elements返回false)。
* Gets the current position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @return {Array} 元素的XY位置。The XY position of the element
*/
getXY : function(){
return D.getXY(this.dom);
},
/**
* 返回当前元素与送入元素的距离。
* 这两个元素都必须是属于DOM树中的一部分才拥有正确的页面坐标(display:none或未加入的elements返回false)。
* Returns the offsets of this element from the passed element. Both element must be part of the DOM tree and not have display:none to have page coordinates.
* @param {Mixed} element 测距离的那个元素。The element to get the offsets from.
* @return {Array} 页面会上两点的距离。The XY page offsets (e.g. [100, -200])
*/
getOffsetsTo : function(el){
var o = this.getXY();
var e = Ext.fly(el, '_internal').getXY();
return [o[0]-e[0],o[1]-e[1]];
},
/**
* 设置元素相对于页面坐标的X位置。
* 元素必须是属于DOM树中的一部分才拥有正确的页面坐标(display:none或未加入的elements返回false)。
* Sets the X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @param {Number} x 元素的Y位置The X position of the element
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
setX : function(x, animate){
if(!animate || !A){
D.setX(this.dom, x);
}else{
this.setXY([x, this.getY()], this.preanim(arguments, 1));
}
return this;
},
/**
* 设置元素基于页面坐标的Y位置。
* 元素必须是DOM树中的一部分才拥有页面坐标(display:none或未加入的elements会当作无效而返回false)。
* Sets the Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @param {Number} The Y position of the element
* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
setY : function(y, animate){
if(!animate || !A){
D.setY(this.dom, y);
}else{
this.setXY([this.getX(), y], this.preanim(arguments, 1));
}
return this;
},
/**
* 直接使用CSS样式(代替{@link #setX}),设定元素的left位置。
* Sets the element's left position directly using CSS style (instead of {@link #setX}).
* @param {String} left CSS left属性值。The left CSS property value
* @return {Ext.Element} this
*/
setLeft : function(left){
this.setStyle("left", this.addUnits(left));
return this;
},
/**
* 直接使用CSS样式(代替{@link #setY}),设定元素的top位置。
* Sets the element's top position directly using CSS style (instead of {@link #setY}).
* @param {String} top CSS属性top的值。The top CSS property value
* @return {Ext.Element} this
*/
setTop : function(top){
this.setStyle("top", this.addUnits(top));
return this;
},
/**
* 设置元素CSS Right的样式。
* Sets the element's CSS right style.
* @param {String} right Bottom CSS属性值。The right CSS property value
* @return {Ext.Element} this
*/
setRight : function(right){
this.setStyle("right", this.addUnits(right));
return this;
},
/**
* 设置元素CSS Bottom的样式。
* Sets the element's CSS bottom style.
* @param {String} bottom Bottom CSS属性值。The bottom CSS property value
* @return {Ext.Element} this
*/
setBottom : function(bottom){
this.setStyle("bottom", this.addUnits(bottom));
return this;
},
/**
* 无论这个元素如何定位,设置其在页面的坐标位置,。
* 元素必须是DOM树中的一部分才拥有页面坐标(display:none或未加入的elements会当作无效而返回false)。
* Sets the position of the element in page coordinates, regardless of how the element is positioned.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @param {Array} pos 对于新位置(基于页面坐标)包含X & Y [x, y]的值Contains X & Y [x, y] values for new position (coordinates are page-based)
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
setXY : function(pos, animate){
if(!animate || !A){
D.setXY(this.dom, pos);
}else{
this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion');
}
return this;
},
/**
* 无论这个元素如何定位,设置其在页面的坐标位置。
* 元素必须是DOM树中的一部分才拥有页面坐标(display:none或未加入的elements会当作无效而返回false)。
* Sets the position of the element in page coordinates, regardless of how the element is positioned.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @param {Number} x 新定位的X值(基于页面坐标)。X value for new position (coordinates are page-based)
* @param {Number} y 新定位的Y值(基于页面坐标)。Y value for new position (coordinates are page-based)
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。
* (optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
setLocation : function(x, y, animate){
this.setXY([x, y], this.preanim(arguments, 2));
return this;
},
/**
* 无论这个元素如何定位,设置其在页面的坐标位置,。
* 元素必须是DOM树中的一部分才拥有页面坐标(display:none或未加入的elements会当作无效而返回false)。
* Sets the position of the element in page coordinates, regardless of how the element is positioned.
* The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
* @param {Number} x 新定位的X值(基于页面坐标)。X value for new position (coordinates are page-based)
* @param {Number} y 新定位的Y值(基于页面坐标)。Y value for new position (coordinates are page-based)
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。
* (optional) True for the default animation, or a standard Element animation config object
* @return {Ext.Element} this
*/
moveTo : function(x, y, animate){
this.setXY([x, y], this.preanim(arguments, 2));
return this;
},
/**
* 返回当前元素的区域。元素必须是DOM树中的一部分才拥有页面坐标(display:none或未加入的elements会当作无效而返回false)。
* Returns the region of the given element.
* The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
* @return {Region} Ext.lib.Region包含"top, left, bottom, right"成员数据A Ext.lib.Region containing "top, left, bottom, right" member data.
*/
getRegion : function(){
return D.getRegion(this.dom);
},
/**
* 返回元素的偏移(offset)高度。
* Returns the offset height of the element
* @param {Boolean} contentHeight (可选的) true表示为返回的是减去边框和内补丁(borders & padding)的宽度。
* (optional) true to get the height minus borders and padding
* @return {Number} The element's height
*/
getHeight : function(contentHeight){
var h = this.dom.offsetHeight || 0;
h = contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb");
return h < 0 ? 0 : h;
},
/**
* 返回元素的偏移(offset)宽度。
* @param {Boolean} contentWidth (可选的) true表示为返回的是减去边框和内补丁(borders & padding)的宽度。
* (optional) true to get the width minus borders and padding
* @return {Number} 元素宽度The element's width
*/
getWidth : function(contentWidth){
var w = this.dom.offsetWidth || 0;
w = contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr");
return w < 0 ? 0 : w;
},
/**
* 当偏移值不可用时就模拟一个出来。该方法返回由padding或borders调整过的元素CSS高度,也可能是偏移的高度。
* 如果不用CSS设置高度而且是display:none的元素,可能会没有。
* @return {Number}
*/
getComputedHeight : function(){
var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight);
if(!h){
h = parseInt(this.getStyle('height'), 10) || 0;
if(!this.isBorderBox()){
h += this.getFrameWidth('tb');
}
}
return h;
},
/**
* 当偏移值不可用时就模拟一个出来。该方法返回由padding或borders调整过的元素CSS宽度,也可能是偏移的宽度。
* 如果不用CSS设置宽度而且是display:none的元素,可能会没有。
* Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
* when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
* if a width has not been set using CSS.
* @return {Number}
*/
getComputedWidth : function(){
var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth);
if(!w){
w = parseInt(this.getStyle('width'), 10) || 0;
if(!this.isBorderBox()){
w += this.getFrameWidth('lr');
}
}
return w;
},
/**
* 返回元素大小。
* Returns the size of the element.
* @param {Boolean} contentSize (可选的) true表示为获取的是减去border和padding的宽度大小(optional) true to get the width/size minus borders and padding
* @return {Object} 包含元素大小尺寸的对象An object containing the element's size {width: (element width), height: (element height)}
*/
getSize : function(contentSize){
return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)};
},
getStyleSize : function(){
var w, h, d = this.dom, s = d.style;
if(s.width && s.width != 'auto'){
w = parseInt(s.width, 10);
if(this.isBorderBox()){
w -= this.getFrameWidth('lr');
}
}
if(s.height && s.height != 'auto'){
h = parseInt(s.height, 10);
if(this.isBorderBox()){
h -= this.getFrameWidth('tb');
}
}
return {width: w || this.getWidth(true), height: h || this.getHeight(true)};
},
/**
* 返回视图的高度和宽度。
* Returns the width and height of the viewport.
* @return {Object} 包含视图大小尺寸的对象,如{width: (viewport width), height: (viewport height)}An object containing the viewport's size {width: (viewport width), height: (viewport height)}
*/
getViewSize : function(){
var d = this.dom, doc = document, aw = 0, ah = 0;
if(d == doc || d == doc.body){
return {width : D.getViewWidth(), height: D.getViewHeight()};
}else{
return {
width : d.clientWidth,
height: d.clientHeight
};
}
},
/**
* 返回“值的”属性值。
* Returns the value of the "value" attribute
* @param {Boolean} asNumber 表示为将值解析为数字。true to parse the value as a number
* @return {String/Number}
*/
getValue : function(asNumber){
return asNumber ? parseInt(this.dom.value, 10) : this.dom.value;
},
// private
adjustWidth : function(width){
if(typeof width == "number"){
if(this.autoBoxAdjust && !this.isBorderBox()){
width -= (this.getBorderWidth("lr") + this.getPadding("lr"));
}
if(width < 0){
width = 0;
}
}
return width;
},
// private
adjustHeight : function(height){
if(typeof height == "number"){
if(this.autoBoxAdjust && !this.isBorderBox()){
height -= (this.getBorderWidth("tb") + this.getPadding("tb"));
}
if(height < 0){
height = 0;
}
}
return height;
},
/**
* 设置元素的宽度。
* Set the width of the element
* @param {Number} width 新宽度。The new width
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。
* (optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setWidth : function(width, animate){
width = this.adjustWidth(width);
if(!animate || !A){
this.dom.style.width = this.addUnits(width);
}else{
this.anim({width: {to: width}}, this.preanim(arguments, 1));
}
return this;
},
/**
* 设置元素的高度。
* Set the height of the element
* @param {Number} height 新高度。The new height
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象。
* (optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setHeight : function(height, animate){
height = this.adjustHeight(height);
if(!animate || !A){
this.dom.style.height = this.addUnits(height);
}else{
this.anim({height: {to: height}}, this.preanim(arguments, 1));
}
return this;
},
/**
* 设置元素的大小尺寸。如果动画选项被打开,高度和宽度都会顺带产生变化的动画效果。
* Set the size of the element. If animation is true, both width an height will be animated concurrently.
* @param {Number} width 新宽度The new width
* @param {Number} height 新高度The new height
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setSize : function(width, height, animate){
if(typeof width == "object"){ // in case of object from getSize()
height = width.height; width = width.width;
}
width = this.adjustWidth(width); height = this.adjustHeight(height);
if(!animate || !A){
this.dom.style.width = this.addUnits(width);
this.dom.style.height = this.addUnits(height);
}else{
this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2));
}
return this;
},
/**
* 同时设置元素的位置和大小。如果动画选项被打开,高度和宽度都会顺带产生变化的动画效果。
* Sets the element's position and size in one shot. If animation is true then width, height, x and y will be animated concurrently.
* @param {Number} x 新位置上的x值(基于页面的坐标)X value for new position (coordinates are page-based)
* @param {Number} y 新位置上的y值(基于页面的坐标)Y value for new position (coordinates are page-based)
* @param {Number} width 新宽度The new width
* @param {Number} height 新高度The new height
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setBounds : function(x, y, width, height, animate){
if(!animate || !A){
this.setSize(width, height);
this.setLocation(x, y);
}else{
width = this.adjustWidth(width); height = this.adjustHeight(height);
this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}},
this.preanim(arguments, 4), 'motion');
}
return this;
},
/**
* 设置元素的位置并调整大小到指定的位置。如果动画选项被打开,高度和宽度都会顺带产生变化的动画效果。
* Sets the element's position and size the specified region. If animation is true then width, height, x and y will be animated concurrently.
* @param {Ext.lib.Region} region 要填充的区域The region to fill
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setRegion : function(region, animate){
this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1));
return this;
},
/**
* 加入一个事件处理函数。{@link #on}是其简写方式。
* Appends an event handler to this element. The shorthand version {@link #on} is equivalent.
* @param {String} eventName 事件处理函数的名称The type of event to handle
* @param {Function} fn 事件处理函数。该函数会送入以下的参数:The handler function the event invokes. This function is passed
* the following parameters:<ul>
* <li>evt : EventObject<div class="sub-desc">用于描述这次事件{@link Ext.EventObject EventObject}的事件对象The {@link Ext.EventObject EventObject} describing the event.</div></li>
* <li>t : Element<div class="sub-desc">事件源对象,类型是{@link Ext.Element Element} The {@link Ext.Element Element} which was the target of the event.
* 注意该项可能会选项<tt>delegate</tt>筛选而发生变化Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
* <li>o : Object<div class="sub-desc">调用addListener时送入的选项对象The options object from the addListener call.</div></li>
* </ul>
* @param {Object} scope (可选的) 事件处理函数执行时所在的作用域。处理函数“this”的上下文。(optional) The scope (The <tt>this</tt> reference) of the handler function. Defaults
* to this Element.
* @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会下来的属性:(optional) An object containing handler configuration properties.
* This may contain any of the following properties:<ul>
* <li>scope {Object} : 事件处理函数执行时所在的作用域。处理函数“this”的上下文环境。The scope in which to execute the handler function. The handler function's "this" context.</li>
* <li>delegate {String} : 一个简易选择符,用于过滤目标,或是查找目标的子孙。A simple selector to filter the target or look for a descendant of the target</li>
* <li>stopEvent {Boolean} : true表示为阻止事件。即停止传播、阻止默认动作。True to stop the event. That is stop propagation, and prevent the default action.</li>
* <li>preventDefault {Boolean} : true表示为阻止默认动作True to prevent the default action</li>
* <li>stopPropagation {Boolean} : true表示为阻止事件传播True to prevent event propagation</li>
* <li>normalized {Boolean} : false表示对处理函数送入一个原始、未封装过的浏览器对象而非标准的Ext.EventObjectFalse to pass a browser event to the handler function instead of an Ext.EventObject</li>
* <li>delay {Number} : 触发事件后处理函数延时执行的时间The number of milliseconds to delay the invocation of the handler after te event fires.</li>
* <li>single {Boolean} : true代表为下次事件触发加入一个要处理的函数,然后再移除本身。True to add a handler to handle just the next firing of the event, and then remove itself.</li>
* <li>buffer {Number} : 若指定一个毫秒数会把该处理函数安排到{@link Ext.util.DelayedTask}延时之后才执行。
* 如果事件在那个事件再次触发,则原句柄将<em>不会</em> 被启用,但是新句柄会安排在其位置。Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
* by the specified number of milliseconds. If the event fires again within that time, the original
* handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
* </ul><br>
* <p>
* <b>不同配搭方式的选项Combining Options</b><br>
* In the following examples, the shorthand form {@link #on} is used rather than the more verbose
* addListener. The two are equivalent.
* 下面的例子,使用的是{@link #on}的简写方式。和addListener是等价的。
* 利用参数选项,可以组合成不同类型的侦听器:
* Using the options argument, it is possible to combine different
* types of listeners:<br>
* <br>
* 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId)的一次性侦听器。这些事件设置在处理函数(也就是第三个的参数)中也可以找到的。
* A normalized, delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the
* options object. The options object is available as the third parameter in the handler function.<div style="margin: 5px 20px 20px;">
* 代码:Code:<pre><code>
el.on('click', this.onClick, this, {
single: true,
delay: 100,
stopEvent : true,
forumId: 4
});</code></pre></p>
* <p>
* <b>多个处理函数一次性登记Attaching multiple handlers in 1 call</b><br>
* 这样的话,可允许多个事件处理函数都共享一个配置事件的配置项对象。The method also allows for a single argument to be passed which is a config object containing properties
* which specify multiple handlers.</p>
* <p>
* 代码:Code:<pre><code>
el.on({
'click' : {
fn: this.onClick,
scope: this,
delay: 100
},
'mouseover' : {
fn: this.onMouseOver,
scope: this
},
'mouseout' : {
fn: this.onMouseOut,
scope: this
}
});</code></pre></p>
* <p>
* 或者是简写的语法:Or a shorthand syntax:<br>
* Code:<pre><code>
el.on({
'click' : this.onClick,
'mouseover' : this.onMouseOver,
'mouseout' : this.onMouseOut,
scope: this
});</code></pre></p>
*/
addListener : function(eventName, fn, scope, options){
Ext.EventManager.on(this.dom, eventName, fn, scope || this, options);
},
/**
* 从这个元素上移除一个事件处理函数。{@link #un}是它的简写方式。
* Removes an event handler from this element. The shorthand version {@link #un} is equivalent. Example:
* <pre><code>
el.removeListener('click', this.handlerFn);
// 或者
el.un('click', this.handlerFn);
</code></pre>
* @param {String} eventName 要移除的事件处理函数的名称the type of event to remove
* @param {Function} fn 事件处理器the method the event invokes
* @param {Object} scope (可选的)函数的作用域(默认这个元素)(optional) The scope (The <tt>this</tt> reference) of the handler function. Defaults
* to this Element.
* @return {Ext.Element} this
*/
removeListener : function(eventName, fn, scope){
Ext.EventManager.removeListener(this.dom, eventName, fn, scope || this);
return this;
},
/**
* 在该元素身上移除所有已加入的侦听器。
* Removes all previous added listeners from this element
* @return {Ext.Element} this
*/
removeAllListeners : function(){
Ext.EventManager.removeAll(this.dom);
return this;
},
/**
* 创建此元素的事件句柄,由此元素接替另外的对象触发和处理事件。
* Create an event handler on this element such that when the event fires and is handled by this element,
* it will be relayed to another object (i.e., fired again as if it originated from that object instead).
* @param {String} eventName 要接替的事件名称The type of event to relay
* @param {Object} object 任何继承自{@link Ext.util.Observable}的对象用于在上下文里触发接替的事件Any object that extends {@link Ext.util.Observable} that will provide the context
* for firing the relayed event
*/
relayEvent : function(eventName, observable){
this.on(eventName, function(e){
observable.fireEvent(eventName, e);
});
},
/**
* 设置元素的透明度。
* Set the opacity of the element
* @param {Float} opacity 新的透明度。0 = 透明,.5 = 50% 可见,1 = 完全可见……The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setOpacity : function(opacity, animate){
if(!animate || !A){
var s = this.dom.style;
if(Ext.isIE){
s.zoom = 1;
s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") +
(opacity == 1 ? "" : " alpha(opacity=" + opacity * 100 + ")");
}else{
s.opacity = opacity;
}
}else{
this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn');
}
return this;
},
/**
* 获取左边的X坐标。
* Gets the left X coordinate
* @param {Boolean} local True表示为获取局部CSS位置而非页面坐标。
* True to get the local css position instead of page coordinate
* @return {Number}
*/
getLeft : function(local){
if(!local){
return this.getX();
}else{
return parseInt(this.getStyle("left"), 10) || 0;
}
},
/**
* 获取元素右边的X坐标(元素X位置 + 元素宽度)。
* Gets the right X coordinate of the element (element X position + element width)
* @param {Boolean} local True表示为获取局部CSS位置而非页面坐标。
* True to get the local css position instead of page coordinate
* @return {Number}
*/
getRight : function(local){
if(!local){
return this.getX() + this.getWidth();
}else{
return (this.getLeft(true) + this.getWidth()) || 0;
}
},
/**
* 获取顶部Y坐标。
* Gets the top Y coordinate
* @param {Boolean} local True表示为获取局部CSS位置而非页面坐标。
* True to get the local css position instead of page coordinate
* @return {Number}
*/
getTop : function(local) {
if(!local){
return this.getY();
}else{
return parseInt(this.getStyle("top"), 10) || 0;
}
},
/**
* 获取元素的底部Y坐标(元素Y位置 + 元素宽度)。
* Gets the bottom Y coordinate of the element (element Y position + element height)
* @param {Boolean} local True表示为获取局部CSS位置而非页面坐标。
* True to get the local css position instead of page coordinate
* @return {Number}
*/
getBottom : function(local){
if(!local){
return this.getY() + this.getHeight();
}else{
return (this.getTop(true) + this.getHeight()) || 0;
}
},
/**
* 初始化元素的位置。如果未传入期待的位置,而又还没定位的话,将会设置当前元素为相对(relative)定位。
* Initializes positioning on this element. If a desired position is not passed, it will make the
* the element positioned relative IF it is not already positioned.
* @param {String} pos (可选的) 使用"relative","absolute"或"fixed"的定位。(optional) Positioning to use "relative", "absolute" or "fixed"
* @param {Number} zIndex (可选的) z-Index值。(optional) The zIndex to apply
* @param {Number} x (可选的)设置页面X方向位置。(optional) Set the page X position
* @param {Number} y (可选的)设置页面Y方向位置。(optional) Set the page Y position
*/
position : function(pos, zIndex, x, y){
if(!pos){
if(this.getStyle('position') == 'static'){
this.setStyle('position', 'relative');
}
}else{
this.setStyle("position", pos);
}
if(zIndex){
this.setStyle("z-index", zIndex);
}
if(x !== undefined && y !== undefined){
this.setXY([x, y]);
}else if(x !== undefined){
this.setX(x);
}else if(y !== undefined){
this.setY(y);
}
},
/**
* 当文档加载后清除位置并复位到默认。
* Clear positioning back to the default when the document was loaded
* @param {String} value (可选的) 用于left,right,top,bottom的值,默认为''(空白字符串)。你可使用'auto'。
* (optional) The value to use for the left,right,top,bottom, defaults to '' (empty string). You could use 'auto'.
* @return {Ext.Element} this
*/
clearPositioning : function(value){
value = value ||'';
this.setStyle({
"left": value,
"right": value,
"top": value,
"bottom": value,
"z-index": "",
"position" : "static"
});
return this;
},
/**
* 返回一个包含CSS定位信息的对象。
* 有用的技巧:连同setPostioning一起,可在更新执行之前,先做一个快照(snapshot),之后便可恢复该元素。
* Gets an object with all CSS positioning properties. Useful along with setPostioning to get
* snapshot before performing an update and then restoring the element.
* @return {Object}
*/
getPositioning : function(){
var l = this.getStyle("left");
var t = this.getStyle("top");
return {
"position" : this.getStyle("position"),
"left" : l,
"right" : l ? "" : this.getStyle("right"),
"top" : t,
"bottom" : t ? "" : this.getStyle("bottom"),
"z-index" : this.getStyle("z-index")
};
},
/**
* 返回指定边(side(s))的padding宽度。
* Gets the width of the border(s) for the specified side(s)
* @param {String} side 可以是t, l, r, b或是任何组合。例如,传入lr的参数会得到(l)eft padding +(r)ight padding。
* Can be t, l, r, b or any combination of those to add multiple values. For example,
* passing lr would get the border (l)eft width + the border (r)ight width.
* @return {Number} 四边的padding之和。The width of the sides passed added together
*/
getBorderWidth : function(side){
return this.addStyles(side, El.borders);
},
/**
* 获取指定方位(side(s))的padding宽度。
* Gets the width of the padding(s) for the specified side(s)
* @param {String} side 可以是t, l, r, b或是任何组合,例如,传入lr的参数会得到(l)eft padding +(r)ight padding。Can be t, l, r, b or any combination of those to add multiple values. For example,
* passing lr would get the padding (l)eft + the padding (r)ight.
* @return {Number} 四边的padding之和The padding of the sides passed added together
*/
getPadding : function(side){
return this.addStyles(side, El.paddings);
},
/**
* 由getPositioning()返回的对象去进行定位。
* Set positioning with an object returned by getPositioning().
* @param {Object} posCfg
* @return {Ext.Element} this
*/
setPositioning : function(pc){
this.applyStyles(pc);
if(pc.right == "auto"){
this.dom.style.right = "";
}
if(pc.bottom == "auto"){
this.dom.style.bottom = "";
}
return this;
},
// private
fixDisplay : function(){
if(this.getStyle("display") == "none"){
this.setStyle("visibility", "hidden");
this.setStyle("display", this.originalDisplay); // first try reverting to default
if(this.getStyle("display") == "none"){ // if that fails, default to block
this.setStyle("display", "block");
}
}
},
// private
setOverflow : function(v){
if(v=='auto' && Ext.isMac && Ext.isGecko2){ // work around stupid FF 2.0/Mac scroll bar bug
this.dom.style.overflow = 'hidden';
(function(){this.dom.style.overflow = 'auto';}).defer(1, this);
}else{
this.dom.style.overflow = v;
}
},
/**
* 快速设置left和top(采用默认单位)。
* Quick set left and top adding default units
* @param {String} left CSS的left属性值The left CSS property value
* @param {String} top CSS的top属性值The top CSS property value
* @return {Ext.Element} this
*/
setLeftTop : function(left, top){
this.dom.style.left = this.addUnits(left);
this.dom.style.top = this.addUnits(top);
return this;
},
/**
* 移动这个元素到相对于当前的位置。
* Move this element relative to its current position.
* @param {String} direction 允许的值:Possible values are: "l" (or "left"), "r" (or "right"), "t" (or "top", or "up"), "b" (or "bottom", or "down").
* @param {Number} distance 元素移动有多远(像素)How far to move the element in pixels
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
move : function(direction, distance, animate){
var xy = this.getXY();
direction = direction.toLowerCase();
switch(direction){
case "l":
case "left":
this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2));
break;
case "r":
case "right":
this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2));
break;
case "t":
case "top":
case "up":
this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2));
break;
case "b":
case "bottom":
case "down":
this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2));
break;
}
return this;
},
/**
* 保存当前的溢出(overflow),然后进行裁剪元素的溢出部分 - 使用{@link #unclip}来移除。
* Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
* @return {Ext.Element} this
*/
clip : function(){
if(!this.isClipped){
this.isClipped = true;
this.originalClip = {
"o": this.getStyle("overflow"),
"x": this.getStyle("overflow-x"),
"y": this.getStyle("overflow-y")
};
this.setStyle("overflow", "hidden");
this.setStyle("overflow-x", "hidden");
this.setStyle("overflow-y", "hidden");
}
return this;
},
/**
* 在调用clip()之前,返回原始的裁剪部分(溢出的)。
* Return clipping (overflow) to original clipping before clip() was called
* @return {Ext.Element} this
*/
unclip : function(){
if(this.isClipped){
this.isClipped = false;
var o = this.originalClip;
if(o.o){this.setStyle("overflow", o.o);}
if(o.x){this.setStyle("overflow-x", o.x);}
if(o.y){this.setStyle("overflow-y", o.y);}
}
return this;
},
// private
adjustForConstraints : function(xy, parent, offsets){
return this.getConstrainToXY(parent || document, false, offsets, xy) || xy;
},
/**
* 清除这个元素的透明度设置。IE有时候会用到。
* Clears any opacity settings from this element. Required in some cases for IE.
* @return {Ext.Element} this
*/
clearOpacity : function(){
if (window.ActiveXObject) {
if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){
this.dom.style.filter = "";
}
} else {
this.dom.style.opacity = "";
this.dom.style["-moz-opacity"] = "";
this.dom.style["-khtml-opacity"] = "";
}
return this;
},
/**
* 隐藏此元素-使用display mode来决定用"display"抑或"visibility"。请参阅{@link #setVisible}。
* Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
hide : function(animate){
this.setVisible(false, this.preanim(arguments, 0));
return this;
},
/**
* 显示此元素-使用display mode来决定用"display"抑或"visibility"。请参阅{@link #setVisible}。
* Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}.
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
show : function(animate){
this.setVisible(true, this.preanim(arguments, 0));
return this;
},
/**
* @private Test if size has a unit, otherwise appends the default
*/
addUnits : function(size){
return Ext.Element.addUnits(size, this.defaultUnit);
},
/**
* 更新该元素的innerHTML属性,有时遇到脚本便可以执行。
* Update the innerHTML of this element, optionally searching for and processing scripts
* @param {String} html 新的HTMLThe new HTML
* @param {Boolean} loadScripts (可选的) true表示为遇到脚本要执行(optional) True to look for and process scripts (defaults to false)
* @param {Function} callback 当更新完成后,你加载一个异步函数执行它,以得知更新完成。(optional) For async script loading you can be notified when the update completes
* @return {Ext.Element} this
*/
update : function(html, loadScripts, callback){
if(typeof html == "undefined"){
html = "";
}
if(loadScripts !== true){
this.dom.innerHTML = html;
if(typeof callback == "function"){
callback();
}
return this;
}
var id = Ext.id();
var dom = this.dom;
html += '<span id="' + id + '"></span>';
E.onAvailable(id, function(){
var hd = document.getElementsByTagName("head")[0];
var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig;
var srcRe = /\ssrc=([\'\"])(.*?)\1/i;
var typeRe = /\stype=([\'\"])(.*?)\1/i;
var match;
while(match = re.exec(html)){
var attrs = match[1];
var srcMatch = attrs ? attrs.match(srcRe) : false;
if(srcMatch && srcMatch[2]){
var s = document.createElement("script");
s.src = srcMatch[2];
var typeMatch = attrs.match(typeRe);
if(typeMatch && typeMatch[2]){
s.type = typeMatch[2];
}
hd.appendChild(s);
}else if(match[2] && match[2].length > 0){
if(window.execScript) {
window.execScript(match[2]);
} else {
window.eval(match[2]);
}
}
}
var el = document.getElementById(id);
if(el){Ext.removeNode(el);}
if(typeof callback == "function"){
callback();
}
});
dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, "");
return this;
},
/**
* 直接访问Updater的{@link Ext.Updater#update}方法(相同的参数)。
* 参数与{@link Ext.Updater#update}方法的一致。
* Direct access to the Updater {@link Ext.Updater#update} method. The method takes the same object
* parameter as {@link Ext.Updater#update}
* @return {Ext.Element} this
*/
load : function(){
var um = this.getUpdater();
um.update.apply(um, arguments);
return this;
},
/**
* 获取这个元素的UpdateManager。
* Gets this element's Updater
* @return {Ext.Updater} The Updater
*/
getUpdater : function(){
if(!this.updateManager){
this.updateManager = new Ext.Updater(this);
}
return this.updateManager;
},
/**
* 禁止该元素的文本可被选择(可跨浏览器)。
* Disables text selection for this element (normalized across browsers)
* @return {Ext.Element} this
*/
unselectable : function(){
this.dom.unselectable = "on";
this.swallowEvent("selectstart", true);
this.applyStyles("-moz-user-select:none;-khtml-user-select:none;");
this.addClass("x-unselectable");
return this;
},
/**
* 返回该元素的x,y到屏幕中心的值
* Calculates the x, y to center this element on the screen
* @return {Array} The x, y values [x, y]
*/
getCenterXY : function(){
return this.getAlignToXY(document, 'c-c');
},
/**
* 在视图或其他元素中,居中元素。
* Centers the Element in either the viewport, or another Element.
* @param {Mixed} centerIn (可选的)视图或其他元素(optional) The element in which to center the element.
*/
center : function(centerIn){
this.alignTo(centerIn || document, 'c-c');
return this;
},
/**
* 测试不同的CSS规则/浏览器以确定该元素是否使用Border Box。
* Tests various css rules/browsers to determine if this element uses a border box
* @return {Boolean}
*/
isBorderBox : function(){
return noBoxAdjust[this.dom.tagName.toLowerCase()] || Ext.isBorderBox;
},
/**
* 返回一个BOX对象,形如{x, y, width, height},可用于设置其他与之匹配的元素的大小/位置。
* Return a box {x, y, width, height} that can be used to set another elements
* size/location to match this element.
* @param {Boolean} contentBox (可选的)true表示为返回元素内容的BOX(optional)。If true a box for the content of the element is returned.
* @param {Boolean} local (可选的) true表示为返回元素的left和top代替页面的x/y。(optional) If true the element's left and top are returned instead of page x/y.
* @return {Object} box BOX对象,形如{x, y, width, height}
*/
getBox : function(contentBox, local){
var xy;
if(!local){
xy = this.getXY();
}else{
var left = parseInt(this.getStyle("left"), 10) || 0;
var top = parseInt(this.getStyle("top"), 10) || 0;
xy = [left, top];
}
var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx;
if(!contentBox){
bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h};
}else{
var l = this.getBorderWidth("l")+this.getPadding("l");
var r = this.getBorderWidth("r")+this.getPadding("r");
var t = this.getBorderWidth("t")+this.getPadding("t");
var b = this.getBorderWidth("b")+this.getPadding("b");
bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)};
}
bx.right = bx.x + bx.width;
bx.bottom = bx.y + bx.height;
return bx;
},
/**
* 传入的“side”的参数,统计边框和内补丁(padding & borders)的宽度并返回该值。
* 参阅getBorderWidth()以得到更多sides的资料。
* Returns the sum width of the padding and borders for the passed "sides". See getBorderWidth()
for more information about the sides.
* @param {String} sides
* @return {Number}
*/
getFrameWidth : function(sides, onlyContentBox){
return onlyContentBox && this.isBorderBox() ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides));
},
/**
* 设置元素之Box。使用getBox() 在其他对象身上获取box对象。
* 如果动画为true,那么高度和宽度都会同时出现动画效果。
* Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently.
* @param {Object} box 填充的Box {x, y, width, height}The box to fill {x, y, width, height}
* @param {Boolean} adjust (可选的) 是否自动调整由“箱子”问题引起的高度和宽度设置(optional) Whether to adjust for box-model issues automatically
* @param {Boolean/Object} animate (可选的)true表示为默认的动画,或是一个配置项对象,这个配置项是标准的“元素动画”对象(optional) true for the default animation or a standard Element animation config object
* @return {Ext.Element} this
*/
setBox : function(box, adjust, animate){
var w = box.width, h = box.height;
if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){
w -= (this.getBorderWidth("lr") + this.getPadding("lr"));
h -= (this.getBorderWidth("tb") + this.getPadding("tb"));
}
this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2));
return this;
},
/**
* 强制浏览器重新渲染该元素。
* Forces the browser to repaint this element
* @return {Ext.Element} this
*/
repaint : function(){
var dom = this.dom;
this.addClass("x-repaint");
setTimeout(function(){
Ext.get(dom).removeClass("x-repaint");
}, 1);
return this;
},
/**
* 返回该元素的top、left、right和bottom属性,以表示margin(外补丁)除非有side参数。
* 若有sides参数传入,即返回已计算好的sides宽度(参见getPading)。
* Returns an object with properties top, left, right and bottom representing the margins of this element unless sides is passed,
* then it returns the calculated width of the sides (see getPadding)
* @param {String} sides (可选的) 任何 l, r, t, b的组合,以获取该sides的统计。(optional) Any combination of l, r, t, b to get the sum of those sides
* @return {Object/Number}
*/
getMargins : function(side){
if(!side){
return {
top: parseInt(this.getStyle("margin-top"), 10) || 0,
left: parseInt(this.getStyle("margin-left"), 10) || 0,
bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0,
right: parseInt(this.getStyle("margin-right"), 10) || 0
};
}else{
return this.addStyles(side, El.margins);
}
},
// private
addStyles : function(sides, styles){
var val = 0, v, w;
for(var i = 0, len = sides.length; i < len; i++){
v = this.getStyle(styles[sides.charAt(i)]);
if(v){
w = parseInt(v, 10);
if(w){ val += (w >= 0 ? w : -1 * w); }
}
}
return val;
},
/**
* 创建当前元素的代理(Proxy)元素。
* Creates a proxy element of this element
* @param {String/Object} config 代理元素的class名称或是DomHelper配置项对象The class name of the proxy element or a DomHelper config object
* @param {String/HTMLElement} renderTo (可选的) 成为代理的元素或是元素ID(默认为 document.body)(optional) The element or element id to render the proxy to (defaults to document.body)
* @param {Boolean} matchBox (optional) (可选的) true表示为立即与代理对齐和设置大小(默认为false)True to align and size the proxy to this element now (defaults to false)
* @return {Ext.Element} 新代理元素The new proxy element
*/
createProxy : function(config, renderTo, matchBox){
config = typeof config == "object" ?
config : {tag : "div", cls: config};
var proxy;
if(renderTo){
proxy = Ext.DomHelper.append(renderTo, config, true);
}else {
proxy = Ext.DomHelper.insertBefore(this.dom, config, true);
}
if(matchBox){
proxy.setBox(this.getBox());
}
return proxy;
},
/**
* 在元素身上遮上一个蒙板(mask),以禁止用户操作。须依赖core.css文件。
* 这个方法只能作用于接受子节点(child nodes)的元素。
* Puts a mask over this element to disable user interaction. Requires core.css.
* This method can only be applied to elements which accept child nodes.
* @param {String} msg (可选的) 蒙板作用时显示的信息(optional) A message to display in the mask
* @param {String} msgCls (可选的) 蒙板元素的CSS类(optional) A css class to apply to the msg element
* @return {Element} 蒙板元素The mask element
*/
mask : function(msg, msgCls){
if(this.getStyle("position") == "static"){
this.addClass("x-masked-relative");
}
if(this._maskMsg){
this._maskMsg.remove();
}
if(this._mask){
this._mask.remove();
}
this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true);
this.addClass("x-masked");
this._mask.setDisplayed(true);
if(typeof msg == 'string'){
this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true);
var mm = this._maskMsg;
mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg";
mm.dom.firstChild.innerHTML = msg;
mm.setDisplayed(true);
mm.center(this);
}
if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
this._mask.setSize(this.dom.clientWidth, this.getHeight());
}
return this._mask;
},
/**
* 移除之前用过的蒙板。
* Removes a previously applied mask.
*/
unmask : function(){
if(this._mask){
if(this._maskMsg){
this._maskMsg.remove();
delete this._maskMsg;
}
this._mask.remove();
delete this._mask;
}
this.removeClass(["x-masked", "x-masked-relative"]);
},
/**
* 返回true表示为这个元素应用了蒙板。
* Returns true if this element is masked
* @return {Boolean}
*/
isMasked : function(){
return this._mask && this._mask.isVisible();
},
/**
* 创建一个“iframe垫片”来使得select和其他windowed对象在该元素显示之下。
* Creates an iframe shim for this element to keep selects and other windowed objects from
* showing through.
* @return {Ext.Element} 新垫片元素The new shim element
*/
createShim : function(){
var el = document.createElement('iframe');
el.frameBorder = '0';
el.className = 'ext-shim';
if(Ext.isIE && Ext.isSecure){
el.src = Ext.SSL_SECURE_URL;
}
var shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom));
shim.autoBoxAdjust = false;
return shim;
},
/**
* 从DOM里面移除当前元素,并从缓存中删除。
* Removes this element from the DOM and deletes it from the cache
*/
remove : function(){
Ext.removeNode(this.dom);
delete El.cache[this.dom.id];
},
/**
* 设置事件句柄,当鼠标在此元素之上作用的Css样式类。自动过滤因mouseout事件引起在子元素上的轻移(Flicker)
* Sets up event handlers to call the passed functions when the mouse is over this element. Automatically
* filters child element mouse events.
* @param {Function} overFn
* @param {Function} outFn
* @param {Object} scope (optional)
* @return {Ext.Element} this
*/
hover : function(overFn, outFn, scope){
var preOverFn = function(e){
if(!e.within(this, true)){
overFn.apply(scope || this, arguments);
}
};
var preOutFn = function(e){
if(!e.within(this, true)){
outFn.apply(scope || this, arguments);
}
};
this.on("mouseover", preOverFn, this.dom);
this.on("mouseout", preOutFn, this.dom);
return this;
},
/**
* 数组当鼠标位于元素上方时作用的CSS样式类。
* Sets up event handlers to add and remove a css class when the mouse is over this element
* @param {String} className
* @return {Ext.Element} this
*/
addClassOnOver : function(className){
this.hover(
function(){
Ext.fly(this, '_internal').addClass(className);
},
function(){
Ext.fly(this, '_internal').removeClass(className);
}
);
return this;
},
/**
* 设置当元素得到焦点(focus)时作用的CSS样式类。
* Sets up event handlers to add and remove a css class when this element has the focus
* @param {String} className
* @return {Ext.Element} this
*/
addClassOnFocus : function(className){
this.on("focus", function(){
Ext.fly(this, '_internal').addClass(className);
}, this.dom);
this.on("blur", function(){
Ext.fly(this, '_internal').removeClass(className);
}, this.dom);
return this;
},
/**
* 当鼠标在该元素上面按下接着松开(即单击效果),设置事件处理器来添加和移除css类。
* Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
* @param {String} className
* @return {Ext.Element} this
*/
addClassOnClick : function(className){
var dom = this.dom;
this.on("mousedown", function(){
Ext.fly(dom, '_internal').addClass(className);
var d = Ext.getDoc();
var fn = function(){
Ext.fly(dom, '_internal').removeClass(className);
d.removeListener("mouseup", fn);
};
d.on("mouseup", fn);
});
return this;
},
/**
* 事件上报(bubbling)的过程中停止特定的事件,阻止默认动作(可选的)。
* Stops the specified event(s) from bubbling and optionally prevents the default action
* @param {String/Array} eventName 要在上报过程中停止的事件或事件构成的数组an event / array of events to stop from bubbling
* @param {Boolean} preventDefault (可选的)true表示阻止默认动作(optional) true to prevent the default action too
* @return {Ext.Element} this
*/
swallowEvent : function(eventName, preventDefault){
var fn = function(e){
e.stopPropagation();
if(preventDefault){
e.preventDefault();
}
};
if(Ext.isArray(eventName)){
for(var i = 0, len = eventName.length; i < len; i++){
this.on(eventName[i], fn);
}
return this;
}
this.on(eventName, fn);
return this;
},
/**
* 返回当前节点的那个父节点,可选地可送入一个期待的选择符。
* Gets the parent node for this element, optionally chaining up trying to match a selector
* @param {String} selector (optional) 通过简易选择符来查找父节点Find a parent node that matches the passed simple selector
* @param {Boolean} returnDom (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素(optional) True to return a raw dom node instead of an Ext.Element
* @return {Ext.Element/HTMLElement} 父节点或是null
*/
parent : function(selector, returnDom){
return this.matchNode('parentNode', 'parentNode', selector, returnDom);
},
/**
* 获取下一个侧边节点,跳过文本节点。
* Gets the next sibling, skipping text nodes
* @param {String} selector (可选的) 通过简易选择符来查找下一个侧边节点(optional) Find the next sibling that matches the passed simple selector
* @param {Boolean} returnDom (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素(optional) True to return a raw dom node instead of an Ext.Element
* @return {Ext.Element/HTMLElement} 下一个侧边节点或nullThe next sibling or null
*/
next : function(selector, returnDom){
return this.matchNode('nextSibling', 'nextSibling', selector, returnDom);
},
/**
* 获取上一个侧边节点,跳过文本节点。
* Gets the previous sibling, skipping text nodes
* @param {String} selector (可选的) 通过简易选择符来查找上一个侧边节点(optional) Find the previous sibling that matches the passed simple selector
* @param {Boolean} returnDom (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素(optional) True to return a raw dom node instead of an Ext.Element
* @return {Ext.Element/HTMLElement} 上一个侧边节点或nullThe previous sibling or null
*/
prev : function(selector, returnDom){
return this.matchNode('previousSibling', 'previousSibling', selector, returnDom);
},
/**
* 获取第一个子元素,跳过文本节点。
* Gets the first child, skipping text nodes
* @param {String} selector (可选的) 通过简易选择符来查找第一个子元素(optional) Find the next sibling that matches the passed simple selector
* @param {Boolean} returnDom (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素(optional) True to return a raw dom node instead of an Ext.Element
* @return {Ext.Element/HTMLElement} 第一个子元素或nullThe first child or null
*/
first : function(selector, returnDom){
return this.matchNode('nextSibling', 'firstChild', selector, returnDom);
},
/**
* 获取最后一个子元素,跳过文本节点。
* Gets the last child, skipping text nodes
* @param {String} selector (可选的) 通过简易选择符来查找最后一个元素(optional) Find the previous sibling that matches the passed simple selector
* @param {Boolean} returnDom (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素(optional) True to return a raw dom node instead of an Ext.Element
* @return {Ext.Element/HTMLElement} 最后一个元素或nullThe last child or null
*/
last : function(selector, returnDom){
return this.matchNode('previousSibling', 'lastChild', selector, returnDom);
},
matchNode : function(dir, start, selector, returnDom){
var n = this.dom[start];
while(n){
if(n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))){
return !returnDom ? Ext.get(n) : n;
}
n = n[dir];
}
return null;
},
/**
* 传入一个DomHelper配置项对象的参数,将其创建并加入到该元素。
* Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element.
* @param {Object} config DomHelper元素配置项对象。如果没有传入特定的要求,如{tag:'input'},那么将自动用DIV去创建,并附有一些属性。DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be
* automatically generated with the specified attributes.
* @param {HTMLElement} insertBefore (可选的) 该元素的子元素(optional) a child element of this element
* @param {Boolean} returnDom (optional) (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素true to return the dom node instead of creating an Element
* @return {Ext.Element} 新的子元素The new child element
*/
createChild: function(config, insertBefore, returnDom){
config = config || {tag:'div'};
if(insertBefore){
return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true);
}
return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true);
},
/**
* 创建一个新的元素,包裹在当前元素外面。
* Creates and wraps this element with another element
* @param {Object} config (可选的) 包裹元素(null的话则是一个空白的div)的DomHelper配置项对象(optional) DomHelper element config object for the wrapper element or null for an empty div
* @param {Boolean} returnDom (optional) (可选的) true表示为返回原始过的DOM元素,而非Ext.Element类型的元素True to return the raw DOM element instead of Ext.Element
* @return {HTMLElement/Element} 刚创建好的包裹元素The newly created wrapper element
*/
wrap: function(config, returnDom){
if(!config){
config = {tag: "div"};
}
var newEl = Ext.DomHelper.insertBefore(this.dom, config, !returnDom);
newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom);
return newEl;
},
/**
* 插入HTML片断到这个元素。
* Inserts an html fragment into this element
* @param {String} where 要插入的html放在元素的哪里。-Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
* @param {String} html HTML片断。The HTML fragment
* @param {Boolean} returnEl true表示为返回一个Ext.Element类型的DOM对象。(optional) True to return an Ext.Element (defaults to false)
* @return {HTMLElement/Ext.Element} 被插入之节点(或最近的,如果超过一处插入的话)。The inserted node (or nearest related if more than 1 inserted)
*/
insertHtml : function(where, html, returnEl){
var el = Ext.DomHelper.insertHtml(where, this.dom, html);
return returnEl ? Ext.get(el) : el;
},
/**
* 传入属性(attributes)的参数,使之成为该元素的属性(一个样式的属性可以是字符串,对象或函数function)。
* Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function)
* @param {Object} o 属性对象。The object with the attributes
* @param {Boolean} useSet (可选的) false表示为用expandos来重写默认的setAttribute。(optional) false to override the default setAttribute to use expandos.
* @return {Ext.Element} this
*/
set : function(o, useSet){
var el = this.dom;
useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet;
for(var attr in o){
if(attr == "style" || typeof o[attr] == "function") continue;
if(attr=="cls"){
el.className = o["cls"];
}else if(o.hasOwnProperty(attr)){
if(useSet) el.setAttribute(attr, o[attr]);
else el[attr] = o[attr];
}
}
if(o.style){
Ext.DomHelper.applyStyles(el, o.style);
}
return this;
},
/**
* 送入一个页面坐标的参数,将其翻译到元素的CSS left/top值。
* Translates the passed page coordinates into left/top css values for this element
* @param {Number/Array} x 页面x or 数组 [x, y]The page x or an array containing [x, y]
* @param {Number} y (可选的)如x不是数组那必须指定y(optional) The page y, required if x is not an array
* @return {Object} 包含left、top属性的对象,如 {left: (值), top: (值)}An object with left and top properties. e.g. {left: (value), top: (value)}
*/
translatePoints : function(x, y){
if(typeof x == 'object' || Ext.isArray(x)){
y = x[1]; x = x[0];
}
var p = this.getStyle('position');
var o = this.getXY();
var l = parseInt(this.getStyle('left'), 10);
var t = parseInt(this.getStyle('top'), 10);
if(isNaN(l)){
l = (p == "relative") ? 0 : this.dom.offsetLeft;
}
if(isNaN(t)){
t = (p == "relative") ? 0 : this.dom.offsetTop;
}
return {left: (x - o[0] + l), top: (y - o[1] + t)};
},
/**
* 返回元素当前滚动的位置。
* Returns the current scroll position of the element.
* @return {Object} 包含滚动位置的对象,格式如 {left: (scrollLeft), top: (scrollTop)}An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
*/
getScroll : function(){
var d = this.dom, doc = document;
if(d == doc || d == doc.body){
var l, t;
if(Ext.isIE && Ext.isStrict){
l = doc.documentElement.scrollLeft || (doc.body.scrollLeft || 0);
t = doc.documentElement.scrollTop || (doc.body.scrollTop || 0);
}else{
l = window.pageXOffset || (doc.body.scrollLeft || 0);
t = window.pageYOffset || (doc.body.scrollTop || 0);
}
return {left: l, top: t};
}else{
return {left: d.scrollLeft, top: d.scrollTop};
}
},
/**
* 为指定的CSS属性返回CSS颜色。RGB、三位数(像#fff)和有效值都被转换到标准六位十六进制的颜色。Return the CSS color for the specified CSS attribute. rgb, 3 digit (like #fff) and valid values。
* @param {String} attr CSS属性The css attribute
* @param {String} defaultValue 当找不到有效的颜色时所用的默认值。The default value to use when a valid color isn't found
* @param {String} prefix (可选的) 默认为#。当应用到颜色动画时须为空白字串符。Use an empty string when working with
* color anims.
*/
getColor : function(attr, defaultValue, prefix){
var v = this.getStyle(attr);
if(!v || v == "transparent" || v == "inherit") {
return defaultValue;
}
var color = typeof prefix == "undefined" ? "#" : prefix;
if(v.substr(0, 4) == "rgb("){
var rvs = v.slice(4, v.length -1).split(",");
for(var i = 0; i < 3; i++){
var h = parseInt(rvs[i]);
var s = h.toString(16);
if(h < 16){
s = "0" + s;
}
color += s;
}
} else {
if(v.substr(0, 1) == "#"){
if(v.length == 4) {
for(var i = 1; i < 4; i++){
var c = v.charAt(i);
color += c + c;
}
}else if(v.length == 7){
color += v.substr(1);
}
}
}
return(color.length > 5 ? color.toLowerCase() : defaultValue);
},
/**
* 将指定的元素打包到一个特定的样式/markup块,渲染成为斜纹背景、圆角和四边投影的灰色容器。
* 用法举例:<pre><code>
//
Ext.get("foo").boxWrap();
Ext.get("foo").boxWrap().addClass("x-box-blue");
</pre></code>
* @param {String} class (可选的)一个CSS基类,应用到包裹元素(默认为'x-box')。
* 注意有许多依赖该CSS规则来产生整体的效果。
* 所以你提供一个交替的基样式,必须保证你所提供的都是所需的规则。
* @return {Ext.Element} this
*/
/**
* Wrap()的高级版本。Wrap将指定的元素打包到一个特定的样式/markup块,产生斜纹背景、圆角和四边投影的灰色容器。用法举例:
* Wraps the specified element with a special markup/CSS block that renders by default as a gray container with a
* gradient background, rounded corners and a 4-way shadow. Example usage:
* <pre><code>
// 基本box打包Basic box wrap
Ext.get("foo").boxWrap();
// 你也可以加入新的CSS样式类来定义box的外观。You can also add a custom class and use CSS inheritance rules to customize the box look.
// 'x-box-blue'是内建的参考项。看看例子中是怎么创建一个自定义的样式。'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example
// for how to create a custom box wrap style.
Ext.get("foo").boxWrap().addClass("x-box-blue");
</pre></code>
* @param {String} class (可选的)一个CSS基类,应用到包裹元素(默认为'x-box')(optional) A base CSS class to apply to the containing wrapper element (defaults to 'x-box').
* 注意这里须要依赖一些CSS样式规则来产生整体的效果。所以你提供一个交替的基样式,必须保证你所提供的都是所需的规则。
* Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
* so if you supply an alternate base class, make sure you also supply all of the necessary rules.
* @return {Ext.Element} this
*/
boxWrap : function(cls){
cls = cls || 'x-box';
var el = Ext.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls)));
el.child('.'+cls+'-mc').dom.appendChild(this.dom);
return el;
},
/**
* 在DOM节点中的某个元素,返回其一个命名空间属性的值。
* Returns the value of a namespaced attribute from the element's underlying DOM node.
* @param {String} namespace 要查找属性所在的命名空间The namespace in which to look for the attribute
* @param {String} name 属性名称The attribute name
* @return {String} 属性值The attribute value
*/
getAttributeNS : Ext.isIE ? function(ns, name){
var d = this.dom;
var type = typeof d[ns+":"+name];
if(type != 'undefined' && type != 'unknown'){
return d[ns+":"+name];
}
return d[name];
} : function(ns, name){
var d = this.dom;
return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name];
}
};
var ep = El.prototype;
El.addMethods = function(o){
Ext.apply(ep, o);
};
/**
* 加入一个事件处理函数({@link #addListener}的简写方式)Appends an event handler (shorthand for {@link #addListener}).
* @param {String} eventName 事件处理函数的名称The type of event to handle
* @param {Function} fn 事件处理函数The handler function the event invokes
* @param {Object} scope (可选的)函数的作用域(默认这个元素)(optional) The scope (this element) of the handler function
* @param {Object} options (可选的)标准的事件{@link #addListener} 配置项对象(optional) An object containing standard {@link #addListener} options
* @member Ext.Element
* @method on
*/
ep.on = ep.addListener;
ep.getUpdateManager = ep.getUpdater;
/**
* 从这个元素上移除一个事件处理函数({@link #removeListener}的简写方式)。
* Removes an event handler from this element (shorthand for {@link #removeListener}).
* @param {String} eventName 要移除的事件处理函数的名称the type of event to remove
* @param {Function} fn 事件处理器the method the event invokes
* @param {Object} scope (可选的)函数的作用域(默认这个元素)(optional) The scope (The <tt>this</tt> reference) of the handler function. Defaults
* to this Element.
* @return {Ext.Element} this
* @member Ext.Element
* @method un
*/
ep.un = ep.removeListener;
/**
* true表示为自动调整由box-mode问题引起的高度和宽度设置(默认true)。
* true to automatically adjust width and height settings for box-model issues (default to true)
*/
ep.autoBoxAdjust = true;
// private
El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i;
// private
El.addUnits = function(v, defaultUnit){
if(v === "" || v == "auto"){
return v;
}
if(v === undefined){
return '';
}
if(typeof v == "number" || !El.unitPattern.test(v)){
return v + (defaultUnit || 'px');
}
return v;
};
// special markup used throughout Ext when box wrapping elements
El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';
/**
* 显示模式(Visibility mode)的两个常量之一:使用Visibility来隐藏元素
* Visibility mode constant - Use visibility to hide element
* @static
* @type Number
*/
El.VISIBILITY = 1;
/**
* 显示模式(Visibility mode)的两个常量之一:使用Display来隐藏元素
* Visibility mode constant - Use display to hide element
* @static
* @type Number
*/
El.DISPLAY = 2;
El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"};
El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"};
El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"};
/**
* @private
*/
El.cache = {};
var docEl;
/**
* 获取元素对象的静态方法。
* Static method to retrieve Ext.Element objects.
* <p><b>这个方法并非能获取{@link Ext.Component Component}。</b> 这是一个对DOM元素进行Ext.Element类型的封装方法。要获取组件,请使用{@link Ext.ComponentMgr#get}方法。This method
* retrieves Ext.Element objects which encapsulate DOM elements. To retrieve a Component by
* its ID, use {@link Ext.ComponentMgr#get}.</p>
* <p>如果是相同的对象的话,只是从缓存中提取。Uses simple caching to consistently return the same object.
* 如果通过AJAX或DOM再创建对象,那么它是同一个ID,这里会自动修正。
* Automatically fixes if an object was recreated with the same id via AJAX or DOM.</p>
* @param {Mixed} el 节点的id,一个DOM节点或是已存在的元素The id of the node, a DOM Node or an existing Element.
* @return {Element} {@link Ext.Element Element}类型的元素对象(null的话就代表没有找到元素)The {@link Ext.Element Element} object (or null if no matching element was found)
* @static
*/
El.get = function(el){
var ex, elm, id;
if(!el){ return null; }
if(typeof el == "string"){ // element id
if(!(elm = document.getElementById(el))){
return null;
}
if(ex = El.cache[el]){
ex.dom = elm;
}else{
ex = El.cache[el] = new El(elm);
}
return ex;
}else if(el.tagName){ // dom element
if(!(id = el.id)){
id = Ext.id(el);
}
if(ex = El.cache[id]){
ex.dom = el;
}else{
ex = El.cache[id] = new El(el);
}
return ex;
}else if(el instanceof El){
if(el != docEl){
el.dom = document.getElementById(el.id) || el.dom; // refresh dom element in case no longer valid,
// catch case where it hasn't been appended
El.cache[el.id] = el; // in case it was created directly with Element(), let's cache it
}
return el;
}else if(el.isComposite){
return el;
}else if(Ext.isArray(el)){
return El.select(el);
}else if(el == document){
// create a bogus element object representing the document object
if(!docEl){
var f = function(){};
f.prototype = El.prototype;
docEl = new f();
docEl.dom = document;
}
return docEl;
}
return null;
};
// private
El.uncache = function(el){
for(var i = 0, a = arguments, len = a.length; i < len; i++) {
if(a[i]){
delete El.cache[a[i].id || a[i]];
}
}
};
// private
// Garbage collection - uncache elements/purge listeners on orphaned elements
// so we don't hold a reference and cause the browser to retain them
El.garbageCollect = function(){
if(!Ext.enableGarbageCollector){
clearInterval(El.collectorThread);
return;
}
for(var eid in El.cache){
var el = El.cache[eid], d = el.dom;
// -------------------------------------------------------
// Determining what is garbage:
// -------------------------------------------------------
// !d
// dom node is null, definitely garbage
// -------------------------------------------------------
// !d.parentNode
// no parentNode == direct orphan, definitely garbage
// -------------------------------------------------------
// !d.offsetParent && !document.getElementById(eid)
// display none elements have no offsetParent so we will
// also try to look it up by it's id. However, check
// offsetParent first so we don't do unneeded lookups.
// This enables collection of elements that are not orphans
// directly, but somewhere up the line they have an orphan
// parent.
// -------------------------------------------------------
if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){
delete El.cache[eid];
if(d && Ext.enableListenerCollection){
Ext.EventManager.removeAll(d);
}
}
}
}
El.collectorThreadId = setInterval(El.garbageCollect, 30000);
var flyFn = function(){};
flyFn.prototype = El.prototype;
var _cls = new flyFn();
// dom is optional
El.Flyweight = function(dom){
this.dom = dom;
};
El.Flyweight.prototype = _cls;
El.Flyweight.prototype.isFlyweight = true;
El._flyweights = {};
/**
* 获取享元的元素,传入的节点会成为活动元素。这里不会保存该元素的引用(reference)-可由其它代码重写dom节点。
* Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
* the dom node can be overwritten by other code.
* @param {String/HTMLElement} el Dom节点或idThe dom node or id
* @param {String} named (可选的) 为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。(optional) Allows for creation of named reusable flyweights to
* prevent conflicts (e.g. internally Ext uses "_internal")
* @static
* @return {Element} 共享的Element对象(null表示为找不到元素)The shared Element object (or null if no matching element was found)
*/
El.fly = function(el, named){
named = named || '_global';
el = Ext.getDom(el);
if(!el){
return null;
}
if(!El._flyweights[named]){
El._flyweights[named] = new El.Flyweight();
}
El._flyweights[named].dom = el;
return El._flyweights[named];
};
/**
* 获取元素对象的静态方法。
* Static method to retrieve Ext.Element objects.
* <p><b>这个方法并非能获取{@link Ext.Component Component}。</b> 这是一个对DOM元素进行Ext.Element类型的封装方法。要获取组件,请使用{@link Ext.ComponentMgr#get}方法。This method
* retrieves Ext.Element objects which encapsulate DOM elements. To retrieve a Component by
* its ID, use {@link Ext.ComponentMgr#get}.</p>
* <p>如果是相同的对象的话,只是从缓存中提取。Uses simple caching to consistently return the same object.
* 如果通过AJAX或DOM再创建对象,那么它是同一个ID,这里会自动修正。
* Automatically fixes if an object was recreated with the same id via AJAX or DOM.</p>
* @param {Mixed} el 节点的id,一个DOM节点或是已存在的元素The id of the node, a DOM Node or an existing Element.
* @return {Element} {@link Ext.Element Element}类型的元素对象(null的话就代表没有找到元素)The {@link Ext.Element Element} object (or null if no matching element was found)
* @member Ext
* @method get
*/
Ext.get = El.get;
/**
* 获取享元的元素,传入的节点会成为活动元素。这里不会保存该元素的引用(reference)-可由其它代码重写dom节点。
* Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
* the dom node can be overwritten by other code.
* @param {String/HTMLElement} el Dom节点或idThe dom node or id
* @param {String} named (可选的) 为避免某些冲突(如在ext内部的“_internal”),可另外起一个名字。(optional) Allows for creation of named reusable flyweights to
* prevent conflicts (e.g. internally Ext uses "_internal")
* @static
* @return {Element} 共享的Element对象(null表示为找不到元素)The shared Element object (or null if no matching element was found)
*/
Ext.fly = El.fly;
// speedy lookup for elements never to box adjust
var noBoxAdjust = Ext.isStrict ? {
select:1
} : {
input:1, select:1, textarea:1
};
if(Ext.isIE || Ext.isGecko){
noBoxAdjust['button'] = 1;
}
Ext.EventManager.on(window, 'unload', function(){
delete El.cache;
delete El._flyweights;
});
})();
| JavaScript |
/**
* <p>Extends one class to create a subclass and optionally overrides members with the passed literal. This method
* also adds the function "override()" to the subclass that can be used to override members of the class.</p>
* For example, to create a subclass of Ext GridPanel:
* <pre><code>
MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
constructor: function(config) {
// Create configuration for this Grid.
var store = new Ext.data.Store({...});
var colModel = new Ext.grid.ColumnModel({...});
// Create a new config object containing our computed properties
// *plus* whatever was in the config parameter.
config = Ext.apply({
store: store,
colModel: colModel
}, config);
MyGridPanel.superclass.constructor.call(this, config);
// Your postprocessing here
},
yourMethod: function() {
// etc.
}
});
</code></pre>
*
* <p>This function also supports a 3-argument call in which the subclass's constructor is
* passed as an argument. In this form, the parameters are as follows:</p>
* <div class="mdetail-params"><ul>
* <li><code>subclass</code> : Function <div class="sub-desc">The subclass constructor.</div></li>
* <li><code>superclass</code> : Function <div class="sub-desc">The constructor of class being extended</div></li>
* <li><code>overrides</code> : Object <div class="sub-desc">A literal with members which are copied into the subclass's
* prototype, and are therefore shared among all instances of the new class.</div></li>
* </ul></div>
*
* @param {Function} superclass The constructor of class being extended.
* @param {Object} overrides <p>A literal with members which are copied into the subclass's
* prototype, and are therefore shared between all instances of the new class.</p>
* <p>This may contain a special member named <tt><b>constructor</b></tt>. This is used
* to define the constructor of the new class, and is returned. If this property is
* <i>not</i> specified, a constructor is generated and returned which just calls the
* superclass's constructor passing on its parameters.</p>
* <p><b>It is essential that you call the superclass constructor in any provided constructor. See example code.</b></p>
* @return {Function} The subclass constructor from the <code>overrides</code> parameter, or a generated one if not provided.
*/ | JavaScript |
/**
* OO继承,并由传递的值决定是否覆盖原对象的属性。
* 返回的类对象中也增加了“override()”函数,用于覆盖实例的成员。
* Extends one class with another class and optionally overrides members with the passed literal. This class
* also adds the function "override()" to the class that can be used to override
* members on an instance.
* <p>
* 另外一种用法是,第一个参数不是父类(严格说是父类构造器)的话那么将会发生如下的变化(这是使用2个参数的方式):
* This function also supports a 2-argument call in which the subclass's constructor is
* not passed as an argument. In this form, the parameters are as follows:</p><p>
* <div class="mdetail-params"><ul>
* <li><code>superclass</code>
* <div class="sub-desc">被继承的类。The class being extended</div></li>
* <li><code>overrides</code>
* <div class="sub-desc">
* 成员列表,就是将会复制到子类的prototype对象身上,——这便会让该新类的实例可共享这些成员。
* A literal with members which are copied into the subclass's
* prototype, and are therefore shared among all instances of the new class.<p>
* 注意其中可以包含一个元素为属于子类的构造器,叫<tt><b>constructor</b></tt>的成员。
* 如果该项<i>不</i>指定,就意味引用父类的构造器,父类构造器就会直接接收所有的参数。
* This may contain a special member named <tt><b>constructor</b></tt>. This is used
* to define the constructor of the new class, and is returned. If this property is
* <i>not</i> specified, a constructor is generated and returned which just calls the
* superclass's constructor passing on its parameters.</p></div></li>
* </ul></div></p><p>
* 例如,这样创建Ext GridPanel的子类。
* For example, to create a subclass of the Ext GridPanel:
* <pre><code>
MyGridPanel = Ext.extend(Ext.grid.GridPanel, {
constructor: function(config) {
// 你先这样调用……(就是调用父类的构造函数)
MyGridPanel.superclass.constructor.apply(this, arguments);
// 然后接着是子类的代码……
},
yourMethod: function() {
// ……
}
});
</code></pre>
* </p>
* @param {Function} subclass 子类,用于继承(该类继承了父类所有属性,并最终返回该对象)。The class inheriting the functionality
* @param {Function} superclass 父类,被继承。The class being extended
* @param {Object} overrides (可选的)一个对象,将它本身携带的属性对子类进行覆盖。(optional) A literal with members which are copied into the subclass's
* prototype, and are therefore shared between all instances of the new class.
* @return {Function} 子类的构造器。The subclass constructor.
* @method extend
*/ | 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.state.CookieProvider
* @extends Ext.state.Provider
* 通过cookies保存state的Provider之默认实现。
* <br />用法:
<pre><code>
var cp = new Ext.state.CookieProvider({
path: "/cgi-bin/",
expires: new Date(new Date().getTime()+(1000*60*60*24*30)); //30天
domain: "extjs.com"
})
Ext.state.Manager.setProvider(cp);
</code></pre>
* @constructor
* 创建一个新的CookieProvider
* @param {Object} config 配置项对象
*/
Ext.state.CookieProvider = function(config){
Ext.state.CookieProvider.superclass.constructor.call(this);
this.path = "/";
this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); //7 days
this.domain = null;
this.secure = false;
Ext.apply(this, config);
this.state = this.readCookies();
};
/**
* @cfg {String} domain cookie保存的域名。 注意你在某个页面一旦设置好,将不能够再指定其它的域名,但可以是子域名,
* 或者就是它本身如“extjs.com”,这样可以在不同子域名下访问cookies。
* 默认为null使用相同的域名(包括www如www.extjs.com)
**/
/**
* @cfg {Boolean} secure
* True表示为网站使用SSL加密(默认false)
*/
/**
* @cfg {String} path 激活cookie之路径(默认是根目录”/“,对该网站下所有的页面激活)
*/
/**
* @cfg {Date} expires 过期的日子(默认七日之后)
*/
Ext.extend(Ext.state.CookieProvider, Ext.state.Provider, {
// private
set : function(name, value){
if(typeof value == "undefined" || value === null){
this.clear(name);
return;
}
this.setCookie(name, value);
Ext.state.CookieProvider.superclass.set.call(this, name, value);
},
// private
clear : function(name){
this.clearCookie(name);
Ext.state.CookieProvider.superclass.clear.call(this, name);
},
// private
readCookies : function(){
var cookies = {};
var c = document.cookie + ";";
var re = /\s?(.*?)=(.*?);/g;
var matches;
while((matches = re.exec(c)) != null){
var name = matches[1];
var value = matches[2];
if(name && name.substring(0,3) == "ys-"){
cookies[name.substr(3)] = this.decodeValue(value);
}
}
return cookies;
},
// private
setCookie : function(name, value){
document.cookie = "ys-"+ name + "=" + this.encodeValue(value) +
((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) +
((this.path == null) ? "" : ("; path=" + this.path)) +
((this.domain == null) ? "" : ("; domain=" + this.domain)) +
((this.secure == true) ? "; secure" : "");
},
// private
clearCookie : function(name){
document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" +
((this.path == null) ? "" : ("; path=" + this.path)) +
((this.domain == null) ? "" : ("; domain=" + this.domain)) +
((this.secure == true) ? "; secure" : "");
}
}); | JavaScript |
/*
* 项目地址: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.state.Provider
* 为State Provider的实现提供一个抽象基类。
* 该类对<b>某些类型</b>的变量提供了编码、解码方法,包括日期和定义Provider的接口。
*/
Ext.state.Provider = function(){
/**
* @event statechange
* 当state发生改变时触发
* @param {Provider} this 该state提供者
* @param {String} key 已改名的那个键
* @param {String} value 已编码的state值
*/
this.addEvents("statechange");
this.state = {};
Ext.state.Provider.superclass.constructor.call(this);
};
Ext.extend(Ext.state.Provider, Ext.util.Observable, {
/**
* 返回当前的键值(value for a key)
* @param {String} name 键名称
* @param {Mixed} defaultValue 若键值找不到的情况下,返回的默认值
* @return {Mixed} State数据
*/
get : function(name, defaultValue){
return typeof this.state[name] == "undefined" ?
defaultValue : this.state[name];
},
/**
* 清除某个state的值
* @param {String} name 键名称
*/
clear : function(name){
delete this.state[name];
this.fireEvent("statechange", this, name, null);
},
/**
* 设置键值
* @param {String} name 键名称
* @param {Mixed} value 设置值
*/
set : function(name, value){
this.state[name] = value;
//console.log(value);
this.fireEvent("statechange", this, name, value);
},
/**
* 对之前用过的 {@link #encodeValue}字符串解码。
* @param {String} value 要解码的值
* @return {Mixed} 已解码的值
*/
decodeValue : function(cookie){
var re = /^(a|n|d|b|s|o)\:(.*)$/;
var matches = re.exec(unescape(cookie));
if(!matches || !matches[1]) return; // non state cookie
var type = matches[1];
var v = matches[2];
switch(type){
case "n":
return parseFloat(v);
case "d":
return new Date(Date.parse(v));
case "b":
return (v == "1");
case "a":
var all = [];
var values = v.split("^");
for(var i = 0, len = values.length; i < len; i++){
all.push(this.decodeValue(values[i]));
}
return all;
case "o":
var all = {};
var values = v.split("^");
for(var i = 0, len = values.length; i < len; i++){
var kv = values[i].split("=");
all[kv[0]] = this.decodeValue(kv[1]);
}
return all;
default:
return v;
}
},
/**
* 针对某些类型的编码,可用 {@link #decodeValue}解码。
* @param {Mixed} value 要编码的值
* @return {String} 以编码值
*/
encodeValue : function(v){
var enc;
if(typeof v == "number"){
enc = "n:" + v;
}else if(typeof v == "boolean"){
enc = "b:" + (v ? "1" : "0");
}else if(v instanceof Date){
enc = "d:" + v.toGMTString();
}else if(v instanceof Array){
var flat = "";
for(var i = 0, len = v.length; i < len; i++){
flat += this.encodeValue(v[i]);
if(i != len-1) flat += "^";
}
enc = "a:" + flat;
}else if(typeof v == "object"){
var flat = "";
for(var key in v){
if(typeof v[key] != "function" && v[key] !== undefined){
flat += key + "=" + this.encodeValue(v[key]) + "^";
}
}
enc = "o:" + flat.substring(0, flat.length-1);
}else{
enc = "s:" + v;
}
return escape(enc);
}
});
| JavaScript |
/*
* 项目地址: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.state.Manager
* 这是个全局state管理器。默认情况下,所有的组件都能“感知state”该类以获得state信息,无须传入一个自定义state provider。
* 要实现这个类,必须在应用程序初始化时连同provider一起初始。
<pre><code>
// 在你的初始化函数中
init : function(){
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
...
//假设这是 {@link Ext.BorderLayout}
var layout = new Ext.BorderLayout(...);
layout.restoreState();
// 或者{Ext.BasicDialog}
var dialog = new Ext.BasicDialog(...);
dialog.restoreState();
</code></pre>
* @singleton
*/
Ext.state.Manager = function(){
var provider = new Ext.state.Provider();
return {
/**
* 针对应用程序配置默认的state provider
* @param {Provider} stateProvider 要设置的state provider
*/
setProvider : function(stateProvider){
provider = stateProvider;
},
/**
* 返回当前的键值(value for a key)
* @param {String} name 键名称
* @param {Mixed} defaultValue 若键值找不到的情况下,返回的默认值
* @return {Mixed} State数据
*/
get : function(key, defaultValue){
return provider.get(key, defaultValue);
},
/**
* 设置键值
* @param {String} name 键名称
* @param {Mixed} value 设置值
*/
set : function(key, value){
provider.set(key, value);
},
/**
* 清除某个state的值
* @param {String} name 键名称
*/
clear : function(key){
provider.clear(key);
},
/**
*获取当前已配置的state provider
* @return {Provider} state provider
*/
getProvider : function(){
return provider;
}
};
}(); | JavaScript |
/*
* 项目地址: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.Direct
* @extends Ext.util.Observable
* <p><b><u>概述 Overview</u></b></p>
* <p>
* Ext.Direct的目的在于提供一个无缝的通讯流(streamline)介乎于客户端和服务端之间,形成一种单一的接口,从而使得我们减少一些乏味的编码,例如数据的验证和出来返回的数据包(读数据、错误条件等等)。<br />
* Ext.Direct aims to streamline communication between the client and server
* by providing a single interface that reduces the amount of common code
* typically required to validate data and handle returned data packets
* (reading data, error conditions, etc).</p>
*
* <p>
* Ext.direct命名空间下有若干的类是为了与服务端更密切地整合。Ext.Direct的一些方法产生出来的数据经过Ext.data另外的一些类,就可以转给Ext.data.Stores处理。<br />
* The Ext.direct namespace includes several classes for a closer integration
* with the server-side. The Ext.data namespace also includes classes for working
* with Ext.data.Stores which are backed by data from an Ext.Direct method.</p>
*
* <p><b><u>规范文件 Specification</u></b></p>
*
* <p>For additional information consult the
* <a href="http://extjs.com/products/extjs/direct.php">Ext.Direct Specification</a>.</p>
*
* <p><b><u>供应器 Providers</u></b></p>
*
* <p>
* Ext.Direct的架构属于“供应器(provider)”的架构,一个或多个的供应器负责将数据传输到服务器上。当前有几种关键的供应器:<br />
* Ext.Direct uses a provider architecture, where one or more providers are
* used to transport data to and from the server. There are several providers
* that exist in the core at the moment:</p><div class="mdetail-params"><ul>
*
* <li>{@link Ext.direct.JsonProvider JsonProvider} for simple JSON operations 简易的JSON操作</li>
* <li>{@link Ext.direct.PollingProvider PollingProvider} for repeated requests 重复的请求</li>
* <li>{@link Ext.direct.RemotingProvider RemotingProvider} exposes server side
* on the client.向客户端暴露了服务端</li>
* </ul></div>
*
* <p>供应器本身不能直接的使用,应该通过{@link Ext.Direct}.{@link Ext.Direct#add add}加入。<br />
* A provider does not need to be invoked directly, providers are added via
* {@link Ext.Direct}.{@link Ext.Direct#add add}.</p>
*
* <p><b><u>路由器 Router</u></b></p>
*
* <p>
* 在客户端与服务端部分方法之间,Ext.Direct使用了服务端“路由器(router)”的概念来直接请求。
* 由于Ext.Direct是真正平台无关性的,所以你完全可以在以Java为解决方案的服务端,立刻替换成为C#的服务端,过程中你不需要对JavaScript作任何的变动或修改。
* <br />
* Ext.Direct utilizes a "router" on the server to direct requests from the client
* to the appropriate server-side method. Because the Ext.Direct API is completely
* platform-agnostic, you could completely swap out a Java based server solution
* and replace it with one that uses C# without changing the client side JavaScript
* at all.</p>
*
* <p><b><u>服务端事件。Server side events</u></b></p>
*
* <p>
* 由服务器通知而来的事件,可以添加一个事件侦听器来应接并触发:<br />
* Custom events from the server may be handled by the client by adding
* listeners, for example:</p>
* <pre><code>
{"type":"event","name":"message","data":"Successfully polled at: 11:19:30 am"}
// 对应服务端“message”的事件的处理函数。add a handler for a 'message' event sent by the server
Ext.Direct.on('message', function(e){
out.append(String.format('<p><i>{0}</i></p>', e.data));
out.el.scrollTo('t', 100000, true);
});
* </code></pre>
* @singleton
*/
Ext.Direct = Ext.extend(Ext.util.Observable, {
/**
* 每个事件类型实现一个getData()方法。缺省的事件类型是:<br />
* Each event type implements a getData() method. The default event types are:
* <div class="mdetail-params"><ul>
* <li><b><tt>event</tt></b> : Ext.Direct.Event</li>
* <li><b><tt>exception</tt></b> : Ext.Direct.ExceptionEvent</li>
* <li><b><tt>rpc</tt></b> : Ext.Direct.RemotingEvent</li>
* </ul></div>
* @property eventTypes
* @type Object
*/
/**
* 对于可能出现的异常的四种类型有:<br />
* Four types of possible exceptions which can occur:
* <div class="mdetail-params"><ul>
* <li><b><tt>Ext.Direct.exceptions.TRANSPORT</tt></b> : 'xhr'</li>
* <li><b><tt>Ext.Direct.exceptions.PARSE</tt></b> : 'parse'</li>
* <li><b><tt>Ext.Direct.exceptions.LOGIN</tt></b> : 'login'</li>
* <li><b><tt>Ext.Direct.exceptions.SERVER</tt></b> : 'exception'</li>
* </ul></div>
* @property exceptions
* @type Object
*/
exceptions: {
TRANSPORT: 'xhr',
PARSE: 'parse',
LOGIN: 'login',
SERVER: 'exception'
},
// private
constructor: function(){
this.addEvents(
/**
* @event event
* 一个事件之后触发。
* Fires after an event.
* @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
*/
'event',
/**
* @event exception
* 一个异常事件之后触发。
* Fires after an event exception.
* @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
*/
'exception'
);
this.transactions = {};
this.providers = {};
},
/**
* 加入一个Ext.Direct供应器并创建代理,或者对服务端执行的方法进行一个快照。
* 如果供应器还没有链接,那么就会自动链接。下面的例子创建了两个provider。<br />
* Adds an Ext.Direct Provider and creates the proxy or stub methods to execute server-side methods.
* If the provider is not already connected, it will auto-connect.
* <pre><code>
var pollProv = new Ext.direct.PollingProvider({
url: 'php/poll2.php'
});
Ext.Direct.addProvider(
{
"type":"remoting", // create a {@link Ext.direct.RemotingProvider}
"url":"php\/router.php", // url to connect to the Ext.Direct server-side router.
"actions":{ // each property within the actions object represents a Class
"TestAction":[ // array of methods within each server side Class
{
"name":"doEcho", // name of method
"len":1
},{
"name":"multiply",
"len":1
},{
"name":"doForm",
"formHandler":true, // handle form on server with Ext.Direct.Transaction
"len":1
}]
},
"namespace":"myApplication",// namespace to create the Remoting Provider in
},{
type: 'polling', // create a {@link Ext.direct.PollingProvider}
url: 'php/poll.php'
},
pollProv // reference to previously created instance
);
* </code></pre>
* @param {Object/Array} provider 供应器,可以多个一起传入。每个供应器告诉了 Ext.Direct如何创建客户端快照的方法。
* Accepts either an Array of Provider descriptions (an instance
* or config object for a Provider) or any number of Provider descriptions as arguments. Each
* Provider description instructs Ext.Direct how to create client-side stub methods.
*/
addProvider : function(provider){
var a = arguments;
if(a.length > 1){
for(var i = 0, len = a.length; i < len; i++){
this.addProvider(a[i]);
}
return;
}
// if provider has not already been instantiated
if(!provider.events){
provider = new Ext.Direct.PROVIDERS[provider.type](provider);
}
provider.id = provider.id || Ext.id();
this.providers[provider.id] = provider;
provider.on('data', this.onProviderData, this);
provider.on('exception', this.onProviderException, this);
if(!provider.isConnected()){
provider.connect();
}
return provider;
},
/**
* 通过{@link #addProvider 已经加入}的{@link Ext.direct.Provider 供应器},可以指定一个<b><tt>{@link Ext.direct.Provider#id id}</tt></b>执行该方法返回。
* <br />
* Retrieve a {@link Ext.direct.Provider provider} by the
* <b><tt>{@link Ext.direct.Provider#id id}</tt></b> specified when the provider is
* {@link #addProvider added}.
* @param {String} id 执行{@link #addProvider}的时候,都会分配一个ID表示供应器。Unique identifier assigned to the provider when calling {@link #addProvider}
*/
getProvider : function(id){
return this.providers[id];
},
removeProvider : function(id){
var provider = id.id ? id : this.providers[id.id];
provider.un('data', this.onProviderData, this);
provider.un('exception', this.onProviderException, this);
delete this.providers[provider.id];
return provider;
},
addTransaction: function(t){
this.transactions[t.tid] = t;
return t;
},
removeTransaction: function(t){
delete this.transactions[t.tid || t];
return t;
},
getTransaction: function(tid){
return this.transactions[tid.tid || tid];
},
onProviderData : function(provider, e){
if(Ext.isArray(e)){
for(var i = 0, len = e.length; i < len; i++){
this.onProviderData(provider, e[i]);
}
return;
}
if(e.name && e.name != 'event' && e.name != 'exception'){
this.fireEvent(e.name, e);
}else if(e.type == 'exception'){
this.fireEvent('exception', e);
}
this.fireEvent('event', e, provider);
},
createEvent : function(response, extraProps){
return new Ext.Direct.eventTypes[response.type](Ext.apply(response, extraProps));
}
});
// overwrite impl. with static instance
Ext.Direct = new Ext.Direct();
Ext.Direct.TID = 1;
Ext.Direct.PROVIDERS = {}; | 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.Direct.Transaction
* @extends Object
* <p>Supporting Class for Ext.Direct (not intended to be used directly).</p>
* @constructor
* @param {Object} config
*/
Ext.Direct.Transaction = function(config){
Ext.apply(this, config);
this.tid = ++Ext.Direct.TID;
this.retryCount = 0;
};
Ext.Direct.Transaction.prototype = {
send: function(){
this.provider.queueTransaction(this);
},
retry: function(){
this.retryCount++;
this.send();
},
getProvider: function(){
return this.provider;
}
}; | 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.direct.Provider
* @extends Ext.util.Observable
* <p>Ext.direct.Provider是一个抽象类,用来扩展的。
* Ext.direct.Provider is an abstract class meant to be extended.</p>
*
* <p>例如ExtJS现在就实现了以下的子类了:
* For example ExtJs implements the following subclasses:</p>
* <pre><code>
Provider
|
+---{@link Ext.direct.JsonProvider JsonProvider}
|
+---{@link Ext.direct.PollingProvider PollingProvider}
|
+---{@link Ext.direct.RemotingProvider RemotingProvider}
* </code></pre>
* @abstract
*/
Ext.direct.Provider = Ext.extend(Ext.util.Observable, {
/**
* @cfg {String} id
* 供应器的id(默认的由{@link Ext#id auto-assigned id}方法产生)。
* 如果你没有用全局变量保存着这个供应器,那么你就应该分配一个id来记住这个供应器,以便日后寻找。例如:
* The unique id of the provider (defaults to an {@link Ext#id auto-assigned id}).
* You should assign an id if you need to be able to access the provider later and you do
* not have an object reference available, for example:
* <pre><code>
Ext.Direct.addProvider(
{
type: 'polling',
url: 'php/poll.php',
id: 'poll-provider'
}
);
var p = {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#getProvider getProvider}('poll-provider');
p.disconnect();
* </code></pre>
*/
/**
* @cfg {Number} priority
* 请求的优先权(priority),数值愈低表示优先权愈高,<tt>0</tt>就表示“双工的”(总是打开)。
* 所有的供应器默认为<tt>1</tt>,但PollingProvider就除外,默认为<tt>3</tt>。<br />
* Priority of the request. Lower is higher priority, <tt>0</tt> means "duplex" (always on).
* All Providers default to <tt>1</tt> except for PollingProvider which defaults to <tt>3</tt>.
*/
priority: 1,
/**
* @cfg {String} type
* 这是{@link Ext.Direct Ext.Direct}的类型,这是<b>必须的</b>,默认是<tt>undefined</tt>。
* 执行{@link Ext.Direct#addProvider addProvider}创建新的供应器的时候就会用到这个类型。
* 默认可识别的类型如下规格:<br />
* <b>Required</b>, <tt>undefined</tt> by default. The <tt>type</tt> of provider specified
* to {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#addProvider addProvider} to create a
* new Provider. Acceptable values by default are:<div class="mdetail-params"><ul>
* <li><b><tt>polling</tt></b> : {@link Ext.direct.PollingProvider PollingProvider}</li>
* <li><b><tt>remoting</tt></b> : {@link Ext.direct.RemotingProvider RemotingProvider}</li>
* </ul></div>
*/
// private
constructor : function(config){
Ext.apply(this, config);
this.addEvents(
/**
* @event connect
* 当连接服务端之后触发。
* Fires when the Provider connects to the server-side
* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
*/
'connect',
/**
* @event disconnect
* 当与服务端断开之后触发。
* Fires when the Provider disconnects from the server-side
* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
*/
'disconnect',
/**
* @event data
* 当接收到来自服务端的数据的时候触发。
* Fires when the Provider receives data from the server-side
* @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
* @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
*/
'data',
/**
* @event exception
* 当供应器接收一个服务端的异常后触发。
* Fires when the Provider receives an exception from the server-side
*/
'exception'
);
Ext.direct.Provider.superclass.constructor.call(this, config);
},
/**
* 返回是否与服务端链接者的。由子类实现的抽象方法。
* Returns whether or not the server-side is currently connected.
* Abstract method for subclasses to implement.
*/
isConnected: function(){
return false;
},
/**
* 由子类实现的抽象方法。
* Abstract methods for subclasses to implement.
*/
connect: Ext.emptyFn,
/**
* 由子类实现的抽象方法。
* Abstract methods for subclasses to implement.
*/
disconnect: 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.direct.PollingProvider
* @extends Ext.direct.JsonProvider
*
* <p>
* 按一定的{@link #interval 周期}不断轮询服务端。最开始的数据由客户端发出,然后由服务端响应。<br />
* Provides for repetitive polling of the server at distinct {@link #interval intervals}.
* The initial request for data originates from the client, and then is responded to by the
* server.</p>
*
* <p>
* 应该由运行在服务端其余部分的Ext.Direct包来生成PollingProvider的所有配置内容。<br />
* All configurations for the PollingProvider should be generated by the server-side
* API portion of the Ext.Direct stack.</p>
*
* <p>
* 创建一个PollingProvider实例可以通过new关键字实现,或者只是指定<tt>type = 'polling'</tt>就可以,例如:<br />
* An instance of PollingProvider may be created directly via the new keyword or by simply
* specifying <tt>type = 'polling'</tt>. For example:</p>
* <pre><code>
var pollA = new Ext.direct.PollingProvider({
type:'polling',
url: 'php/pollA.php',
});
Ext.Direct.addProvider(pollA);
pollA.disconnect();
Ext.Direct.addProvider(
{
type:'polling',
url: 'php/pollB.php',
id: 'pollB-provider'
}
);
var pollB = Ext.Direct.getProvider('pollB-provider');
* </code></pre>
*/
Ext.direct.PollingProvider = Ext.extend(Ext.direct.JsonProvider, {
/**
* @cfg {Number} priority
* 请求的优先级(默认是<tt>3</tt>)。请参阅{@link Ext.direct.Provider#priority}。
* Priority of the request (defaults to <tt>3</tt>). See {@link Ext.direct.Provider#priority}.
*/
// override default priority
priority: 3,
/**
* @cfg {Number} interval
* 隔多久的时候轮询服务端,单位是毫秒(默认是<tt>3000</tt>,三秒钟)
* How often to poll the server-side in milliseconds (defaults to <tt>3000</tt> - every
* 3 seconds).
*/
interval: 3000,
/**
* @cfg {Object} baseParams 每一次轮询所发出的请求当中所包含的参数对象。An object containing properties which are to be sent as parameters
* on every polling request
*/
/**
* @cfg {String/Function} url
* 每次请求PollingProvider连接url的地址。这配置项也可以是一个Ext.Direct方法,参数就是baseParams这一个。The url which the PollingProvider should contact with each request. This can also be
* an imported Ext.Direct method which will accept the baseParams as its only argument.
*/
// private
constructor : function(config){
Ext.direct.PollingProvider.superclass.constructor.call(this, config);
this.addEvents(
/**
* @event beforepoll
* 在轮询发生之前的时候触发,过程中任一次返回false都会中止整个轮询。
* Fired immediately before a poll takes place, an event handler can return false
* in order to cancel the poll.
* @param {Ext.direct.PollingProvider} pObj PollingProvider对象
*/
'beforepoll',
/**
* @event poll
* This event has not yet been implemented.
* @param {Ext.direct.PollingProvider} pObj PollingProvider对象
*/
'poll'
);
},
// inherited
isConnected: function(){
return !!this.pollTask;
},
/**
* 连接到服务器并开始轮询的进程。要处理每一次的响应内容就要订阅数据data事件。
* Connect to the server-side and begin the polling process. To handle each
* response subscribe to the data event.
*/
connect: function(){
if(this.url && !this.pollTask){
this.pollTask = Ext.TaskMgr.start({
run: function(){
if(this.fireEvent('beforepoll', this) !== false){
if(typeof this.url == 'function'){
this.url(this.baseParams);
}else{
Ext.Ajax.request({
url: this.url,
callback: this.onData,
scope: this,
params: this.baseParams
});
}
}
},
interval: this.interval,
scope: this
});
this.fireEvent('connect', this);
}else if(!this.url){
throw 'Error initializing PollingProvider, no url configured.';
}
},
/**
* 停止轮询的进程并与服务器断开。断开成功后会触发disconnect事件。
* Disconnect from the server-side and stop the polling process. The disconnect
* event will be fired on a successful disconnect.
*/
disconnect: function(){
if(this.pollTask){
Ext.TaskMgr.stop(this.pollTask);
delete this.pollTask;
this.fireEvent('disconnect', this);
}
},
// private
onData: function(opt, success, xhr){
if(success){
var events = this.getEvents(xhr);
for(var i = 0, len = events.length; i < len; i++){
var e = events[i];
this.fireEvent('data', this, e);
}
}else{
var e = new Ext.Direct.ExceptionEvent({
data: e,
code: Ext.Direct.exceptions.TRANSPORT,
message: 'Unable to connect to the server.',
xhr: xhr
});
this.fireEvent('data', this, e);
}
}
});
Ext.Direct.PROVIDERS['polling'] = Ext.direct.PollingProvider; | 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.direct.JsonProvider
* @extends Ext.direct.Provider
*/
Ext.direct.JsonProvider = Ext.extend(Ext.direct.Provider, {
parseResponse: function(xhr){
if(!Ext.isEmpty(xhr.responseText)){
if(typeof xhr.responseText == 'object'){
return xhr.responseText;
}
return Ext.decode(xhr.responseText);
}
return null;
},
getEvents: function(xhr){
var data = null;
try{
data = this.parseResponse(xhr);
}catch(e){
var event = new Ext.Direct.ExceptionEvent({
data: e,
xhr: xhr,
code: Ext.Direct.exceptions.PARSE,
message: 'Error parsing json response: \n\n ' + data
})
return [event];
}
var events = [];
if(Ext.isArray(data)){
for(var i = 0, len = data.length; i < len; i++){
events.push(Ext.Direct.createEvent(data[i]));
}
}else{
events.push(Ext.Direct.createEvent(data));
}
return events;
}
}); | JavaScript |
Ext.Direct.Event = function(config){
Ext.apply(this, config);
}
Ext.Direct.Event.prototype = {
status: true,
getData: function(){
return this.data;
}
};
Ext.Direct.RemotingEvent = Ext.extend(Ext.Direct.Event, {
type: 'rpc',
getTransaction: function(){
return this.transaction || Ext.Direct.getTransaction(this.tid);
}
});
Ext.Direct.ExceptionEvent = Ext.extend(Ext.Direct.RemotingEvent, {
status: false,
type: 'exception'
});
Ext.Direct.eventTypes = {
'rpc': Ext.Direct.RemotingEvent,
'event': Ext.Direct.Event,
'exception': Ext.Direct.ExceptionEvent
};
| 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.direct.RemotingProvider
* @extends Ext.direct.JsonProvider
*
* <p>
* {@link Ext.direct.RemotingProvider RemotingProvider}暴露了在客户端上访问服务端方法的方式方法。
* 这是一种RPC(remote procedure call,远程过程调录)的连接类型,即客户端可以初始化服务端上的进程。<br />
* The {@link Ext.direct.RemotingProvider RemotingProvider} exposes access to
* server side methods on the client (a remote procedure call (RPC) type of
* connection where the client can initiate a procedure on the server).
* </p>
*
* <p>
* 这样的话,组织代码的时候会更具可维护性,客户端与服务端之间的道路怎么走也会越加地清晰。如果单使用URL的话这点是不容易做到的。
* <br />
* This allows for code to be organized in a fashion that is maintainable,
* while providing a clear path between client and server, something that is
* not always apparent when using URLs.</p>
*
* <p>
* 完成上述功能,服务端必须将有关类和方法的信息告诉给客户端知道。一般这些配置的信息由服务端的Ext.Direct包完成,构建一系列的API信息输出。<br />
* To accomplish this the server-side needs to describe what classes and methods
* are available on the client-side. This configuration will typically be
* outputted by the server-side Ext.Direct stack when the API description is built.</p>
*/
Ext.direct.RemotingProvider = Ext.extend(Ext.direct.JsonProvider, {
/**
* @cfg {Object} actions
* 用对象字面化(Object literal)确定服务端的动作或方法。例如,如果供应器(Provider)是如下配置的:
* Object literal defining the server side actions and methods. For example, if
* the Provider is configured with:
* <pre><code>
"actions":{ // actions对象下面的属性每个都代表者对应服务端的类。each property within the 'actions' object represents a server side Class
"TestAction":[ // 服务端的类其方法所组成的数组,要将他们暴露给客户端。array of methods within each server side Class to be
{ // stubbed out on client
"name":"doEcho",
"len":1
},{
"name":"multiply",// name of method
"len":2 // 参数的个数是多少。一定要是数字类型,而不能是字符串。The number of parameters that will be used to create an
// array of data to send to the server side function.
// Ensure the server sends back a Number, not a String.
},{
"name":"doForm",
"formHandler":true, // direct the client to use specialized form handling method
"len":1
}]
}
* </code></pre>
* <p>
* 注意Store不是必须的,一个服务端方法可以在任何的时候被调用。下面的例子中我们<b>客户端</b>的方法调用服务端中的“乘法”,就在服务端的“TestAction”类中:
* <br />
* Note that a Store is not required, a server method can be called at any time.
* In the following example a <b>client side</b> handler is used to call the
* server side method "multiply" in the server-side "TestAction" Class:</p>
* <pre><code>
TestAction.multiply(
2, 4, // 这两个参数都会传到服务器中,所以指定len=2。pass two arguments to server, so specify len=2
// 下面的回调函数在服务端调用后执行。callback function after the server is called
// result: the result returned by the server
// e: Ext.Direct.RemotingEvent object result就是由服务端返回的对象,例如Ext.Direct.RemotingEvent类型的对象
function(result, e){
var t = e.getTransaction();
var action = t.action; // 调用服务端的类。server side Class called
var method = t.method; // 调用服务端的方法。server side method called
if(e.status){
var answer = Ext.encode(result); // 8
}else{
var msg = e.message; // 失败的信息 failure message
}
}
);
* </code></pre>
* 上面的例子中,服务端的“multiply”函数会送入两个参数(2和4)。“multiply”函数就应该返回8,最后变为<tt>result</tt>变量。
* In the example above, the server side "multiply" function will be passed two
* arguments (2 and 4). The "multiply" method should return the value 8 which will be
* available as the <tt>result</tt> in the example above.
*/
/**
* @cfg {String/Object} namespace
* 远程供应器的命名空间(默认为浏览器的全局空间<i>window</i>)。完全命名这个空间,或者指定一个String执行{@link Ext#namespace namespace created}隐式命名。 <br />
* Namespace for the Remoting Provider (defaults to the browser global scope of <i>window</i>).
* Explicitly specify the namespace Object, or specify a String to have a
* {@link Ext#namespace namespace created} implicitly.
*/
/**
* @cfg {String} url
* 该项是必须的。连接到{@link Ext.Direct}所在的服务端路由器(router)。
* <b>Required<b>. The url to connect to the {@link Ext.Direct} server-side router.
*/
/**
* @cfg {String} enableUrlEncode
* 指定哪个param会保存方法的参数。默认是<tt>'data'</tt>。
* Specify which param will hold the arguments for the method.
* Defaults to <tt>'data'</tt>.
*/
/**
* @cfg {Number/Boolean} enableBuffer
* <p>
* 设置为<tt>true</tt>或<tt>false</tt>决定是否捆绑多个方法调用在一起。如果指定一个数字表示就等待形成一次批调用的机会(默认为10毫秒)。<br />
* <tt>true</tt> or <tt>false</tt> to enable or disable combining of method
* calls. If a number is specified this is the amount of time in milliseconds
* to wait before sending a batched request (defaults to <tt>10</tt>).</p>
* <br>
* <p>
* 多个调用按一定的时候聚集在一起然后统一在一次请求中发出,就可以优化程序了,因为减少了服务端之间的往返次数。<br />
* Calls which are received within the specified timeframe will be
* concatenated together and sent in a single request, optimizing the
* application by reducing the amount of round trips that have to be made
* to the server.</p>
*/
enableBuffer: 10,
/**
* @cfg {Number} maxRetries
* 当failure后,尝试再连接的次数。默认为一次。
* Number of times to re-attempt delivery on failure of a call. Defaults to <tt>1</tt>.
*/
maxRetries: 1,
/**
* @cfg {Number} timeout
* 每次请求的超时时限。默认为<tt>undefined</tt>。
* The timeout to use for each request. Defaults to <tt>undefined</tt>.
*/
timeout: undefined,
constructor : function(config){
Ext.direct.RemotingProvider.superclass.constructor.call(this, config);
this.addEvents(
/**
* @event beforecall
* 在客户端发送PRC请求之前触发。事件处理器中返回false的话表示阻止这次远程调用。
* Fires immediately before the client-side sends off the RPC call.
* By returning false from an event handler you can prevent the call from
* executing.
* @param {Ext.direct.RemotingProvider} provider
* @param {Ext.Direct.Transaction} transaction
*/
'beforecall',
/**
* @event call
* 当送往服务端的请求发送后触发。有响应的时候不会触发该事件。
* Fires immediately after the request to the server-side is sent. This does
* NOT fire after the response has come back from the call.
* @param {Ext.direct.RemotingProvider} provider
* @param {Ext.Direct.Transaction} transaction
*/
'call'
);
this.namespace = (Ext.isString(this.namespace)) ? Ext.ns(this.namespace) : this.namespace || window;
this.transactions = {};
this.callBuffer = [];
},
// private
initAPI : function(){
var o = this.actions;
for(var c in o){
var cls = this.namespace[c] || (this.namespace[c] = {}),
ms = o[c];
for(var i = 0, len = ms.length; i < len; i++){
var m = ms[i];
cls[m.name] = this.createMethod(c, m);
}
}
},
// inherited
isConnected: function(){
return !!this.connected;
},
connect: function(){
if(this.url){
this.initAPI();
this.connected = true;
this.fireEvent('connect', this);
}else if(!this.url){
throw 'Error initializing RemotingProvider, no url configured.';
}
},
disconnect: function(){
if(this.connected){
this.connected = false;
this.fireEvent('disconnect', this);
}
},
onData: function(opt, success, xhr){
if(success){
var events = this.getEvents(xhr);
for(var i = 0, len = events.length; i < len; i++){
var e = events[i],
t = this.getTransaction(e);
this.fireEvent('data', this, e);
if(t){
this.doCallback(t, e, true);
Ext.Direct.removeTransaction(t);
}
}
}else{
var ts = [].concat(opt.ts);
for(var i = 0, len = ts.length; i < len; i++){
var t = this.getTransaction(ts[i]);
if(t && t.retryCount < this.maxRetries){
t.retry();
}else{
var e = new Ext.Direct.ExceptionEvent({
data: e,
transaction: t,
code: Ext.Direct.exceptions.TRANSPORT,
message: 'Unable to connect to the server.',
xhr: xhr
});
this.fireEvent('data', this, e);
if(t){
this.doCallback(t, e, false);
Ext.Direct.removeTransaction(t);
}
}
}
}
},
getCallData: function(t){
return {
action: t.action,
method: t.method,
data: t.data,
type: 'rpc',
tid: t.tid
};
},
doSend : function(data){
var o = {
url: this.url,
callback: this.onData,
scope: this,
ts: data,
timeout: this.timeout
}, callData;
if(Ext.isArray(data)){
callData = [];
for(var i = 0, len = data.length; i < len; i++){
callData.push(this.getCallData(data[i]));
}
}else{
callData = this.getCallData(data);
}
if(this.enableUrlEncode){
var params = {};
params[Ext.isString(this.enableUrlEncode) ? this.enableUrlEncode : 'data'] = Ext.encode(callData);
o.params = params;
}else{
o.jsonData = callData;
}
Ext.Ajax.request(o);
},
combineAndSend : function(){
var len = this.callBuffer.length;
if(len > 0){
this.doSend(len == 1 ? this.callBuffer[0] : this.callBuffer);
this.callBuffer = [];
}
},
queueTransaction: function(t){
if(t.form){
this.processForm(t);
return;
}
this.callBuffer.push(t);
if(this.enableBuffer){
if(!this.callTask){
this.callTask = new Ext.util.DelayedTask(this.combineAndSend, this);
}
this.callTask.delay(Ext.isNumber(this.enableBuffer) ? this.enableBuffer : 10);
}else{
this.combineAndSend();
}
},
doCall : function(c, m, args){
var data = null, hs = args[m.len], scope = args[m.len+1];
if(m.len !== 0){
data = args.slice(0, m.len);
}
var t = new Ext.Direct.Transaction({
provider: this,
args: args,
action: c,
method: m.name,
data: data,
cb: scope && Ext.isFunction(hs) ? hs.createDelegate(scope) : hs
});
if(this.fireEvent('beforecall', this, t) !== false){
Ext.Direct.addTransaction(t);
this.queueTransaction(t);
this.fireEvent('call', this, t);
}
},
doForm : function(c, m, form, callback, scope){
var t = new Ext.Direct.Transaction({
provider: this,
action: c,
method: m.name,
args:[form, callback, scope],
cb: scope && Ext.isFunction(callback) ? callback.createDelegate(scope) : callback,
isForm: true
});
if(this.fireEvent('beforecall', this, t) !== false){
Ext.Direct.addTransaction(t);
var isUpload = String(form.getAttribute("enctype")).toLowerCase() == 'multipart/form-data',
params = {
extTID: t.tid,
extAction: c,
extMethod: m.name,
extType: 'rpc',
extUpload: String(isUpload)
};
// change made from typeof callback check to callback.params
// to support addl param passing in DirectSubmit EAC 6/2
Ext.apply(t, {
form: Ext.getDom(form),
isUpload: isUpload,
params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params
});
this.fireEvent('call', this, t);
this.processForm(t);
}
},
processForm: function(t){
Ext.Ajax.request({
url: this.url,
params: t.params,
callback: this.onData,
scope: this,
form: t.form,
isUpload: t.isUpload,
ts: t
});
},
createMethod : function(c, m){
var f;
if(!m.formHandler){
f = function(){
this.doCall(c, m, Array.prototype.slice.call(arguments, 0));
}.createDelegate(this);
}else{
f = function(form, callback, scope){
this.doForm(c, m, form, callback, scope);
}.createDelegate(this);
}
f.directCfg = {
action: c,
method: m
};
return f;
},
getTransaction: function(opt){
return opt && opt.tid ? Ext.Direct.getTransaction(opt.tid) : null;
},
doCallback: function(t, e){
var fn = e.status ? 'success' : 'failure';
if(t && t.cb){
var hs = t.cb,
result = Ext.isDefined(e.result) ? e.result : e.data;
if(Ext.isFunction(hs)){
hs(result, e);
} else{
Ext.callback(hs[fn], hs.scope, [result, e]);
Ext.callback(hs.callback, hs.scope, [result, e]);
}
}
}
});
Ext.Direct.PROVIDERS['remoting'] = Ext.direct.RemotingProvider; | JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
// Easing functions
(function(){
// shortcuts to aid compression
var abs = Math.abs,
pi = Math.PI,
asin = Math.asin,
pow = Math.pow,
sin = Math.sin;
Ext.apply(Ext.lib.Easing, {
easeBoth: function (t, b, c, d) {
return ((t /= d / 2) < 1) ? c / 2 * t * t + b : -c / 2 * ((--t) * (t - 2) - 1) + b;
},
easeInStrong: function (t, b, c, d) {
return c * (t /= d) * t * t * t + b;
},
easeOutStrong: function (t, b, c, d) {
return -c * ((t = t / d - 1) * t * t * t - 1) + b;
},
easeBothStrong: function (t, b, c, d) {
return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t + b : -c / 2 * ((t -= 2) * t * t * t - 2) + b;
},
elasticIn: function (t, b, c, d, a, p) {
if (t == 0 || (t /= d) == 1) {
return t == 0 ? b : b + c;
}
p = p || (d * .3);
var s;
if (a >= abs(c)) {
s = p / (2 * pi) * asin(c / a);
} else {
a = c;
s = p / 4;
}
return -(a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p)) + b;
},
elasticOut: function (t, b, c, d, a, p) {
if (t == 0 || (t /= d) == 1) {
return t == 0 ? b : b + c;
}
p = p || (d * .3);
var s;
if (a >= abs(c)) {
s = p / (2 * pi) * asin(c / a);
} else {
a = c;
s = p / 4;
}
return a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p) + c + b;
},
elasticBoth: function (t, b, c, d, a, p) {
if (t == 0 || (t /= d / 2) == 2) {
return t == 0 ? b : b + c;
}
p = p || (d * (.3 * 1.5));
var s;
if (a >= abs(c)) {
s = p / (2 * pi) * asin(c / a);
} else {
a = c;
s = p / 4;
}
return t < 1 ?
-.5 * (a * pow(2, 10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p)) + b :
a * pow(2, -10 * (t -= 1)) * sin((t * d - s) * (2 * pi) / p) * .5 + c + b;
},
backIn: function (t, b, c, d, s) {
s = s || 1.70158;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
},
backOut: function (t, b, c, d, s) {
if (!s) {
s = 1.70158;
}
return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
},
backBoth: function (t, b, c, d, s) {
s = s || 1.70158;
return ((t /= d / 2 ) < 1) ?
c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b :
c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
},
bounceIn: function (t, b, c, d) {
return c - this.bounceOut(d - t, 0, c, d) + b;
},
bounceOut: function (t, b, c, d) {
if ((t /= d) < (1 / 2.75)) {
return c * (7.5625 * t * t) + b;
} else if (t < (2 / 2.75)) {
return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
} else if (t < (2.5 / 2.75)) {
return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
}
return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
},
bounceBoth: function (t, b, c, d) {
return (t < d / 2) ?
this.bounceIn(t * 2, 0, c, d) * .5 + b :
this.bounceOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
}
});
})();
(function() {
// Color Animation
Ext.lib.Anim.color = function(el, args, duration, easing, cb, scope) {
return Ext.lib.Anim.run(el, args, duration, easing, cb, scope, Ext.lib.ColorAnim);
}
Ext.lib.ColorAnim = function(el, attributes, duration, method) {
Ext.lib.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method);
};
Ext.extend(Ext.lib.ColorAnim, Ext.lib.AnimBase);
var superclass = Ext.lib.ColorAnim.superclass,
colorRE = /color$/i,
transparentRE = /^transparent|rgba\(0, 0, 0, 0\)$/;
// private
function parseColor(s) {
var pi = parseInt,
c;
if (s.length == 3) {
c = s;
} else if (s.charAt(0) == "r") {
c = s.replace(/[^0-9,]/g,"").split(',');
c = [ pi(c[1], 10), pi(c[2], 10), pi(c[3], 10) ];
} else if (s.length < 6) {
c = s.replace("#","").match(/./g);
c = [ pi(c[0] + c[0], 16), pi(c[1] + c[1], 16), pi(c[2] + c[2], 16) ];
} else {
c = s.replace("#","").match(/./g);
c = [ pi(c[0] + c[1] , 16), pi(c[2] + c[3], 16), pi(c[4] + c[5], 16) ];
}
return c;
}
Ext.apply(Ext.lib.ColorAnim.prototype, {
getAttr : function(attr) {
var me = this,
el = me.el,
val;
if (colorRE.test(attr)) {
while(el && transparentRE.test(val = fly(el).getStyle(attr))) {
el = el.parentNode;
val = "fff";
}
} else {
val = superclass.getAttr.call(me, attr);
}
return val;
},
doMethod : function(attr, start, end) {
var me = this,
val,
floor = Math.floor;
if (colorRE.test(attr)) {
val = [];
Ext.each(start, function(v, i) {
val[i] = superclass.doMethod.call(me, attr, v, end[i]);
});
val = 'rgb(' + floor(val[0]) + ',' + floor(val[1]) + ',' + floor(val[2]) + ')';
} else {
val = superclass.doMethod.call(me, attr, start, end);
}
return val;
},
setRunAttr : function(attr) {
var me = this,
isEmpty = Ext.isEmpty;
superclass.setRunAttr.call(me, attr);
if (colorRE.test(attr)) {
var attribute = me.attrs[attr],
ra = me.runAttrs[attr],
start = parseColor(ra.start),
end = parseColor(ra.end);
if (isEmpty(attribute.to) && !isEmpty(attribute.by)) {
end = parseColor(attribute.by);
Ext.each(start, function(v, i) {
end[i] = v + end[i];
});
}
ra.start = start;
ra.end = end;
}
}
});
})();
(function() {
// Scroll Animation
Ext.lib.Anim.scroll = function(el, args, duration, easing, cb, scope) {
return Ext.lib.Anim.run(el, args, duration, easing, cb, scope, Ext.lib.Scroll);
}
Ext.lib.Scroll = function(el, attributes, duration, method) {
if (el) {
Ext.lib.Scroll.superclass.constructor.call(this, el, attributes, duration, method);
}
};
Ext.extend(Ext.lib.Scroll, Ext.lib.ColorAnim);
var Y = Ext.lib,
superclass = Y.Scroll.superclass,
SCROLL = 'scroll';
Ext.apply(Y.Scroll.prototype, {
toString : function() {
var el = this.el;
return ("Scroll " + (el.id || el.tagName));
},
doMethod : function(attr, start, end) {
var val,
me = this,
curFrame = me.curFrame,
totalFrames = me.totalFrames;
if (attr == SCROLL) {
val = [me.method(curFrame, start[0], end[0] - start[0], totalFrames),
me.method(curFrame, start[1], end[1] - start[1], totalFrames)];
} else {
val = superclass.doMethod.call(me, attr, start, end);
}
return val;
},
getAttr : function(attr) {
var val = null,
me = this;
if (attr == SCROLL) {
val = [ me.el.scrollLeft, me.el.scrollTop ];
} else {
val = superclass.getAttr.call(me, attr);
}
return val;
},
setAttr : function(attr, val, unit) {
var me = this;
if (attr == SCROLL) {
me.el.scrollLeft = val[0];
me.el.scrollTop = val[1];
} else {
superclass.setAttr.call(me, attr, val, unit);
}
}
});
})(); | JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
(function(){
var EXTLIB = Ext.lib,
noNegativesRE = /width|height|opacity|padding/i,
defaultUnitRE = /width|height|top$|bottom$|left$|right$/i,
offsetUnitRE = /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i;
EXTLIB.Anim = {
motion : function(el, args, duration, easing, cb, scope) {
return this.run(el, args, duration, easing, cb, scope, EXTLIB.Motion);
},
run : function(el, args, duration, easing, cb, scope, type) {
type = type || EXTLIB.AnimBase;
anim = new type(el, args, duration, EXTLIB.Easing[easing] || easing);
anim.animate(function() {
if(cb) cb.call(scope);
});
return anim;
}
};
EXTLIB.AnimBase = function(el, attrs, duration, method) {
if (el) {
this.init(el, attrs, duration, method);
}
};
EXTLIB.AnimBase.prototype = {
doMethod: function(attr, start, end) {
var me = this;
return me.method(me.curFrame, start, end - start, me.totalFrames);
},
setAttr: function(attr, val, unit) {
if (noNegativesRE.test(attr) && val < 0) {
val = 0;
}
Ext.fly(this.el, '_anim').setStyle(attr, val + unit);
},
getAttr: function(attr) {
var flyEl = fly(this.el),
val = flyEl.getStyle(attr),
getter;
if (val !== 'auto' && !offsetUnitRE.test(val)) {
return parseFloat(val);
}
getter = flyEl['get' + attr.charAt(0).toUpperCase() + attr.substr(1)];
return getter ? getter.call(flyEl) : 0;
},
setRunAttr: function(attr) {
var me = this,
isEmpty = Ext.isEmpty,
a = me.attrs[attr],
unit = a.unit,
by = a.by,
from = a.from,
to = a.to,
ra = (me.runAttrs[attr] = {}),
start,
end;
if (isEmpty(to) && isEmpty(by)) return false;
start = !isEmpty(from) ? from : me.getAttr(attr);
end = !isEmpty(to) ? to : [];
if (!isEmpty(by)) {
if (Ext.isArray(start)) {
Ext.each(start, function(v,i,s){ end[i] = v + by[i];});
} else {
end = start + by;
}
}
ra.start = start;
ra.end = end;
ra.unit = !isEmpty(unit) ? unit : (defaultUnitRE.test(attr) ? 'px' : '');
},
init : function(el, attribute, duration, method) {
var me = this,
actualFrames = 0,
ease = EXTLIB.Easing,
anmgr = EXTLIB.AnimMgr;
me.attrs = attribute || {};
me.dur = duration || 1;
me.method = method || ease.easeNone;
me.useSec = true;
me.curFrame = 0;
me.totalFrames = anmgr.fps;
me.el = Ext.getDom(el);
me.isAnimated = false;
me.startTime = null;
me.runAttrs = {};
me.animate = function(callback, scope) {
function f() {
var me = this;
me.onComplete.removeListener(f);
if (typeof callback == "function") {
callback.call(scope || me, me);
}
};
var me = this;
me.onComplete.addListener(f, me);
me.curFrame = 0;
me.totalFrames = ( me.useSec ) ? Math.ceil(anmgr.fps * duration) : duration;
if (!me.isAnimated) anmgr.registerElement(me);
};
me.stop = function(finish) {
if (finish) {
me.curFrame = me.totalFrames;
me._onTween.fire();
}
anmgr.stop(me);
};
function onStart() {
me.onStart.fire();
me.runAttrs = {};
for (var attr in me.attrs) {
me.setRunAttr(attr);
}
me.isAnimated = !!(me.startTime = new Date());
actualFrames = 0;
};
function onTween() {
me.onTween.fire({
duration: new Date() - me.startTime,
curFrame: me.curFrame
});
for (var attr in me.runAttrs) {
var ra = me.runAttrs[attr];
me.setAttr(attr, me.doMethod(attr, ra.start, ra.end), ra.unit);
}
actualFrames++;
};
function onComplete() {
me.isAnimated = false;
me.onComplete.fire({
duration: (new Date() - me.startTime) / 1000,
frames: actualFrames,
fps: actualFrames / this.duration
});
actualFrames = 0;
};
me.onStart = new Ext.util.Event(me);
me.onTween = new Ext.util.Event(me);
me.onComplete = new Ext.util.Event(me);
(me._onStart = new Ext.util.Event(me)).addListener(onStart);
(me._onTween = new Ext.util.Event(me)).addListener(onTween);
(me._onComplete = new Ext.util.Event(me)).addListener(onComplete);
}
};
EXTLIB.AnimMgr = function() {
var thread = new Ext.util.TaskRunner(),
pub;
function correctFrame(tween) {
var frames = tween.totalFrames,
frame = tween.curFrame,
duration = tween.dur,
expected = (frame * duration * 1000 / frames),
elapsed = (new Date() - tween.startTime),
tweak = 0;
if (elapsed < duration * 1000) {
tweak = Math.round((elapsed / expected - 1) * frame);
} else {
tweak = frames - (frame + 1);
}
if (tweak > 0 && isFinite(tweak)) {
if (frame + tweak >= frames) {
tweak = frames - (frame + 1);
}
tween.curFrame += tweak;
}
};
pub = {
fps : 1000,
delay : 1,
registerElement : function(tween) {
tween.run = function(tween){
if (!tween || !tween.isAnimated) {
return;
}
if (tween.curFrame++ < tween.totalFrames) {
if (tween.useSec) {
correctFrame(tween);
}
tween._onTween.fire();
} else {
pub.stop(tween);
}
};
tween.args = [tween];
tween.scope = pub;
tween.onStop = function(){
tween._onComplete.fire();
};
tween.interval = pub.delay;
thread.start(tween);
tween._onStart.fire();
},
stop : function(tween) {
thread.stop(tween);
}
}
return pub;
}();
EXTLIB.Easing = {
easeNone: function (t, b, c, d) {
return c * t / d + b;
},
easeIn: function (t, b, c, d) {
return c * (t /= d) * t + b;
},
easeOut: function (t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}
};
// Motion animation
(function() {
// private
function bezier (points, t) {
var len = points.length,
tmp = points.slice(0),
C = (1 - t),
i,
j;
for (j = 1; j < len; ++j) {
for (i = 0; i < len - j; ++i) {
var ti = tmp[i];
ti[0] = C * ti[0] + t * tmp[i + 1][0];
ti[1] = C * ti[1] + t * tmp[i + 1][1];
}
}
return [tmp[0][0], tmp[0][1]];
}
EXTLIB.Motion = function(el, attrs, duration, method) {
if (el) {
EXTLIB.Motion.superclass.constructor.call(this, el, attrs, duration, method);
}
};
Ext.extend(EXTLIB.Motion, EXTLIB.AnimBase);
var superclass = EXTLIB.Motion.superclass,
pointsRE = /^points$/i;
Ext.apply(EXTLIB.Motion.prototype, {
setAttr : function(attr, val, unit) {
var setAttr = superclass.setAttr,
me = this;
if (pointsRE.test(attr)) {
unit = unit || 'px';
setAttr.call(me, 'left', val[0], unit);
setAttr.call(me, 'top', val[1], unit);
} else {
setAttr.call(me, attr, val, unit);
}
},
getAttr : function(attr) {
var getAttr = superclass.getAttr,
me = this;
return pointsRE.test(attr) ?
[getAttr.call(me,'left'),getAttr.call(me,'top')] :
getAttr.call(me,attr);
},
doMethod : function(attr, start, end) {
var me = this;
return pointsRE.test(attr)
? bezier(me.runAttrs[attr],
me.method(me.curFrame, 0, 100, me.totalFrames) / 100)
: superclass.doMethod.call(me, attr, start, end);
},
setRunAttr : function(attr) {
var me = this;
if (pointsRE.test(attr)) {
var el = me.el,
attrs = me.attrs,
points = attrs.points,
control = points.control || [],
runAttrs = me.runAttrs,
getXY = EXTLIB.Dom.getXY,
from = attrs.points.from || getXY(el),
start;
function translateValues(val, start, to) {
var pageXY = to ? getXY(me.el) : [0,0];
return val ? [(val[0] || 0) - pageXY[0] + start[0],
(val[1] || 0) - pageXY[1] + start[1]]
: null;
}
control = typeof control == "string" ? [control] : Ext.toArray(control);
Ext.fly(el, '_anim').position();
EXTLIB.Dom.setXY(el, from);
// now set the attribute
runAttrs[attr] = [start = me.getAttr('points')].concat(control);
// add end calculation to the attribute array. It could be null
runAttrs[attr].push(
translateValues( points.to || points.by || null, start, !Ext.isEmpty(points.to))
);
}
else {
superclass.setRunAttr.call(me, attr);
}
}
});
})();
})(); | JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
(function(){
var doc = document,
isCSS1 = doc.compatMode == "CSS1Compat",
MAX = Math.max,
PARSEINT = parseInt;
Ext.lib.Dom = {
/*
c是否是p的子元素
*/
isAncestor : function(p, c) {
var ret = false;
p = Ext.getDom(p);
c = Ext.getDom(c);
if (p && c) {
if (p.contains) {
return p.contains(c);
} else if (p.compareDocumentPosition) {
return !!(p.compareDocumentPosition(c) & 16);
} else {
while (c = c.parentNode) {
ret = c == p || ret;
}
}
}
return ret;
},
/*
如果full为真返回页面的实际宽度,否则返回可视宽度
*/
getViewWidth : function(full) {
return full ? this.getDocumentWidth() : this.getViewportWidth();
},
/*
如果full为真返回页面的实际高度,否则返回可视高度
*/
getViewHeight : function(full) {
return full ? this.getDocumentHeight() : this.getViewportHeight();
},
/*
得到页面的实际高度
*/
getDocumentHeight: function() {
return MAX(!isCSS1 ? doc.body.scrollHeight : doc.documentElement.scrollHeight, this.getViewportHeight());
},
/*
得到页面的实际宽度
*/
getDocumentWidth: function() {
return MAX(!isCSS1 ? doc.body.scrollWidth : doc.documentElement.scrollWidth, this.getViewportWidth());
},
/*
得到页面的可视高度
*/
getViewportHeight: function(){
return Ext.isIE ?
(Ext.isStrict ? doc.documentElement.clientHeight : doc.body.clientHeight) :
self.innerHeight;
},
/*
得到页面的可视宽度
*/
getViewportWidth : function() {
return !Ext.isStrict && !Ext.isOpera ? doc.body.clientWidth :
Ext.isIE ? doc.documentElement.clientWidth : self.innerWidth;
},
/*
得到给定元素的top
*/
getY : function(el) {
return this.getXY(el)[1];
},
/*
得到给定元素的left
*/
getX : function(el) {
return this.getXY(el)[0];
},
/*
得到给定元素的[top,left]
*/
getXY : function(el) {
var p,
pe,
b,
bt,
bl,
dbd,
x = 0,
y = 0,
scroll,
hasAbsolute,
bd = (doc.body || doc.documentElement),
ret = [0,0];
el = Ext.getDom(el);
if(el != bd){
if (el.getBoundingClientRect) {
b = el.getBoundingClientRect();
scroll = fly(document).getScroll();
ret = [b.left + scroll.left, b.top + scroll.top];
} else {
p = el;
hasAbsolute = fly(el).isStyle("position", "absolute");
while (p) {
pe = fly(p);
x += p.offsetLeft;
y += p.offsetTop;
hasAbsolute = hasAbsolute || pe.isStyle("position", "absolute");
if (Ext.isGecko) {
y += bt = PARSEINT(pe.getStyle("borderTopWidth"), 10) || 0;
x += bl = PARSEINT(pe.getStyle("borderLeftWidth"), 10) || 0;
if (p != el && !pe.isStyle('overflow','visible')) {
x += bl;
y += bt;
}
}
p = p.offsetParent;
}
if (Ext.isSafari && hasAbsolute) {
x -= bd.offsetLeft;
y -= bd.offsetTop;
}
if (Ext.isGecko && !hasAbsolute) {
dbd = fly(bd);
x += PARSEINT(dbd.getStyle("borderLeftWidth"), 10) || 0;
y += PARSEINT(dbd.getStyle("borderTopWidth"), 10) || 0;
}
p = el.parentNode;
while (p && p != bd) {
if (!Ext.isOpera || (p.tagName != 'TR' && !fly(p).isStyle("display", "inline"))) {
x -= p.scrollLeft;
y -= p.scrollTop;
}
p = p.parentNode;
}
ret = [x,y];
}
}
return ret
},
/*
设置给定元素的top,left
*/
setXY : function(el, xy) {
(el = Ext.fly(el, '_setXY')).position();
var pts = el.translatePoints(xy),
style = el.dom.style,
pos;
for (pos in pts) {
if(!isNaN(pts[pos])) style[pos] = pts[pos] + "px"
}
},
/*
设置给定元素的left
*/
setX : function(el, x) {
this.setXY(el, [x, false]);
},
/*
设置给定元素的top
*/
setY : function(el, y) {
this.setXY(el, [false, y]);
}
};
})(); | JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/*
ext中用到的最主要的设计模式flyweight设计模式
el是dom元素
返回一个Ext.Element对象
*/
(function(){
var libFlyweight;
function fly(el) {
if (!libFlyweight) {
libFlyweight = new Ext.Element.Flyweight();
}
libFlyweight.dom = el;
return libFlyweight;
}
| JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/*
* Portions of this file are based on pieces of Yahoo User Interface Library
* Copyright (c) 2007, Yahoo! Inc. All rights reserved.
* YUI licensed under the BSD License:
* http://developer.yahoo.net/yui/license.txt
*/
Ext.lib.Ajax = function() {
var activeX = ['MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'];
// private
function setHeader(o) {
var conn = o.conn,
prop;
function setTheHeaders(conn, headers){
for (prop in headers) {
if (headers.hasOwnProperty(prop)) {
conn.setRequestHeader(prop, headers[prop]);
}
}
}
if (pub.defaultHeaders) {
setTheHeaders(conn, pub.defaultHeaders);
}
if (pub.headers) {
setTheHeaders(conn, pub.headers);
pub.headers = null;
}
}
// private
function createExceptionObject(tId, callbackArg, isAbort) {
return {
tId : tId,
status : isAbort ? -1 : 0,
statusText : isAbort ? 'transaction aborted' : 'communication failure',
argument : callbackArg
};
}
// private
function initHeader(label, value) {
(pub.headers = pub.headers || {})[label] = value;
}
// private
function createResponseObject(o, callbackArg) {
var headerObj = {},
headerStr,
conn = o.conn;
try {
headerStr = o.conn.getAllResponseHeaders();
Ext.each(headerStr.split('\n'), function(v){
var t = v.split(':');
headerObj[t[0]] = t[1];
});
} catch(e) {}
return {
tId : o.tId,
status : conn.status,
statusText : conn.statusText,
getResponseHeader : headerObj,
getAllResponseHeaders : headerStr,
responseText : conn.responseText,
responseXML : conn.responseXML,
argument : callbackArg
};
}
// private
function handleTransactionResponse(o, callback, isAbort) {
var status = o.conn.status,
httpStatus,
responseObject;
if (callback) {
// Not sure the point of the try catch...?
//try {
httpStatus = status || 13030;
//} catch(e) {
// httpStatus = 13030;
//}
if (httpStatus >= 200 && httpStatus < 300) {
responseObject = createResponseObject(o, callback.argument);
if (callback.success) {
callback.success.call(callback.scope, responseObject);
}
} else {
if ([12002, 12029, 12030, 12031, 12152, 13030].indexOf( httpStatus ) > -1) {
responseObject = createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
if (callback.failure) {
callback.failure.call(callback.scope, responseObject);
}
} else {
responseObject = createResponseObject(o, callback.argument);
if (callback.failure) {
callback.failure.call(callback.scope, responseObject);
}
}
}
}
o = o.conn = responseObject = null;
}
// private
function handleReadyState(o, callback){
callback = callback || {};
var conn = o.conn,
tId = o.tId,
poll = pub.poll,
cbTimeout = callback.timeout || null;
if (cbTimeout) {
pub.timeout[tId] = setTimeout(function() {
pub.abort(o, callback, true);
}, cbTimeout);
}
poll[tId] = setInterval(
function() {
if (conn && conn.readyState == 4) {
clearInterval(poll[tId]);
poll[tId] = null;
if (cbTimeout) {
clearTimeout(pub.timeout[tId]);
pub.timeout[tId] = null;
}
handleTransactionResponse(o, callback);
}
},
pub.pollInterval);
}
// private
function asyncRequest(method, uri, callback, postData) {
var o = getConnectionObject() || null;
if (o) {
o.conn.open(method, uri, true);
if (pub.useDefaultXhrHeader) {
initHeader('X-Requested-With', pub.defaultXhrHeader);
}
if(postData && pub.useDefaultHeader && (!pub.headers || !pub.headers['Content-Type'])){
initHeader('Content-Type', pub.defaultPostHeader);
}
if (pub.defaultHeaders || pub.headers) {
setHeader(o);
}
handleReadyState(o, callback);
o.conn.send(postData || null);
}
return o;
}
// private
function getConnectionObject() {
var o;
try {
if (o = createXhrObject(pub.transactionId)) {
pub.transactionId++;
}
} catch(e) {
} finally {
return o;
}
}
// private
function createXhrObject(transactionId) {
var http;
try {
http = new XMLHttpRequest();
} catch(e) {
for (var i = 0; i < activeX.length; ++i) {
try {
http = new ActiveXObject(activeX[i]);
break;
} catch(e) {}
}
} finally {
return {conn : http, tId : transactionId};
}
}
var pub = {
request : function(method, uri, cb, data, options) {
if(options){
var me = this,
xmlData = options.xmlData,
jsonData = options.jsonData;
Ext.applyIf(me, options);
if(xmlData || jsonData){
initHeader('Content-Type', xmlData ? 'text/xml' : 'application/json');
data = xmlData || Ext.encode(jsonData);
}
}
return asyncRequest(method || options.method || "POST", uri, cb, data);
},
serializeForm : function(form) {
var fElements = form.elements || (document.forms[form] || Ext.getDom(form)).elements,
hasSubmit = false,
encoder = encodeURIComponent,
element,
options,
name,
val,
data = '',
type;
Ext.each(fElements, function(element) {
name = element.name;
type = element.type;
if (!element.disabled && name){
if(/select-(one|multiple)/i.test(type)){
Ext.each(element.options, function(opt) {
if (opt.selected) {
data += String.format("{0}={1}&",
encoder(name),
(opt.hasAttribute ? opt.hasAttribute('value') : opt.getAttribute('value') !== null) ? opt.value : opt.text);
}
});
} else if(!/file|undefined|reset|button/i.test(type)) {
if(!(/radio|checkbox/i.test(type) && !element.checked) && !(type == 'submit' && hasSubmit)){
data += encoder(name) + '=' + encoder(element.value) + '&';
hasSubmit = /submit/i.test(type);
}
}
}
});
return data.substr(0, data.length - 1);
},
useDefaultHeader : true,
defaultPostHeader : 'application/x-www-form-urlencoded; charset=UTF-8',
useDefaultXhrHeader : true,
defaultXhrHeader : 'XMLHttpRequest',
poll : {},
timeout : {},
pollInterval : 50,
transactionId : 0,
// This is never called - Is it worth exposing this?
// setProgId : function(id) {
// activeX.unshift(id);
// },
// This is never called - Is it worth exposing this?
// setDefaultPostHeader : function(b) {
// this.useDefaultHeader = b;
// },
// This is never called - Is it worth exposing this?
// setDefaultXhrHeader : function(b) {
// this.useDefaultXhrHeader = b;
// },
// This is never called - Is it worth exposing this?
// setPollingInterval : function(i) {
// if (typeof i == 'number' && isFinite(i)) {
// this.pollInterval = i;
// }
// },
// This is never called - Is it worth exposing this?
// resetDefaultHeaders : function() {
// this.defaultHeaders = null;
// },
abort : function(o, callback, isTimeout) {
var me = this,
tId = o.tId,
isAbort = false;
if (me.isCallInProgress(o)) {
o.conn.abort();
clearInterval(me.poll[tId]);
me.poll[tId] = null;
if (isTimeout) {
me.timeout[tId] = null;
}
handleTransactionResponse(o, callback, (isAbort = true));
}
return isAbort;
},
isCallInProgress : function(o) {
return o.conn && !{1:1,4:4}[o.conn.readyState];
}
};
return pub;
}(); | JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/*
如果是ie就追加一个fnCleanUp事件
清除ext对于Function原型的扩展
*/
if(Ext.isIE) {
function fnCleanUp() {
var p = Function.prototype;
delete p.createSequence;
delete p.defer;
delete p.createDelegate;
delete p.createCallback;
delete p.createInterceptor;
window.detachEvent("onunload", fnCleanUp);
}
window.attachEvent("onunload", fnCleanUp);
}
})(); | JavaScript |
/*
* Ext Core Library 3.0 Beta
* http://extjs.com/
* Copyright(c) 2006-2009, Ext JS, LLC.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
Ext.lib.Event = function() {
var loadComplete = false,
listeners = [],
unloadListeners = [],
retryCount = 0,
onAvailStack = [],
_interval,
locked = false,
win = window,
doc = document,
// constants
POLL_RETRYS = 200,
POLL_INTERVAL = 20,
EL = 0,
TYPE = 1,
FN = 2,
WFN = 3,
OBJ = 3,
ADJ_SCOPE = 4,
// private
/*
* 返回一个符合当前浏览器的函数用来添加事件,对于非ie下的浏览器也让其可以支持mouseleave/mouseenter
*/
doAdd = function() {
var ret;
if (win.addEventListener) {
ret = function(el, eventName, fn, capture) {
if (eventName == 'mouseenter') {
fn = fn.createInterceptor(checkRelatedTarget);
el.addEventListener('mouseover', fn, (capture));
} else if (eventName == 'mouseleave') {
fn = fn.createInterceptor(checkRelatedTarget);
el.addEventListener('mouseout', fn, (capture));
} else {
el.addEventListener(eventName, fn, (capture));
}
return fn;
};
} else if (win.attachEvent) {
ret = function(el, eventName, fn, capture) {
el.attachEvent("on" + eventName, fn);
return fn;
};
} else {
ret = function(){};
}
return ret;
}(),
// private
/*
* 返回一个符合当前浏览器的函数用来注销事件,对于非ie下的浏览器也让其可以支持mouseleave/mouseenter
*/
doRemove = function(){
var ret;
if (win.removeEventListener) {
ret = function (el, eventName, fn, capture) {
if (eventName == 'mouseenter') {
eventName = 'mouseover'
} else if (eventName == 'mouseleave') {
eventName = 'mouseout'
}
el.removeEventListener(eventName, fn, (capture));
};
} else if (win.detachEvent) {
ret = function (el, eventName, fn) {
el.detachEvent("on" + eventName, fn);
};
} else {
ret = function(){};
}
return ret;
}();
/*
* 判断引起事件触发的元素是否是事件注册元素的子元素或者就是该注册元素
*/
function checkRelatedTarget(e) {
var related = e.relatedTarget,
isXulEl = Object.prototype.toString.apply(related) == '[object XULElement]';
if (!related) return false;
return (!isXulEl && related != this && this.tag != 'document' && !elContains(this, related));
}
/*
* 判断是否是其子元素或者就是其自身
*/
function elContains(parent, child) {
while(child) {
if(child === parent) {
return true;
}
try {
child = child.parentNode;
} catch(e) {
// In FF if you mouseout an text input element
// thats inside a div sometimes it randomly throws
// Permission denied to get property HTMLDivElement.parentNode
// See https://bugzilla.mozilla.org/show_bug.cgi?id=208427
//如果在ff 1.5版本下,对一个input text元素添加mouseout/mouseover时,他的父级是一个div那么在r = e.relatedTarget,while(r=r.parentNode)时会抛异常
//这个问题我在3.0的版本上没有发现
return false;
}
if(child && (child.nodeType != 1)) {
child = null;
}
}
return false;
}
/*
* listeners里缓存了所有添加的事件的名字,dom对象,时间函数等
* 这个就是返回参数el,eventName,fn该组事件在listeners中的索引
* 如果存在返回位置,不存在返回-1
*/
// private
function _getCacheIndex(el, eventName, fn) {
var index = -1;
Ext.each(listeners, function (v,i) {
if(v && v[FN] == fn && v[EL] == el && v[TYPE] == eventName) {
index = i;
}
});
return index;
}
// private
function _tryPreloadAttach() {
var ret = false,
notAvail = [],
element,
tryAgain = !loadComplete || (retryCount > 0);
if (!locked) {
locked = true;
Ext.each(onAvailStack, function (v,i,a){
if(v && (element = doc.getElementById(v.id))){
if(!v.checkReady || loadComplete || element.nextSibling || (doc && doc.body)) {
element = v.override ? (v.override === true ? v.obj : v.override) : element;
v.fn.call(element, v.obj);
onAvailStack[i] = null;
} else {
notAvail.push(item);
}
}
});
retryCount = (notAvail.length == 0) ? 0 : retryCount - 1;
if (tryAgain) {
startInterval();
} else {
clearInterval(_interval);
_interval = null;
}
ret = !(locked = false);
}
return ret;
}
// private
function startInterval() {
if (!Ext.isEmpty(_interval)) {
var callback = function() {
_tryPreloadAttach();
};
_interval = setInterval(callback, pub.POLL_INTERVAL);
}
}
/*
* 得到
*/
// private
function getScroll() {
var scroll = Ext.get(doc).getScroll();
return [scroll.top, scroll.top];
}
// private
function getPageCoord (ev, xy) {
ev = ev.browserEvent || ev;
var coord = ev['page' + xy];
if (!coord && 0 != coord) {
coord = ev['client' + xy] || 0;
if (Ext.isIE) {
coord += getScroll()[xy == "X" ? 0 : 1];
}
}
return coord;
}
var pub = {
onAvailable : function(p_id, p_fn, p_obj, p_override) {
onAvailStack.push({
id: p_id,
fn: p_fn,
obj: p_obj,
override: p_override,
checkReady: false });
retryCount = this.POLL_RETRYS;
startInterval();
},
addListener: function(el, eventName, fn) {
var ret;
el = Ext.getDom(el);
if (el && fn) {
if ("unload" == eventName) {
ret = !!(unloadListeners[unloadListeners.length] = [el, eventName, fn]);
} else {
listeners.push([el, eventName, fn, ret = doAdd(el, eventName, fn, false)]);
}
}
return !!ret;
},
removeListener: function(el, eventName, fn) {
var ret = false,
index,
cacheItem;
el = Ext.getDom(el);
if(!fn) {
ret = this.purgeElement(el, false, eventName);
} else if ("unload" == eventName) {
Ext.each(unloadListeners, function(v, i, a) {
if( v && v[0] == el && v[1] == evantName && v[2] == fn) {
unloadListeners.splice(i, 1);
ret = true;
}
});
} else {
index = arguments[3] || _getCacheIndex(el, eventName, fn);
cacheItem = listeners[index];
if (el && cacheItem) {
doRemove(el, eventName, cacheItem[WFN], false);
cacheItem[WFN] = cacheItem[FN] = null;
listeners.splice(index, 1);
ret = true;
}
}
return ret;
},
getTarget : function(ev) {
ev = ev.browserEvent || ev;
return this.resolveTextNode(ev.target || ev.srcElement);
},
resolveTextNode : function(node) {
return Ext.isSafari && node && 3 == node.nodeType ? node.parentNode : node;
},
getPageX : function(ev) {
return getPageCoord(ev, "X");
},
getPageY : function(ev) {
return getPageCoord(ev, "Y");
},
getXY : function(ev) {
return [this.getPageX(ev), this.getPageY(ev)];
},
getRelatedTarget : function(ev) {
ev = ev.browserEvent || ev;
return this.resolveTextNode(ev.relatedTarget ||
(ev.type == "mouseout" ? ev.toElement :
ev.type == "mouseover" ? ev.fromElement : null));
},
// Is this useful? Removing to save space unless use case exists.
// getTime: function(ev) {
// ev = ev.browserEvent || ev;
// if (!ev.time) {
// var t = new Date().getTime();
// try {
// ev.time = t;
// } catch(ex) {
// return t;
// }
// }
// return ev.time;
// },
stopEvent : function(ev) {
this.stopPropagation(ev);
this.preventDefault(ev);
},
stopPropagation : function(ev) {
ev = ev.browserEvent || ev;
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
},
preventDefault : function(ev) {
ev = ev.browserEvent || ev;
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
},
getEvent : function(e) {
e = e || win.event;
if (!e) {
var c = this.getEvent.caller;
while (c) {
e = c.arguments[0];
if (e && Event == e.constructor) {
break;
}
c = c.caller;
}
}
return e;
},
getCharCode : function(ev) {
ev = ev.browserEvent || ev;
return ev.charCode || ev.keyCode || 0;
},
//clearCache: function() {},
_load : function(e) {
loadComplete = true;
var EU = Ext.lib.Event;
if (Ext.isIE) {
doRemove(win, "load", EU._load);
}
},
purgeElement : function(el, recurse, eventName) {
var me = this;
Ext.each( me.getListeners(el, eventName), function(v){
if(v) me.removeListener(el, v.type, v.fn);
});
if (recurse && el && el.childNodes) {
Ext.each(el.childNodes, function(v){
me.purgeElement(v, recurse, eventName);
});
}
},
getListeners : function(el, eventName) {
var me = this,
results = [],
searchLists = [listeners, unloadListeners];
if (eventName) {
searchLists.splice(eventName == "unload" ? 0 : 1 ,1);
} else {
searchLists = searchLists[0].concat(searchLists[1]);
}
Ext.each(searchLists, function(v, i){
if (v && v[me.EL] == el && (!eventName || eventName == v[me.type])) {
results.push({
type: v[TYPE],
fn: v[FN],
obj: v[OBJ],
adjust: v[ADJ_SCOPE],
index: i
});
}
});
return results.length ? results : null;
},
_unload : function(e) {
var EU = Ext.lib.Event,
i,
j,
l,
len,
index,
scope;
Ext.each(unloadListeners, function(v) {
if (v) {
scope = v[ADJ_SCOPE] ? (v[ADJ_SCOPE] === true ? v[OBJ] : v[ADJ_SCOPE]) : win;
v[FN].call(scope, EU.getEvent(e), v[OBJ]);
}
});
unloadListeners = null;
if (listeners && (j = listeners.length)) {
while (j) {
if (l = listeners[index = --j]) {
EU.removeListener(l[EL], l[TYPE], l[FN], index);
}
}
//EU.clearCache();
}
doRemove(win, "unload", EU._unload);
}
};
// Initialize stuff.
pub.on = pub.addListener;
pub.un = pub.removeListener;
if (doc && doc.body) {
pub._load();
} else {
doAdd(win, "load", pub._load);
}
doAdd(win, "unload", pub._unload);
_tryPreloadAttach();
return pub;
}(); | 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.util.CSS
* 操控CSS规则的工具类
* @singleton
*/
Ext.util.CSS = function(){
var rules = null;
var doc = document;
var camelRe = /(-[a-z])/gi;
var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); };
return {
/**
* 动态生成样式表。用style标签围绕样式后加入到文档头部中。
* @param {String} cssText 包含css的文本
* @return {StyleSheet}
*/
createStyleSheet : function(cssText, id){
var ss;
var head = doc.getElementsByTagName("head")[0];
var rules = doc.createElement("style");
rules.setAttribute("type", "text/css");
if(id){
rules.setAttribute("id", id);
}
if(Ext.isIE){
head.appendChild(rules);
ss = rules.styleSheet;
ss.cssText = cssText;
}else{
try{
rules.appendChild(doc.createTextNode(cssText));
}catch(e){
rules.cssText = cssText;
}
head.appendChild(rules);
ss = rules.styleSheet ? rules.styleSheet : (rules.sheet || doc.styleSheets[doc.styleSheets.length-1]);
}
this.cacheStyleSheet(ss);
return ss;
},
/**
* 由id移除样式或连接
* @param {String} id 标签的ID
*/
removeStyleSheet : function(id){
var existing = doc.getElementById(id);
if(existing){
existing.parentNode.removeChild(existing);
}
},
/**
* 动态交换现有的样式,指向新的一个
* @param {String} id 要移除的现有链接标签的ID
* @param {String} url 要包含新样式表的href
*/
swapStyleSheet : function(id, url){
this.removeStyleSheet(id);
var ss = doc.createElement("link");
ss.setAttribute("rel", "stylesheet");
ss.setAttribute("type", "text/css");
ss.setAttribute("id", id);
ss.setAttribute("href", url);
doc.getElementsByTagName("head")[0].appendChild(ss);
},
/**
* 如果动态地加入样式表,刷新样式cache。
* @return {Object} 由选择器索引的样式对象(hash)
*/
refreshCache : function(){
return this.getRules(true);
},
// private
cacheStyleSheet : function(ss){
if(!rules){
rules = {};
}
try{// try catch for cross domain access issue
var ssRules = ss.cssRules || ss.rules;
for(var j = ssRules.length-1; j >= 0; --j){
rules[ssRules[j].selectorText] = ssRules[j];
}
}catch(e){}
},
/**
* 获取文档内的所有的CSS rules
* @param {Boolean} refreshCache true:刷新内置缓存
* @return {Object} 由选择器索引的样式对象(hash)
*/
getRules : function(refreshCache){
if(rules == null || refreshCache){
rules = {};
var ds = doc.styleSheets;
for(var i =0, len = ds.length; i < len; i++){
try{
this.cacheStyleSheet(ds[i]);
}catch(e){}
}
}
return rules;
},
/**
* 由选择符获取不同的CSS规则
* @param {String/Array} selector 选择符支持数组,在匹配第一个结果后立刻停止继续寻找
* @param {Boolean} refreshCache true表示为如果你最近有更新或新加样式的话,就刷新内置缓存
* @return {CSSRule} 找到的CSS rule或null(找不到)
*/
getRule : function(selector, refreshCache){
var rs = this.getRules(refreshCache);
if(!(selector instanceof Array)){
return rs[selector];
}
for(var i = 0; i < selector.length; i++){
if(rs[selector[i]]){
return rs[selector[i]];
}
}
return null;
},
/**
* 更新样式属性
* @param {String/Array} selector 选择符支持数组,在匹配第一个结果后立刻停止继续寻找
* @param {String} property css属性
* @param {String} value 属性的新值
* @return {Boolean} true:如果样式找到并更新
*/
updateRule : function(selector, property, value){
if(!(selector instanceof Array)){
var rule = this.getRule(selector);
if(rule){
rule.style[property.replace(camelRe, camelFn)] = value;
return true;
}
}else{
for(var i = 0; i < selector.length; i++){
if(this.updateRule(selector[i], property, value)){
return true;
}
}
}
return false;
}
};
}(); | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.util.Format
* 可复用的数据格式化函数。
* @singleton
*/
Ext.util.Format = function(){
var trimRe = /^\s+|\s+$/g;
return {
/**
* 对大于指定长度部分的字符串,进行裁剪,增加省略号(“...”)的显示。
* @param {String} value 要裁剪的字符串
* @param {Number} length 允许的最大长度
* @param {Boolean} word True表示尝试以一个单词来结束
* @return {String} 转换后的文本
*/
ellipsis : function(value, len, word){
if(value && value.length > len){
if(word){
var vs = value.substr(0, len - 2);
var index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
if(index == -1 || index < (len - 15)){
return value.substr(0, len - 3) + "...";
}else{
return vs.substr(0, index) + "...";
}
} else{
return value.substr(0, len - 3) + "...";
}
}
return value;
},
/**
* 检查一个引用值是否为underfined,若是的话转换其为空值。
* @param {Mixed} value 要检查的值
* @return {Mixed} 转换成功为空白字符串,否则为原来的值
*/
undef : function(value){
return value !== undefined ? value : "";
},
/**
* 检查一个引用值是否为空,若是则转换到缺省值。
* @param {Mixed} value 要检查的引用值
* @param {String} defaultValue 默认赋予的值(默认为"")
* @return {String}
*/
defaultValue : function(value, defaultValue){
return value !== undefined && value !== '' ? value : defaultValue;
},
/**
* 为能在HTML显示的字符转义&、<、>以及'。
* @param {String} value 要编码的字符串
* @return {String} 编码后的文本
*/
htmlEncode : function(value){
return !value ? value : String(value).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
},
/**
* 将&, <, >, and '字符从HTML显示的格式还原。
* @param {String} value 解码的字符串
* @return {String} 编码后的文本
*/
htmlDecode : function(value){
return !value ? value : String(value).replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"').replace(/&/g, "&");
},
/**
* 裁剪一段文本的前后多余的空格。
* @param {String} value 要裁剪的文本
* @return {String} 裁剪后的文本
*/
trim : function(value){
return String(value).replace(trimRe, "");
},
/**
* 返回一个从指定位置开始的指定长度的子字符串。
* @param {String} value 原始文本
* @param {Number} start 所需的子字符串的起始位置
* @param {Number} length 在返回的子字符串中应包括的字符个数。
* @return {String} 指定长度的子字符串
*/
substr : function(value, start, length){
return String(value).substr(start, length);
},
/**
* 返回一个字符串,该字符串中的字母被转换为小写字母。
* @param {String} value 要转换的字符串
* @return {String} 转换后的字符串
*/
lowercase : function(value){
return String(value).toLowerCase();
},
/**
* 返回一个字符串,该字符串中的字母被转换为大写字母。
* @param {String} value 要转换的字符串
* @return {String} 转换后的字符串
*/
uppercase : function(value){
return String(value).toUpperCase();
},
/**
* 返回一个字符串,该字符串中的第一个字母转化为大写字母,剩余的为小写。
* @param {String} value 要转换的字符串
* @return {String} 转换后的字符串
*/
capitalize : function(value){
return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
},
// private
call : function(value, fn){
if(arguments.length > 2){
var args = Array.prototype.slice.call(arguments, 2);
args.unshift(value);
return eval(fn).apply(window, args);
}else{
return eval(fn).call(window, value);
}
},
/**
* 格式化数字到美元货币
* @param {Number/String} value 要格式化的数字
* @return {String} 已格式化的货币
*/
usMoney : function(v){
v = (Math.round((v-0)*100))/100;
v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
v = String(v);
var ps = v.split('.');
var whole = ps[0];
var sub = ps[1] ? '.'+ ps[1] : '.00';
var r = /(\d+)(\d{3})/;
while (r.test(whole)) {
whole = whole.replace(r, '$1' + ',' + '$2');
}
v = whole + sub;
if(v.charAt(0) == '-'){
return '-$' + v.substr(1);
}
return "$" + v;
},
/**
* 将某个值解析成为一个特定格式的日期。
* @param {Mixed} value 要格式化的值
* @param {String} format (可选的)任何有效的日期字符串(默认为“月/日/年”)
* @return {Function} 日期格式函数
*/
date : function(v, format){
if(!v){
return "";
}
if(!Ext.isDate(v)){
v = new Date(Date.parse(v));
}
return v.dateFormat(format || "m/d/Y");
},
/**
* 返回一个函数,该函数的作用是渲染日期格式,便于复用。
* @param {String} format 任何有效的日期字符串
* @return {Function} 日期格式函数
*/
dateRenderer : function(format){
return function(v){
return Ext.util.Format.date(v, format);
};
},
// private
stripTagsRE : /<\/?[^>]+>/gi,
/**
* 剥去所有HTML标签。
* @param {Mixed} value 要剥去的文本
* @return {String} 剥去后的HTML标签
*/
stripTags : function(v){
return !v ? v : String(v).replace(this.stripTagsRE, "");
},
stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
/**
* 剥去所有脚本(<script>...</script>)标签
* @param {Mixed} value 要剥去的文本
* @return {String} 剥去后的HTML标签
*/
stripScripts : function(v){
return !v ? v : String(v).replace(this.stripScriptsRe, "");
},
/**
* 对文件大小进行简单的格式化(xxx bytes、xxx KB、xxx MB)
* @param {Number/String} size 要格式化的数值
* @return {String} 已格式化的值
*/
fileSize : function(size){
if(size < 1024) {
return size + " bytes";
} else if(size < 1048576) {
return (Math.round(((size*10) / 1024))/10) + " KB";
} else {
return (Math.round(((size*10) / 1048576))/10) + " MB";
}
},
math : function(){
var fns = {};
return function(v, a){
if(!fns[a]){
fns[a] = new Function('v', 'return v ' + a + ';');
}
return fns[a](v);
}
}(),
/**
* 依据某种(字符串)格式来转换数字。
* <div style="margin-left:40px">例子 (123456.789):
* <div style="margin-left:10px">
* 0 - (123456) 只显示整数,没有小数位<br>
* 0.00 - (123456.78) 显示整数,保留两位小数位<br>
* 0.0000 - (123456.7890) 显示整数,保留四位小数位<br>
* 0,000 - (123,456) 只显示整数,用逗号分开<br>
* 0,000.00 - (123,456.78) 显示整数,用逗号分开,保留两位小数位<br>
* 0,0.00 - (123,456.78) 快捷方法,显示整数,用逗号分开,保留两位小数位<br>
* 在一些国际化的场合需要反转分组(,)和小数位(.),那么就在后面加上/i
* 例如: 0.000,00/i
* </div></div>
*
* @method format
* @param {Number} v 要转换的数字。
* @param {String} format 格式化数字的“模”。
* @return {String} 已转换的数字。
* @public
*/
number: function(v, format) {
if(!format){
return v;
}
v *= 1;
if(typeof v != 'number' || isNaN(v)){
return '';
}
var comma = ',';
var dec = '.';
var i18n = false;
if(format.substr(format.length - 2) == '/i'){
format = format.substr(0, format.length-2);
i18n = true;
comma = '.';
dec = ',';
}
var hasComma = format.indexOf(comma) != -1,
psplit = (i18n ? format.replace(/[^\d\,]/g,'') : format.replace(/[^\d\.]/g,'')).split(dec);
if (1 < psplit.length) {
v = v.toFixed(psplit[1].length);
}
else if (2 < psplit.length) {
throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
}
else {
v = v.toFixed(0);
}
var fnum = v.toString();
if (hasComma) {
psplit = fnum.split('.');
var cnum = psplit[0],
parr = [],
j = cnum.length,
m = Math.floor(j / 3),
n = cnum.length % 3 || 3;
for (var i = 0; i < j; i += n) {
if (i != 0) {n = 3;}
parr[parr.length] = cnum.substr(i, n);
m -= 1;
}
fnum = parr.join(comma);
if (psplit[1]) {
fnum += dec + psplit[1];
}
}
return format.replace(/[\d,?\.?]+/, fnum);
},
/**
* 在多次转换数字时,为提高效率,不断复用由这个方法返回的函数。
* @param {String} format 任何{@link #number}可接受的字符串
* @return {Function} 数字格式化函数
*/
numberRenderer : function(format){
return function(v){
return Ext.util.Format.number(v, format);
};
},
/**
* 可选地为一个单词转为为复数形式。例如在模板中,{commentCount:plural("Comment")}这样的模板语言如果commentCount是1那就是 "1 Comment";
* 如果是0或者大于1就是"x Comments"。
* @param {Number} value 参与比较的数
* @param {String} singular 单词的单数形式
* @param {String} plural (可选的) 单词的复数部分(默认为加上's')
*/
plural : function(v, s, p){
return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
}
}
}(); | 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.util.DelayedTask
* 提供快捷的方法执行setTimeout,新的超时时限会取消旧的超时时限.
* 例如验证表单的时候,键盘按下(keypress)那一瞬,就可用上该类(不会立即验证表单,稍作延时)。
* keypress事件会稍作停顿之后(某个时间)才继续执行。
* Provides a convenient method of performing setTimeout where a new
* timeout cancels the old timeout. An example would be performing validation on a keypress.
* You can use this class to buffer
* the keypress events for a certain number of milliseconds, and perform only if they stop
* for that amount of time.
* @constructor 该构建器无须参数,用默认的即可。The parameters to this constructor serve as defaults and are not required.
* @param {Function} fn (可选的) 默认超时的函数(optional) The default function to timeout
* @param {Object} scope (可选的) 默认超时的作用域(optional) The default scope of that timeout
* @param {Array} args (可选的) 默认参数数组(optional) The default Array of arguments
*/
Ext.util.DelayedTask = function(fn, scope, args){
var id = null, d, t;
var call = function(){
var now = new Date().getTime();
if(now - t >= d){
clearInterval(id);
id = null;
fn.apply(scope, args || []);
}
};
/**
* 取消所有待定的超时(any pending timeout),并重新排列(queues)。
* Cancels any pending timeout and queues a new one
* @param {Number} delay 延迟毫秒数The milliseconds to delay
* @param {Function} newFn (可选的) 重写传入到构建器的函数(optional) Overrides function passed to constructor
* @param {Object} newScope (可选的) 重写传入到构建器的作用域(optional) Overrides scope passed to constructor
* @param {Array} newArgs (可选的) 重写传入到构建器的参数(optional) Overrides args passed to constructor
*/
this.delay = function(delay, newFn, newScope, newArgs){
if(id && delay != d){
this.cancel();
}
d = delay;
t = new Date().getTime();
fn = newFn || fn;
scope = newScope || scope;
args = newArgs || args;
if(!id){
id = setInterval(call, d);
}
};
/**
* 取消最后的排列超时。
* Cancel the last queued timeout
*/
this.cancel = function(){
if(id){
clearInterval(id);
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.util.Observable
* 一个抽象基类(Abstract base class),为事件机制的管理提供一个公共接口。子类应有一个"events"属性来定义所有的事件。
* Abstract base class that provides a common interface for publishing events. Subclasses are expected to
* to have a property "events" with all the events defined.<br>
* 例如:For example:
* <pre><code>
Employee = function(name){
this.name = name;
this.addEvents({
"fired" : true,
"quit" : true
});
}
Ext.extend(Employee, Ext.util.Observable);
</code></pre>
*/
Ext.util.Observable = function(){
/**
* @cfg {Object} listeners (optional) A config object containing one or more event handlers to be added to this
* object during initialization. This should be a valid listeners config object as specified in the
* {@link #addListener} example for attaching multiple handlers at once.
*/
if(this.listeners){
this.on(this.listeners);
delete this.listeners;
}
if(!this.events){
this.events = {};
}
};
Ext.util.Observable.prototype = {
/**
* 触发指定的事件,并在这里把处理函数的参数传入(应该至少要有事件的名称)。
* Fires the specified event with the passed parameters (minus the event name).
* @param {String} eventName 事件名称The name of the event to fire. If the event is to bubble
* up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) then
* the first argument must be passed as <tt>true</tt>, and the event name is passed
* as the second argument.
* 如果这个事件是要在Observable父类上逐层上报(参阅{@link Ext.Component#getBubbleTarget}),那么第一个参数一定是<tt>true</tt>,然后第二个参数是事件名称。
* @param {Object...} args 传入事件处理函数的参数Variable number of parameters are passed to handlers
* @return {Boolean} 从处理函数返回true或者false returns false if any of the handlers return false otherwise it returns true
*/
fireEvent : function(){
var a = Array.prototype.slice.call(arguments, 0);
var ename = a[0];
if(ename === true){
a.shift();
var c = this;
while(c){
if(c.fireEvent.apply(c, a) === false){
return false;
}
c = c.getBubbleTarget ? c.getBubbleTarget() : null;
}
return true;
}
if(this.eventsSuspended === true){
var q = this.suspendedEventsQueue;
if (q) {
q[q.length] = a;
}
} else {
var ce = this.events[ename.toLowerCase()];
if(typeof ce == "object"){
a.shift();
return ce.fire.apply(ce, a);
}
}
return true;
},
// private
filterOptRe : /^(?:scope|delay|buffer|single)$/,
/**
* 加入一个事件处理函数。{@link #on}是其简写方式。
* Appends an event handler to this element. The shorthand version {@link #on} is equivalent.
* @param {String} eventName 事件处理函数的名称。The type of event to handle
* @param {Function} fn 事件处理函数。该函数会送入以下的参数:The handler function the event invokes. This function is passed
* the following parameters:<ul>
* <li>evt : EventObject<div class="sub-desc">用于描述这次事件{@link Ext.EventObject EventObject}的事件对象。The {@link Ext.EventObject EventObject} describing the event.</div></li>
* <li>t : Element<div class="sub-desc">事件源对象,类型是{@link Ext.Element Element} The {@link Ext.Element Element} which was the target of the event.
* 注意该项可能会选项<tt>delegate</tt>筛选而发生变化Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
* <li>o : Object<div class="sub-desc">调用addListener时送入的选项对象The options object from the addListener call.</div></li>
* </ul>
* @param {Object} scope (可选的) 事件处理函数执行时所在的作用域。处理函数“this”的上下文。(optional) The scope (The <tt>this</tt> reference) of the handler function. Defaults
* to this Element.
* @param {Object} options (可选的) 包含句柄配置属性的一个对象。该对象可能会下来的属性:
* (optional) An object containing handler configuration properties.
* This may contain any of the following properties:<ul>
* <li>scope {Object} : 事件处理函数执行时所在的作用域。处理函数“this”的上下文环境。The scope in which to execute the handler function. The handler function's "this" context.</li>
* <li>delegate {String} : 一个简易选择符,用于过滤目标,或是查找目标的子孙。A simple selector to filter the target or look for a descendant of the target</li>
* <li>stopEvent {Boolean} : true表示为阻止事件。即停止传播、阻止默认动作。True to stop the event. That is stop propagation, and prevent the default action.</li>
* <li>preventDefault {Boolean} : true表示为阻止默认动作。True to prevent the default action</li>
* <li>stopPropagation {Boolean} : true表示为阻止事件传播。True to prevent event propagation</li>
* <li>normalized {Boolean} : false表示对处理函数送入一个原始、未封装过的浏览器对象而非标准的Ext.EventObject。False to pass a browser event to the handler function instead of an Ext.EventObject</li>
* <li>delay {Number} : 触发事件后处理函数延时执行的时间。The number of milliseconds to delay the invocation of the handler after te event fires.</li>
* <li>single {Boolean} : true代表为事件触发后加入一个下次移除本身的处理函数。True to add a handler to handle just the next firing of the event, and then remove itself.</li>
* <li>buffer {Number} : 若指定一个毫秒数会把该处理函数安排到{@link Ext.util.DelayedTask}延时之后才执行。
* 如果事件在那个事件再次触发,则原处理器句柄将<em>不会</em> 被启用,但是新处理器句柄会安排在其位置。Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
* by the specified number of milliseconds. If the event fires again within that time, the original
* handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
* </ul><br>
* <p>
* <b>不同配搭方式的选项 Combining Options</b><br>
* 下面的例子,使用的是{@link #on}的简写方式。和addListener是等价的。
* 利用参数选项,可以组合成不同类型的侦听器:
* In the following examples, the shorthand form {@link #on} is used rather than the more verbose
* addListener. The two are equivalent.
* Using the options argument, it is possible to combine different
* types of listeners:<br>
* <br>
* 这个事件的含义是,已常规化的,延时的,自动停止事件并有传入一个自定义的参数(forumId)的一次性侦听器。这些事件设置在处理函数(也就是第三个的参数)中也可以找到的。
* A normalized, delayed, one-time listener that auto stops the event and adds a custom argument (forumId) to the
* options object. The options object is available as the third parameter in the handler function.<div style="margin: 5px 20px 20px;">
* 代码:Code:<pre><code>
el.on('click', this.onClick, this, {
single: true,
delay: 100,
stopEvent : true,
forumId: 4
});</code></pre></p>
* <p>
* <b>多个处理函数一次性登记。Attaching multiple handlers in 1 call</b><br>
* 这样的话,可允许多个事件处理函数都共享一个配置事件的配置项对象。
* The method also allows for a single argument to be passed which is a config object containing properties
* which specify multiple handlers.</p>
* <p>
* 代码:Code:<pre><code>
el.on({
'click' : {
fn: this.onClick,
scope: this,
delay: 100
},
'mouseover' : {
fn: this.onMouseOver,
scope: this
},
'mouseout' : {
fn: this.onMouseOut,
scope: this
}
});</code></pre></p>
* <p>
* 或者是简写的语法:Or a shorthand syntax:<br>
* Code:<pre><code>
el.on({
'click' : this.onClick,
'mouseover' : this.onMouseOver,
'mouseout' : this.onMouseOut,
scope: this
});</code></pre></p>
*/
addListener : function(eventName, fn, scope, o){
if(typeof eventName == "object"){
o = eventName;
for(var e in o){
if(this.filterOptRe.test(e)){
continue;
}
if(typeof o[e] == "function"){
// shared options
this.addListener(e, o[e], o.scope, o);
}else{
// individual options
this.addListener(e, o[e].fn, o[e].scope, o[e]);
}
}
return;
}
o = (!o || typeof o == "boolean") ? {} : o;
eventName = eventName.toLowerCase();
var ce = this.events[eventName] || true;
if(typeof ce == "boolean"){
ce = new Ext.util.Event(this, eventName);
this.events[eventName] = ce;
}
ce.addListener(fn, scope, o);
},
/**
* 移除侦听器Removes a listener
* @param {String} eventName 侦听事件的类型The type of event to listen for
* @param {Function} handler 移除的处理函数The handler to remove
* @param {Object} scope (可选的) 处理函数之作用域(optional) The scope (this object) for the handler
*/
removeListener : function(eventName, fn, scope){
var ce = this.events[eventName.toLowerCase()];
if(typeof ce == "object"){
ce.removeListener(fn, scope);
}
},
/**
* 从这个对象身上移除所有的侦听器。Removes all listeners for this object
*/
purgeListeners : function(){
for(var evt in this.events){
if(typeof this.events[evt] == "object"){
this.events[evt].clearListeners();
}
}
},
/**
* Relays selected events from the specified Observable as if the events were fired by <tt><b>this</b></tt>.
* @param {Object} o The Observable whose events this object is to relay.
* @param {Array} events Array of event names to relay.
*/
relayEvents : function(o, events){
var createHandler = function(ename){
return function(){
return this.fireEvent.apply(this, Ext.combine(ename, Array.prototype.slice.call(arguments, 0)));
};
};
for(var i = 0, len = events.length; i < len; i++){
var ename = events[i];
if(!this.events[ename]){ this.events[ename] = true; };
o.on(ename, createHandler(ename), this);
}
},
/**
* 定义观察者的事件。Used to define events on this Observable
* @param {Object} o 定义的事件对象。object The object with the events defined
*/
addEvents : function(o){
if(!this.events){
this.events = {};
}
if(typeof o == 'string'){
for(var i = 0, a = arguments, v; v = a[i]; i++){
if(!this.events[a[i]]){
this.events[a[i]] = true;
}
}
}else{
Ext.applyIf(this.events, o);
}
},
/**
* 检测当前对象是否有指定的事件。
* Checks to see if this object has any listeners for a specified event
* @param {String} eventName 要检查的事件名称。The name of the event to check for
* @return {Boolean} True表示有事件正在被监听,否则为false。True if the event is being listened for, else false
*/
hasListener : function(eventName){
var e = this.events[eventName];
return typeof e == "object" && e.listeners.length > 0;
},
/**
* 暂停触发所有的事件(参阅{@link #resumeEvents})。
* Suspend the firing of all events. (see {@link #resumeEvents})
* @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
* after the {@link #resumeEvents} call instead of discarding all suspended events;
*/
suspendEvents : function(queueSuspended){
this.eventsSuspended = true;
if (queueSuspended === true) {
this.suspendedEventsQueue = [];
}
},
/**
* 重新触发事件(参阅{@link #suspendEvents})。
* Resume firing events. (see {@link #suspendEvents})
* If events were suspended using the <tt><b>queueSuspended</b></tt> parameter, then all
* events fired during event suspension will be sent to any listeners now.
*/
resumeEvents : function(){
this.eventsSuspended = false;
if (this.suspendedEventsQueue) {
for (var i = 0, e = this.suspendedEventsQueue, l = e.length; i < l; i++) {
this.fireEvent.apply(this, e[i]);
}
delete this.suspendedEventQueue;
}
},
// these are considered experimental
// allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
// private
getMethodEvent : function(method){
if(!this.methodEvents){
this.methodEvents = {};
}
var e = this.methodEvents[method];
if(!e){
e = {};
this.methodEvents[method] = e;
e.originalFn = this[method];
e.methodName = method;
e.before = [];
e.after = [];
var returnValue, v, cancel;
var obj = this;
var makeCall = function(fn, scope, args){
if((v = fn.apply(scope || obj, args)) !== undefined){
if(typeof v === 'object'){
if(v.returnValue !== undefined){
returnValue = v.returnValue;
}else{
returnValue = v;
}
if(v.cancel === true){
cancel = true;
}
}else if(v === false){
cancel = true;
}else {
returnValue = v;
}
}
}
this[method] = function(){
returnValue = v = undefined; cancel = false;
var args = Array.prototype.slice.call(arguments, 0);
for(var i = 0, len = e.before.length; i < len; i++){
makeCall(e.before[i].fn, e.before[i].scope, args);
if(cancel){
return returnValue;
}
}
if((v = e.originalFn.apply(obj, args)) !== undefined){
returnValue = v;
}
for(var i = 0, len = e.after.length; i < len; i++){
makeCall(e.after[i].fn, e.after[i].scope, args);
if(cancel){
return returnValue;
}
}
return returnValue;
};
}
return e;
},
// adds an "interceptor" called before the original method
beforeMethod : function(method, fn, scope){
var e = this.getMethodEvent(method);
e.before.push({fn: fn, scope: scope});
},
// adds a "sequence" called after the original method
afterMethod : function(method, fn, scope){
var e = this.getMethodEvent(method);
e.after.push({fn: fn, scope: scope});
},
removeMethodListener : function(method, fn, scope){
var e = this.getMethodEvent(method);
for(var i = 0, len = e.before.length; i < len; i++){
if(e.before[i].fn == fn && e.before[i].scope == scope){
e.before.splice(i, 1);
return;
}
}
for(var i = 0, len = e.after.length; i < len; i++){
if(e.after[i].fn == fn && e.after[i].scope == scope){
e.after.splice(i, 1);
return;
}
}
}
};
/**
* 为该元素添加事件处理函数(addListener的简写方式)。
* Appends an event handler to this element (shorthand for addListener)
* @param {String} eventName 事件名称The type of event to listen for
* @param {Function} handler 处理函数The method the event invokes
* @param {Object} scope (可选的) 执行处理函数的作用域。“this”对象指针(optional) The scope in which to execute the handler
* function. The handler function's "this" context.
* @param {Object} options (可选的)(optional)
* @method
*/
Ext.util.Observable.prototype.on = Ext.util.Observable.prototype.addListener;
/**
* 移除侦听器(removeListener的快捷方式)Removes a listener (shorthand for removeListener)
* @param {String} eventName 侦听事件的类型The type of event to listen for
* @param {Function} handler 事件涉及的方法 The handler to remove
* @param {Object} scope (可选的) 处理函数的作用域(optional) The scope (this object) for the handler
* @method
*/
Ext.util.Observable.prototype.un = Ext.util.Observable.prototype.removeListener;
/**
* 开始捕捉特定的观察者。
* 在事件触发<b>之前</b>,所有的事件会以“事件名称+标准签名”的形式传入到函数(传入的参数是function类型)。
* 如果传入的函数执行后返回false,则接下的事件将不会触发。
* Starts capture on the specified Observable. All events will be passed
* to the supplied function with the event name + standard signature of the event
* <b>before</b> the event is fired. If the supplied function returns false,
* the event will not fire.
* @param {Observable} o 要捕捉的观察者The Observable to capture
* @param {Function} fn 要调用的函数The function to call
* @param {Object} scope (可选的) 函数作用域(optional) The scope (this object) for the fn
* @static
*/
Ext.util.Observable.capture = function(o, fn, scope){
o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
};
/**
* 从Observable身上移除<b>所有</b>已加入的捕捉captures。Removes <b>all</b> added captures from the Observable.
* @param {Observable} o 要释放的观察者The Observable to release
* @static
*/
Ext.util.Observable.releaseCapture = function(o){
o.fireEvent = Ext.util.Observable.prototype.fireEvent;
};
(function(){
var createBuffered = function(h, o, scope){
var task = new Ext.util.DelayedTask();
return function(){
task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
};
};
var createSingle = function(h, e, fn, scope){
return function(){
e.removeListener(fn, scope);
return h.apply(scope, arguments);
};
};
var createDelayed = function(h, o, scope){
return function(){
var args = Array.prototype.slice.call(arguments, 0);
setTimeout(function(){
h.apply(scope, args);
}, o.delay || 10);
};
};
var createTargeted = function(h, o, scope){
return function(){
if(o.target == arguments[0]){
h.apply(scope, Array.prototype.slice.call(arguments, 0));
}
};
};
Ext.util.Event = function(obj, name){
this.name = name;
this.obj = obj;
this.listeners = [];
};
Ext.util.Event.prototype = {
addListener : function(fn, scope, options){
scope = scope || this.obj;
if(!this.isListening(fn, scope)){
var l = this.createListener(fn, scope, options);
if(!this.firing){
this.listeners.push(l);
}else{ // if we are currently firing this event, don't disturb the listener loop
this.listeners = this.listeners.slice(0);
this.listeners.push(l);
}
}
},
createListener : function(fn, scope, o){
o = o || {};
scope = scope || this.obj;
var l = {fn: fn, scope: scope, options: o};
var h = fn;
if(o.target){
h = createTargeted(h, o, scope);
}
if(o.delay){
h = createDelayed(h, o, scope);
}
if(o.single){
h = createSingle(h, this, fn, scope);
}
if(o.buffer){
h = createBuffered(h, o, scope);
}
l.fireFn = h;
return l;
},
findListener : function(fn, scope){
scope = scope || this.obj;
var ls = this.listeners;
for(var i = 0, len = ls.length; i < len; i++){
var l = ls[i];
if(l.fn == fn && l.scope == scope){
return i;
}
}
return -1;
},
isListening : function(fn, scope){
return this.findListener(fn, scope) != -1;
},
removeListener : function(fn, scope){
var index;
if((index = this.findListener(fn, scope)) != -1){
if(!this.firing){
this.listeners.splice(index, 1);
}else{
this.listeners = this.listeners.slice(0);
this.listeners.splice(index, 1);
}
return true;
}
return false;
},
clearListeners : function(){
this.listeners = [];
},
fire : function(){
var ls = this.listeners, scope, len = ls.length;
if(len > 0){
this.firing = true;
var args = Array.prototype.slice.call(arguments, 0);
for(var i = 0; i < len; i++){
var l = ls[i];
if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
this.firing = false;
return false;
}
}
this.firing = false;
}
return true;
}
};
})(); | JavaScript |
/*
* 项目地址: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.util.JSON
* Douglas Crockford的json.js之修改版本 该版本没有“入侵”Object对象的prototype
* http://www.json.org/js.html
* @singleton
*/
Ext.util.JSON = new (function(){
var useHasOwn = {}.hasOwnProperty ? true : false;
// crashes Safari in some instances
//var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
var pad = function(n) {
return n < 10 ? "0" + n : n;
};
var m = {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"' : '\\"',
"\\": '\\\\'
};
var encodeString = function(s){
if (/["\\\x00-\x1f]/.test(s)) {
return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if(c){
return c;
}
c = b.charCodeAt();
return "\\u00" +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + s + '"';
};
var encodeArray = function(o){
var a = ["["], b, i, l = o.length, v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null" : Ext.util.JSON.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
};
var encodeDate = function(o){
return '"' + o.getFullYear() + "-" +
pad(o.getMonth() + 1) + "-" +
pad(o.getDate()) + "T" +
pad(o.getHours()) + ":" +
pad(o.getMinutes()) + ":" +
pad(o.getSeconds()) + '"';
};
/**
* 对一个对象,数组,或是其它值编码。
* @param {Mixed} o 要编码的变量
* @return {String} JSON字符串
*/
this.encode = function(o){
if(typeof o == "undefined" || o === null){
return "null";
}else if(o instanceof Array){
return encodeArray(o);
}else if(o instanceof Date){
return encodeDate(o);
}else if(typeof o == "string"){
return encodeString(o);
}else if(typeof o == "number"){
return isFinite(o) ? String(o) : "null";
}else if(typeof o == "boolean"){
return String(o);
}else {
var a = ["{"], b, i, v;
for (i in o) {
if(!useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if(b){
a.push(',');
}
a.push(this.encode(i), ":",
v === null ? "null" : this.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
};
/**
* 将JSON字符串解码(解析)成为对象。如果JSON是无效的,该函数抛出一个“语法错误”。
* @param {String} json JSON字符串
* @return {Object} 对象
*/
this.decode = function(json){
return eval("(" + json + ')');
};
})();
/**
* {@link Ext.util.JSON#encode}的简写方式
* @member Ext encode
* @method */
Ext.encode = Ext.util.JSON.encode;
/**
* {@link Ext.util.JSON#decode}的简写方式
* @member Ext decode
* @method */
Ext.decode = Ext.util.JSON.decode; | JavaScript |
/*
* 项目地址:http://code.google.com/p/chineseext/
* 欢迎参与我们翻译的工作!详见《EXT API2Chinese 相关事宜》:
* http://bbs.ajaxjs.com Ext中文站翻译小组
*
* 本翻译采用“创作共同约定、Creative Commons”。您可以自由:
* 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
* 创作演绎作品
* 请遵守:
* 署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
* # 对任何再使用或者发行,您都必须向他人清楚地展示本作品使用的许可协议条款。
* # 如果得到著作权人的许可,您可以不受任何这些条件的限制
* http://creativecommons.org/licenses/by/2.5/cn/
*/
/**
* @class Ext.KeyMap
* Ext.KeyMap类负责在某一元素上,键盘和用户动作(Actions)之间的映射。
* 构建器可接收由{@link #addBinding}定义的相同配置项对象。
* 如果你绑定了一个KeyMap的回调函数,KeyMap会在该回调函数上提供下列参数(String key, Ext.EventObject e)
* 如果匹配的是组合键,回调函数也只会执行一次)
* KepMap能够实现以字符串来表示key<br />
* 一个key可用于多个动作。
* 用法:
<pre><code>
// 映射key(由keycode指定)
var map = new Ext.KeyMap("my-element", {
key: 13, // 或者是 Ext.EventObject.ENTER
fn: myHandler,
scope: myObject
});
// 映射组合键(由字符串指定)
var map = new Ext.KeyMap("my-element", {
key: "a\r\n\t",
fn: myHandler,
scope: myObject
});
// 映射多个动作的组合键(由字符串和code数组指定)
var map = new Ext.KeyMap("my-element", [
{
key: [10,13],
fn: function(){ alert("Return was pressed"); }
}, {
key: "abc",
fn: function(){ alert('a, b or c was pressed'); }
}, {
key: "\t",
ctrl:true,
shift:true,
fn: function(){ alert('Control + shift + tab was pressed.'); }
}
]);
</code></pre>
* <b>一个KeyMap开始激活</b>
* @constructor
* @param {Mixed} el 绑定的元素
* @param {Object} config T配置项
* @param {String} eventName (可选地)绑定的事件(默认“keydown”)
*/
Ext.KeyMap = function(el, config, eventName){
this.el = Ext.get(el);
this.eventName = eventName || "keydown";
this.bindings = [];
if(config){
this.addBinding(config);
}
this.enable();
};
Ext.KeyMap.prototype = {
/**
* 如果让KeyMap来处理key,设置true的话,则停止事件上报(event from bubbling),并阻拦默认浏览器动作(默认为false)
* @type Boolean
*/
stopEvent : false,
/**
* 新增该KeyMap的新绑定。下列配置项(对象的属性)均被支持:
* <pre>
属性 类型 描述
---------- --------------- ----------------------------------------------------------------------
key String/Array 进行处理的单个keycode或keycodes组成的数组
shift Boolean True:只有shift按下的的同时处理key (默认false)
ctrl Boolean True:只有ctrl按下的的同时处理key (默认false)
handler Function 当KeyMap找到预期的组合键时所执行的函数
alt Boolean True:只有alt按下的的同时处理key (默认false)
fn Function 当组合键按下后回调函数
scope Object 回调函数的作用域
</pre>
*
* 用法:
* <pre><code>
// 创建一个KeyMap
var map = new Ext.KeyMap(document, {
key: Ext.EventObject.ENTER,
fn: handleKey,
scope: this
});
//对现有的KeyMap延迟再绑定
map.addBinding({
key: 'abc',
shift: true,
fn: handleKey,
scope: this
});
</code></pre>
* @param {Object} config 单个KeyMap配置
*/
addBinding : function(config){
if(config instanceof Array){
for(var i = 0, len = config.length; i < len; i++){
this.addBinding(config[i]);
}
return;
}
var keyCode = config.key,
shift = config.shift,
ctrl = config.ctrl,
alt = config.alt,
fn = config.fn || config.handler,
scope = config.scope;
if(typeof keyCode == "string"){
var ks = [];
var keyString = keyCode.toUpperCase();
for(var j = 0, len = keyString.length; j < len; j++){
ks.push(keyString.charCodeAt(j));
}
keyCode = ks;
}
var keyArray = keyCode instanceof Array;
var handler = function(e){
if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){
var k = e.getKey();
if(keyArray){
for(var i = 0, len = keyCode.length; i < len; i++){
if(keyCode[i] == k){
if(this.stopEvent){
e.stopEvent();
}
fn.call(scope || window, k, e);
return;
}
}
}else{
if(k == keyCode){
if(this.stopEvent){
e.stopEvent();
}
fn.call(scope || window, k, e);
}
}
}
};
this.bindings.push(handler);
},
/**
* 加入单个键侦听器的简写方式
* @param {Number/Array/Object} key 既可是key code,也可以是key codes的集合,或者是下列的对象
* {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}
* @param {Function} fn 调用的函数
* @param {Object} scope (optional) 函数的作用域
*/
on : function(key, fn, scope){
var keyCode, shift, ctrl, alt;
if(typeof key == "object" && !(key instanceof Array)){
keyCode = key.key;
shift = key.shift;
ctrl = key.ctrl;
alt = key.alt;
}else{
keyCode = key;
}
this.addBinding({
key: keyCode,
shift: shift,
ctrl: ctrl,
alt: alt,
fn: fn,
scope: scope
})
},
// private
handleKeyDown : function(e){
if(this.enabled){ //以防万一
var b = this.bindings;
for(var i = 0, len = b.length; i < len; i++){
b[i].call(this, e);
}
}
},
/**
KeyMap是已激活的话返回true
* @return {Boolean}
*/
isEnabled : function(){
return this.enabled;
},
/**
* 激活KeyMap
*/
enable: function(){
if(!this.enabled){
this.el.on(this.eventName, this.handleKeyDown, this);
this.enabled = true;
}
},
/**
* 禁止该KeyMap
*/
disable: function(){
if(this.enabled){
this.el.removeListener(this.eventName, this.handleKeyDown, this);
this.enabled = false;
}
}
}; | JavaScript |
/*
* 项目地址: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.KeyNav
* <p>
* 为跨浏览器的键盘方向键加上一层快捷的包装器(wrapper)。
* KeyNav允许你为某个功能绑定方向键,按下的时候即调用该功能。
* KeyNav允许你对方向键进行函数调用的绑定,即按下相应的键便立即执行函数,轻松实现了对任意UI组件的键盘事件控制</p>
* <p>下列是全部有可能会出现的键(已实现的): enter, left, right, up, down, tab, esc,
* pageUp, pageDown, del, home, end。 举例:</p>
<pre><code>
var nav = new Ext.KeyNav("my-element", {
"left" : function(e){
this.moveLeft(e.ctrlKey);
},
"right" : function(e){
this.moveRight(e.ctrlKey);
},
"enter" : function(e){
this.save();
},
scope : this
});
</code></pre>
* @constructor
* @param {Mixed} el 绑定的元素
* @param {Object} config 配置项
*/
Ext.KeyNav = function(el, config){
this.el = Ext.get(el);
Ext.apply(this, config);
if(!this.disabled){
this.disabled = true;
this.enable();
}
};
Ext.KeyNav.prototype = {
/**
* @cfg {Boolean} disabled
* True表示为禁止该KeyNav的实例(默认为false)
*/
disabled : false,
/**
* @cfg {String} defaultEventAction
* 当KeyNav拦截某键之后,所调用的{@link Ext.EventObject}方法。该值可以是
* {@link Ext.EventObject#stopEvent}, {@link Ext.EventObject#preventDefault}与
* {@link Ext.EventObject#stopPropagation}(默认为“stopEvent”)
*/
defaultEventAction: "stopEvent",
/**
* @cfg {Boolean} forceKeyDown
* 以keydown事件代替keypress(默认为false)。
* 由于IE上按下special键不能有效触发keypress事件,所以IE上会自动设置为true。
* 然而将该项规定为true的话,则表示所以浏览器上都以以keydown事件代替keypress
*/
forceKeyDown : false,
// private
prepareEvent : function(e){
var k = e.getKey();
var h = this.keyToHandler[k];
if(Ext.isSafari2 && h && k >= 37 && k <= 40){
e.stopEvent();
}
},
// private
relay : function(e){
var k = e.getKey();
var h = this.keyToHandler[k];
if(h && this[h]){
if(this.doRelay(e, this[h], h) !== true){
e[this.defaultEventAction]();
}
}
},
// private
doRelay : function(e, h, hname){
return h.call(this.scope || this, e);
},
// possible handlers
enter : false,
left : false,
right : false,
up : false,
down : false,
tab : false,
esc : false,
pageUp : false,
pageDown : false,
del : false,
home : false,
end : false,
// quick lookup hash
keyToHandler : {
37 : "left",
39 : "right",
38 : "up",
40 : "down",
33 : "pageUp",
34 : "pageDown",
46 : "del",
36 : "home",
35 : "end",
13 : "enter",
27 : "esc",
9 : "tab"
},
/**
* 激活这个KeyNav
*/
enable: function(){
if(this.disabled){
// ie won't do special keys on keypress, no one else will repeat keys with keydown
// the EventObject will normalize Safari automatically
if(this.forceKeyDown || Ext.isIE || Ext.isSafari3 || Ext.isAir){
this.el.on("keydown", this.relay, this);
}else{
this.el.on("keydown", this.prepareEvent, this);
this.el.on("keypress", this.relay, this);
}
this.disabled = false;
}
},
/**
* 禁用这个KeyNav
*/
disable: function(){
if(!this.disabled){
if(this.forceKeyDown || Ext.isIE || Ext.isSafari3 || Ext.isAir){
this.el.un("keydown", this.relay, this);
}else{
this.el.un("keydown", this.prepareEvent, this);
this.el.un("keypress", this.relay, this);
}
this.disabled = 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.util.MixedCollection
* 一个负责维护数字下标(numeric indexes)和键值(key)的集合类,并暴露了一些事件。
* @constructor
* @param {Boolean} allowFunctions True表示为允许加入函数的引用到集合内(默认为false)
* @param {Function} keyFn 对于一个在该Mixed集合中已保存类型的item,可用这个函数返回对应item的键值。
* 执行MixedCollection方法时不需要特定传入一个key参数便可查找出键值。传入这个参数等同于实现了{@link #getKey}方法。
*/
Ext.util.MixedCollection = function(allowFunctions, keyFn){
this.items = [];
this.map = {};
this.keys = [];
this.length = 0;
this.addEvents(
/**
* @event clear
* 当集合被清除后触发。
*/
"clear",
/**
* @event add
* 当item被加入到集合之后触发。
* @param {Number} index 加入item的索引
* @param {Object} o 加入的item
* @param {String} key 加入item的键名称
*/
"add",
/**
* @event replace
* 集合中的item被替换后触发。
* @param {String} key 新加入item的键名称
* @param {Object} old 被替换之item
* @param {Object} new 新item.
*/
"replace",
/**
* @event remove
* 当item被移除集合时触发。
* @param {Object} o 被移除的item
* @param {String} key (可选的)被移除的item的键名称
*/
"remove",
"sort"
);
this.allowFunctions = allowFunctions === true;
if(keyFn){
this.getKey = keyFn;
}
Ext.util.MixedCollection.superclass.constructor.call(this);
};
Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, {
allowFunctions : false,
/**
* 加入一个item到集合中。
* @param {String} key item的键名称
* @param {Object} o 加入的item
* @return {Object} 已加入的item
*/
add : function(key, o){
if(arguments.length == 1){
o = arguments[0];
key = this.getKey(o);
}
if(typeof key == "undefined" || key === null){
this.length++;
this.items.push(o);
this.keys.push(null);
}else{
var old = this.map[key];
if(old){
return this.replace(key, o);
}
this.length++;
this.items.push(o);
this.map[key] = o;
this.keys.push(key);
}
this.fireEvent("add", this.length-1, o, key);
return o;
},
/**
* 如果你执行getKey的方法,MixedCollection有一个通用的方法来取得keys。
* 默认的实现只是简单地返回<tt style="font-weight:bold;">item.id</tt>,
* 不过你可以按照下面的例子自定义一个实现,以返回另外一个值
<pre><code>
// 一般方式
var mc = new Ext.util.MixedCollection();
mc.add(someEl.dom.id, someEl);
mc.add(otherEl.dom.id, otherEl);
//等等
// 使用getKey
var mc = new Ext.util.MixedCollection();
mc.getKey = function(el){
return el.dom.id;
};
mc.add(someEl);
mc.add(otherEl);
// 或通过构造器
var mc = new Ext.util.MixedCollection(false, function(el){
return el.dom.id;
});
mc.add(someEl);
mc.add(otherEl);
</code></pre>
* @param {Object} o 根据item找到key
* @return {Object} 传入item的key
*/
getKey : function(o){
return o.id;
},
/**
* 替换集合中的item。完成后触发{@link #replace}事件。
* @param {String} key 要替换item所关联的那个key,或是item。
* @param o {Object} o (可选的)如果传入的第一个参数是key,那么item就是key的键名称。
* @return {Object} 新的item。
*/
replace : function(key, o){
if(arguments.length == 1){
o = arguments[0];
key = this.getKey(o);
}
var old = this.item(key);
if(typeof key == "undefined" || key === null || typeof old == "undefined"){
return this.add(key, o);
}
var index = this.indexOfKey(key);
this.items[index] = o;
this.map[key] = o;
this.fireEvent("replace", key, old, o);
return o;
},
/**
* 将数组中或是对象中的所有元素加入到集合中。
* @param {Object/Array} objs 对象中包含的所有属性,或是数组中所有的值,都分别逐一加入集合中。
*/
addAll : function(objs){
if(arguments.length > 1 || objs instanceof Array){
var args = arguments.length > 1 ? arguments : objs;
for(var i = 0, len = args.length; i < len; i++){
this.add(args[i]);
}
}else{
for(var key in objs){
if(this.allowFunctions || typeof objs[key] != "function"){
this.add(key, objs[key]);
}
}
}
},
/**
* 在集合中执行每个Item的指定函数。函数执行时,会有下列的参数:
* <div class="mdetail-params"><ul>
* <li><b>item</b> : Mixed<p class="sub-desc">集合中的item</p></li>
* <li><b>index</b> : Number<p class="sub-desc">item的索引</p></li>
* <li><b>length</b> : Number<p class="sub-desc">集合中的items的总数</p></li>
* </ul></div>
* 那个函数应该要返回一个布尔值。若函数返回false便终止枚举。
* @param {Function} fn 每个item要执行的函数
* @param {Object} scope (optional) 函数执行时的作用域
*/
each : function(fn, scope){
var items = [].concat(this.items); // each safe for removal
for(var i = 0, len = items.length; i < len; i++){
if(fn.call(scope || items[i], items[i], i, len) === false){
break;
}
}
},
/**
* 传入一个函数类型的参数,然后在集合中的每个Item执行。key和其相关的item都作为头两个参数传入。
* @param {Function} fn 每个item要执行的函数。
* @param {Object} scope (可选的)执行函数的作用域
*/
eachKey : function(fn, scope){
for(var i = 0, len = this.keys.length; i < len; i++){
fn.call(scope || window, this.keys[i], this.items[i], i, len);
}
},
/**
* 根据传入的函数,执行该函数若返回true便说明这是要找到的那个item。
* @param {Function} fn 每个item要执行的查询函数。
* @param {Object} scope (可选的)执行函数的作用域
* @return {Object} 根据规则函数在集合中第一个找到的item
*/
find : function(fn, scope){
for(var i = 0, len = this.items.length; i < len; i++){
if(fn.call(scope || window, this.items[i], this.keys[i])){
return this.items[i];
}
}
return null;
},
/**
* 指定集合中的某个索引然后插入一个Item
* @param {Number} index 要插入item的索引。
* @param {String} key 包含新item的key名称,或item本身
* @param {Object} o (可选的) 如果第二个参数是key,新item
* @return {Object}以插入的item
*/
insert : function(index, key, o){
if(arguments.length == 2){
o = arguments[1];
key = this.getKey(o);
}
if(index >= this.length){
return this.add(key, o);
}
this.length++;
this.items.splice(index, 0, o);
if(typeof key != "undefined" && key != null){
this.map[key] = o;
}
this.keys.splice(index, 0, key);
this.fireEvent("add", index, o, key);
return o;
},
/**
* 从集合中移除Item
* @param {Object} o 移除的item
* @return {Object} 被移除的Item
*/
remove : function(o){
return this.removeAt(this.indexOf(o));
},
/**
* 从集合中移除由index指定的Item。完成后触发{@link #remove}事件。
* @param {Number} index 移除item的索引
* @return {Object} 被移除的item或是false就代表没有移除。
*/
removeAt : function(index){
if(index < this.length && index >= 0){
this.length--;
var o = this.items[index];
this.items.splice(index, 1);
var key = this.keys[index];
if(typeof key != "undefined"){
delete this.map[key];
}
this.keys.splice(index, 1);
this.fireEvent("remove", o, key);
return o;
}
return false;
},
/**
* 根据传入参数key,从集合中移除相关的item
* @param {String} key 要移除item的key
* @return {Object} 被移除的item或是false就代表没有移除。
*/
removeKey : function(key){
return this.removeAt(this.indexOfKey(key));
},
/**
* 返回集合中的item总数。
* @return {Number} item总数
*/
getCount : function(){
return this.length;
},
/**
* 传入一个对象,返回它的索引。
* @param {Object} o 要寻找索引的item
* @return {Number} item的索引。返回-1表示找不到。
*/
indexOf : function(o){
return this.items.indexOf(o);
},
/**
* 传入一个Key,返回它的索引。
* @param {String} key 寻找索引的key
* @return {Number} key的索引
*/
indexOfKey : function(key){
return this.keys.indexOf(key);
},
/**
* 根据key或索引(index)返回item。key的优先权高于索引。
* 这个方法相当于先调用{@link #key},如不匹配在调用{@link #itemAt}。
* @param {String/Number} key或者是item的索引
* @return {Object} 传入key所关联的item
*/
item : function(key){
var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key];
return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype!
},
/**
* 根据索引找到item
* @param {Number} index item的索引index
* @return {Object} 指定索引的item
*/
itemAt : function(index){
return this.items[index];
},
/**
* 根据key找到item
* @param {String/Number} key item的key
* @return {Object} key所关联的item
*/
key : function(key){
return this.map[key];
},
/**
* 若在集合中找到传入的item,则返回true。
* @param {Object} o 要在集合中查找的对象
* @return {Boolean} True表示为在集合中找到该item
*/
contains : function(o){
return this.indexOf(o) != -1;
},
/**
* 若在集合中找到传入的key,则返回true。
* @param {Object} o 要在集合中查找的对象
* @return {Boolean} True表示为在集合中找到该key
*/
containsKey : function(key){
return typeof this.map[key] != "undefined";
},
/**
* 清除集合中所有item
*/
clear : function(){
this.length = 0;
this.items = [];
this.keys = [];
this.map = {};
this.fireEvent("clear");
},
/**
* 返回集合中第一个item
* @return {Object} 集合中第一个item
*/
first : function(){
return this.items[0];
},
/**
* 返回集合中最后一个item
* @return {Object} 集合中最后一个item
*/
last : function(){
return this.items[this.length-1];
},
// private
_sort : function(property, dir, fn){
var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1;
fn = fn || function(a, b){
return a-b;
};
var c = [], k = this.keys, items = this.items;
for(var i = 0, len = items.length; i < len; i++){
c[c.length] = {key: k[i], value: items[i], index: i};
}
c.sort(function(a, b){
var v = fn(a[property], b[property]) * dsc;
if(v == 0){
v = (a.index < b.index ? -1 : 1);
}
return v;
});
for(var i = 0, len = c.length; i < len; i++){
items[i] = c[i].value;
k[i] = c[i].key;
}
this.fireEvent("sort", this);
},
/**
* 按传入的函数排列集合
* @param {String} dir 方向(可选的) "ASC" 或 "DESC"
* @param {Function} fn (可选的)一个供参照的function
*/
sort : function(dir, fn){
this._sort("value", dir, fn);
},
/**
* 按key顺序排列集合
* @param {String} dir 方向(可选的) "ASC" 或 "DESC"
* @param {Function} fn (可选的)一个参照的function(默认为非敏感字符串)
*/
keySort : function(dir, fn){
this._sort("key", dir, fn || function(a, b){
var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase();
return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
});
},
/**
* 返回这个集合中的某个范围内的items
* @param {Number} startIndex (可选的) 默认为 0
* @param {Number} endIndex (可选的) 默认为最后的item
* @return {Array} items数组
*/
getRange : function(start, end){
var items = this.items;
if(items.length < 1){
return [];
}
start = start || 0;
end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1);
var r = [];
if(start <= end){
for(var i = start; i <= end; i++) {
r[r.length] = items[i];
}
}else{
for(var i = start; i >= end; i--) {
r[r.length] = items[i];
}
}
return r;
},
/**
* 由指定的属性过滤集合中的<i>对象</i>。
* 返回以过滤后的新集合。
* @param {String} property 你对象身上的属性
* @param {String/RegExp} value 也可以是属性开始的值或对于这个属性的正则表达式
* @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
* @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False).
* @return {MixedCollection} 过滤后的新对象
*/
filter : function(property, value, anyMatch, caseSensitive){
if(Ext.isEmpty(value, false)){
return this.clone();
}
value = this.createValueMatcher(value, anyMatch, caseSensitive);
return this.filterBy(function(o){
return o && value.test(o[property]);
});
},
/**
* 由函数过滤集合中的<i>对象</i>。
* 返回以过滤后的<i>新</i>集合
* 传入的函数会被集合中每个对象执行。如果函数返回true,则value会被包含否则会被过滤、
* @param {Function} fn 被调用的函数,会接收o(object)和k (the key)参数
* @param {Object} scope (可选的)函数的作用域(默认为 this)
* @return {MixedCollection} 过滤后的新对象
*/
filterBy : function(fn, scope){
var r = new Ext.util.MixedCollection();
r.getKey = this.getKey;
var k = this.keys, it = this.items;
for(var i = 0, len = it.length; i < len; i++){
if(fn.call(scope||this, it[i], k[i])){
r.add(k[i], it[i]);
}
}
return r;
},
/**
* 由指定的属性/值查找集合中的第一个匹配对象。
* 这个对象是过滤后的<i>新</i>集合
* @param {String} property 当前对象下的属性名称
* @param {String/RegExp} value 代表属性值的字符串,也可以是一个正则表达式以测试属性。y.
* @param {Number} start (可选的)从第几个字符开始搜索(默认为0)
* @param {Boolean} anyMatch (可选的)True表示为匹配字符串的任意一部分,不只是开始的部分
* @param {Boolean} caseSensitive (可选的)True表示为打开大小写敏感
* @return {Number} 匹配的索引或-1
*/
findIndex : function(property, value, start, anyMatch, caseSensitive){
if(Ext.isEmpty(value, false)){
return -1;
}
value = this.createValueMatcher(value, anyMatch, caseSensitive);
return this.findIndexBy(function(o){
return o && value.test(o[property]);
}, null, start);
},
/**
* 由函数过滤集合中的<i>对象</i>。
* 返回以过滤后的<i>新</i>集合
* 传入的函数会被集合中每个对象执行。如果函数返回true,则value会被包含否则会被过滤、
* @param {Function} fn 被调用的函数,会接收o(object)和k (the key)参数
* @param {Object} scope (可选的)函数的作用域(默认为 this)
* @param {Number} start (可选的)从第几个字符开始搜索(默认为0)
* @return {MixedCollection} 匹配的索引或-1
*/
findIndexBy : function(fn, scope, start){
var k = this.keys, it = this.items;
for(var i = (start||0), len = it.length; i < len; i++){
if(fn.call(scope||this, it[i], k[i])){
return i;
}
}
if(typeof start == 'number' && start > 0){
for(var i = 0; i < start; i++){
if(fn.call(scope||this, it[i], k[i])){
return i;
}
}
}
return -1;
},
// private
createValueMatcher : function(value, anyMatch, caseSensitive){
if(!value.exec){ // not a regex
value = String(value);
value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), caseSensitive ? '' : 'i');
}
return value;
},
/**
* 创建该集合的浅表副本shallow copy(shallow copy)
* @return {MixedCollection}
*/
clone : function(){
var r = new Ext.util.MixedCollection();
var k = this.keys, it = this.items;
for(var i = 0, len = it.length; i < len; i++){
r.add(k[i], it[i]);
}
r.getKey = this.getKey;
return r;
}
});
/**
* 根据key或索引返回item。key的优先权高于索引。
* @method
* @param {String/Number} key 或者是item的索引
* @return {Object} 传入key所关联的item
*/
Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item; | JavaScript |
/*
* 项目地址: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.util.TextMetrics
* 为一段文字提供一个精确象素级的测量,以便可以得到某段文字的高度和宽度。
* @singleton
*/
Ext.util.TextMetrics = function(){
var shared;
return {
/**
* 测量指定文字尺寸。
* @param {String/HTMLElement} el 元素,DOM节点或ID,使得被渲染之文字获得新的CSS样式。
* @param {String} text 欲测量的文字。
* @param {Number} fixedWidth (optional) 如果文字是多行的,您必须先设置好一个宽度。以便正确的测出高度。
* @return {Object} 由文字尺寸组成的对象 {width: (width), height: (height)}
*/
measure : function(el, text, fixedWidth){
if(!shared){
shared = Ext.util.TextMetrics.Instance(el, fixedWidth);
}
shared.bind(el);
shared.setFixedWidth(fixedWidth || 'auto');
return shared.getSize(text);
},
/**
* 返回一个唯一的TextMetrics实例,直接绑定到某个元素和复用,
* 这样会减少在每个测量上初始样式属性的多次调用。
* @param {String/HTMLElement} el 将实例绑定到的元素,DOM节点或ID。
* @param {Number} fixedWidth (optional) 如果文字是多行的,您必须先设置好一个宽度。以便正确地测出高度。
* @return {Ext.util.TextMetrics.Instance} instance 新实例
*/
createInstance : function(el, fixedWidth){
return Ext.util.TextMetrics.Instance(el, fixedWidth);
}
};
}();
Ext.util.TextMetrics.Instance = function(bindTo, fixedWidth){
var ml = new Ext.Element(document.createElement('div'));
document.body.appendChild(ml.dom);
ml.position('absolute');
ml.setLeftTop(-1000, -1000);
ml.hide();
if(fixedWidth){
ml.setWidth(fixedWidth);
}
var instance = {
/**
* 返回一个指定文字的尺寸。该文字内置元素的样式和宽度属性
* @param {String} text 要测量的文字
* @return {Object} 由文字尺寸组成的对象 {width: (width), height: (height)}
*/
getSize : function(text){
ml.update(text);
var s = ml.getSize();
ml.update('');
return s;
},
/**
* 绑定某个样式的TextMetrics实例,使得被渲染之文字重新获得CSS样式。
* @param {String/HTMLElement} el 元素,DOM节点或ID
*/
bind : function(el){
ml.setStyle(
Ext.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height')
);
},
/**
* 对内置的测量元素设置一个固定的宽度。 如果文字是多行的,您必须先设置好一个宽度。
* 以便正确地测出高度。
* @param {Number} width 设置元素的宽度。
*/
setFixedWidth : function(width){
ml.setWidth(width);
},
/**
* 返回指定文字的宽度
* @param {String} text 要测量的文字
* @return {Number} width 宽度(象素)
*/
getWidth : function(text){
ml.dom.style.width = 'auto';
return this.getSize(text).width;
},
/**
* 返回指定文字的高度,对于多行文本,有可能需要调用 {@link #setFixedWidth} 。
* @param {String} text 要测量的文字
* @return {Number} height 高度(象素)
*/
getHeight : function(text){
return this.getSize(text).height;
}
};
instance.bind(bindTo);
return instance;
};
Ext.Element.addMethods({
/**
* 返回传入文本的宽度,或者该元素下文本的宽度。
* @param {String} text 欲检测的文本。默认为元素的innerHTML。
* @param {Number} min (可选的) 返回的最小值。
* @param {Number} max (可选的) 返回的最大值。
* @return {Number} 文本的宽度(像素)
* @member Ext.Element getTextWidth
*/
getTextWidth : function(text, min, max){
return (Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width).constrain(min || 0, max || 1000000);
}
}); | 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.XTemplate
* <p>支持高级功能的模板类,
* 如自动数组输出、条件判断、子模板、基本数学运行、特殊内建的模板变量,
* 直接执行代码和更多的功能。XTemplate亦提供相应的机制整合到 {@link Ext.DataView}.
* </p>
* <p>XTemplate有些特殊的标签和内建的操作运算符,是模板创建时生成的,不属于API条目的一部分。
* 下面的例子就演示了这些特殊部分的用法。每一个例子使用的数据对象如下:</p>
* <pre><code>
var data = {
name: 'Jack Slocum',
title: 'Lead Developer',
company: 'Ext JS, LLC',
email: 'jack@extjs.com',
address: '4 Red Bulls Drive',
city: 'Cleveland',
state: 'Ohio',
zip: '44102',
drinks: ['Red Bull', 'Coffee', 'Water'],
kids: [{
name: 'Sara Grace',
age:3
},{
name: 'Zachary',
age:2
},{
name: 'John James',
age:0
}]
};
</cpde></pre>
* <p>
* 配合使用标签<code>tpl</code>和操作符<code>for</code>,
* 你可自由切换<code>for<code>所指定的对象作用域,即可访问声明于模板之中对象。
* 如果这个对象是一个数组,它就会自动循环输出,不断重复<code>tpl</code>标签内的模板代码块,输出数组内的每一条内容:
* <b>自动数组输出和作用域切换。</b>
* </p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Title: {title}</p>',
'<p>Company: {company}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<p>{name}</p>',
'</tpl></p>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* <p><b>在子模板的范围内访问父元素对象。</b>
* 当正在处理子模板时,例如在循环子数组的时候,
* 可以通过<code>parent</code>对象访问父级的对象成员。
* </p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<tpl if="age > 1">',
'<p>{name}</p>',
'<p>Dad: {parent.name}</p>',
'</tpl>',
'</tpl></p>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* <p><b>数组元素索引和简单匹配支持。</b>
当正在处理数组的时候,特殊变量<code>#</code>表示当前数组索引+1(由1开始,不是0)。
* 如遇到数字型的元素,模板也支持简单的数学运算符+ - * /。
* </p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<tpl if="age > 1">',
'<p>{#}: {name}</p>', // <-- 每一项都加上序号
'<p>In 5 Years: {age+5}</p>', // <-- 简单的运算
'<p>Dad: {parent.name}</p>',
'</tpl>',
'</tpl></p>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* <p><b>自动渲染单根数组(flat arrays)。</b>
* 单根数组(Flat arrays),指的是不包含分支对象只包含值的数组。
* 使用特殊变量<code>{.}</code>可循环输出这类型的数组:
* </p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>{name}\'s favorite beverages:</p>',
'<tpl for="drinks">',
'<div> - {.}</div>',
'</tpl>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* <p><b>基本的条件逻辑判断</b>
* 配合标签<coed>tpl</code>和操作符<code>if</code>的使用,可为你执行条件判断,以决定模板的哪一部分需要被渲染出来。
* 注意这没有<code>else</code>的操作符--如需要,就要写两个逻辑相反的<code>if</code>的语句。
* 属性项要记得进行编码,好像下面的例子:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<tpl if="age &gt; 1">', // <-- 注意>要被编码
'<p>{name}</p>',
'</tpl>',
'</tpl></p>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* <p><b>即时执行任意的代码</b> <br/>
* 在XTemplate中,{[ ... ]}范围内的内容会在模板作用域的范围下执行。这里有一些特殊的变量:
* <ul>
* <li><b><tt>values</tt></b>:当前作用域下的值。若想改变其中的<tt>值</tt>,你可以切换子模板的作用域。</li>
* <li><b><tt>parent</tt></b>:父级模板的对象</li>
* <li><b><tt>xindex</tt></b>:若是循环模板,这是当前循环的索引index(从1开始)。</li>
* <li><b><tt>xcount</tt></b>:若是循环模板,这是循环的次数。</li>
* <li><b><tt>fm</tt></b>:<tt>Ext.util.Format</tt>的简写方式。</li>
* </ul>
* 这是一个例子说明怎么利用这个知识点生成交错行:
</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Company: {[company.toUpperCase() + ', ' + title]}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">,
'{name}',
'</div>',
'</tpl></p>'
);
tpl.overwrite(panel.body, data);
</code></pre>
* <p><b>模板成员函数。</b> 对于一些复制的处理,
* 可以配置项对象的方式传入一个或一个以上的成员函数到XTemplate构造器中:</p>
* <pre><code>
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<tpl if="this.isGirl(name)">',
'<p>Girl: {name} - {age}</p>',
'</tpl>',
'<tpl if="this.isGirl(name) == false">',
'<p>Boy: {name} - {age}</p>',
'</tpl>',
'<tpl if="this.isBaby(age)">',
'<p>{name} is a baby!</p>',
'</tpl>',
'</tpl></p>', {
isGirl: function(name){
return name == 'Sara Grace';
},
isBaby: function(age){
return age < 1;
}
});
tpl.overwrite(panel.body, data);
</code></pre>
* @constructor
* @param {String/Array/Object} parts HTML判断或片断组成的数组,或多个参数然后执行join("")。
*/
Ext.XTemplate = function(){
Ext.XTemplate.superclass.constructor.apply(this, arguments);
var s = this.html;
s = ['<tpl>', s, '</tpl>'].join('');
var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/;
var nameRe = /^<tpl\b[^>]*?for="(.*?)"/;
var ifRe = /^<tpl\b[^>]*?if="(.*?)"/;
var execRe = /^<tpl\b[^>]*?exec="(.*?)"/;
var m, id = 0;
var tpls = [];
while(m = s.match(re)){
var m2 = m[0].match(nameRe);
var m3 = m[0].match(ifRe);
var m4 = m[0].match(execRe);
var exp = null, fn = null, exec = null;
var name = m2 && m2[1] ? m2[1] : '';
if(m3){
exp = m3 && m3[1] ? m3[1] : null;
if(exp){
fn = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ return '+(Ext.util.Format.htmlDecode(exp))+'; }');
}
}
if(m4){
exp = m4 && m4[1] ? m4[1] : null;
if(exp){
exec = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ '+(Ext.util.Format.htmlDecode(exp))+'; }');
}
}
if(name){
switch(name){
case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break;
case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break;
default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }');
}
}
tpls.push({
id: id,
target: name,
exec: exec,
test: fn,
body: m[1]||''
});
s = s.replace(m[0], '{xtpl'+ id + '}');
++id;
}
for(var i = tpls.length-1; i >= 0; --i){
this.compileTpl(tpls[i]);
}
this.master = tpls[tpls.length-1];
this.tpls = tpls;
};
Ext.extend(Ext.XTemplate, Ext.Template, {
// private
re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
// private
codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
// private
applySubTemplate : function(id, values, parent, xindex, xcount){
var t = this.tpls[id];
if(t.test && !t.test.call(this, values, parent, xindex, xcount)){
return '';
}
if(t.exec && t.exec.call(this, values, parent, xindex, xcount)){
return '';
}
var vs = t.target ? t.target.call(this, values, parent) : values;
parent = t.target ? values : parent;
if(t.target && vs instanceof Array){
var buf = [];
for(var i = 0, len = vs.length; i < len; i++){
buf[buf.length] = t.compiled.call(this, vs[i], parent, i+1, len);
}
return buf.join('');
}
return t.compiled.call(this, vs, parent, xindex, xcount);
},
// private
compileTpl : function(tpl){
var fm = Ext.util.Format;
var useF = this.disableFormats !== true;
var sep = Ext.isGecko ? "+" : ",";
var fn = function(m, name, format, args, math){
if(name.substr(0, 4) == 'xtpl'){
return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'";
}
var v;
if(name === '.'){
v = 'values';
}else if(name === '#'){
v = 'xindex';
}else if(name.indexOf('.') != -1){
v = name;
}else{
v = "values['" + name + "']";
}
if(math){
v = '(' + v + math + ')';
}
if(format && useF){
args = args ? ',' + args : "";
if(format.substr(0, 5) != "this."){
format = "fm." + format + '(';
}else{
format = 'this.call("'+ format.substr(5) + '", ';
args = ", values";
}
}else{
args= ''; format = "("+v+" === undefined ? '' : ";
}
return "'"+ sep + format + v + args + ")"+sep+"'";
};
var codeFn = function(m, code){
return "'"+ sep +'('+code+')'+sep+"'";
};
var body;
//这里作个分支的判断,gecko的浏览器用+操作符,其它的用[].join()
if(Ext.isGecko){
body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
"';};";
}else{
body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
body.push("'].join('');};");
body = body.join('');
}
eval(body);
return this;
},
/**
* {@link #applyTemplate}的简写方式。
*/
apply : function(values){
return this.master.compiled.call(this, values, {}, 1, 1);
},
/**
* 返回HTML片断,这块片断是由数据填充模板之后而成的。
* @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.
* @return {String} HTML片断
*/
applyTemplate : function(values){
return this.master.compiled.call(this, values, {}, 1, 1);
},
/**
* 把这个模板编译为一个函数,推荐多次使用这个模板时用这个方法,以提高性能。
* @return {Function} 编译后的函数
*/
compile : function(){return this;}
});
/**
* 从某个元素的value或innerHTML中创建模板(推荐<i>display:none</i> textarea元素)。
* Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML.
* @param {String/HTMLElement} el DOM元素或其id。A DOM element or its id
* @return {Ext.Template} 模板对象。The created Template.
* @static
*/
Ext.XTemplate.from = function(el){
el = Ext.getDom(el);
return new Ext.XTemplate(el.value || el.innerHTML);
}; | 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 Date
* 日期的处理和格式化是<a href="http://www.php.net/date">PHP's date() function</a>的一个子集,
* 提供的格式和转换后的结果将和 PHP 版本的一模一样。下面列出的是目前所有支持的格式:
*<pre>
样本数据:
'Wed Jan 10 2007 15:05:01 GMT-0600 (中区标准时间)'
Format Description Example returned values
------ ----------------------------------------------------------------------- -----------------------
d Day of the month, 2 digits with leading zeros 01 to 31
D A short textual representation of the day of the week Mon to Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday to Saturday
N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
z The day of the year (starting from 0) 0 to 364 (365 in leap years)
W ISO-8601 week number of year, weeks starting on Monday 01 to 53
F A full textual representation of a month, such as January or March January to December
m Numeric representation of a month, with leading zeros 01 to 12
M A short textual representation of a month Jan to Dec
n Numeric representation of a month, without leading zeros 1 to 12
t Number of days in the given month 28 to 31
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
belongs to the previous or next year, that year is used instead)
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
g 12-hour format of an hour without leading zeros 1 to 12
G 24-hour format of an hour without leading zeros 0 to 23
h 12-hour format of an hour with leading zeros 01 to 12
H 24-hour format of an hour with leading zeros 00 to 23
i Minutes, with leading zeros 00 to 59
s Seconds, with leading zeros 00 to 59
u Decimal fraction of a second Examples:
(minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
100 (i.e. 0.100s) or
999 (i.e. 0.999s) or
999876543210 (i.e. 0.999876543210s)
O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
c ISO 8601 date
Notes: Examples:
1) If unspecified, the month / day defaults to the current month / day, 1991 or
the time defaults to midnight, while the timezone defaults to the 1992-10 or
browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
are optional. 1995-07-18T17:21:28-02:00 or
2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
date-time granularity which are supported, or see 2000-02-13T21:25:33
http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
M$ Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
\/Date(1238606590509+0800)\/
格式符 输出 说明
------ ---------- --------------------------------------------------------------
d 10 月份中的天数,两位数字,不足位补“0”
D Wed 当前星期的缩写,三个字母
j 10 月份中的天数,不补“0”
l Wednesday 当前星期的完整拼写
S th 英语中月份天数的序数词的后缀,2个字符(与格式符“j”连用)
w 3 一周之中的天数(0~6)(周日为0, 周六为6)
z 9 一年之中的天数(0~365)
W 01 一年之中的周数,两位数字(00~53)
F January 当前月份的拼写
m 01 当前的月份,两位数字,不足位补“0”
M Jan 当前月份的完整拼写,三个字母
n 1 当前的月份,不补“0”
t 31 当前月份的总天数
L 0 是否闰年(“1”为闰年,“0”为平年)
Y 2007 4位数字表示的当前年数
y 07 2位数字表示的当前年数
a pm 小写的“am”和“pm”
A PM 大写的“AM”和“PM”
g 3 12小时制表示的当前小时数,不补“0”
G 15 24小时制表示的当前小时数,不补“0”
h 03 12小时制表示的当前小时数,不足位补“0”
H 15 24小时制表示的当前小时数,不足位补“0”
i 05 不足位补“0”的分钟数
s 01 不足位补“0”的秒数
u 0.1 秒数的小数形式
O -0600 用小时数表示的与 GMT 差异数
T CST 当前系统设定的时区
Z -21600 用秒数表示的时区偏移量(西方为负数,东方为正数)
</pre>
*
* 用法举例:(注意你必须在字母前使用转意字符“\\”才能将其作为字母本身而不是格式符输出):
* <pre><code>
var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
document.write(dt.format('Y-m-d')); //2007-01-10
document.write(dt.format('F j, Y, g:i a')); //January 10, 2007, 3:05 pm
document.write(dt.format('l, \\t\\he dS of F Y h:i:s A')); //Wednesday, the 10th of January 2007 03:05:01 PM
</code></pre>
*
* 下面有一些标准的日期/时间模板可能会对你有用。它们不是 Date.js 的一部分,但是你可以将下列代码拷出,并放在 Date.js 之后所引用的任何脚本内,都将成为一个全局变量,并对所有的 Date 对象起作用。你可以按照你的需要随意增加、删除此段代码。
* <pre><code>
Date.patterns = {
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
};
</code></pre>
*
* 用法举例:
* <pre><code>
var dt = new Date();
document.write(dt.format(Date.patterns.ShortDate));
</code></pre>
* <p>
* 开发者可以通过设置 {@link #parseFunctions} 和 {@link #formatFunctions} 实现自定义日期格式化与解释功能,以满足特殊的需求。
* Developer-written, custom formats may be used by supplying both a formatting and a parsing function
* which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
*/
/*
* Most of the date-formatting functions below are the excellent work of Baron Schwartz.
* They generate precompiled functions from date formats instead of parsing and
* processing the pattern every time you format a date. These functions are available
* on every Date object (any javascript function).
*
* 下列大部分的日期格式化函数都是 Baron Schwartz 的杰作。
* 它们会由日期格式生成预编译函数,而不是在你每次格式化一个日期的时候根据模板转换和处理日期对象。
* 这些函数可以应用于每一个日期对象(在任何 JS 函数中)。
*
* The original article and download are here:
* 原文及下载在这里:
* http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/
*
*/
// private
Date.parseFunctions = {count:0};
// private
Date.parseRegexes = [];
// private
Date.formatFunctions = {count:0};
// private
Date.prototype.dateFormat = function(format) {
if (Date.formatFunctions[format] == null) {
Date.createNewFormat(format);
}
var func = Date.formatFunctions[format];
return this[func]();
};
/**
* 根据指定的格式将对象格式化。
* @param {String} v 格式符
* @return {String} 格式化后的日期对象
* @method
*/
Date.prototype.format = Date.prototype.dateFormat;
// private
Date.createNewFormat = function(format) {
var funcName = "format" + Date.formatFunctions.count++;
Date.formatFunctions[format] = funcName;
var code = "Date.prototype." + funcName + " = function(){return ";
var special = false;
var ch = '';
for (var i = 0; i < format.length; ++i) {
ch = format.charAt(i);
if (!special && ch == "\\") {
special = true;
}
else if (special) {
special = false;
code += "'" + String.escape(ch) + "' + ";
}
else {
code += Date.getFormatCode(ch);
}
}
eval(code.substring(0, code.length - 3) + ";}");
};
// private
Date.getFormatCode = function(character) {
switch (character) {
case "d":
return "String.leftPad(this.getDate(), 2, '0') + ";
case "D":
return "Date.dayNames[this.getDay()].substring(0, 3) + ";
case "j":
return "this.getDate() + ";
case "l":
return "Date.dayNames[this.getDay()] + ";
case "S":
return "this.getSuffix() + ";
case "w":
return "this.getDay() + ";
case "z":
return "this.getDayOfYear() + ";
case "W":
return "this.getWeekOfYear() + ";
case "F":
return "Date.monthNames[this.getMonth()] + ";
case "m":
return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
case "M":
return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
case "n":
return "(this.getMonth() + 1) + ";
case "t":
return "this.getDaysInMonth() + ";
case "L":
return "(this.isLeapYear() ? 1 : 0) + ";
case "Y":
return "this.getFullYear() + ";
case "y":
return "('' + this.getFullYear()).substring(2, 4) + ";
case "a":
return "(this.getHours() < 12 ? 'am' : 'pm') + ";
case "A":
return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
case "g":
return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + ";
case "G":
return "this.getHours() + ";
case "h":
return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + ";
case "H":
return "String.leftPad(this.getHours(), 2, '0') + ";
case "i":
return "String.leftPad(this.getMinutes(), 2, '0') + ";
case "s":
return "String.leftPad(this.getSeconds(), 2, '0') + ";
case "O":
return "this.getGMTOffset() + ";
case "T":
return "this.getTimezone() + ";
case "Z":
return "(this.getTimezoneOffset() * -60) + ";
default:
return "'" + String.escape(character) + "' + ";
}
};
/**
* 将输入的字串按照指定的格式转换为日期对象。
* 请注意此函数接受的是普通的日历格式,这意味着月份由1开始(1 = 1月)而不是像 JS 的日期对象那样由0开始。
* 任何没有指定的日期部分将默认为当前日期中对应的部分。
* 时间部分也是可以指定的,默认值为 0.
*
* 在format字串中任何没有被的部分都将首先被Defaults的Hash值所取代,如果Defaults值并未指定,则取当前日期(年,月,日或夏令制零时时间?)。
*
* 一定要注意输入的日期字串必须与指定的格式化字串相符,否则处理操作将会失败。
*
* 用法举例:
<pre><code>
//dt = Fri May 25 2007(当前日期)
var dt = new Date();
//dt = Thu May 25 2006 (today's month/day in 2006)
dt = Date.parseDate("2006", "Y");
//dt = Sun Jan 15 2006 (指定日期的所有部分)
dt = Date.parseDate("2006-1-15", "Y-m-d");
//dt = Sun Jan 15 2006 15:20:01 GMT-0600 (CST)
dt = Date.parseDate("2006-1-15 3:20:01 PM", "Y-m-d h:i:s A" );
</code></pre>
* @param {String} input 输入的日期字串
* @param {String} format 转换格式符
* @return {Date} 转换后的日期对象
* @static
*/
Date.parseDate = function(input, format) {
if (Date.parseFunctions[format] == null) {
Date.createParser(format);
}
var func = Date.parseFunctions[format];
return Date[func](input);
};
// private
Date.createParser = function(format) {
var funcName = "parse" + Date.parseFunctions.count++;
var regexNum = Date.parseRegexes.length;
var currentGroup = 1;
Date.parseFunctions[format] = funcName;
var code = "Date." + funcName + " = function(input){\n"
+ "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, o, z, v;\n"
+ "var d = new Date();\n"
+ "y = d.getFullYear();\n"
+ "m = d.getMonth();\n"
+ "d = d.getDate();\n"
+ "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
+ "if (results && results.length > 0) {";
var regex = "";
var special = false;
var ch = '';
for (var i = 0; i < format.length; ++i) {
ch = format.charAt(i);
if (!special && ch == "\\") {
special = true;
}
else if (special) {
special = false;
regex += String.escape(ch);
}
else {
var obj = Date.formatCodeToRegex(ch, currentGroup);
currentGroup += obj.g;
regex += obj.s;
if (obj.g && obj.c) {
code += obj.c;
}
}
}
code += "if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
+ "{v = new Date(y, m, d, h, i, s);}\n"
+ "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
+ "{v = new Date(y, m, d, h, i);}\n"
+ "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n"
+ "{v = new Date(y, m, d, h);}\n"
+ "else if (y >= 0 && m >= 0 && d > 0)\n"
+ "{v = new Date(y, m, d);}\n"
+ "else if (y >= 0 && m >= 0)\n"
+ "{v = new Date(y, m);}\n"
+ "else if (y >= 0)\n"
+ "{v = new Date(y);}\n"
+ "}return (v && (z || o))?\n" // favour UTC offset over GMT offset
+ " ((z)? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" // reset to UTC, then add offset
+ " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" // reset to GMT, then add offset
+ ";}";
Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
eval(code);
};
// private
Date.formatCodeToRegex = function(character, currentGroup) {
switch (character) {
case "D":
return {g:0,
c:null,
s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
case "j":
return {g:1,
c:"d = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{1,2})"}; // day of month without leading zeroes
case "d":
return {g:1,
c:"d = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{2})"}; // day of month with leading zeroes
case "l":
return {g:0,
c:null,
s:"(?:" + Date.dayNames.join("|") + ")"};
case "S":
return {g:0,
c:null,
s:"(?:st|nd|rd|th)"};
case "w":
return {g:0,
c:null,
s:"\\d"};
case "z":
return {g:0,
c:null,
s:"(?:\\d{1,3})"};
case "W":
return {g:0,
c:null,
s:"(?:\\d{2})"};
case "F":
return {g:1,
c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
s:"(" + Date.monthNames.join("|") + ")"};
case "M":
return {g:1,
c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
case "n":
return {g:1,
c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
s:"(\\d{1,2})"}; // Numeric representation of a month, without leading zeros
case "m":
return {g:1,
c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
s:"(\\d{2})"}; // Numeric representation of a month, with leading zeros
case "t":
return {g:0,
c:null,
s:"\\d{1,2}"};
case "L":
return {g:0,
c:null,
s:"(?:1|0)"};
case "Y":
return {g:1,
c:"y = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{4})"};
case "y":
return {g:1,
c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
+ "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
s:"(\\d{1,2})"};
case "a":
return {g:1,
c:"if (results[" + currentGroup + "] == 'am') {\n"
+ "if (h == 12) { h = 0; }\n"
+ "} else { if (h < 12) { h += 12; }}",
s:"(am|pm)"};
case "A":
return {g:1,
c:"if (results[" + currentGroup + "] == 'AM') {\n"
+ "if (h == 12) { h = 0; }\n"
+ "} else { if (h < 12) { h += 12; }}",
s:"(AM|PM)"};
case "g":
case "G":
return {g:1,
c:"h = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{1,2})"}; // 12/24-hr format format of an hour without leading zeroes
case "h":
case "H":
return {g:1,
c:"h = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{2})"}; // 12/24-hr format format of an hour with leading zeroes
case "i":
return {g:1,
c:"i = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{2})"};
case "s":
return {g:1,
c:"s = parseInt(results[" + currentGroup + "], 10);\n",
s:"(\\d{2})"};
case "O":
return {g:1,
c:[
"o = results[", currentGroup, "];\n",
"var sn = o.substring(0,1);\n", // get + / - sign
"var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", // get hours (performs minutes-to-hour conversion also)
"var mn = o.substring(3,5) % 60;\n", // get minutes
"o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", // -12hrs <= GMT offset <= 14hrs
" (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"
].join(""),
s:"([+\-]\\d{4})"};
case "T":
return {g:0,
c:null,
s:"[A-Z]{1,4}"}; // timezone abbrev. may be between 1 - 4 chars
case "Z":
return {g:1,
c:"z = results[" + currentGroup + "];\n" // -43200 <= UTC offset <= 50400
+ "z = (-43200 <= z*1 && z*1 <= 50400)? z : null;\n",
s:"([+\-]?\\d{1,5})"}; // leading '+' sign is optional for UTC offset
default:
return {g:0,
c:null,
s:String.escape(character)};
}
};
/**
* 返回当前所在时区的缩写(等同于指定输出格式“T”)。
* @return {String} 时区缩写(例如:“CST”)
*/
Date.prototype.getTimezone = function() {
return this.toString().replace(/^.*? ([A-Z]{1,4})[\-+][0-9]{4} .*$/, "$1");
};
/**
* 返回 GMT 到当前日期的偏移量(等同于指定输出格式“O”)。
* @return {String} 以“+”或“-”加上4位字符表示的偏移量(例如:“-0600”)
*/
Date.prototype.getGMTOffset = function() {
return (this.getTimezoneOffset() > 0 ? "-" : "+")
+ String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0")
+ String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
};
/**
* 返回当前年份中天数的数值,已经根据闰年调整过。
* @return {Number} 0 到 365(闰年时为 366)
*/
Date.prototype.getDayOfYear = function() {
var num = 0;
Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
for (var i = 0; i < this.getMonth(); ++i) {
num += Date.daysInMonth[i];
}
return num + this.getDate() - 1;
};
/**
* 返回当前的星期数(等同于指定输出格式“W”)。
* @return {String} “00”~“52”
*/
Date.prototype.getWeekOfYear = function() {
// Skip to Thursday of this week
var now = this.getDayOfYear() + (4 - this.getDay());
// Find the first Thursday of the year
var jan1 = new Date(this.getFullYear(), 0, 1);
var then = (7 - jan1.getDay() + 4);
return String.leftPad(((now - then) / 7) + 1, 2, "0");
};
/**
* 返回当前日期是否闰年。
* @return {Boolean} 闰年为“true”,平年为“false”
*/
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
};
/**
* 返回当前月份第一天的数值,已经根据闰年调整过。
* 返回值为以数字表示的一周中的第几天(0~6)
* 可以与数组 dayNames (译者注:此处原文为“{@link #monthNames}”。)一起使用来表示当天的星期。
* 例子:
*<pre><code>
var dt = new Date('1/10/2007');
document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //输出: 'Monday'
</code></pre>
* @return {Number} 一周中的天数(0~6)
*/
Date.prototype.getFirstDayOfMonth = function() {
var day = (this.getDay() - (this.getDate() - 1)) % 7;
return (day < 0) ? (day + 7) : day;
};
/**
* 返回当前月份最后一天的数值,已经根据闰年调整过。
* 返回值为以数字表示的一周中的第几天(0~6)
* 可以与数组 dayNames (译者注:此处原文为“{@link #monthNames}”。)一起使用来表示当天的星期。
* 例子:
*<pre><code>
var dt = new Date('1/10/2007');
document.write(Date.dayNames[dt.getLastDayOfMonth()]); //输出: 'Monday'
</code></pre>
* @return {Number} 一周中的天数(0~6)
*/
Date.prototype.getLastDayOfMonth = function() {
var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7;
return (day < 0) ? (day + 7) : day;
};
/**
* 返回当前月份第一天的日期对象。
* @return {Date}
*/
Date.prototype.getFirstDateOfMonth = function() {
return new Date(this.getFullYear(), this.getMonth(), 1);
};
/**
* 返回当前月份中最后一天的日期对象。
* @return {Date}
*/
Date.prototype.getLastDateOfMonth = function() {
return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth());
};
/**
* 返回当前月份中天数的数值,已经根据闰年调整过。
* @return {Number} 月份中的天数
*/
Date.prototype.getDaysInMonth = function() {
Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
return Date.daysInMonth[this.getMonth()];
};
/**
* 返回当天的英文单词的后缀(等同于指定输出格式“S”)。
* @return {String} 'st, 'nd', 'rd' or 'th'
*/
Date.prototype.getSuffix = function() {
switch (this.getDate()) {
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
};
// private
Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
/**
* 月份名称的数组。
* 覆盖此属性即可实现日期对象的本地化,例如:
* Date.monthNames = ['一月', '二月', '三月' ...];
* @type Array
* @static
*/
Date.monthNames =
["January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"];
/**
* 天数名称的数组。
* 覆盖此属性即可实现日期对象的本地化,例如:
* Date.dayNames = ['日', '一', '二' ...];
* @type Array
* @static
*/
Date.dayNames =
["Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"];
// private
Date.y2kYear = 50;
// private
Date.monthNumbers = {
Jan:0,
Feb:1,
Mar:2,
Apr:3,
May:4,
Jun:5,
Jul:6,
Aug:7,
Sep:8,
Oct:9,
Nov:10,
Dec:11};
/**
* 创建并返回一个新的与原来一模一样的日期实例。
* 新的实例通过地址复制,因此新的实例的变量发生改变后,原来的实例的变量也会随之改变。
* 当你想要创建一个新的变量而又不希望对原始实例产生影响时,你应该复制一个原始的实例。
* 正确复制一个日期实例的例子:
* <pre><code>
//错误的方式:
var orig = new Date('10/1/2006');
var copy = orig;
copy.setDate(5);
document.write(orig); //返回 'Thu Oct 05 2006'!
//正确的方式:
var orig = new Date('10/1/2006');
var copy = orig.clone();
copy.setDate(5);
document.write(orig); //返回 'Thu Oct 01 2006'
</code></pre>
* @return {Date} 新的日期实例
*/
Date.prototype.clone = function() {
return new Date(this.getTime());
};
/**
* 清除日期对象中的所有时间信息。
@param {Boolean} clone 值为“true”时复制一个当前日期实例,清除时间信息后返回。
@return {Date} 实例本身或复制的实例
*/
Date.prototype.clearTime = function(clone){
if(clone){
return this.clone().clearTime();
}
this.setHours(0);
this.setMinutes(0);
this.setSeconds(0);
this.setMilliseconds(0);
return this;
};
// private
// safari setMonth is broken
if(Ext.isSafari){
Date.brokenSetMonth = Date.prototype.setMonth;
Date.prototype.setMonth = function(num){
if(num <= -1){
var n = Math.ceil(-num);
var back_year = Math.ceil(n/12);
var month = (n % 12) ? 12 - n % 12 : 0 ;
this.setFullYear(this.getFullYear() - back_year);
return Date.brokenSetMonth.call(this, month);
} else {
return Date.brokenSetMonth.apply(this, arguments);
}
};
}
/** Date interval constant @static @type String */
Date.MILLI = "ms";
/** Date interval constant @static @type String */
Date.SECOND = "s";
/** Date interval constant @static @type String */
Date.MINUTE = "mi";
/** Date interval constant @static @type String */
Date.HOUR = "h";
/** Date interval constant @static @type String */
Date.DAY = "d";
/** Date interval constant @static @type String */
Date.MONTH = "mo";
/** Date interval constant @static @type String */
Date.YEAR = "y";
/**
* 一个便利的日期运算的方法。
* 这个方法不会改变日期实例本身,而是返回一个以运算结果创建的日期对象新实例。
* 例如:
* <pre><code>
//基本用法:
var dt = new Date('10/29/2006').add(Date.DAY, 5);
document.write(dt); //返回 'Fri Oct 06 2006 00:00:00'
//负数的值将会减去数值:
var dt2 = new Date('10/1/2006').add(Date.DAY, -5);
document.write(dt2); //返回 'Tue Sep 26 2006 00:00:00'
//你甚至可以连续多次调用此方法
var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30);
document.write(dt3); //返回 'Fri Oct 06 2006 07:30:00'
</code></pre>
*
* @param {String} interval 一个合法的日期间隔常数
* @param {Number} value 修改的数值
* @return {Date} 新的日期对象实例
*/
Date.prototype.add = function(interval, value){
var d = this.clone();
if (!interval || value === 0) return d;
switch(interval.toLowerCase()){
case Date.MILLI:
d.setMilliseconds(this.getMilliseconds() + value);
break;
case Date.SECOND:
d.setSeconds(this.getSeconds() + value);
break;
case Date.MINUTE:
d.setMinutes(this.getMinutes() + value);
break;
case Date.HOUR:
d.setHours(this.getHours() + value);
break;
case Date.DAY:
d.setDate(this.getDate() + value);
break;
case Date.MONTH:
var day = this.getDate();
if(day > 28){
day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate());
}
d.setDate(day);
d.setMonth(this.getMonth() + value);
break;
case Date.YEAR:
d.setFullYear(this.getFullYear() + value);
break;
}
return d;
};
/**
* 返回date对象创建时间与现在时间的时间差,单位为毫秒。
* Returns the number of milliseconds between this date and date
* (译注:)例:var date = new Date();
* var x=0;
* while(x<2){
* alert('x');
* x++;
* }
*
* var theTime = date.getElapsed();
* alert(theTime); //将显示间隔的时间,单位是毫秒
*
* @param {Date} date (可选的)默认时间是now。(optional) Defaults to now
* @return {Number} 间隔毫秒数。The diff in milliseconds
* @member Date getElapsed
*/
Date.prototype.getElapsed = function(date) {
return Math.abs((date || new Date()).getTime()-this.getTime());
}; | 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.History
* @extends Ext.util.Observable
* History management component that allows you to register arbitrary tokens that signify application
* history state on navigation actions. You can then handle the history {@link #change} event in order
* to reset your application UI to the appropriate state when the user navigates forward or backward through
* the browser history stack.
* @singleton
*/
Ext.History = (function () {
var iframe, hiddenField;
var ready = false;
var currentToken;
function getHash() {
var href = top.location.href, i = href.indexOf("#");
return i >= 0 ? href.substr(i + 1) : null;
}
function doSave() {
hiddenField.value = currentToken;
}
function handleStateChange(token) {
currentToken = token;
Ext.History.fireEvent('change', token);
}
function updateIFrame (token) {
var html = ['<html><body><div id="state">',token,'</div></body></html>'].join('');
try {
var doc = iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
return true;
} catch (e) {
return false;
}
}
function checkIFrame() {
if (!iframe.contentWindow || !iframe.contentWindow.document) {
setTimeout(checkIFrame, 10);
return;
}
var doc = iframe.contentWindow.document;
var elem = doc.getElementById("state");
var token = elem ? elem.innerText : null;
var hash = getHash();
setInterval(function () {
doc = iframe.contentWindow.document;
elem = doc.getElementById("state");
var newtoken = elem ? elem.innerText : null;
var newHash = getHash();
if (newtoken !== token) {
token = newtoken;
handleStateChange(token);
top.location.hash = token;
hash = token;
doSave();
} else if (newHash !== hash) {
hash = newHash;
updateIFrame(newHash);
}
}, 50);
ready = true;
Ext.History.fireEvent('ready', Ext.History);
}
function startUp() {
currentToken = hiddenField.value ? hiddenField.value : getHash();
if (Ext.isIE) {
checkIFrame();
} else {
var hash = getHash();
setInterval(function () {
var newHash = getHash();
if (newHash !== hash) {
hash = newHash;
handleStateChange(hash);
doSave();
}
}, 50);
ready = true;
Ext.History.fireEvent('ready', Ext.History);
}
}
return {
/**
* The id of the hidden field required for storing the current history token.
* @type String
* @property fieldId
*/
fieldId: 'x-history-field',
/**
* The id of the iframe required by IE to manage the history stack.
* @type String
* @property iframeId
*/
iframeId: 'x-history-frame',
events:{},
/**
* Initialize the global History instance.
* @param {Boolean} onReady (optional) A callback function that will be called once the history
* component is fully initialized.
* @param {Object} scope (optional) The callback scope
*/
init: function (onReady, scope) {
if(ready) {
Ext.callback(onReady, scope, [this]);
return;
}
if(!Ext.isReady){
Ext.onReady(function(){
Ext.History.init(onReady, scope);
});
return;
}
hiddenField = Ext.getDom(Ext.History.fieldId);
if (Ext.isIE) {
iframe = Ext.getDom(Ext.History.iframeId);
}
this.addEvents('ready', 'change');
if(onReady){
this.on('ready', onReady, scope, {single:true});
}
startUp();
},
/**
* Add a new token to the history stack. This can be any arbitrary value, although it would
* commonly be the concatenation of a component id and another id marking the specifc history
* state of that component. Example usage:
* <pre><code>
// Handle tab changes on a TabPanel
tabPanel.on('tabchange', function(tabPanel, tab){
Ext.History.add(tabPanel.id + ':' + tab.id);
});
</code></pre>
* @param {String} token The value that defines a particular application-specific history state
* @param {Boolean} preventDuplicates When true, if the passed token matches the current token
* it will not save a new history step. Set to false if the same state can be saved more than once
* at the same history stack location (defaults to true).
*/
add: function (token, preventDup) {
if(preventDup !== false){
if(this.getToken() == token){
return true;
}
}
if (Ext.isIE) {
return updateIFrame(token);
} else {
top.location.hash = token;
return true;
}
},
/**
* Programmatically steps back one step in browser history (equivalent to the user pressing the Back button).
*/
back: function(){
history.go(-1);
},
/**
* Programmatically steps forward one step in browser history (equivalent to the user pressing the Forward button).
*/
forward: function(){
history.go(1);
},
/**
* Retrieves the currently-active history token.
* @return {String} The token
*/
getToken: function() {
return ready ? currentToken : getHash();
}
};
})();
Ext.apply(Ext.History, new 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.util.Cookies
* 控制Cookies的类
*/
Ext.util.Cookies = {
set : function(name, value){
var argv = arguments;
var argc = arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : '/';
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
},
get : function(name){
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
var j = 0;
while(i < clen){
j = i + alen;
if(document.cookie.substring(i, j) == arg)
return Ext.util.Cookies.getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0)
break;
}
return null;
},
clear : function(name){
if(Ext.util.Cookies.get(name)){
document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
},
getCookieVal : function(offset){
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1){
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
}; | 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.util.TaskRunner
* Provides the ability to execute one or more arbitrary tasks in a multithreaded manner. Generally, you can use
* the singleton {@link Ext.TaskMgr} instead, but if needed, you can create separate instances of TaskRunner. Any
* number of separate tasks can be started at any time and will run independently of each other. Example usage:
* <pre><code>
// Start a simple clock task that updates a div once per second
var task = {
run: function(){
Ext.fly('clock').update(new Date().format('g:i:s A'));
},
interval: 1000 //1 second
}
var runner = new Ext.util.TaskRunner();
runner.start(task);
</code></pre>
* @constructor
* @param {Number} interval (optional) The minimum precision in milliseconds supported by this TaskRunner instance
* (defaults to 10)
*/
Ext.util.TaskRunner = function(interval){
interval = interval || 10;
var tasks = [], removeQueue = [];
var id = 0;
var running = false;
// private
var stopThread = function(){
running = false;
clearInterval(id);
id = 0;
};
// private
var startThread = function(){
if(!running){
running = true;
id = setInterval(runTasks, interval);
}
};
// private
var removeTask = function(t){
removeQueue.push(t);
if(t.onStop){
t.onStop.apply(t.scope || t);
}
};
// private
var runTasks = function(){
if(removeQueue.length > 0){
for(var i = 0, len = removeQueue.length; i < len; i++){
tasks.remove(removeQueue[i]);
}
removeQueue = [];
if(tasks.length < 1){
stopThread();
return;
}
}
var now = new Date().getTime();
for(var i = 0, len = tasks.length; i < len; ++i){
var t = tasks[i];
var itime = now - t.taskRunTime;
if(t.interval <= itime){
var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]);
t.taskRunTime = now;
if(rt === false || t.taskRunCount === t.repeat){
removeTask(t);
return;
}
}
if(t.duration && t.duration <= (now - t.taskStartTime)){
removeTask(t);
}
}
};
/**
* @member Ext.util.TaskRunner
* @method start
* Starts a new task.
* @param {Object} task A config object that supports the following properties:<ul>
* <li><code>run</code> : Function<div class="sub-desc">The function to execute each time the task is run. The
* function will be called at each interval and passed the <code>args</code> argument if specified. If a
* particular scope is required, be sure to specify it using the <code>scope</scope> argument.</div></li>
* <li><code>interval</code> : Number<div class="sub-desc">The frequency in milliseconds with which the task
* should be executed.</div></li>
* <li><code>args</code> : Array<div class="sub-desc">(optional) An array of arguments to be passed to the function
* specified by <code>run</code>.</div></li>
* <li><code>scope</code> : Object<div class="sub-desc">(optional) The scope in which to execute the
* <code>run</code> function.</div></li>
* <li><code>duration</code> : Number<div class="sub-desc">(optional) The length of time in milliseconds to execute
* the task before stopping automatically (defaults to indefinite).</div></li>
* <li><code>repeat</code> : Number<div class="sub-desc">(optional) The number of times to execute the task before
* stopping automatically (defaults to indefinite).</div></li>
* </ul>
* @return {Object} The task
*/
this.start = function(task){
tasks.push(task);
task.taskStartTime = new Date().getTime();
task.taskRunTime = 0;
task.taskRunCount = 0;
startThread();
return task;
};
/**
* @member Ext.util.TaskRunner
* @method stop
* Stops an existing running task.
* @param {Object} task The task to stop
* @return {Object} The task
*/
this.stop = function(task){
removeTask(task);
return task;
};
/**
* @member Ext.util.TaskRunner
* @method stopAll
* Stops all tasks that are currently running.
*/
this.stopAll = function(){
stopThread();
for(var i = 0, len = tasks.length; i < len; i++){
if(tasks[i].onStop){
tasks[i].onStop();
}
}
tasks = [];
removeQueue = [];
};
};
/**
* @class Ext.TaskMgr
* A static {@link Ext.util.TaskRunner} instance that can be used to start and stop arbitrary tasks. See
* {@link Ext.util.TaskRunner} for supported methods and task config properties.
* <pre><code>
// Start a simple clock task that updates a div once per second
var task = {
run: function(){
Ext.fly('clock').update(new Date().format('g:i:s A'));
},
interval: 1000 //1 second
}
Ext.TaskMgr.start(task);
</code></pre>
* @singleton
*/
Ext.TaskMgr = new Ext.util.TaskRunner(); | 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.util.ClickRepeater
@extends Ext.util.Observable
适用于任何元素的包装类。当鼠标按下时触发一个“单击”的事件。
可在配置项中设置间隔时间,默认是20毫秒。可选地,按下的过程中可能会加入一个CSS类。
@cfg {Mixed} el 该元素作为一个按钮。
@cfg {Number} delay 开始触发事件重复之前的初始延迟,类似自动重复键延时。
@cfg {Number} interval “fire”事件之间的间隔时间。默认20ms。
@cfg {String} pressClass 当元素被按下时所指定的CSS样式。
@cfg {Boolean} accelerate True:如果要自动重复开始时缓慢,然后加速的话,设置为TRUE。 "interval" 和 "delay"将会被忽略。
@cfg {Boolean} preventDefault True:预防默认的单击事件。
@cfg {Boolean} stopDefault True:停止默认的单击事件。
@constructor
@param {String/HTMLElement/Element} el 侦听的函数。
@param {Object} config
*/
Ext.util.ClickRepeater = function(el, config)
{
this.el = Ext.get(el);
this.el.unselectable();
Ext.apply(this, config);
this.addEvents(
/**
* @event mousedown
* 当鼠标按下的时候触发。
* Fires when the mouse button is depressed.
* @param {Ext.util.ClickRepeater} this
*/
"mousedown",
/**
* @event click
* 当元素被按下接受到按下的消息的时候出发,比mousedown事件慢。
* Fires on a specified interval during the time the element is pressed.
* @param {Ext.util.ClickRepeater} this
*/
"click",
/**
* @event mouseup
* 当鼠标释放后触发。
* Fires when the mouse key is released.
* @param {Ext.util.ClickRepeater} this
*/
"mouseup"
);
this.el.on("mousedown", this.handleMouseDown, this);
if(this.preventDefault || this.stopDefault){
this.el.on("click", function(e){
if(this.preventDefault){
e.preventDefault();
}
if(this.stopDefault){
e.stopEvent();
}
}, this);
}
// allow inline handler
if(this.handler){
this.on("click", this.handler, this.scope || this);
}
Ext.util.ClickRepeater.superclass.constructor.call(this);
};
Ext.extend(Ext.util.ClickRepeater, Ext.util.Observable, {
interval : 20,
delay: 250,
preventDefault : true,
stopDefault : false,
timer : 0,
destroy : function() {
Ext.destroy(this.el);
this.purgeListeners();
},
// private
handleMouseDown : function(){
clearTimeout(this.timer);
this.el.blur();
if(this.pressClass){
this.el.addClass(this.pressClass);
}
this.mousedownTime = new Date();
Ext.getDoc().on("mouseup", this.handleMouseUp, this);
this.el.on("mouseout", this.handleMouseOut, this);
this.fireEvent("mousedown", this);
this.fireEvent("click", this);
// Do not honor delay or interval if acceleration wanted.
if (this.accelerate) {
this.delay = 400;
}
this.timer = this.click.defer(this.delay || this.interval, this);
},
// private
click : function(){
this.fireEvent("click", this);
this.timer = this.click.defer(this.accelerate ?
this.easeOutExpo(this.mousedownTime.getElapsed(),
400,
-390,
12000) :
this.interval, this);
},
easeOutExpo : function (t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
// private
handleMouseOut : function(){
clearTimeout(this.timer);
if(this.pressClass){
this.el.removeClass(this.pressClass);
}
this.el.on("mouseover", this.handleMouseReturn, this);
},
// private
handleMouseReturn : function(){
this.el.un("mouseover", this.handleMouseReturn);
if(this.pressClass){
this.el.addClass(this.pressClass);
}
this.click();
},
// private
handleMouseUp : function(){
clearTimeout(this.timer);
this.el.un("mouseover", this.handleMouseReturn);
this.el.un("mouseout", this.handleMouseOut);
Ext.getDoc().un("mouseup", this.handleMouseUp);
this.el.removeClass(this.pressClass);
this.fireEvent("mouseup", this);
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/*
* These classes are derivatives of the similarly named classes in the YUI Library.
* The original license:
* Copyright (c) 2006, Yahoo! Inc. All rights reserved.
* Code licensed under the BSD License:
* http://developer.yahoo.net/yui/license.txt
*/
(function() {
var Event=Ext.EventManager;
var Dom=Ext.lib.Dom;
/**
* 对于可被拖动(drag)或可被放下(drop)的目标,进行接口和各项基本操作的定义。
* 你应该通过继承的方式使用该类,并重写startDrag, onDrag, onDragOver和onDragOut的事件处理器,.
* 共有三种html元素可以被关联到DragDrop实例:
* <ul>
* <li>关联元素(linked element):传入到构造器的元素。
* 这是一个为与其它拖放对象交互定义边界的元素</li>
* <li>执行元素(handle element):只有被点击的元素是执行元素,
* 这个拖动操作才会发生。默认就是关联元素,不过有情况你只是想关联元素的某一部分
* 来初始化拖动操作。可用setHandleElId()方法重新定义</li>
* <li>拖动元素(drag element):表示在拖放过程中,参与和鼠标指针一起的那个元素。
* 默认就是关联元素本身,如{@link Ext.dd.DD},setDragElId()可让你定义一个
* 可移动的独立元素,如{@link Ext.dd.DDProxy}</li>
* </ul>
*/
/**
* 必须在onload事件发生之后才能实例化这个类,以保证关联元素已准备可用。
* 下列语句会将拖放对象放进"group1"的组中,与组内其他拖放对象交互:
* <pre>
* dd = new Ext.dd.DragDrop("div1", "group1");
* </pre>
* 由于没有实现任何的事件处理器,所以上面的代码运行后不会有实际的效果发生。
* 通常的做法是你要先重写这个类或者某个默的实现,但是你可以重写你想出现在这个实例上的方法
* <pre>
* dd.onDragDrop = function(e, id) {
* alert("DD落在" + id+"的身上");
* }
* </pre>
* @constructor
* @param {String} id 关联到这个实例的那个元素的id
* @param {String} sGroup 相关拖放对象的组
* @param {object} config 包含可配置的对象属性
* DragDrop的有效属性:
* padding, isTarget, maintainOffset, primaryButtonOnly
*/
Ext.dd.DragDrop = function(id, sGroup, config) {
if (id) {
this.init(id, sGroup, config);
}
};
Ext.dd.DragDrop.prototype = {
/**
* 关联该对象元素之id,这便是我们所提及的“关联元素”,
* 因为拖动过程中的交互行为取决于该元素的大小和尺寸。
* @property id
* @type String
*/
id: null,
/**
* 传入构造器的配置项对象
* @property config
* @type object
*/
config: null,
/**
* 被拖动的元素id,默认与关联元素相同,但可替换为其他元素,如:Ext.dd.DDProxy
* @property dragElId
* @type String
* @private
*/
dragElId: null,
/**
* 初始化拖动操作的元素id,这是一个关联元素,但可改为这个元素的子元素。
* @property handleElId
* @type String
* @private
*/
handleElId: null,
/**
* 点击时要忽略的HTML标签名称。
* @property invalidHandleTypes
* @type {string: string}
*/
invalidHandleTypes: null,
/**
* 点击时要忽略的元素id。
* @property invalidHandleIds
* @type {string: string}
*/
invalidHandleIds: null,
/**
* 点击时要忽略的元素的css样式类名称所组成的数组。
* @property invalidHandleClasses
* @type string[]
*/
invalidHandleClasses: null,
/**
* 拖动开始时的x绝对位置
* @property startPageX
* @type int
* @private
*/
startPageX: 0,
/**
* 拖动开始时的y绝对位置
* @property startPageY
* @type int
* @private
*/
startPageY: 0,
/**
* 组(Group)定义,相关拖放对象的逻辑集合。
* 实例只能通过事件与同一组下面的其他拖放对象交互。
* 这使得我们可以将多个组定义在同一个子类下面。
* @property groups
* @type {string: string}
*/
groups: null,
/**
* 每个拖动/落下的实例可被锁定。
* 这会禁止onmousedown开始拖动。
* @property locked
* @type boolean
* @private
*/
locked: false,
/**
* 锁定实例
* @method lock
*/
lock: function() { this.locked = true; },
/**
* 解锁实例
* @method unlock
*/
unlock: function() { this.locked = false; },
/**
* 默认地,所有实例可以是降落目标。
* 该项可设置isTarget为false来禁止。
* @method isTarget
* @type boolean
*/
isTarget: true,
/**
* 当拖放对象与落下区域交互时的外补丁配置。
* @method padding
* @type int[]
*/
padding: null,
/**
* 缓存关联元素的引用。
* @property _domRef
* @private
*/
_domRef: null,
/**
* Internal typeof flag
* @property __ygDragDrop
* @private
*/
__ygDragDrop: true,
/**
* 当水平约束应用时为true。
* @property constrainX
* @type boolean
* @private
*/
constrainX: false,
/**
* 当垂直约束应用时为false。
* @property constrainY
* @type boolean
* @private
*/
constrainY: false,
/**
* 左边坐标
* @property minX
* @type int
* @private
*/
minX: 0,
/**
* 右边坐标
* @property maxX
* @type int
* @private
*/
maxX: 0,
/**
* 上方坐标
* @property minY
* @type int
* @type int
* @private
*/
minY: 0,
/**
* 下方坐标
* @property maxY
* @type int
* @private
*/
maxY: 0,
/**
* 当重置限制时(constraints)修正偏移。
* 如果你想在页面变动时,元素的位置与其父级元素的位置不发生变化,可设为true。
* @property maintainOffset
* @type boolean
*/
maintainOffset: false,
/**
* 如果我们指定一个垂直的间隔值,元素会作一个象素位置的取样,放到数组中。
* 如果你定义了一个tick interval,该数组将会自动生成。
* @property xTicks
* @type int[]
*/
xTicks: null,
/**
* 如果我们指定一个水平的间隔值,元素会作一个象素位置的取样,放到数组中。
* 如果你定义了一个tick interval,该数组将会自动生成。
* @property yTicks
* @type int[]
*/
yTicks: null,
/**
* 默认下拖放的实例只会响应主要的按钮键(左键和右键)。
* 设置为true表示开放其他的鼠标的键,只要是浏览器支持的。
* @property primaryButtonOnly
* @type boolean
*/
primaryButtonOnly: true,
/**
* 关联的dom元素访问之后该属性才为false。
* @property available
* @type boolean
*/
available: false,
/**
* 默认状态下,拖动只会是mousedown发生在关联元素的区域才会初始化。
* 但是因为某些浏览器的bug,如果之前的mouseup发生在window外部地方,浏览器会漏报告这个事件。
* 如果已定义外部的处理,这个属性应该设置为true.
* @property hasOuterHandles
* @type boolean
* @default false
*/
hasOuterHandles: false,
/**
* 在startDrag时间之前立即执行的代码。
* @method b4StartDrag
* @private
*/
b4StartDrag: function(x, y) { },
/**
* 抽象方法:在拖放对象被点击后和已跨入拖动或mousedown启动时间的时候调用。
* @method startDrag
* @param {int} X 方向点击位置
* @param {int} Y 方向点击位置
*/
startDrag: function(x, y) { /* override this */ },
/**
* onDrag事件发生之前执行的代码。
* @method b4Drag
* @private
*/
b4Drag: function(e) { },
/**
* 抽象方法:当拖动某个对象时发生onMouseMove时调用。
* @method onDrag
* @param {Event} e mousemove事件
*/
onDrag: function(e) { /* override this */ },
/**
* 抽象方法:在这个元素刚刚开始悬停在其他DD对象身上时调用。
* @method onDragEnter
* @param {Event} e mousemove事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组
*/
onDragEnter: function(e, id) { /* override this */ },
/**
* onDragOver事件发生在前执行的代码。
* @method b4DragOver
* @private
*/
b4DragOver: function(e) { },
/**
* 抽象方法:在这个元素悬停在其他DD对象范围内的调用。
* @method onDragOver
* @param {Event} e mousemove事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组
*/
onDragOver: function(e, id) { /* override this */ },
/**
* onDragOut事件发生之前执行的代码。
* @method b4DragOut
* @private
*/
b4DragOut: function(e) { },
/**
* 抽象方法:当不再有任何悬停DD对象的时候调用。
* @method onDragOut
* @param {Event} e mousemove事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, DD项不再悬浮。
*/
onDragOut: function(e, id) { /* override this */ },
/**
* onDragDrop事件发生之前执行的代码。
* @method b4DragDrop
* @private
*/
b4DragDrop: function(e) { },
/**
* 抽象方法:该项在另外一个DD对象上落下的时候调用。
* @method onDragDrop
* @param {Event} e mouseup事件
* @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组
*/
onDragDrop: function(e, id) { /* override this */ },
/**
* 抽象方法:当各项在一个没有置下目标的地方置下时调用。
* @method onInvalidDrop
* @param {Event} e mouseup事件
*/
onInvalidDrop: function(e) { /* override this */ },
/**
* 在endDrag事件触发之前立即执行的代码。
* @method b4EndDrag
* @private
*/
b4EndDrag: function(e) { },
/**
* 当我们完成拖动对象时触发的事件。
* @method endDrag
* @param {Event} e mouseup事件
*/
endDrag: function(e) { /* override this */ },
/**
* 在onMouseDown事件触发之前立即执行的代码。
* @method b4MouseDown
* @param {Event} e mousedown事件
* @private
*/
b4MouseDown: function(e) { },
/**
* 当拖放对象mousedown触发时的事件处理器。
* @method onMouseDown
* @param {Event} e mousedown事件
*/
onMouseDown: function(e) { /* override this */ },
/**
* 当DD对象发生mouseup事件时的事件处理器。
* @method onMouseUp
* @param {Event} e mouseup事件
*/
onMouseUp: function(e) { /* override this */ },
/**
* 重写onAvailable的方法以便我们在初始化之后做所需要的事情
* position was determined.
* @method onAvailable
*/
onAvailable: function () {
},
/*
* 为“constrainTo”的元素提供默认的外补丁限制。默认为{left: 0, right:0, top:0, bottom:0}
* @type Object
*/
defaultPadding : {left:0, right:0, top:0, bottom:0},
/**
*
* 初始化拖放对象的限制,以便控制在某个元的范围内移动
* 举例:
<pre><code>
var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest",
{ dragElId: "existingProxyDiv" });
dd.startDrag = function(){
this.constrainTo("parent-id");
};
</code></pre>
*或者你可以使用 {@link Ext.Element}对象初始化它:
<pre><code>
Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
startDrag : function(){
this.constrainTo("parent-id");
}
});
</code></pre>
* @param {String/HTMLElement/Element} constrainTo 要限制的元素
* @param {Object/Number} pad (可选的) Pad提供了指定“外补丁”的限制的一种方式。
* 例如 {left:4, right:4, top:4, bottom:4})或{right:10, bottom:10}
* @param {Boolean} inContent (可选的) 限制在元素的正文内容内拖动(包含外补丁和边框)
*/
constrainTo : function(constrainTo, pad, inContent){
if(typeof pad == "number"){
pad = {left: pad, right:pad, top:pad, bottom:pad};
}
pad = pad || this.defaultPadding;
var b = Ext.get(this.getEl()).getBox();
var ce = Ext.get(constrainTo);
var s = ce.getScroll();
var c, cd = ce.dom;
if(cd == document.body){
c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight()};
}else{
xy = ce.getXY();
c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight};
}
var topSpace = b.y - c.y;
var leftSpace = b.x - c.x;
this.resetConstraints();
this.setXConstraint(leftSpace - (pad.left||0), // left
c.width - leftSpace - b.width - (pad.right||0) //right
);
this.setYConstraint(topSpace - (pad.top||0), //top
c.height - topSpace - b.height - (pad.bottom||0) //bottom
);
},
/**
* 返回关联元素的引用
* @method getEl
* @return {HTMLElement} html元素
*/
getEl: function() {
if (!this._domRef) {
this._domRef = Ext.getDom(this.id);
}
return this._domRef;
},
/**
* 返回实际拖动元素的引用,默认时和html element一样,不过它可分配给其他元素,可在这里找到。
* @method getDragEl
* @return {HTMLElement} html元素
*/
getDragEl: function() {
return Ext.getDom(this.dragElId);
},
/**
* 设置拖放对象,须在Ext.dd.DragDrop子类的构造器调用。
* @method init
* @param id 关联元素之id
* @param {String} sGroup 相关项的组
* @param {object} config 配置属性
*/
init: function(id, sGroup, config) {
this.initTarget(id, sGroup, config);
Event.on(this.id, "mousedown", this.handleMouseDown, this);
// Event.on(this.id, "selectstart", Event.preventDefault);
},
/**
* 只是有针对性的初始化目标...对象获取不了mousedown handler
* @method initTarget
* @param id 关联元素之id
* @param {String} sGroup 相关项的组
* @param {object} config 配置属性
*/
initTarget: function(id, sGroup, config) {
// configuration attributes
this.config = config || {};
// create a local reference to the drag and drop manager
this.DDM = Ext.dd.DDM;
// initialize the groups array
this.groups = {};
// assume that we have an element reference instead of an id if the
// parameter is not a string
if (typeof id !== "string") {
id = Ext.id(id);
}
// set the id
this.id = id;
// add to an interaction group
this.addToGroup((sGroup) ? sGroup : "default");
// We don't want to register this as the handle with the manager
// so we just set the id rather than calling the setter.
this.handleElId = id;
// the linked element is the element that gets dragged by default
this.setDragElId(id);
// by default, clicked anchors will not start drag operations.
this.invalidHandleTypes = { A: "A" };
this.invalidHandleIds = {};
this.invalidHandleClasses = [];
this.applyConfig();
this.handleOnAvailable();
},
/**
* 将配置参数应用到构造器。该方法应该在继承链上的每一个环节调用。
* 所以为了获取每个对象的可用参数,配置将会由DDPRoxy实现应用在DDProxy, DD,DragDrop身上。
* @method applyConfig
*/
applyConfig: function() {
// configurable properties:
// padding, isTarget, maintainOffset, primaryButtonOnly
this.padding = this.config.padding || [0, 0, 0, 0];
this.isTarget = (this.config.isTarget !== false);
this.maintainOffset = (this.config.maintainOffset);
this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
},
/**
* 当关联元素有效时执行。
* @method handleOnAvailable
* @private
*/
handleOnAvailable: function() {
this.available = true;
this.resetConstraints();
this.onAvailable();
},
/**
* 配置目标区域的外补丁(px)。
* @method setPadding
* @param {int} iTop Top pad
* @param {int} iRight Right pad
* @param {int} iBot Bot pad
* @param {int} iLeft Left pad
*/
setPadding: function(iTop, iRight, iBot, iLeft) {
// this.padding = [iLeft, iRight, iTop, iBot];
if (!iRight && 0 !== iRight) {
this.padding = [iTop, iTop, iTop, iTop];
} else if (!iBot && 0 !== iBot) {
this.padding = [iTop, iRight, iTop, iRight];
} else {
this.padding = [iTop, iRight, iBot, iLeft];
}
},
/**
* 储存关联元素的初始位置。
* @method setInitialPosition
* @param {int} diffX X偏移,默认为0
* @param {int} diffY Y偏移,默认为0
*/
setInitPosition: function(diffX, diffY) {
var el = this.getEl();
if (!this.DDM.verifyEl(el)) {
return;
}
var dx = diffX || 0;
var dy = diffY || 0;
var p = Dom.getXY( el );
this.initPageX = p[0] - dx;
this.initPageY = p[1] - dy;
this.lastPageX = p[0];
this.lastPageY = p[1];
this.setStartPosition(p);
},
/**
* 设置元素的开始位置。对象初始化时便设置,拖动开始时复位。
* @method setStartPosition
* @param pos 当前位置(利用刚才的lookup)
* @private
*/
setStartPosition: function(pos) {
var p = pos || Dom.getXY( this.getEl() );
this.deltaSetXY = null;
this.startPageX = p[0];
this.startPageY = p[1];
},
/**
* 将该对象加入到相关的拖放组之中。
* 所有组实例至少要分配到一个组,也可以是多个组。
* @method addToGroup
* @param sGroup {string} 组名称
*/
addToGroup: function(sGroup) {
this.groups[sGroup] = true;
this.DDM.regDragDrop(this, sGroup);
},
/**
* 传入一个“交互组” interaction group的参数,从中删除该实例。
* @method removeFromGroup
* @param {string} sGroup 组名称
*/
removeFromGroup: function(sGroup) {
if (this.groups[sGroup]) {
delete this.groups[sGroup];
}
this.DDM.removeDDFromGroup(this, sGroup);
},
/**
* 允许你指定一个不是被移动的关联元素的元素作为拖动处理。
* @method setDragElId
* @param id {string} 将会用于初始拖动的元素id
*/
setDragElId: function(id) {
this.dragElId = id;
},
/**
* 允许你指定一个关联元素下面的子元素以初始化拖动操作。
* 一个例子就是假设你有一段套着div文本和若干连接,点击正文的区域便引发拖动的操作。
* 使用这个方法来指定正文内的div元素,然后拖动操作就会从这个元素开始了。
* @method setHandleElId
* @param id {string} 将会用于初始拖动的元素id
*/
setHandleElId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
this.handleElId = id;
this.DDM.regHandle(this.id, id);
},
/**
* 允许你在关联元素之外设置一个元素作为拖动处理。
* @method setOuterHandleElId
* @param id 将会用于初始拖动的元素id
*/
setOuterHandleElId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
Event.on(id, "mousedown",
this.handleMouseDown, this);
this.setHandleElId(id);
this.hasOuterHandles = true;
},
/**
* 移除所有钩在该元素身上的拖放对象。
* @method unreg
*/
unreg: function() {
Event.un(this.id, "mousedown",
this.handleMouseDown);
this._domRef = null;
this.DDM._remove(this);
},
destroy : function(){
this.unreg();
},
/**
* 返回true表示为该实例已被锁定,或者说是拖放控制器(DD Mgr)被锁定。
* @method isLocked
* @return {boolean} true表示禁止页面上的所有拖放操作,反之为false
*/
isLocked: function() {
return (this.DDM.isLocked() || this.locked);
},
/**
* 当对象单击时触发。
* @method handleMouseDown
* @param {Event} e
* @param {Ext.dd.DragDrop} 单击的 DD 对象(this DD obj)
* @private
*/
handleMouseDown: function(e, oDD){
if (this.primaryButtonOnly && e.button != 0) {
return;
}
if (this.isLocked()) {
return;
}
this.DDM.refreshCache(this.groups);
var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e));
if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
} else {
if (this.clickValidator(e)) {
// set the initial element position
this.setStartPosition();
this.b4MouseDown(e);
this.onMouseDown(e);
this.DDM.handleMouseDown(e, this);
this.DDM.stopEvent(e);
} else {
}
}
},
clickValidator: function(e) {
var target = e.getTarget();
return ( this.isValidHandleChild(target) &&
(this.id == this.handleElId ||
this.DDM.handleWasClicked(target, this.id)) );
},
/**
* 指定某个标签名称(tag Name),这个标签的元素单击时便不会引发拖动的操作。
* 这个设计目的在于某个拖动区域中同时又有链接(links)避免执行拖动的动作。
* @method addInvalidHandleType
* @param {string} tagName 避免执行元素的类型
*/
addInvalidHandleType: function(tagName) {
var type = tagName.toUpperCase();
this.invalidHandleTypes[type] = type;
},
/**
* 可指定某个元素的id,则这个id下的子元素将不会引发拖动的操作。
* @method addInvalidHandleId
* @param {string} id 你希望会被忽略的元素id
*/
addInvalidHandleId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
this.invalidHandleIds[id] = id;
},
/**
* 可指定某个css样式类,则这个css样式类的子元素将不会引发拖动的操作。
* @method addInvalidHandleClass
* @param {string} cssClass 你希望会被忽略的css样式类
*/
addInvalidHandleClass: function(cssClass) {
this.invalidHandleClasses.push(cssClass);
},
/**
* 移除由addInvalidHandleType方法所执行的标签名称。
* @method removeInvalidHandleType
* @param {string} tagName 元素类型
*/
removeInvalidHandleType: function(tagName) {
var type = tagName.toUpperCase();
// this.invalidHandleTypes[type] = null;
delete this.invalidHandleTypes[type];
},
/**
* 移除一个无效的handle id
* @method removeInvalidHandleId
* @param {string} id 要再“激活”的元素id
*/
removeInvalidHandleId: function(id) {
if (typeof id !== "string") {
id = Ext.id(id);
}
delete this.invalidHandleIds[id];
},
/**
* 移除一个无效的css class
* @method removeInvalidHandleClass
* @param {string} cssClass 你希望要再“激活”的元素id
* re-enable
*/
removeInvalidHandleClass: function(cssClass) {
for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
if (this.invalidHandleClasses[i] == cssClass) {
delete this.invalidHandleClasses[i];
}
}
},
/**
* 检查这次单击是否属于在标签排除列表里。
* @method isValidHandleChild
* @param {HTMLElement} node 检测的HTML元素
* @return {boolean} true 表示为这是一个有效的标签类型,反之为false
*/
isValidHandleChild: function(node) {
var valid = true;
// var n = (node.nodeName == "#text") ? node.parentNode : node;
var nodeName;
try {
nodeName = node.nodeName.toUpperCase();
} catch(e) {
nodeName = node.nodeName;
}
valid = valid && !this.invalidHandleTypes[nodeName];
valid = valid && !this.invalidHandleIds[node.id];
for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
}
return valid;
},
/**
* 若指定了间隔(interval),将会创建水平点击的标记(horizontal tick marks)的数组。
* @method setXTicks
* @private
*/
setXTicks: function(iStartX, iTickSize) {
this.xTicks = [];
this.xTickSize = iTickSize;
var tickMap = {};
for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
if (!tickMap[i]) {
this.xTicks[this.xTicks.length] = i;
tickMap[i] = true;
}
}
for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
if (!tickMap[i]) {
this.xTicks[this.xTicks.length] = i;
tickMap[i] = true;
}
}
this.xTicks.sort(this.DDM.numericSort) ;
},
/**
* 若指定了间隔(interval),将会创建垂直点击的标记(horizontal tick marks)的数组。
* @method setYTicks
* @private
*/
setYTicks: function(iStartY, iTickSize) {
this.yTicks = [];
this.yTickSize = iTickSize;
var tickMap = {};
for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
if (!tickMap[i]) {
this.yTicks[this.yTicks.length] = i;
tickMap[i] = true;
}
}
for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
if (!tickMap[i]) {
this.yTicks[this.yTicks.length] = i;
tickMap[i] = true;
}
}
this.yTicks.sort(this.DDM.numericSort) ;
},
/**
* 默认情况下,元素可被拖动到屏幕的任何一个位置。
* 使用该方法能限制元素的水平方向上的摇动。
* 如果打算只限制在Y轴的拖动,可传入0,0的参数。
* @method setXConstraint
* @param {int} iLeft 元素向左移动的像素值
* @param {int} iRight 元素向右移动的像素值
* @param {int} iTickSize (可选项)指定每次元素移动的步幅。
*/
setXConstraint: function(iLeft, iRight, iTickSize) {
this.leftConstraint = iLeft;
this.rightConstraint = iRight;
this.minX = this.initPageX - iLeft;
this.maxX = this.initPageX + iRight;
if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
this.constrainX = true;
},
/**
* 清除该实例的所有坐标。
* 也清除ticks,因为这时候已不存在任何的坐标。
* @method clearConstraints
*/
clearConstraints: function() {
this.constrainX = false;
this.constrainY = false;
this.clearTicks();
},
/**
* 清除该实例的所有tick间歇定义。
* @method clearTicks
*/
clearTicks: function() {
this.xTicks = null;
this.yTicks = null;
this.xTickSize = 0;
this.yTickSize = 0;
},
/**
* 默认情况下,元素可被拖动到屏幕的任何一个位置。
* 使用该方法能限制元素的水平方向上的摇动。
* 如果打算只限制在X轴的拖动,可传入0,0的参数。
* @method setYConstraint
* @param {int} iUp 元素向上移动的像素值
* @param {int} iDown 元素向下移动的像素值
* @param {int} iTickSize (可选项)指定每次元素移动的步幅。
*/
setYConstraint: function(iUp, iDown, iTickSize) {
this.topConstraint = iUp;
this.bottomConstraint = iDown;
this.minY = this.initPageY - iUp;
this.maxY = this.initPageY + iDown;
if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
this.constrainY = true;
},
/**
* 坐标复位需在你手动重新定位一个DD元素是调用。
* @method resetConstraints
* @param {boolean} maintainOffset
*/
resetConstraints: function() {
// Maintain offsets if necessary
if (this.initPageX || this.initPageX === 0) {
// figure out how much this thing has moved
var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
this.setInitPosition(dx, dy);
// This is the first time we have detected the element's position
} else {
this.setInitPosition();
}
if (this.constrainX) {
this.setXConstraint( this.leftConstraint,
this.rightConstraint,
this.xTickSize );
}
if (this.constrainY) {
this.setYConstraint( this.topConstraint,
this.bottomConstraint,
this.yTickSize );
}
},
/**
* 通常情况下拖动元素是逐个像素地移动的。
* 不过我们也可以指定一个移动的数值。
* @method getTick
* @param {int} val 打算将对象放到的地方
* @param {int[]} tickArray 已排序的有效点
* @return {int} 最近的点
* @private
*/
getTick: function(val, tickArray) {
if (!tickArray) {
// If tick interval is not defined, it is effectively 1 pixel,
// so we return the value passed to us.
return val;
} else if (tickArray[0] >= val) {
// The value is lower than the first tick, so we return the first
// tick.
return tickArray[0];
} else {
for (var i=0, len=tickArray.length; i<len; ++i) {
var next = i + 1;
if (tickArray[next] && tickArray[next] >= val) {
var diff1 = val - tickArray[i];
var diff2 = tickArray[next] - val;
return (diff2 > diff1) ? tickArray[i] : tickArray[next];
}
}
// The value is larger than the last tick, so we return the last
// tick.
return tickArray[tickArray.length - 1];
}
},
/**
* toString方法
* @method toString
* @return {string} string 表示DD对象之字符
*/
toString: function() {
return ("DragDrop " + this.id);
}
};
})();
/**
* The drag and drop utility provides a framework for building drag and drop
* applications. In addition to enabling drag and drop for specific elements,
* the drag and drop elements are tracked by the manager class, and the
* interactions between the various elements are tracked during the drag and
* the implementing code is notified about these important moments.
*/
// Only load the library once. Rewriting the manager class would orphan
// existing drag and drop instances.
if (!Ext.dd.DragDropMgr) {
/**
* @class Ext.dd.DragDropMgr
* DragDropMgr是一个对窗口内所有拖放项跟踪元素交互过程的单例。
* 一般来说你不会直接调用该类,但是你所实现的拖放中,会提供一些有用的方法。
* @singleton
*/
Ext.dd.DragDropMgr = function() {
var Event = Ext.EventManager;
return {
/**
* 已登记拖放对象的二维数组。
* 第一维是拖放项的组,第二维是拖放对象。
* @property ids
* @type {string: string}
* @private
* @static
*/
ids: {},
/**
* 元素id组成的数组,由拖动处理定义。
* 如果元素触发了mousedown事件实际上是一个处理(handle)而非html元素本身。
* @property handleIds
* @type {string: string}
* @private
* @static
*/
handleIds: {},
/**
* 正在被拖放的DD对象。
* @property dragCurrent
* @type DragDrop
* @private
* @static
**/
dragCurrent: null,
/**
* 正被悬浮着的拖放对象。
* @property dragOvers
* @type Array
* @private
* @static
*/
dragOvers: {},
/**
* 正被拖动对象与指针之间的X间距。
* @property deltaX
* @type int
* @private
* @static
*/
deltaX: 0,
/**
* 正被拖动对象与指针之间的Y间距。
* @property deltaY
* @type int
* @private
* @static
*/
deltaY: 0,
/**
* 一个是否应该阻止我们所定义的默认行为的标识。
* 默认为true,如需默认的行为可设为false(但不推荐)。
* @property preventDefault
* @type boolean
* @static
*/
preventDefault: true,
/**
* 一个是否在该停止事件繁殖的标识(events propagation)。
* 默认下为true,但如果HTML元素包含了其他mouse点击的所需功能,就可设为false。
* @property stopPropagation
* @type boolean
* @static
*/
stopPropagation: true,
/**
* 一个内置使用的标识,True说明拖放已被初始化。
* @property initialized
* @private
* @static
*/
initalized: false,
/**
* 所有拖放的操作可被禁用。
* @property locked
* @private
* @static
*/
locked: false,
/**
* 元素首次注册时调用。
* @method init
* @private
* @static
*/
init: function() {
this.initialized = true;
},
/**
* 由拖放过程中的鼠标指针来定义拖放的交互操作。
* @property POINT
* @type int
* @static
*/
POINT: 0,
/**
* Intersect模式下,拖放的交互是由两个或两个以上的拖放对象的重叠来定义。
* @property INTERSECT
* @type int
* @static
*/
INTERSECT: 1,
/**
* 当前拖放的模式,默认为:POINT
* @property mode
* @type int
* @static
*/
mode: 0,
/**
* 在拖放对象上运行方法
* @method _execOnAll
* @private
* @static
*/
_execOnAll: function(sMethod, args) {
for (var i in this.ids) {
for (var j in this.ids[i]) {
var oDD = this.ids[i][j];
if (! this.isTypeOfDD(oDD)) {
continue;
}
oDD[sMethod].apply(oDD, args);
}
}
},
/**
* 拖放的初始化,设置全局的事件处理器。
* @method _onLoad
* @private
* @static
*/
_onLoad: function() {
this.init();
Event.on(document, "mouseup", this.handleMouseUp, this, true);
Event.on(document, "mousemove", this.handleMouseMove, this, true);
Event.on(window, "unload", this._onUnload, this, true);
Event.on(window, "resize", this._onResize, this, true);
// Event.on(window, "mouseout", this._test);
},
/**
* 重置拖放对象身上的全部限制。
* @method _onResize
* @private
* @static
*/
_onResize: function(e) {
this._execOnAll("resetConstraints", []);
},
/**
* 锁定拖放的功能。
* @method lock
* @static
*/
lock: function() { this.locked = true; },
/**
* 解锁拖放的功能。
* @method unlock
* @static
*/
unlock: function() { this.locked = false; },
/**
* 拖放是否已锁定?
* @method isLocked
* @return {boolean} True 表示为拖放已锁定,反之为false。
* @static
*/
isLocked: function() { return this.locked; },
/**
* 拖动一开始,就会有“局部缓存”伴随着拖放对象,而拖动完毕就会清除。
* @property locationCache
* @private
* @static
*/
locationCache: {},
/**
* 设置useCache为false的话,表示你想强制对象不断在每个拖放关联对象中轮询。
* @property useCache
* @type boolean
* @static
*/
useCache: true,
/**
* 在mousedown之后,拖动初始化之前,鼠标需要移动的像素值。默认值为3
* @property clickPixelThresh
* @type int
* @static
*/
clickPixelThresh: 3,
/**
* 在mousedown事件触发之后,接着开始拖动但不想触发mouseup的事件的毫秒数。默认值为1000
* @property clickTimeThresh
* @type int
* @static
*/
clickTimeThresh: 350,
/**
* 每当满足拖动像素或mousedown时间的标识。
* @property dragThreshMet
* @type boolean
* @private
* @static
*/
dragThreshMet: false,
/**
* 开始点击的超时时限。
* @property clickTimeout
* @type Object
* @private
* @static
*/
clickTimeout: null,
/**
* 拖动动作刚开始,保存mousedown事件的X位置。
* @property startX
* @type int
* @private
* @static
*/
startX: 0,
/**
* 拖动动作刚开始,保存mousedown事件的Y位置。
* @property startY
* @type int
* @private
* @static
*/
startY: 0,
/**
* 每个拖放实例必须在DragDropMgr登记好的。
* @method regDragDrop
* @param {DragDrop} oDD 要登记的拖动对象
* @param {String} sGroup 元素所属的组名称
* @static
*/
regDragDrop: function(oDD, sGroup) {
if (!this.initialized) { this.init(); }
if (!this.ids[sGroup]) {
this.ids[sGroup] = {};
}
this.ids[sGroup][oDD.id] = oDD;
},
/**
* 传入两个参数oDD、sGroup,从传入的组之中删除DD实例。
* 由DragDrop.removeFromGroup执行,所以不会直接调用这个函数。
* @method removeDDFromGroup
* @private
* @static
*/
removeDDFromGroup: function(oDD, sGroup) {
if (!this.ids[sGroup]) {
this.ids[sGroup] = {};
}
var obj = this.ids[sGroup];
if (obj && obj[oDD.id]) {
delete obj[oDD.id];
}
},
/**
* 注销拖放项,由DragDrop.unreg所调用,直接使用那个方法即可。
* @method _remove
* @private
* @static
*/
_remove: function(oDD) {
for (var g in oDD.groups) {
if (g && this.ids[g][oDD.id]) {
delete this.ids[g][oDD.id];
}
}
delete this.handleIds[oDD.id];
},
/**
* 每个拖放处理元素必须先登记。
* 执行DragDrop.setHandleElId()时会自动完成这工作。
* @method regHandle
* @param {String} sDDId 处理拖放对象的id
* @param {String} sHandleId 在拖动的元素id
* handle
* @static
*/
regHandle: function(sDDId, sHandleId) {
if (!this.handleIds[sDDId]) {
this.handleIds[sDDId] = {};
}
this.handleIds[sDDId][sHandleId] = sHandleId;
},
/**
* 确认一个元素是否属于已注册的拖放项的实用函数。
* @method isDragDrop
* @param {String} id 要检查的元素id
* @return {boolean} true 表示为该元素是一个拖放项,反之为false
* @static
*/
isDragDrop: function(id) {
return ( this.getDDById(id) ) ? true : false;
},
/**
* 传入一个拖放实例的参数,返回在这个实例“组”下面的全部其他拖放实例。
* @method getRelated
* @param {DragDrop} p_oDD 获取相关数据的对象
* @param {boolean} bTargetsOnly if true 表示为只返回目标对象
* @return {DragDrop[]} 相关的实例
* @static
*/
getRelated: function(p_oDD, bTargetsOnly) {
var oDDs = [];
for (var i in p_oDD.groups) {
for (j in this.ids[i]) {
var dd = this.ids[i][j];
if (! this.isTypeOfDD(dd)) {
continue;
}
if (!bTargetsOnly || dd.isTarget) {
oDDs[oDDs.length] = dd;
}
}
}
return oDDs;
},
/**
* 针对某些特定的拖动对象,如果传入的dd目标是合法的目标,返回ture。
* @method isLegalTarget
* @param {DragDrop} 拖动对象
* @param {DragDrop} 目标
* @return {boolean} true 表示为目标是dd对象合法
* @static
*/
isLegalTarget: function (oDD, oTargetDD) {
var targets = this.getRelated(oDD, true);
for (var i=0, len=targets.length;i<len;++i) {
if (targets[i].id == oTargetDD.id) {
return true;
}
}
return false;
},
/**
* My goal is to be able to transparently determine if an object is
* typeof DragDrop, and the exact subclass of DragDrop. typeof
* returns "object", oDD.constructor.toString() always returns
* "DragDrop" and not the name of the subclass. So for now it just
* evaluates a well-known variable in DragDrop.
* @method isTypeOfDD
* @param {Object} 要计算的对象
* @return {boolean} true 表示为typeof oDD = DragDrop
* @static
*/
isTypeOfDD: function (oDD) {
return (oDD && oDD.__ygDragDrop);
},
/**
* 指定拖放对象,检测给出的元素是否属于已登记的拖放处理中的一员。
* @method isHandle
* @param {String} id 要检测的对象
* @return {boolean} True表示为元素是拖放的处理
* @static
*/
isHandle: function(sDDId, sHandleId) {
return ( this.handleIds[sDDId] &&
this.handleIds[sDDId][sHandleId] );
},
/**
* 指定一个id,返回该id的拖放实例。
* @method getDDById
* @param {String} id 拖放对象的id
* @return {DragDrop} 拖放对象,null表示为找不到
* @static
*/
getDDById: function(id) {
for (var i in this.ids) {
if (this.ids[i][id]) {
return this.ids[i][id];
}
}
return null;
},
/**
* 在一个已登记的拖放对象上发生mousedown事件之后触发。
* @method handleMouseDown
* @param {Event} e 事件
* @param oDD 被拖动的拖放对象
* @private
* @static
*/
handleMouseDown: function(e, oDD) {
if(Ext.QuickTips){
Ext.QuickTips.disable();
}
this.currentTarget = e.getTarget();
this.dragCurrent = oDD;
var el = oDD.getEl();
// track start position
this.startX = e.getPageX();
this.startY = e.getPageY();
this.deltaX = this.startX - el.offsetLeft;
this.deltaY = this.startY - el.offsetTop;
this.dragThreshMet = false;
this.clickTimeout = setTimeout(
function() {
var DDM = Ext.dd.DDM;
DDM.startDrag(DDM.startX, DDM.startY);
},
this.clickTimeThresh );
},
/**
* 当拖动象素开始启动或mousedown保持事件正好发生的时候发生。
* @method startDrag
* @param x {int} 原始mousedown发生的X位置
* @param y {int} 原始mousedown发生的Y位置
* @static
*/
startDrag: function(x, y) {
clearTimeout(this.clickTimeout);
if (this.dragCurrent) {
this.dragCurrent.b4StartDrag(x, y);
this.dragCurrent.startDrag(x, y);
}
this.dragThreshMet = true;
},
/**
* 处理MouseUp事件的内置函数,会涉及文档的上下文内容。
* @method handleMouseUp
* @param {Event} e 事件
* @private
* @static
*/
handleMouseUp: function(e) {
if(Ext.QuickTips){
Ext.QuickTips.enable();
}
if (! this.dragCurrent) {
return;
}
clearTimeout(this.clickTimeout);
if (this.dragThreshMet) {
this.fireEvents(e, true);
} else {
}
this.stopDrag(e);
this.stopEvent(e);
},
/**
* 如果停止事件值和默认(event propagation)的一项被打开,要执行的实用函数。
* @method stopEvent
* @param {Event} e 由this.getEvent()返回的事件
* @static
*/
stopEvent: function(e){
if(this.stopPropagation) {
e.stopPropagation();
}
if (this.preventDefault) {
e.preventDefault();
}
},
/**
* 内置函数,用于在拖动操作完成后清理事件处理器(event handlers)
* @method stopDrag
* @param {Event} e 事件
* @private
* @static
*/
stopDrag: function(e) {
// Fire the drag end event for the item that was dragged
if (this.dragCurrent) {
if (this.dragThreshMet) {
this.dragCurrent.b4EndDrag(e);
this.dragCurrent.endDrag(e);
}
this.dragCurrent.onMouseUp(e);
}
this.dragCurrent = null;
this.dragOvers = {};
},
/**
* 处理mousemove事件的内置函数,会涉及html元素的上下文内容。
* @TODO figure out what we can do about mouse events lost when the
* user drags objects beyond the window boundary. Currently we can
* detect this in internet explorer by verifying that the mouse is
* down during the mousemove event. Firefox doesn't give us the
* button state on the mousemove event.
* @method handleMouseMove
* @param {Event} e 事件
* @private
* @static
*/
handleMouseMove: function(e) {
if (! this.dragCurrent) {
return true;
}
// var button = e.which || e.button;
// check for IE mouseup outside of page boundary
if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
this.stopEvent(e);
return this.handleMouseUp(e);
}
if (!this.dragThreshMet) {
var diffX = Math.abs(this.startX - e.getPageX());
var diffY = Math.abs(this.startY - e.getPageY());
if (diffX > this.clickPixelThresh ||
diffY > this.clickPixelThresh) {
this.startDrag(this.startX, this.startY);
}
}
if (this.dragThreshMet) {
this.dragCurrent.b4Drag(e);
this.dragCurrent.onDrag(e);
if(!this.dragCurrent.moveOnly){
this.fireEvents(e, false);
}
}
this.stopEvent(e);
return true;
},
/**
* 遍历所有的拖放对象找出我们悬浮或落下的那一个。
* @method fireEvents
* @param {Event} e 事件
* @param {boolean} isDrop 是drop还是mouseover?
* @private
* @static
*/
fireEvents: function(e, isDrop) {
var dc = this.dragCurrent;
// If the user did the mouse up outside of the window, we could
// get here even though we have ended the drag.
if (!dc || dc.isLocked()) {
return;
}
var pt = e.getPoint();
// cache the previous dragOver array
var oldOvers = [];
var outEvts = [];
var overEvts = [];
var dropEvts = [];
var enterEvts = [];
// Check to see if the object(s) we were hovering over is no longer
// being hovered over so we can fire the onDragOut event
for (var i in this.dragOvers) {
var ddo = this.dragOvers[i];
if (! this.isTypeOfDD(ddo)) {
continue;
}
if (! this.isOverTarget(pt, ddo, this.mode)) {
outEvts.push( ddo );
}
oldOvers[i] = true;
delete this.dragOvers[i];
}
for (var sGroup in dc.groups) {
if ("string" != typeof sGroup) {
continue;
}
for (i in this.ids[sGroup]) {
var oDD = this.ids[sGroup][i];
if (! this.isTypeOfDD(oDD)) {
continue;
}
if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
if (this.isOverTarget(pt, oDD, this.mode)) {
// look for drop interactions
if (isDrop) {
dropEvts.push( oDD );
// look for drag enter and drag over interactions
} else {
// initial drag over: dragEnter fires
if (!oldOvers[oDD.id]) {
enterEvts.push( oDD );
// subsequent drag overs: dragOver fires
} else {
overEvts.push( oDD );
}
this.dragOvers[oDD.id] = oDD;
}
}
}
}
}
if (this.mode) {
if (outEvts.length) {
dc.b4DragOut(e, outEvts);
dc.onDragOut(e, outEvts);
}
if (enterEvts.length) {
dc.onDragEnter(e, enterEvts);
}
if (overEvts.length) {
dc.b4DragOver(e, overEvts);
dc.onDragOver(e, overEvts);
}
if (dropEvts.length) {
dc.b4DragDrop(e, dropEvts);
dc.onDragDrop(e, dropEvts);
}
} else {
// fire dragout events
var len = 0;
for (i=0, len=outEvts.length; i<len; ++i) {
dc.b4DragOut(e, outEvts[i].id);
dc.onDragOut(e, outEvts[i].id);
}
// fire enter events
for (i=0,len=enterEvts.length; i<len; ++i) {
// dc.b4DragEnter(e, oDD.id);
dc.onDragEnter(e, enterEvts[i].id);
}
// fire over events
for (i=0,len=overEvts.length; i<len; ++i) {
dc.b4DragOver(e, overEvts[i].id);
dc.onDragOver(e, overEvts[i].id);
}
// fire drop events
for (i=0, len=dropEvts.length; i<len; ++i) {
dc.b4DragDrop(e, dropEvts[i].id);
dc.onDragDrop(e, dropEvts[i].id);
}
}
// notify about a drop that did not find a target
if (isDrop && !dropEvts.length) {
dc.onInvalidDrop(e);
}
},
/**
* 当INTERSECT模式时,通过拖放事件返回拖放对象的列表。
* 这个辅助函数的作用是在这份列表中获取最适合的配对。
* 有时返回指鼠标下方的第一个对象,有时返回与拖动对象重叠的最大一个对象。
* @method getBestMatch
* @param {DragDrop[]} dds 拖放对象之数组
* targeted
* @return {DragDrop} 最佳的单个配对
* @static
*/
getBestMatch: function(dds) {
var winner = null;
// Return null if the input is not what we expect
//if (!dds || !dds.length || dds.length == 0) {
// winner = null;
// If there is only one item, it wins
//} else if (dds.length == 1) {
var len = dds.length;
if (len == 1) {
winner = dds[0];
} else {
// Loop through the targeted items
for (var i=0; i<len; ++i) {
var dd = dds[i];
// If the cursor is over the object, it wins. If the
// cursor is over multiple matches, the first one we come
// to wins.
if (dd.cursorIsOver) {
winner = dd;
break;
// Otherwise the object with the most overlap wins
} else {
if (!winner ||
winner.overlap.getArea() < dd.overlap.getArea()) {
winner = dd;
}
}
}
}
return winner;
},
/**
* 在指定组中,刷新位于左上方和右下角的点的缓存。
* 这是保存在拖放实例中的格式。所以典型的用法是:
* <code>
* Ext.dd.DragDropMgr.refreshCache(ddinstance.groups);
* </code>
* 也可这样:
* <code>
* Ext.dd.DragDropMgr.refreshCache({group1:true, group2:true});
* </code>
* @TODO this really should be an indexed array. Alternatively this
* method could accept both.
* @method refreshCache
* @param {Object} groups 要刷新的关联组的数组
* @static
*/
refreshCache: function(groups) {
for (var sGroup in groups) {
if ("string" != typeof sGroup) {
continue;
}
for (var i in this.ids[sGroup]) {
var oDD = this.ids[sGroup][i];
if (this.isTypeOfDD(oDD)) {
// if (this.isTypeOfDD(oDD) && oDD.isTarget) {
var loc = this.getLocation(oDD);
if (loc) {
this.locationCache[oDD.id] = loc;
} else {
delete this.locationCache[oDD.id];
// this will unregister the drag and drop object if
// the element is not in a usable state
// oDD.unreg();
}
}
}
}
},
/**
* 检验一个元素是否存在DOM树中,该方法用于innerHTML。
* @method verifyEl
* @param {HTMLElement} el 要检测的元素
* @return {boolean} true 表示为元素似乎可用
* @static
*/
verifyEl: function(el) {
if (el) {
var parent;
if(Ext.isIE){
try{
parent = el.offsetParent;
}catch(e){}
}else{
parent = el.offsetParent;
}
if (parent) {
return true;
}
}
return false;
},
/**
* 返回一个区域对象(Region Object)。
* 这个区域包含拖放元素位置、大小、和针对其配置好的内补丁(padding)
* @method getLocation
* @param {DragDrop} oDD 要获取所在位置的拖放对象
* @return {Ext.lib.Region} 区域对象,包括元素占位,该实例配置的外补丁。
* @static
*/
getLocation: function(oDD) {
if (! this.isTypeOfDD(oDD)) {
return null;
}
var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
try {
pos= Ext.lib.Dom.getXY(el);
} catch (e) { }
if (!pos) {
return null;
}
x1 = pos[0];
x2 = x1 + el.offsetWidth;
y1 = pos[1];
y2 = y1 + el.offsetHeight;
t = y1 - oDD.padding[0];
r = x2 + oDD.padding[1];
b = y2 + oDD.padding[2];
l = x1 - oDD.padding[3];
return new Ext.lib.Region( t, r, b, l );
},
/**
* 检查鼠标指针是否位于目标的上方。
* @method isOverTarget
* @param {Ext.lib.Point} pt 要检测的点
* @param {DragDrop} oTarget 要检测的拖放对象
* @return {boolean} true 表示为鼠标位于目标上方
* @private
* @static
*/
isOverTarget: function(pt, oTarget, intersect) {
// use cache if available
var loc = this.locationCache[oTarget.id];
if (!loc || !this.useCache) {
loc = this.getLocation(oTarget);
this.locationCache[oTarget.id] = loc;
}
if (!loc) {
return false;
}
oTarget.cursorIsOver = loc.contains( pt );
// DragDrop is using this as a sanity check for the initial mousedown
// in this case we are done. In POINT mode, if the drag obj has no
// contraints, we are also done. Otherwise we need to evaluate the
// location of the target as related to the actual location of the
// dragged element.
var dc = this.dragCurrent;
if (!dc || !dc.getTargetCoord ||
(!intersect && !dc.constrainX && !dc.constrainY)) {
return oTarget.cursorIsOver;
}
oTarget.overlap = null;
// Get the current location of the drag element, this is the
// location of the mouse event less the delta that represents
// where the original mousedown happened on the element. We
// need to consider constraints and ticks as well.
var pos = dc.getTargetCoord(pt.x, pt.y);
var el = dc.getDragEl();
var curRegion = new Ext.lib.Region( pos.y,
pos.x + el.offsetWidth,
pos.y + el.offsetHeight,
pos.x );
var overlap = curRegion.intersect(loc);
if (overlap) {
oTarget.overlap = overlap;
return (intersect) ? true : oTarget.cursorIsOver;
} else {
return false;
}
},
/**
* 卸下事件处理器。
* @method _onUnload
* @private
* @static
*/
_onUnload: function(e, me) {
Ext.dd.DragDropMgr.unregAll();
},
/**
* 清除拖放事件和对象。
* @method unregAll
* @private
* @static
*/
unregAll: function() {
if (this.dragCurrent) {
this.stopDrag();
this.dragCurrent = null;
}
this._execOnAll("unreg", []);
for (i in this.elementCache) {
delete this.elementCache[i];
}
this.elementCache = {};
this.ids = {};
},
/**
* DOM元素的缓存。
* @property elementCache
* @private
* @static
*/
elementCache: {},
/**
* 返回DOM元素所指定的包装器。
* @method getElWrapper
* @param {String} id 要获取的元素id
* @return {Ext.dd.DDM.ElementWrapper} 包装好的元素
* @private
* @deprecated 该包装器用途较小
* @static
*/
getElWrapper: function(id) {
var oWrapper = this.elementCache[id];
if (!oWrapper || !oWrapper.el) {
oWrapper = this.elementCache[id] =
new this.ElementWrapper(Ext.getDom(id));
}
return oWrapper;
},
/**
* 返回实际的DOM元素。
* @method getElement
* @param {String} id 要获取的元素的id
* @return {Object} 元素
* @deprecated 推荐使用Ext.lib.Ext.getDom
* @static
*/
getElement: function(id) {
return Ext.getDom(id);
},
/**
* 返回该DOM元素的样式属性。
* @method getCss
* @param {String} id 要获取元素的id
* @return {Object} 元素样式属性
* @deprecated 推荐使用Ext.lib.Dom
* @static
*/
getCss: function(id) {
var el = Ext.getDom(id);
return (el) ? el.style : null;
},
/**
* 缓冲元素的内置类
* @class DragDropMgr.ElementWrapper
* @for DragDropMgr
* @private
* @deprecated
*/
ElementWrapper: function(el) {
/**
* The element
* @property el
*/
this.el = el || null;
/**
* The element id
* @property id
*/
this.id = this.el && el.id;
/**
* A reference to the style property
* @property css
*/
this.css = this.el && el.style;
},
/**
* 返回html元素的X坐标。
* @method getPosX
* @param el 指获取坐标的元素
* @return {int} x坐标
* @for DragDropMgr
* @deprecated 推荐使用Ext.lib.Dom.getX
* @static
*/
getPosX: function(el) {
return Ext.lib.Dom.getX(el);
},
/**
* 返回html元素的Y坐标。
* @method getPosY
* @param el 指获取坐标的元素
* @return {int} y坐标
* @deprecated 推荐使用Ext.lib.Dom.getY
* @static
*/
getPosY: function(el) {
return Ext.lib.Dom.getY(el);
},
/**
* 调换两个节点,对于IE,我们使用原生的方法。
* @method swapNode
* @param n1 要调换的第一个节点
* @param n2 要调换的其他节点
* @static
*/
swapNode: function(n1, n2) {
if (n1.swapNode) {
n1.swapNode(n2);
} else {
var p = n2.parentNode;
var s = n2.nextSibling;
if (s == n1) {
p.insertBefore(n1, n2);
} else if (n2 == n1.nextSibling) {
p.insertBefore(n2, n1);
} else {
n1.parentNode.replaceChild(n2, n1);
p.insertBefore(n1, s);
}
}
},
/**
* 返回当前滚动位置。
* @method getScroll
* @private
* @static
*/
getScroll: function () {
var t, l, dde=document.documentElement, db=document.body;
if (dde && (dde.scrollTop || dde.scrollLeft)) {
t = dde.scrollTop;
l = dde.scrollLeft;
} else if (db) {
t = db.scrollTop;
l = db.scrollLeft;
} else {
}
return { top: t, left: l };
},
/**
* 指定一个元素,返回其样式的某个属性。
* @method getStyle
* @param {HTMLElement} el 元素
* @param {string} styleProp 样式名称
* @return {string} 样式值
* @deprecated use Ext.lib.Dom.getStyle
* @static
*/
getStyle: function(el, styleProp) {
return Ext.fly(el).getStyle(styleProp);
},
/**
* 获取scrollTop
* @method getScrollTop
* @return {int} 文档的scrollTop
* @static
*/
getScrollTop: function () { return this.getScroll().top; },
/**
* 获取scrollLeft
* @method getScrollLeft
* @return {int} 文档的scrollTop
* @static
*/
getScrollLeft: function () { return this.getScroll().left; },
/**
* 根据目标元素的位置,设置元素的X/Y位置。
* @method moveToEl
* @param {HTMLElement} moveEl 要移动的元素
* @param {HTMLElement} targetEl 引用元素的位置
* @static
*/
moveToEl: function (moveEl, targetEl) {
var aCoord = Ext.lib.Dom.getXY(targetEl);
Ext.lib.Dom.setXY(moveEl, aCoord);
},
/**
* 数组排列函数
* @method numericSort
* @static
*/
numericSort: function(a, b) { return (a - b); },
/**
* 局部计算器
* @property _timeoutCount
* @private
* @static
*/
_timeoutCount: 0,
/**
* 试着押后加载,这样便不会在Event Utility文件加载之前出现的错误。
* @method _addListeners
* @private
* @static
*/
_addListeners: function() {
var DDM = Ext.dd.DDM;
if ( Ext.lib.Event && document ) {
DDM._onLoad();
} else {
if (DDM._timeoutCount > 2000) {
} else {
setTimeout(DDM._addListeners, 10);
if (document && document.body) {
DDM._timeoutCount += 1;
}
}
}
},
/**
* 递归搜索最靠近的父、子元素,以便确定处理的元素是否被单击。
* @method handleWasClicked
* @param node 要检测的html元素
* @static
*/
handleWasClicked: function(node, id) {
if (this.isHandle(id, node.id)) {
return true;
} else {
// check to see if this is a text node child of the one we want
var p = node.parentNode;
while (p) {
if (this.isHandle(id, p.id)) {
return true;
} else {
p = p.parentNode;
}
}
}
return false;
}
};
}();
// shorter alias, save a few bytes
Ext.dd.DDM = Ext.dd.DragDropMgr;
Ext.dd.DDM._addListeners();
}
/**
* @class Ext.dd.DD
* 在拖动过程中随伴鼠标指针关联元素的一个播放实现。
* @extends Ext.dd.DragDrop
* @constructor
* @param {String} id 关联元素的id
* @param {String} sGroup 关联拖放项的组
* @param {object} config 包含DD的有效配置属性:
* scroll
*/
Ext.dd.DD = function(id, sGroup, config) {
if (id) {
this.init(id, sGroup, config);
}
};
Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, {
/**
* 设置为true时,游览器窗口会自动滚动,如果拖放元素被拖到视图的边界,默认为true。
* @property scroll
* @type boolean
*/
scroll: true,
/**
* 在关联元素的左上角和元素点击所在位置之间设置一个指针偏移的距离。
* @method autoOffset
* @param {int} iPageX 点击的X坐标
* @param {int} iPageY 点击的Y坐标
*/
autoOffset: function(iPageX, iPageY) {
var x = iPageX - this.startPageX;
var y = iPageY - this.startPageY;
this.setDelta(x, y);
},
/**
* 设置指针偏移,你可以直接调用以强制偏移到新特殊的位置(像传入0,0,即设置成为对象的一角)。
* @method setDelta
* @param {int} iDeltaX 从左边算起的距离
* @param {int} iDeltaY 从上面算起的距离
*/
setDelta: function(iDeltaX, iDeltaY) {
this.deltaX = iDeltaX;
this.deltaY = iDeltaY;
},
/**
* 设置拖动元素到mousedown或点击事件的位置继续保持指针相关联元素点击的位置。
* 如果打算将元素放到某个位置而非指针位置,你可重写该方法。
* @method setDragElPos
* @param {int} iPageX mousedown或拖动事件的X坐标
* @param {int} iPageY mousedown或拖动事件的Y坐标
*/
setDragElPos: function(iPageX, iPageY) {
// the first time we do this, we are going to check to make sure
// the element has css positioning
var el = this.getDragEl();
this.alignElWithMouse(el, iPageX, iPageY);
},
/**
* 设置元素到mousedown或点击事件的位置继续保持指针相关联元素点击的位置。
* 如果打算将元素放到某个位置而非指针位置,你可重写该方法。
* @method alignElWithMouse
* @param {HTMLElement} el the element to move
* @param {int} iPageX mousedown或拖动事件的X坐标
* @param {int} iPageY mousedown或拖动事件的Y坐标
*/
alignElWithMouse: function(el, iPageX, iPageY) {
var oCoord = this.getTargetCoord(iPageX, iPageY);
var fly = el.dom ? el : Ext.fly(el);
if (!this.deltaSetXY) {
var aCoord = [oCoord.x, oCoord.y];
fly.setXY(aCoord);
var newLeft = fly.getLeft(true);
var newTop = fly.getTop(true);
this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
} else {
fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
}
this.cachePosition(oCoord.x, oCoord.y);
this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
return oCoord;
},
/**
* 保存最近的位置,以便我们重量限制和所需要的点击标记。
* 我们需要清楚这些以便计算元素偏移原来位置的像素值。
* @method cachePosition
* @param iPageX 当前X位置(可选的),只要为了以后不用再查询
* @param iPageY 当前Y位置(可选的),只要为了以后不用再查询
*/
cachePosition: function(iPageX, iPageY) {
if (iPageX) {
this.lastPageX = iPageX;
this.lastPageY = iPageY;
} else {
var aCoord = Ext.lib.Dom.getXY(this.getEl());
this.lastPageX = aCoord[0];
this.lastPageY = aCoord[1];
}
},
/**
* 如果拖动对象移动到可视窗口之外的区域,就自动滚动window。
* @method autoScroll
* @param {int} x 拖动元素X坐标
* @param {int} y 拖动元素Y坐标
* @param {int} h 拖动元素的高度
* @param {int} w 拖动元素的宽度
* @private
*/
autoScroll: function(x, y, h, w) {
if (this.scroll) {
// The client height
var clientH = Ext.lib.Dom.getViewWidth();
// The client width
var clientW = Ext.lib.Dom.getViewHeight();
// The amt scrolled down
var st = this.DDM.getScrollTop();
// The amt scrolled right
var sl = this.DDM.getScrollLeft();
// Location of the bottom of the element
var bot = h + y;
// Location of the right of the element
var right = w + x;
// The distance from the cursor to the bottom of the visible area,
// adjusted so that we don't scroll if the cursor is beyond the
// element drag constraints
var toBot = (clientH + st - y - this.deltaY);
// The distance from the cursor to the right of the visible area
var toRight = (clientW + sl - x - this.deltaX);
// How close to the edge the cursor must be before we scroll
// var thresh = (document.all) ? 100 : 40;
var thresh = 40;
// How many pixels to scroll per autoscroll op. This helps to reduce
// clunky scrolling. IE is more sensitive about this ... it needs this
// value to be higher.
var scrAmt = (document.all) ? 80 : 30;
// Scroll down if we are near the bottom of the visible page and the
// obj extends below the crease
if ( bot > clientH && toBot < thresh ) {
window.scrollTo(sl, st + scrAmt);
}
// Scroll up if the window is scrolled down and the top of the object
// goes above the top border
if ( y < st && st > 0 && y - st < thresh ) {
window.scrollTo(sl, st - scrAmt);
}
// Scroll right if the obj is beyond the right border and the cursor is
// near the border.
if ( right > clientW && toRight < thresh ) {
window.scrollTo(sl + scrAmt, st);
}
// Scroll left if the window has been scrolled to the right and the obj
// extends past the left border
if ( x < sl && sl > 0 && x - sl < thresh ) {
window.scrollTo(sl - scrAmt, st);
}
}
},
/**
* 找到元素应该放下的位置。
* @method getTargetCoord
* @param {int} iPageX 点击的X坐标
* @param {int} iPageY 点击的Y坐标
* @return 包含坐标的对象(Object.x和Object.y)
* @private
*/
getTargetCoord: function(iPageX, iPageY) {
var x = iPageX - this.deltaX;
var y = iPageY - this.deltaY;
if (this.constrainX) {
if (x < this.minX) { x = this.minX; }
if (x > this.maxX) { x = this.maxX; }
}
if (this.constrainY) {
if (y < this.minY) { y = this.minY; }
if (y > this.maxY) { y = this.maxY; }
}
x = this.getTick(x, this.xTicks);
y = this.getTick(y, this.yTicks);
return {x:x, y:y};
},
/*
* 为该类配置指定的选项,这样重写Ext.dd.DragDrop,注意该方法的所有版本都会被调用。
*/
applyConfig: function() {
Ext.dd.DD.superclass.applyConfig.call(this);
this.scroll = (this.config.scroll !== false);
},
/*
* 触发优先的onMouseDown事件。
* 重写Ext.dd.DragDrop.
*/
b4MouseDown: function(e) {
// this.resetConstraints();
this.autoOffset(e.getPageX(),
e.getPageY());
},
/*
* 触发优先的onDrag事件。
* 重写Ext.dd.DragDrop.
*/
b4Drag: function(e) {
this.setDragElPos(e.getPageX(),
e.getPageY());
},
toString: function() {
return ("DD " + this.id);
}
//////////////////////////////////////////////////////////////////////////
// Debugging ygDragDrop events that can be overridden
//////////////////////////////////////////////////////////////////////////
/*
startDrag: function(x, y) {
},
onDrag: function(e) {
},
onDragEnter: function(e, id) {
},
onDragOver: function(e, id) {
},
onDragOut: function(e, id) {
},
onDragDrop: function(e, id) {
},
endDrag: function(e) {
}
*/
});
/**
* @class Ext.dd.DDProxy
* 一种拖放的实现,把一个空白的、带边框的div插入到文档,并会伴随着鼠标指针移动。
* 当点击那一下发生,边框div会调整大小到关联html元素的尺寸大小,然后移动到关联元素的位置。
* “边框”元素的引用指的是页面上我们创建能够被DDProxy元素拖动到的地方的单个代理元素。
* @extends Ext.dd.DD
* @constructor
* @param {String} id 关联html元素之id
* @param {String} sGroup 相关拖放对象的组
* @param {object} config 配置项对象属性
* DDProxy可用的属性有:
* resizeFrame, centerFrame, dragElId
*/
Ext.dd.DDProxy = function(id, sGroup, config) {
if (id) {
this.init(id, sGroup, config);
this.initFrame();
}
};
/**
* 默认的拖动框架div之id
* @property Ext.dd.DDProxy.dragElId
* @type String
* @static
*/
Ext.dd.DDProxy.dragElId = "ygddfdiv";
Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, {
/**
*默认下,我们将实际拖动元素调整大小到与打算拖动的那个元素的大小一致(这就是加边框的效果)。
* 但如果我们想实现另外一种效果可关闭选项。
* @property resizeFrame
* @type boolean
*/
resizeFrame: true,
/**
* 默认下,frame是正好处于拖动元素的位置。
* 因此我们可使Ext.dd.DD来偏移指针。
* 另外一个方法就是,你没有让做任何限制在对象上,然后设置center Frame为true。
* @property centerFrame
* @type boolean
*/
centerFrame: false,
/**
* 如果代理元素仍然不存在,就创建一个。
* @method createFrame
*/
createFrame: function() {
var self = this;
var body = document.body;
if (!body || !body.firstChild) {
setTimeout( function() { self.createFrame(); }, 50 );
return;
}
var div = this.getDragEl();
if (!div) {
div = document.createElement("div");
div.id = this.dragElId;
var s = div.style;
s.position = "absolute";
s.visibility = "hidden";
s.cursor = "move";
s.border = "2px solid #aaa";
s.zIndex = 999;
// appendChild can blow up IE if invoked prior to the window load event
// while rendering a table. It is possible there are other scenarios
// that would cause this to happen as well.
body.insertBefore(div, body.firstChild);
}
},
/**
* 拖动框架元素的初始化,必须在子类的构造器里调用。
* @method initFrame
*/
initFrame: function() {
this.createFrame();
},
applyConfig: function() {
Ext.dd.DDProxy.superclass.applyConfig.call(this);
this.resizeFrame = (this.config.resizeFrame !== false);
this.centerFrame = (this.config.centerFrame);
this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId);
},
/**
* 调查拖动frame的大小到点击对象的尺寸大小、位置,最后显示它。
* @method showFrame
* @param {int} iPageX 点击X位置
* @param {int} iPageY 点击Y位置
* @private
*/
showFrame: function(iPageX, iPageY) {
var el = this.getEl();
var dragEl = this.getDragEl();
var s = dragEl.style;
this._resizeProxy();
if (this.centerFrame) {
this.setDelta( Math.round(parseInt(s.width, 10)/2),
Math.round(parseInt(s.height, 10)/2) );
}
this.setDragElPos(iPageX, iPageY);
Ext.fly(dragEl).show();
},
/**
* 拖动开始时,代理与关联元素自适应尺寸,除非resizeFrame设为false。
* @method _resizeProxy
* @private
*/
_resizeProxy: function() {
if (this.resizeFrame) {
var el = this.getEl();
Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
}
},
// overrides Ext.dd.DragDrop
b4MouseDown: function(e) {
var x = e.getPageX();
var y = e.getPageY();
this.autoOffset(x, y);
this.setDragElPos(x, y);
},
// overrides Ext.dd.DragDrop
b4StartDrag: function(x, y) {
// show the drag frame
this.showFrame(x, y);
},
// overrides Ext.dd.DragDrop
b4EndDrag: function(e) {
Ext.fly(this.getDragEl()).hide();
},
// overrides Ext.dd.DragDrop
// By default we try to move the element to the last location of the frame.
// This is so that the default behavior mirrors that of Ext.dd.DD.
endDrag: function(e) {
var lel = this.getEl();
var del = this.getDragEl();
// Show the drag frame briefly so we can get its position
del.style.visibility = "";
this.beforeMove();
// Hide the linked element before the move to get around a Safari
// rendering bug.
lel.style.visibility = "hidden";
Ext.dd.DDM.moveToEl(lel, del);
del.style.visibility = "hidden";
lel.style.visibility = "";
this.afterDrag();
},
beforeMove : function(){
},
afterDrag : function(){
},
toString: function() {
return ("DDProxy " + this.id);
}
});
/**
* @class Ext.dd.DDTarget
* 一种拖放的实现,不能移动,但可以置下目标,对于事件回调,省略一些简单的实现也可得到相同的结果。
* 但这样降低了event listener和回调的处理成本。
* @extends Ext.dd.DragDrop
* @constructor
* @param {String} id 置下目标的那个元素的id
* @param {String} sGroup 相关拖放对象的组
* @param {object} config 包括配置属性的对象
* 可用的DDTarget属性有DragDrop:
* none
*/
Ext.dd.DDTarget = function(id, sGroup, config) {
if (id) {
this.initTarget(id, sGroup, config);
}
};
// Ext.dd.DDTarget.prototype = new Ext.dd.DragDrop();
Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, {
toString: function() {
return ("DDTarget " + this.id);
}
});
| JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.DragSource
* @extends Ext.dd.DDProxy
* 一个简单的基础类,该实现使得任何元素变成为拖动,以便让拖动的元素放到其身上。
* @constructor
* @param {String/HTMLElement/Element} el 容器元素
* @param {Object} config
*/
Ext.dd.DragSource = function(el, config){
this.el = Ext.get(el);
this.dragData = {};
Ext.apply(this, config);
if(!this.proxy){
this.proxy = new Ext.dd.StatusProxy();
}
Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
{dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
this.dragging = false;
};
Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, {
/**
* @cfg {String} dropAllowed
* 当落下被允许的时候返回到拖动源的样式(默认为"x-dd-drop-ok")。
*/
dropAllowed : "x-dd-drop-ok",
/**
* @cfg {String} dropNotAllowed
* 当落下不允许的时候返回到拖动源的样式(默认为"x-dd-drop-nodrop")。
*/
dropNotAllowed : "x-dd-drop-nodrop",
/**
* 返回与拖动源关联的数据对象
* @return {Object} data 包含自定义数据的对象
*/
getDragData : function(e){
return this.dragData;
},
// private
onDragEnter : function(e, id){
var target = Ext.dd.DragDropMgr.getDDById(id);
this.cachedTarget = target;
if(this.beforeDragEnter(target, e, id) !== false){
if(target.isNotifyTarget){
var status = target.notifyEnter(this, e, this.dragData);
this.proxy.setStatus(status);
}else{
this.proxy.setStatus(this.dropAllowed);
}
if(this.afterDragEnter){
/**
* 默认为一空函数,但你可提供一个自定义动作的实现,这个实现在拖动条目进入落下目标的时候。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @method afterDragEnter
*/
this.afterDragEnter(target, e, id);
}
}
},
/**
* 默认是一个空函数,在拖动项进入落下目标时,你应该提供一个自定义的动作。
* 该动作可被取消onDragEnter。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragEnter : function(target, e, id){
return true;
},
// private
alignElWithMouse: function() {
Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
this.proxy.sync();
},
// private
onDragOver : function(e, id){
var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
if(this.beforeDragOver(target, e, id) !== false){
if(target.isNotifyTarget){
var status = target.notifyOver(this, e, this.dragData);
this.proxy.setStatus(status);
}
if(this.afterDragOver){
/**
* 默认是一个空函数,在拖动项位于落下目标上方时(由实现促成的),你应该提供一个自定义的动作。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @method afterDragOver
*/
this.afterDragOver(target, e, id);
}
}
},
/**
* 默认是一个空函数,在拖动项位于落下目标上方时,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragOver : function(target, e, id){
return true;
},
// private
onDragOut : function(e, id){
var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
if(this.beforeDragOut(target, e, id) !== false){
if(target.isNotifyTarget){
target.notifyOut(this, e, this.dragData);
}
this.proxy.reset();
if(this.afterDragOut){
/**
* 默认是一个空函数,在拖动项离开目标而没有落下之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @method afterDragOut
*/
this.afterDragOut(target, e, id);
}
}
this.cachedTarget = null;
},
/**
* 默认是一个空函数,在拖动项离开目标而没有落下之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragOut : function(target, e, id){
return true;
},
// private
onDragDrop : function(e, id){
var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
if(this.beforeDragDrop(target, e, id) !== false){
if(target.isNotifyTarget){
if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
this.onValidDrop(target, e, id);
}else{
this.onInvalidDrop(target, e, id);
}
}else{
this.onValidDrop(target, e, id);
}
if(this.afterDragDrop){
/**
* 默认是一个空函数,在由实现促成的有效拖放发生之后,你应该提供一个自定义的动作。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 落下元素的id
* @method afterDragDrop
*/
this.afterDragDrop(target, e, id);
}
}
},
/**
* 默认是一个空函数,在拖动项被放下到目标之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 被拖动元素之id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeDragDrop : function(target, e, id){
return true;
},
// private
onValidDrop : function(target, e, id){
this.hideProxy();
if(this.afterValidDrop){
/**
* 默认是一个空函数,在由实现促成的有效落下发生之后,你应该提供一个自定义的动作。
* @param {Object} target DD目标
* @param {Event} e 事件对象
* @param {String} id 落下元素的id
* @method afterInvalidDrop
*/
this.afterValidDrop(target, e, id);
}
},
// private
getRepairXY : function(e, data){
return this.el.getXY();
},
// private
onInvalidDrop : function(target, e, id){
this.beforeInvalidDrop(target, e, id);
if(this.cachedTarget){
if(this.cachedTarget.isNotifyTarget){
this.cachedTarget.notifyOut(this, e, this.dragData);
}
this.cacheTarget = null;
}
this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
if(this.afterInvalidDrop){
/**
* 默认是一个空函数,在由实现促成的无效落下发生之后,你应该提供一个自定义的动作。
* @param {Event} e 事件对象
* @param {String} id 落下元素的id
* @method afterInvalidDrop
*/
this.afterInvalidDrop(e, id);
}
},
// private
afterRepair : function(){
if(Ext.enableFx){
this.el.highlight(this.hlColor || "c3daf9");
}
this.dragging = false;
},
/**
* 默认是一个空函数,在一次无效的落下发生之后,你应该提供一个自定义的动作。
* @param {Ext.dd.DragDrop} target 落下目标
* @param {Event} e 事件对象
* @param {String} id 拖动元素的id
* @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消
*/
beforeInvalidDrop : function(target, e, id){
return true;
},
// private
handleMouseDown : function(e){
if(this.dragging) {
return;
}
var data = this.getDragData(e);
if(data && this.onBeforeDrag(data, e) !== false){
this.dragData = data;
this.proxy.stop();
Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
}
},
/**
* 默认是一个空函数,在初始化拖动事件之前,你应该提供一个自定义的动作。
* 该动作可被取消。
* @param {Object} data 与落下目标共享的自定义数据对象
* @param {Event} e 事件对象
* @return {Boolean} isValid True的话拖动事件有效,否则false取消
*/
onBeforeDrag : function(data, e){
return true;
},
/**
* 默认是一个空函数,一旦拖动事件开始,你应该提供一个自定义的动作。
* 不能在该函数中取消拖动。
* @param {Number} x 在拖动对象身上单击点的x值
* @param {Number} y 在拖动对象身上单击点的y值
*/
onStartDrag : Ext.emptyFn,
// private - YUI override
startDrag : function(x, y){
this.proxy.reset();
this.dragging = true;
this.proxy.update("");
this.onInitDrag(x, y);
this.proxy.show();
},
// private
onInitDrag : function(x, y){
var clone = this.el.dom.cloneNode(true);
clone.id = Ext.id(); // prevent duplicate ids
this.proxy.update(clone);
this.onStartDrag(x, y);
return true;
},
/**
* 返回拖动源所在的{@link Ext.dd.StatusProxy}
* @return {Ext.dd.StatusProxy} proxy StatusProxy对象
*/
getProxy : function(){
return this.proxy;
},
/**
* 隐藏拖动源的{@link Ext.dd.StatusProxy}
*/
hideProxy : function(){
this.proxy.hide();
this.proxy.reset(true);
this.dragging = false;
},
// private
triggerCacheRefresh : function(){
Ext.dd.DDM.refreshCache(this.groups);
},
// private - override to prevent hiding
b4EndDrag: function(e) {
},
// private - override to prevent moving
endDrag : function(e){
this.onEndDrag(this.dragData, e);
},
// private
onEndDrag : function(data, e){
},
// private - pin to cursor
autoOffset : function(x, y) {
this.setDelta(-12, -20);
}
}); | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.ScrollManager
* 执行拖动操作时,自动在页面溢出的区域滚动
* <b>注:该类使用的是”Point模式”,而"Interest模式"未经测试。</b>
* @singleton
*/
Ext.dd.ScrollManager = function(){
var ddm = Ext.dd.DragDropMgr;
var els = {};
var dragEl = null;
var proc = {};
var onStop = function(e){
dragEl = null;
clearProc();
};
var triggerRefresh = function(){
if(ddm.dragCurrent){
ddm.refreshCache(ddm.dragCurrent.groups);
}
};
var doScroll = function(){
if(ddm.dragCurrent){
var dds = Ext.dd.ScrollManager;
if(!dds.animate){
if(proc.el.scroll(proc.dir, dds.increment)){
triggerRefresh();
}
}else{
proc.el.scroll(proc.dir, dds.increment, true, dds.animDuration, triggerRefresh);
}
}
};
var clearProc = function(){
if(proc.id){
clearInterval(proc.id);
}
proc.id = 0;
proc.el = null;
proc.dir = "";
};
var startProc = function(el, dir){
clearProc();
proc.el = el;
proc.dir = dir;
proc.id = setInterval(doScroll, Ext.dd.ScrollManager.frequency);
};
var onFire = function(e, isDrop){
if(isDrop || !ddm.dragCurrent){ return; }
var dds = Ext.dd.ScrollManager;
if(!dragEl || dragEl != ddm.dragCurrent){
dragEl = ddm.dragCurrent;
// 拖动开始时刷新regions
dds.refreshCache();
}
var xy = Ext.lib.Event.getXY(e);
var pt = new Ext.lib.Point(xy[0], xy[1]);
for(var id in els){
var el = els[id], r = el._region;
if(r && r.contains(pt) && el.isScrollable()){
if(r.bottom - pt.y <= dds.thresh){
if(proc.el != el){
startProc(el, "down");
}
return;
}else if(r.right - pt.x <= dds.thresh){
if(proc.el != el){
startProc(el, "left");
}
return;
}else if(pt.y - r.top <= dds.thresh){
if(proc.el != el){
startProc(el, "up");
}
return;
}else if(pt.x - r.left <= dds.thresh){
if(proc.el != el){
startProc(el, "right");
}
return;
}
}
}
clearProc();
};
ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
return {
/**
* 登记新溢出元素,以准备自动滚动
* @param {String/HTMLElement/Element/Array} el 要被滚动的元素id或是数组
*/
register : function(el){
if(el instanceof Array){
for(var i = 0, len = el.length; i < len; i++) {
this.register(el[i]);
}
}else{
el = Ext.get(el);
els[el.id] = el;
}
},
/**
* 注销溢出元素,不可再被滚动
* @param {String/HTMLElement/Element/Array} el 要被滚动的元素id或是数组
*/
unregister : function(el){
if(el instanceof Array){
for(var i = 0, len = el.length; i < len; i++) {
this.unregister(el[i]);
}
}else{
el = Ext.get(el);
delete els[el.id];
}
},
/**
* 需要指针翻转滚动的容器边缘的像素(默认为25)
* @type Number
*/
thresh : 25,
/**
* 每次滚动的幅度,单位:像素(默认为50)
* @type Number
*/
increment : 100,
/**
* 滚动的频率,单位:毫秒(默认为500)
* @type Number
*/
frequency : 500,
/**
* 是否有动画效果(默认为true)
* @type Boolean
*/
animate: true,
/**
* 动画持续时间,单位:秒
* 改值勿少于Ext.dd.ScrollManager.frequency!(默认为.4)
* @type Number
*/
animDuration: .4,
/**
* 手动切换刷新缓冲。
*/
refreshCache : function(){
for(var id in els){
if(typeof els[id] == 'object'){ // for people extending the object prototype
els[id]._region = els[id].getRegion();
}
}
}
};
}(); | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.StatusProxy
* 一个特殊的拖动代理,可支持落下状态时的图标,{@link Ext.Layer} 样式和自动修复。
* Ext.dd components默认都是使用这个代理
* @constructor
* @param {Object} config
*/
Ext.dd.StatusProxy = function(config){
Ext.apply(this, config);
this.id = this.id || Ext.id();
this.el = new Ext.Layer({
dh: {
id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
{tag: "div", cls: "x-dd-drop-icon"},
{tag: "div", cls: "x-dd-drag-ghost"}
]
},
shadow: !config || config.shadow !== false
});
this.ghost = Ext.get(this.el.dom.childNodes[1]);
this.dropStatus = this.dropNotAllowed;
};
Ext.dd.StatusProxy.prototype = {
/**
* @cfg {String} dropAllowed
* 当拖动源到达落下目标上方时的CSS class
*/
dropAllowed : "x-dd-drop-ok",
/**
* @cfg {String} dropNotAllowed
* 当不可以被落下时拖动源的样式(默认为"x-dd-drop-nodrop")。
*/
dropNotAllowed : "x-dd-drop-nodrop",
/**
* 更新代理的可见元素,用来指明在当前元素上可否落下的状态。
* @param {String} cssClass 对指示器图象的新CSS样式
*/
setStatus : function(cssClass){
cssClass = cssClass || this.dropNotAllowed;
if(this.dropStatus != cssClass){
this.el.replaceClass(this.dropStatus, cssClass);
this.dropStatus = cssClass;
}
},
/**
* 对默认dropNotAllowed值的状态提示器进行复位
* @param {Boolean} clearGhost true的话移除所有ghost的内容,false的话保留
*/
reset : function(clearGhost){
this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
this.dropStatus = this.dropNotAllowed;
if(clearGhost){
this.ghost.update("");
}
},
/**
* 更新ghost元素的内容
* @param {String} html 替换当前ghost元素的innerHTML的那个html
*/
update : function(html){
if(typeof html == "string"){
this.ghost.update(html);
}else{
this.ghost.update("");
html.style.margin = "0";
this.ghost.dom.appendChild(html);
}
},
/**
* 返所在在的代理{@link Ext.Layer}
* @return {Ext.Layer} el
*/
getEl : function(){
return this.el;
},
/**
* 返回ghost元素
* @return {Ext.Element} el
*/
getGhost : function(){
return this.ghost;
},
/**
* 隐藏代理
* @param {Boolean} clear True的话复位状态和清除ghost内容,false的话就保留
*/
hide : function(clear){
this.el.hide();
if(clear){
this.reset(true);
}
},
/**
* 如果运行中就停止修复动画
*/
stop : function(){
if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
this.anim.stop();
}
},
/**
* 显示代理
*/
show : function(){
this.el.show();
},
/**
* 迫使层同步阴影和闪烁元素的位置
*/
sync : function(){
this.el.sync();
},
/**
* 通过动画让代理返回到原来位置。
* 应由拖动项在完成一次无效的落下动作之后调用.
* @param {Array} xy 元素的XY位置([x, y])
* @param {Function} callback 完成修复之后的回调函数
* @param {Object} scope 执行回调函数的作用域
*/
repair : function(xy, callback, scope){
this.callback = callback;
this.scope = scope;
if(xy && this.animRepair !== false){
this.el.addClass("x-dd-drag-repair");
this.el.hideUnders(true);
this.anim = this.el.shift({
duration: this.repairDuration || .5,
easing: 'easeOut',
xy: xy,
stopFx: true,
callback: this.afterRepair,
scope: this
});
}else{
this.afterRepair();
}
},
// private
afterRepair : function(){
this.hide(true);
if(typeof this.callback == "function"){
this.callback.call(this.scope || this);
}
this.callback = null;
this.scope = null;
}
}; | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.DropTarget
* @extends Ext.dd.DDTarget.
* 一个简单的基础类,该实现使得任何元素变成为可落下的目标,以便让拖动的元素放到其身上。
* 落下(drop)过程没有特别效果,除非提供了notifyDrop的实现
* @constructor
* @param {String/HTMLElement/Element} el 容器元素
* @param {Object} config
*/
Ext.dd.DropTarget = function(el, config){
this.el = Ext.get(el);
Ext.apply(this, config);
if(this.containerScroll){
Ext.dd.ScrollManager.register(this.el);
}
Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
{isTarget: true});
};
Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, {
/**
* @cfg {String} overClass
* 当拖动源到达落下目标上方时的CSS class
*/
/**
* @cfg {String} dropAllowed
* 当可以被落下时拖动源的样式(默认为"x-dd-drop-ok")。
*/
dropAllowed : "x-dd-drop-ok",
/**
* @cfg {String} dropNotAllowed
* 当不可以被落下时拖动源的样式(默认为"x-dd-drop-nodrop")。
*/
dropNotAllowed : "x-dd-drop-nodrop",
// private
isTarget : true,
// private
isNotifyTarget : true,
/**
* 当源{@link Ext.dd.DragSource}进入到目标的范围内,它执行通知落下目标的那个函数。
* 默认的实现是,如存在overClass(或其它)的样式,将其加入到落下元素(drop element),并返回dropAllowed配置的值。
* 如需对落下验证(drop validation)的话可重写该方法。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyEnter : function(dd, e, data){
if(this.overClass){
this.el.addClass(this.overClass);
}
return this.dropAllowed;
},
/**
* 当源{@link Ext.dd.DragSource}进入到目标的范围内,每一下移动鼠标,它不断执行通知落下目标的那个函数。
* 默认的实现是返回dropAllowed配置值而已
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyOver : function(dd, e, data){
return this.dropAllowed;
},
/**.
* 当源{@link Ext.dd.DragSource}移出落下目标的范围后,它执行通知落下目标的那个函数。
* 默认的实现仅是移除由overClass(或其它)指定的CSS class。
* @param {Ext.dd.DragSource} dd 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
notifyOut : function(dd, e, data){
if(this.overClass){
this.el.removeClass(this.overClass);
}
},
/**
* 当源{@link Ext.dd.DragSource}在落下目标身上完成落下动作后,它执行通知落下目标的那个函数。
* 该方法没有默认的实现并返回false,所以你必须提供处理落下事件的实现并返回true,才能修复拖动源没有运行的动作。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
notifyDrop : function(dd, e, data){
return false;
}
}); | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.DropZone
* @extends Ext.dd.DropTarget
* 对于多个子节点的目标,该类提供一个DD实例的容器(扮演代理角色)。<br />
* 默认地,该类需要一个可拖动的子节点,并且需在{@link Ext.dd.Registry}登记好的。
* @constructor
* @param {String/HTMLElement/Element} el
* @param {Object} config
*/
Ext.dd.DropZone = function(el, config){
Ext.dd.DropZone.superclass.constructor.call(this, el, config);
};
Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, {
/**
* 返回一个自定义数据对象,与事件对象的那个DOM节点关联。
* 默认地,该方法会在事件目标{@link Ext.dd.Registry}中查找对象,
* 但是你亦可以根据自身的需求,重写该方法。
* @param {Event} e 事件对象
* @return {Object} data 自定义数据
*/
getTargetFromEvent : function(e){
return Ext.dd.Registry.getTargetFromEvent(e);
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经进入一个已登记的落下节点(drop node)的范围内,就会调用。
* 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
onNodeEnter : function(n, dd, e, data){
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经位于一个已登记的落下节点(drop node)的上方时,就会调用。
* 默认的实现是返回this.dropAllowed。因此应该重写它以便提供合适的反馈。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
onNodeOver : function(n, dd, e, data){
return this.dropAllowed;
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经离开一个已登记的落下节点(drop node)的范围内,就会调用。
* 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
onNodeOut : function(n, dd, e, data){
},
/**
* 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource},
* 已经在一个已登记的落下节点(drop node)落下的时候,就会调用。
* 默认的方法返回false,应提供一个合适的实现来处理落下的事件,重写该方法,
* 并返回true值,说明拖放行为有效,拖动源的修复动作便不会进行。
* @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样)
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
onNodeDrop : function(n, dd, e, data){
return false;
},
/**
* 内部调用。当DrapZone发现有一个{@link Ext.dd.DragSource}正处于其上方时,但是没有放下任何落下的节点时调用。
* 默认的实现是返回this.dropNotAllowed,如需提供一些合适的反馈,应重写该函数。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
onContainerOver : function(dd, e, data){
return this.dropNotAllowed;
},
/**
* 内部调用。当DrapZone确定{@link Ext.dd.DragSource}落下的动作已经执行,但是没有放下任何落下的节点时调用。
* 欲将DropZone本身也可接收落下的行为,应提供一个合适的实现来处理落下的事件,重写该方法,并返回true值,
* 说明拖放行为有效,拖动源的修复动作便不会进行。默认的实现返回false。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
onContainerDrop : function(dd, e, data){
return false;
},
/**
* 通知DropZone源已经在Zone上方的函数。
* 默认的实现返回this.dropNotAllowed,一般说只有登记的落下节点可以处理拖放操作。
* 欲将DropZone本身也可接收落下的行为,应提供一个自定义的实现,重写该方法,
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyEnter : function(dd, e, data){
return this.dropNotAllowed;
},
/**
* 当{@link Ext.dd.DragSource}在DropZone范围内时,拖动过程中不断调用的函数。
* 拖动源进入DropZone后,进入每移动一下鼠标都会调用该方法。
* 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onNodeOver},
* 如果拖动源进入{@link #onNodeEnter}, {@link #onNodeOut}这样已登记的节点,通知过程会按照需要自动进行指定的节点处理,
* 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onContainerOver}。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。
*/
notifyOver : function(dd, e, data){
var n = this.getTargetFromEvent(e);
if(!n){ // 不在有效的drop target上
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
this.lastOverNode = null;
}
return this.onContainerOver(dd, e, data);
}
if(this.lastOverNode != n){
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
}
this.onNodeEnter(n, dd, e, data);
this.lastOverNode = n;
}
return this.onNodeOver(n, dd, e, data);
},
/**
* 通知DropZone源已经离开Zone上方{@link Ext.dd.DragSource}所调用的函数。
* 如果拖动源当前在已登记的节点上,通知过程会委托{@link #onNodeOut}进行指定的节点处理,
* 否则的话会被忽略。
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
*/
notifyOut : function(dd, e, data){
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
this.lastOverNode = null;
}
},
/**
* 通知DropZone源已经在Zone放下item后{@link Ext.dd.DragSource}所调用的函数。
* 传入事件的参数,DragZone以此查找目标节点,若是事件已登记的节点的话,便会委托{@link #onNodeDrop}进行指定的节点处理。
* 否则的话调用{@link #onContainerDrop}.
* @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源
* @param {Event} e 事件对象
* @param {Object} data 由拖动源规定格式的数据对象
* @return {Boolean} True 有效的落下返回true否则为false
*/
notifyDrop : function(dd, e, data){
if(this.lastOverNode){
this.onNodeOut(this.lastOverNode, dd, e, data);
this.lastOverNode = null;
}
var n = this.getTargetFromEvent(e);
return n ?
this.onNodeDrop(n, dd, e, data) :
this.onContainerDrop(dd, e, data);
},
// private
triggerCacheRefresh : function(){
Ext.dd.DDM.refreshCache(this.groups);
}
}); | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.Registry
* 为在页面上已登记好的拖放组件提供简易的访问。
* 可按照DOM节点的id的方式直接提取组件,或者是按照传入的拖放事件,事件触发后,在事件目标(event target)里查找。
* @singleton
*/
Ext.dd.Registry = function(){
var elements = {};
var handles = {};
var autoIdSeed = 0;
var getId = function(el, autogen){
if(typeof el == "string"){
return el;
}
var id = el.id;
if(!id && autogen !== false){
id = "extdd-" + (++autoIdSeed);
el.id = id;
}
return id;
};
return {
/**
* 登记一个拖放元素
* @param {String/HTMLElement) element 要登记的id或DOM节点
* @param {Object} data (optional) 在拖放过程中,用于在各元素传递的这么一个自定义数据对象
* 你可以按自身需求定义这个对象,另外有些特定的属性是便于与Registry交互的(如可以的话):
* <pre>
值 描述<br />
--------- ------------------------------------------<br />
handles 由DOM节点组成的数组,即被拖动元素,都是已登记好的<br />
isHandle True表示元素传入后已是翻转的拖动本身,否则false<br />
</pre>
*/
register : function(el, data){
data = data || {};
if(typeof el == "string"){
el = document.getElementById(el);
}
data.ddel = el;
elements[getId(el)] = data;
if(data.isHandle !== false){
handles[data.ddel.id] = data;
}
if(data.handles){
var hs = data.handles;
for(var i = 0, len = hs.length; i < len; i++){
handles[getId(hs[i])] = data;
}
}
},
/**
* 注销一个拖放元素
* @param {String/HTMLElement) element 要注销的id或DOM节点
*/
unregister : function(el){
var id = getId(el, false);
var data = elements[id];
if(data){
delete elements[id];
if(data.handles){
var hs = data.handles;
for(var i = 0, len = hs.length; i < len; i++){
delete handles[getId(hs[i], false)];
}
}
}
},
/**
* 按id返回已登记的DOM节点处理
* @param {String/HTMLElement} id 要查找的id或DOM节点
* @return {Object} handle 自定义处理数据
*/
getHandle : function(id){
if(typeof id != "string"){ // 规定是元素?
id = id.id;
}
return handles[id];
},
/**
* 按事件目标返回已登记的DOM节点处理
* @param {Event} e 事件对象
* @return {Object} handle 自定义处理数据
*/
getHandleFromEvent : function(e){
var t = Ext.lib.Event.getTarget(e);
return t ? handles[t.id] : null;
},
/**
* 按id返回已登记的自定义处理对象
* @param {String/HTMLElement} id 要查找的id或DOM节点
* @return {Object} handle 自定义处理数据
*/
getTarget : function(id){
if(typeof id != "string"){ // 规定是元素?
id = id.id;
}
return elements[id];
},
/**
* 按事件目标返回已登记的自定义处理对象
* @param {Event} e 事件对象
* @return {Object} handle 自定义处理数据
*/
getTargetFromEvent : function(e){
var t = Ext.lib.Event.getTarget(e);
return t ? elements[t.id] || handles[t.id] : null;
}
};
}(); | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.dd.DragZone
* 该类继承了Ext.dd.DragSource,对于多节点的源,该类提供了一个DD实理容器来代理.<br/>
* 默认情况下,该类要求可拖动的子节点全都在类(Ext.dd.Registry )中己注册
* @constructor
* @param {String/HTMLElement/Element} el 第一个参数为容器元素
* @param {Object} config 第二个参数为配置对象
*/
Ext.dd.DragZone = function(el, config){
Ext.dd.DragZone.superclass.constructor.call(this, el, config);
if(this.containerScroll){
Ext.dd.ScrollManager.register(this.el);
}
};
Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, {
/**
* @cfg {Boolean} containerScroll
*第一个参数:containerScroll 设为True 用来将此容器在Scrollmanager上注册,使得在拖动操作发生时可以自动卷动.
*/
/**
* @cfg {String} hlColor
*第二个参数:hlColor 用于在一次失败的拖动操作后调用afterRepair方法会用在此设定的颜色(默认颜色为亮蓝"c3daf9")来标识可见的拽源<br/>
*/
/**
* 该方法在鼠标在该容器中按下时激发,参照类(Ext.dd.Registry),因为有效的拖动目标是基于鼠标按下事件获取的.<br/>
* 如果想想实现自己的查找方式(如根据类名查找子对象),可以重载这个主法.但是得确保该方法返回的对象有一个"ddel"属性(即返回一个HTML element),以便别的函数能正常工作<br/>
* @param {EventObject} e 鼠标按下事件
* @return {Object} 被拖拽对象
*/
getDragData : function(e){
return Ext.dd.Registry.getHandleFromEvent(e);
},
/**
* 该方法在拖拽动作开始,初始化代理元素时调用,默认情况下,它克隆this.dragData.ddel.
* @param {Number} x 被点击的拖拽对象的X坐标
* @param {Number} y 被点击的拖拽对象的y坐标
* @return {Boolean} 该方法返回一个布尔常量,当返回true时,表示继续(保持)拖拽,返回false时,表示取消拖拽<br/>
*/
onInitDrag : function(x, y){
this.proxy.update(this.dragData.ddel.cloneNode(true));
this.onStartDrag(x, y);
return true;
},
/**
* 该方法在修复无效的drop操作后调用.默认情况下.高亮显示this.dragData.ddel
*/
afterRepair : function(){
if(Ext.enableFx){
Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
}
this.dragging = false;
},
/**
* 该方法在修复无效的drop操作之前调用,用来获取XY对象来激活(使用对象),默认情况下返回this.dragData.ddel的XY属性
* @param {EventObject} e 鼠标松开事件
* @return {Array} 区域的xy位置 (例如: [100, 200])
*/
getRepairXY : function(e){
return Ext.Element.fly(this.dragData.ddel).getXY();
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.Tree
* @extends Ext.util.Observable
* Represents a tree data structure and bubbles all the events for its nodes. The nodes
* in the tree have most standard DOM functionality.
* @constructor
* @param {Node} root (optional) The root node
*/
/**
* @ Ext.data.Tree类
* @extends Ext.util.Observable
* 代表一个树的数据结构并且向上传递它结点事件.树上的节点有绝大多数的标准dom的功能
* @构造器
* @param {Node} root (optional) 根节点
*/
Ext.data.Tree = function(root){
this.nodeHash = {};
/**
* The root node for this tree
* @type Node
*/
this.root = null;
if(root){
this.setRootNode(root);
}
this.addEvents({
/**
* @event append
* Fires when a new child node is appended to a node in this tree.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The newly appended node
* @param {Number} index The index of the newly appended node
*/
/**
* @ append事件
* 当一个新子节点挂到树上某一切点时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 新的被挂上的节点
* @param {Number} index 新的被挂上的节点的索引
*/
"append" : true,
/**
* @event remove
* Fires when a child node is removed from a node in this tree.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node removed
*/
/**
* @remove 移除事件
* 当一个子节点被从树上的某节点移除时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被移除的子节点
*/
"remove" : true,
/**
* @event move
* Fires when a node is moved to a new location in the tree
* @param {Tree} tree The owner tree
* @param {Node} node The node moved
* @param {Node} oldParent The old parent of this node
* @param {Node} newParent The new parent of this node
* @param {Number} index The index it was moved to
*/
/**
* @ move事件
* 当树上的某一节点移动到新的位置时触发该事件
* @param {Tree} tree 该树
* @param {Node} node 移动的节点
* @param {Node} oldParent 该移动节点的原父
* @param {Node} newParent 移动的节点的新父
* @param {Number} index 移动的节点的在新父下的索引
*/
"move" : true,
/**
* @event insert
* Fires when a new child node is inserted in a node in this tree.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node inserted
* @param {Node} refNode The child node the node was inserted before
*/
/**
* @insert事件
* 当一个新子节点被插入到树中某个节点下时触发该事件
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入后的子节点
* @param {Node} refNode 插入前的子节点
*/
"insert" : true,
/**
* @event beforeappend
* Fires before a new child is appended to a node in this tree, return false to cancel the append.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node to be appended
*/
/**
* @beforeappend 事件
* 在一子点被接挂到树之前触发,如果返回false,则取消接挂.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被接挂的子节点
*/
"beforeappend" : true,
/**
* @event beforeremove
* Fires before a child is removed from a node in this tree, return false to cancel the remove.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node to be removed
*/
/**
* @beforeremove事件
* 当一个子节点被从树某一个节点被移除时触发该事件,返回false时取消移除.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 将被移除的子节点
*/
"beforeremove" : true,
/**
* @event beforemove
* Fires before a node is moved to a new location in the tree. Return false to cancel the move.
* @param {Tree} tree The owner tree
* @param {Node} node The node being moved
* @param {Node} oldParent The parent of the node
* @param {Node} newParent The new parent the node is moving to
* @param {Number} index The index it is being moved to
*/
/**
* @ beforemove事件
* 当树上一节点被移动到树上的新位置之前触发,返回false时取消移动
* @param {Tree} tree The owner tree
* @param {Node} node The node being moved
* @param {Node} oldParent The parent of the node
* @param {Node} newParent The new parent the node is moving to
* @param {Number} index The index it is being moved to
*/
"beforemove" : true,
/**
* @event beforeinsert
* Fires before a new child is inserted in a node in this tree, return false to cancel the insert.
* @param {Tree} tree The owner tree
* @param {Node} parent The parent node
* @param {Node} node The child node to be inserted
* @param {Node} refNode The child node the node is being inserted before
*/
/**
* @ beforeinsert事件
* 当一新子节点被插入到树上某一节点之前触发该事件,返回false时取消插入
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入的子节点
* @param {Node} refNode 插入之前的子节点
*/
"beforeinsert" : true
});
Ext.data.Tree.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Tree, Ext.util.Observable, {
pathSeparator: "/",
proxyNodeEvent : function(){
return this.fireEvent.apply(this, arguments);
},
/**
* Returns the root node for this tree.
* @return {Node}
*/
/**
* 返回树的根节点.
* @return {Node}
*/
getRootNode : function(){
return this.root;
},
/**
* Sets the root node for this tree.
* @param {Node} node
* @return {Node}
*/
/**
* 设置树的根节点
* @param {Node} node
* @return {Node}
*/
setRootNode : function(node){
this.root = node;
node.ownerTree = this;
node.isRoot = true;
this.registerNode(node);
return node;
},
/**
* Gets a node in this tree by its id.
* @param {String} id
* @return {Node}
*/
/**
* 根据节点 ID在树里获取节点
* @param {String} id
* @return {Node}
*/
getNodeById : function(id){
return this.nodeHash[id];
},
registerNode : function(node){
this.nodeHash[node.id] = node;
},
unregisterNode : function(node){
delete this.nodeHash[node.id];
},
toString : function(){
return "[Tree"+(this.id?" "+this.id:"")+"]";
}
});
/**
* @class Ext.data.Node
* @extends Ext.util.Observable
* @cfg {Boolean} leaf true if this node is a leaf and does not have children
* @cfg {String} id The id for this node. If one is not specified, one is generated.
* @constructor
* @param {Object} attributes The attributes/config for the node
*/
/**
* @ Ext.data.Node类
* @extends Ext.util.Observable
* @cfg {Boolean} 该节点是否为叶节点
* @cfg {String}该节点的ID.如果没有指定,则自动生成.
* @constructor
* @param {Object} attributes 该节点的属性集或配置
*/
Ext.data.Node = function(attributes){
/**
* The attributes supplied for the node. You can use this property to access any custom attributes you supplied.
* @type {Object}
*/
/**
* 该节点所支持的属性,你可以用此属性访问任一你指定的客户端属性
* @type {Object}
*/
this.attributes = attributes || {};
this.leaf = this.attributes.leaf;
/**
* The node id. @type String
*/
this.id = this.attributes.id;
if(!this.id){
this.id = Ext.id(null, "ynode-");
this.attributes.id = this.id;
}
/**
* All child nodes of this node. @type Array
*/
/**
* 该节点的所有子节点. @type 类型为数组
*/
this.childNodes = [];
if(!this.childNodes.indexOf){ // indexOf is a must
this.childNodes.indexOf = function(o){
for(var i = 0, len = this.length; i < len; i++){
if(this[i] == o) return i;
}
return -1;
};
}
/**
* The parent node for this node. @type Node
*/
/**
* 该节点的父节点. @type 类型为节点
*/
this.parentNode = null;
/**
* The first direct child node of this node, or null if this node has no child nodes. @type Node
*/
/**
* 第一个子节点,如果没有则返回为空. @type 类型为节点
*/
this.firstChild = null;
/**
* The last direct child node of this node, or null if this node has no child nodes. @type Node
*/
/**
* 该节点的最后一个子节点,如果没有,则返回为空.@type 类型为节点
*/
this.lastChild = null;
/**
* The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node
*/
/**
* 返回该节点前一个兄弟节点.如果没有,则返回空. @type 类型为节点
*/
this.previousSibling = null;
/**
* The node immediately following this node in the tree, or null if there is no sibling node. @type Node
*/
/**
* 返回该节点的后一个兄弟节点.如果没有,则返回空. @type 类型为节点
*/
this.nextSibling = null;
this.addEvents({
/**
* @event append
* Fires when a new child node is appended
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The newly appended node
* @param {Number} index The index of the newly appended node
*/
/**
* @ append事件
* 当一个新子节点挂到树上某一切点时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 新的被挂上的节点
* @param {Number} index 新的被挂上的节点的索引
*/
"append" : true,
/**
* @event remove
* Fires when a child node is removed
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The removed node
*/
/**
* @remove 移除事件
* 当一个子节点被从树上的某节点移除时触发该事件.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被移除的子节点
*/
"remove" : true,
/**
* @event move
* Fires when this node is moved to a new location in the tree
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} oldParent The old parent of this node
* @param {Node} newParent The new parent of this node
* @param {Number} index The index it was moved to
*/
/**
* @ move事件
* 当树上的某一节点移动到新的位置时触发该事件
* @param {Tree} tree 该树
* @param {Node} node 移动的节点
* @param {Node} oldParent 该移动节点的原父
* @param {Node} newParent 移动的节点的新父
* @param {Number} index 移动的节点的在新父下的索引
*/
"move" : true,
/**
* @event insert
* Fires when a new child node is inserted.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node inserted
* @param {Node} refNode The child node the node was inserted before
*/
/**
* @insert事件
* 当一个新子节点被插入到树中某个节点下时触发该事件
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入后的子节点
* @param {Node} refNode 插入前的子节点
*/
"insert" : true,
/**
* @event beforeappend
* Fires before a new child is appended, return false to cancel the append.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node to be appended
*/
/**
* @beforeappend 事件
* 在一子点被接挂到树之前触发,如果返回false,则取消接挂.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 被接挂的子节点
*/
"beforeappend" : true,
/**
* @event beforeremove
* Fires before a child is removed, return false to cancel the remove.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node to be removed
*/
/**
* @beforeremove事件
* 当一个子节点被从树某一个节点被移除时触发该事件,返回false时取消移除.
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 将被移除的子节点
*/
"beforeremove" : true,
/**
* @event beforemove
* Fires before this node is moved to a new location in the tree. Return false to cancel the move.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} oldParent The parent of this node
* @param {Node} newParent The new parent this node is moving to
* @param {Number} index The index it is being moved to
*/
/**
* @ beforemove事件
* 当树上一节点被移动到树上的新位置之前触发,返回false时取消移动
* @param {Tree} tree The owner tree
* @param {Node} node The node being moved
* @param {Node} oldParent The parent of the node
* @param {Node} newParent The new parent the node is moving to
* @param {Number} index The index it is being moved to
*/
"beforemove" : true,
/**
* @event beforeinsert
* Fires before a new child is inserted, return false to cancel the insert.
* @param {Tree} tree The owner tree
* @param {Node} this This node
* @param {Node} node The child node to be inserted
* @param {Node} refNode The child node the node is being inserted before
*/
/**
* @ beforeinsert事件
* 当一新子节点被插入到树上某一节点之前触发该事件,返回false时取消插入
* @param {Tree} tree 该树
* @param {Node} parent 父节点
* @param {Node} node 插入的子节点
* @param {Node} refNode 插入之前的子节点
*/
"beforeinsert" : true
});
this.listeners = this.attributes.listeners;
Ext.data.Node.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Node, Ext.util.Observable, {
fireEvent : function(evtName){
// first do standard event for this node
// 首先响应该节点的标准事件
if(Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false){
return false;
}
// then bubble it up to the tree if the event wasn't cancelled
// 然后在树中向上传递(只要事件未被取消)
var ot = this.getOwnerTree();
if(ot){
if(ot.proxyNodeEvent.apply(ot, arguments) === false){
return false;
}
}
return true;
},
/**
* Returns true if this node is a leaf
* @return {Boolean}
*/
/**
* 如果该节点为叶子节点,则返回true
* @return {Boolean}
*/
isLeaf : function(){
return this.leaf === true;
},
// private
setFirstChild : function(node){
this.firstChild = node;
},
//private
setLastChild : function(node){
this.lastChild = node;
},
/**
* Returns true if this node is the last child of its parent
* @return {Boolean}
*/
/**
* 如果该节点是父节点的子节点中最后一个节点时返回true
* @return {Boolean}
*/
isLast : function(){
return (!this.parentNode ? true : this.parentNode.lastChild == this);
},
/**
* Returns true if this node is the first child of its parent
* @return {Boolean}
*/
/**
* 如果该节点是父节点的子节点的第一个节点时返回true
* @return {Boolean}
*/
isFirst : function(){
return (!this.parentNode ? true : this.parentNode.firstChild == this);
},
hasChildNodes : function(){
return !this.isLeaf() && this.childNodes.length > 0;
},
/**
* Insert node(s) as the last child node of this node.
* @param {Node/Array} node The node or Array of nodes to append
* @return {Node} The appended node if single append, or null if an array was passed
*/
/**
* 插入节点作为该节点的最后一个子节点
* @param {Node/Array} node 要接挂进来的节点或节点数组
* @return {Node} 接挂一个则返回之.接挂多个则返回空
*/
appendChild : function(node){
var multi = false;
if(node instanceof Array){
multi = node;
}else if(arguments.length > 1){
multi = arguments;
}
// if passed an array or multiple args do them one by one
// 如果传入的是数组.或多个参数.则一个一个的加
if(multi){
for(var i = 0, len = multi.length; i < len; i++) {
this.appendChild(multi[i]);
}
}else{
if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){
return false;
}
var index = this.childNodes.length;
var oldParent = node.parentNode;
// it's a move, make sure we move it cleanly
// 这里移动.确保我们移动它cleanly
if(oldParent){
if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){
return false;
}
oldParent.removeChild(node);
}
index = this.childNodes.length;
if(index == 0){
this.setFirstChild(node);
}
this.childNodes.push(node);
node.parentNode = this;
var ps = this.childNodes[index-1];
if(ps){
node.previousSibling = ps;
ps.nextSibling = node;
}else{
node.previousSibling = null;
}
node.nextSibling = null;
this.setLastChild(node);
node.setOwnerTree(this.getOwnerTree());
this.fireEvent("append", this.ownerTree, this, node, index);
if(oldParent){
node.fireEvent("move", this.ownerTree, node, oldParent, this, index);
}
return node;
}
},
/**
* Removes a child node from this node.
* @param {Node} node The node to remove
* @return {Node} The removed node
*/
/**
* 移队该节点的某一子节点
* @param {Node} node 要被移除的节点
* @return {Node} 被移除的节点
*/
removeChild : function(node){
var index = this.childNodes.indexOf(node);
if(index == -1){
return false;
}
if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){
return false;
}
// remove it from childNodes collection
// 从子节点集合中移除掉
this.childNodes.splice(index, 1);
// update siblings
// 更新兄弟
if(node.previousSibling){
node.previousSibling.nextSibling = node.nextSibling;
}
if(node.nextSibling){
node.nextSibling.previousSibling = node.previousSibling;
}
// update child refs
// 更新子节点的引用
if(this.firstChild == node){
this.setFirstChild(node.nextSibling);
}
if(this.lastChild == node){
this.setLastChild(node.previousSibling);
}
node.setOwnerTree(null);
// clear any references from the node
// 清除任何到该节点的引用
node.parentNode = null;
node.previousSibling = null;
node.nextSibling = null;
this.fireEvent("remove", this.ownerTree, this, node);
return node;
},
/**
* Inserts the first node before the second node in this nodes childNodes collection.
* @param {Node} node The node to insert
* @param {Node} refNode The node to insert before (if null the node is appended)
* @return {Node} The inserted node
*/
/**
* 在该节点的子节点集合中插入第一个节点于第二个个节点之前
* @param {Node} node 要插入的节点
* @param {Node} refNode 插入之前的节点 (如果为空.该节点被接挂)
* @return {Node} 返回这插入的节点
*/
insertBefore : function(node, refNode){
if(!refNode){ // like standard Dom, refNode can be null for append
return this.appendChild(node);
}
// nothing to do
if(node == refNode){
return false;
}
if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){
return false;
}
var index = this.childNodes.indexOf(refNode);
var oldParent = node.parentNode;
var refIndex = index;
// when moving internally, indexes will change after remove
// 当移动在内部进行时,索引将会在移动之后改变
if(oldParent == this && this.childNodes.indexOf(node) < index){
refIndex--;
}
// it's a move, make sure we move it cleanly
// 这里移动.确保移动cleanly
if(oldParent){
if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){
return false;
}
oldParent.removeChild(node);
}
if(refIndex == 0){
this.setFirstChild(node);
}
this.childNodes.splice(refIndex, 0, node);
node.parentNode = this;
var ps = this.childNodes[refIndex-1];
if(ps){
node.previousSibling = ps;
ps.nextSibling = node;
}else{
node.previousSibling = null;
}
node.nextSibling = refNode;
refNode.previousSibling = node;
node.setOwnerTree(this.getOwnerTree());
this.fireEvent("insert", this.ownerTree, this, node, refNode);
if(oldParent){
node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode);
}
return node;
},
/**
* Returns the child node at the specified index.
* @param {Number} index
* @return {Node}
*/
/**
* 返回指定索引的子节点.
* @param {Number} 索引
* @return {Node}
*/
item : function(index){
return this.childNodes[index];
},
/**
* Replaces one child node in this node with another.
* @param {Node} newChild The replacement node
* @param {Node} oldChild The node to replace
* @return {Node} The replaced node
*/
/**
* 用另一个节点来替换该节点的一个子节点
* @param {Node} 新节点
* @param {Node} 被替的子节点
* @return {Node} 被替的子节点
*/
replaceChild : function(newChild, oldChild){
this.insertBefore(newChild, oldChild);
this.removeChild(oldChild);
return oldChild;
},
/**
* Returns the index of a child node
* @param {Node} node
* @return {Number} The index of the node or -1 if it was not found
*/
/**
* 返回子节点的索引
* @param {Node} node
* @return {Number} 返回指定子节点的索引,如果未找到则返回空
*/
indexOf : function(child){
return this.childNodes.indexOf(child);
},
/**
* Returns the tree this node is in.
* @return {Tree}
*/
/**
* Returns 返回该节点所在的树.
* @return {Tree}
*/
getOwnerTree : function(){
// if it doesn't have one, look for one
// 如果当前结点直接没有此属性.则向上找
if(!this.ownerTree){
var p = this;
while(p){
if(p.ownerTree){
this.ownerTree = p.ownerTree;
break;
}
p = p.parentNode;
}
}
return this.ownerTree;
},
/**
* Returns depth of this node (the root node has a depth of 0)
* @return {Number}
*/
/**
* 返回节点的深度,根节点深度为0
* @return {Number}
*/
getDepth : function(){
var depth = 0;
var p = this;
while(p.parentNode){
++depth;
p = p.parentNode;
}
return depth;
},
// private
setOwnerTree : function(tree){
// if it's move, we need to update everyone
// 如果移动.我们需要更新所有节点
if(tree != this.ownerTree){
if(this.ownerTree){
this.ownerTree.unregisterNode(this);
}
this.ownerTree = tree;
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].setOwnerTree(tree);
}
if(tree){
tree.registerNode(this);
}
}
},
/**
* Returns the path for this node. The path can be used to expand or select this node programmatically.
* @param {String} attr (optional) The attr to use for the path (defaults to the node's id)
* @return {String} The path
*/
/**
* 返回该节点的路径.路径能被用来扩展或选择节点
* @param {String} attr (可选项) 为路径服务的属性 (默认为节点的ID)
* @return {String} 路径
*/
getPath : function(attr){
attr = attr || "id";
var p = this.parentNode;
var b = [this.attributes[attr]];
while(p){
b.unshift(p.attributes[attr]);
p = p.parentNode;
}
var sep = this.getOwnerTree().pathSeparator;
return sep + b.join(sep);
},
/**
* Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
* function call will be the scope provided or the current node. The arguments to the function
* will be the args provided or the current node. If the function returns false at any point,
* the bubble is stopped.
* @param {Function} fn The function to call
* @param {Object} scope (optional) The scope of the function (defaults to current node)
* @param {Array} args (optional) The args to call the function with (default to passing the current node)
*/
/**
* 在树中.从该节点往上的各节点调用指定的函数, 该函数的作用域为提供的作用域或当前节点.该函数的参数为提供的
* 参数或当前节点作参数.如果该函数在任一点返回false,则停上bubble
* @param {Function} fn 要调用的函数
* @param {Object} scope (可选项) 函数的作用域 (默认为当前节点)
* @param {Array} args (可选项) 调用函数时所带的参数 (默认值为传递当前节点)
*/
bubble : function(fn, scope, args){
var p = this;
while(p){
if(fn.call(scope || p, args || p) === false){
break;
}
p = p.parentNode;
}
},
/**
* Cascades down the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of
* function call will be the scope provided or the current node. The arguments to the function
* will be the args provided or the current node. If the function returns false at any point,
* the cascade is stopped on that branch.
* @param {Function} fn The function to call
* @param {Object} scope (optional) The scope of the function (defaults to current node)
* @param {Array} args (optional) The args to call the function with (default to passing the current node)
*/
/**
* 在树中.从该节点往下的各节点调用指定的函数, 该函数的作用域为提供的作用域或当前节点.该函数的参数为提供的
* 参数或当前节点作参数.如果该函数在任一点返回false,则停上该分支下的遍历
* @param {Function} fn 要调用的函数
* @param {Object} scope (可选项) 函数的作用域 (默认为当前节点)
* @param {Array} args (可选项) 调用函数时所带的参数 (默认值为传递当前节点)
*/
cascade : function(fn, scope, args){
if(fn.call(scope || this, args || this) !== false){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
cs[i].cascade(fn, scope, args);
}
}
},
/**
* Interates the child nodes of this node, calling the specified function with each node. The scope (<i>this</i>) of
* function call will be the scope provided or the current node. The arguments to the function
* will be the args provided or the current node. If the function returns false at any point,
* the iteration stops.
* @param {Function} fn The function to call
* @param {Object} scope (optional) The scope of the function (defaults to current node)
* @param {Array} args (optional) The args to call the function with (default to passing the current node)
*/
/**
* 遍历该节点的子节点, 各节点调用指定的函数. 该函数的作用域是提供的作用域,或是当前节点. 该函数的参数是提供的参数.或当前节点.当任何一点该函数返回false则停止遍历
* @param {Function} fn 调用的函数
* @param {Object} scope (可选项) 函数的作用域 (默认为当前节点)
* @param {Array} args (可选项) 调用函数时所带的参数 (默认值为传递当前节点)
*/
eachChild : function(fn, scope, args){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(fn.call(scope || this, args || cs[i]) === false){
break;
}
}
},
/**
* Finds the first child that has the attribute with the specified value.
* @param {String} attribute The attribute name
* @param {Mixed} value The value to search for
* @return {Node} The found child or null if none was found
*/
/**
* 返回子节点中第一个匹配指字属性值的子切点.
* @param {String} attribute 属性名
* @param {Mixed} value 属性值
* @return {Node} 如果找到则返回之.未找到返回空
*/
findChild : function(attribute, value){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(cs[i].attributes[attribute] == value){
return cs[i];
}
}
return null;
},
/**
* Finds the first child by a custom function. The child matches if the function passed
* returns true.
* @param {Function} fn
* @param {Object} scope (optional)
* @return {Node} The found child or null if none was found
*/
/**
* 根据客户函数找到第一个匹配的子节点. 子节点匹配函数时返回true.
* @param {Function} 函数
* @param {Object} scope (可选项)
* @return {Node} 如果找到则返回之.未找到返回空
*/
findChildBy : function(fn, scope){
var cs = this.childNodes;
for(var i = 0, len = cs.length; i < len; i++) {
if(fn.call(scope||cs[i], cs[i]) === true){
return cs[i];
}
}
return null;
},
/**
* Sorts this nodes children using the supplied sort function
* @param {Function} fn
* @param {Object} scope (optional)
*/
/**
* 使用指定的函数为该节点的子节点排序
* @param {Function} fn
* @param {Object} scope (optional)
*/
sort : function(fn, scope){
var cs = this.childNodes;
var len = cs.length;
if(len > 0){
var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn;
cs.sort(sortFn);
for(var i = 0; i < len; i++){
var n = cs[i];
n.previousSibling = cs[i-1];
n.nextSibling = cs[i+1];
if(i == 0){
this.setFirstChild(n);
}
if(i == len-1){
this.setLastChild(n);
}
}
}
},
/**
* Returns true if this node is an ancestor (at any point) of the passed node.
* @param {Node} node
* @return {Boolean}
*/
/**
* 如果该节点是传入的节点的祖先,则返回true.
* @param {Node} node
* @return {Boolean}
*/
contains : function(node){
return node.isAncestor(this);
},
/**
* Returns true if the passed node is an ancestor (at any point) of this node.
* @param {Node} node
* @return {Boolean}
*/
/**
* 如果传入的节点是该节点的祖先,则返回true.
* @param {Node} node
* @return {Boolean}
*/
isAncestor : function(node){
var p = this.parentNode;
while(p){
if(p == node){
return true;
}
p = p.parentNode;
}
return false;
},
toString : function(){
return "[Node"+(this.id?" "+this.id:"")+"]";
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.DataProxy
* This class is an abstract base class for implementations which provide retrieval of
* unformatted data objects.<br>
* <p>
* DataProxy implementations are usually used in conjunction with an implementation of Ext.data.DataReader
* (of the appropriate type which knows how to parse the data object) to provide a block of
* {@link Ext.data.Records} to an {@link Ext.data.Store}.<br>
* <p>
* Custom implementations must implement the load method as described in
* {@link Ext.data.HttpProxy#load}.
*/
/**
* @ Ext.data.DataProxy类
* 该类是所有实现例的一抽象基类.该实现例能重获未格式化数据对象<br>
* <p>
* 数据代理实现类通常被用来与一Ext.data.DataReader实现(适当类型的DataReader实现类知道如何去解析数据对象)
* 例协作向一Ext.data.Store类提供Ext.data.Records块
* <p>
* 如Ext.data.HttpProxy的load方法要求.客户实现类必须实现load方法
*/
Ext.data.DataProxy = function(){
this.addEvents({
/**
* @event beforeload
* Fires before a network request is made to retrieve a data object.
* @param {Object} This DataProxy object.
* @param {Object} params The params parameter to the load function.
*/
/**
* @ beforeload 事件
* 在一个网络请求(该请求为了获得数据对象)之前触发
* @param {Object} 该 DataProxy 对象.
* @param {Object} params 装载函数的参数
*/
beforeload : true,
/**
* @event load
* Fires before the load method's callback is called.
* @param {Object} This DataProxy object.
* @param {Object} o The data object.
* @param {Object} arg The callback argument object passed to the load function.
*/
/**
* @ load 事件
* 在load方法的回调函数被调用之前触发该事件
* @param {Object} 该 DataProxy 对象.
* @param {Object} o 数据对象
* @param {Object} arg 传入load 函数的回调参数对象
*/
load : true,
/**
* @event loadexception
* Fires if an Exception occurs during data retrieval.
* @param {Object} This DataProxy object.
* @param {Object} o The data object.
* @param {Object} arg The callback argument object passed to the load function.
* @param {Object} e The Exception.
*/
/**
* @ loadexception 事件
* 在获取数据期间有民常发生时触发该事件
* @param {Object} 该 DataProxy 对象.
* @param {Object} o 数据对象.
* @param {Object} arg 传入load 函数的回调参数对象
* @param {Object} e 异常
*/
loadexception : true
});
Ext.data.DataProxy.superclass.constructor.call(this);
};
Ext.extend(Ext.data.DataProxy, Ext.util.Observable); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.Store
* @extends Ext.util.Observable
* The Store class encapsulates a client side cache of {@link Ext.data.Record} objects which provide input data
* for widgets such as the Ext.grid.Grid, or the Ext.form.ComboBox.<br>
* <p>
* A Store object uses an implementation of {@link Ext.data.DataProxy} to access a data object unless you call loadData() directly and pass in your data. The Store object
* has no knowledge of the format of the data returned by the Proxy.<br>
* <p>
* A Store object uses its configured implementation of {@link Ext.data.DataReader} to create {@link Ext.data.Record}
* instances from the data object. These records are cached and made available through accessor functions.
* @constructor
* Creates a new Store.
* @param {Object} config A config object containing the objects needed for the Store to access data,
* and read the data into Records.
*/
/**
* @ Ext.data.Store类
* @继承了 Ext.util.Observable
* 该类封装了一个客户端的Ext.data.Record对象的缓存.该缓存为窗口小部件如grid,combobox等提供了填充数据<br>
* <p>
* 一个store对象使用一个Ext.data.Proxy的实现类来访问一数据对象.直到你调用loadData()直接地传入你的数据.<br>
* <p>
* 该类使用配置的一个Ext.data.DataReader的实例类来从数据对象创建Ext.data.Record实例.这些records都被缓存并且
* 通过访问器函数可利用到
* @构建器
* 创建一新Store
* @param {Object} config 一配置对象,包含了Store用来访问数据,及读数据至Records的对象
*/
Ext.data.Store = function(config){
this.data = new Ext.util.MixedCollection(false);
this.data.getKey = function(o){
return o.id;
};
this.baseParams = {};
// private
this.paramNames = {
"start" : "start",
"limit" : "limit",
"sort" : "sort",
"dir" : "dir"
};
if(config && config.data){
this.inlineData = config.data;
delete config.data;
}
Ext.apply(this, config);
if(this.reader){ // reader passed
if(!this.recordType){
this.recordType = this.reader.recordType;
}
if(this.reader.onMetaChange){
this.reader.onMetaChange = this.onMetaChange.createDelegate(this);
}
}
if(this.recordType){
this.fields = this.recordType.prototype.fields;
}
this.modified = [];
this.addEvents({
/**
* @event datachanged
* Fires when the data cache has changed, and a widget which is using this Store
* as a Record cache should refresh its view.
* @param {Store} this
*/
/**
* @event datachanged
* 当数据缓存有改变时触发该事件.使用了该Store作为Record缓存的窗口部件应当更新
* @param {Store} this
*/
datachanged : true,
/**
* @event metachange
* Fires when this store's reader provides new metadata (fields). This is currently only support for JsonReaders.
* @param {Store} this
* @param {Object} meta The JSON metadata
*/
/**
* @event metachange
* 当store的reader 提供新的元数据字段时触发.这目前仅支持jsonReader
* @param {Store} this
* @param {Object} meta JSON 元数据
*/
metachange : true,
/**
* @event add
* Fires when Records have been added to the Store
* @param {Store} this
* @param {Ext.data.Record[]} records The array of Records added
* @param {Number} index The index at which the record(s) were added
*/
/**
* @event add
* 当Records被添加到store时激发
* @param {Store} this
* @param {Ext.data.Record[]} records The 要被加入的Record数组
* @param {Number} index 被添加进去的record的索引
*/
add : true,
/**
* @event remove
* Fires when a Record has been removed from the Store
* @param {Store} this
* @param {Ext.data.Record} record The Record that was removed
* @param {Number} index The index at which the record was removed
*/
/**
* @event remove
* 当一个record被从store里移出时激发
* @param {Store} this
* @param {Ext.data.Record} record 被移出的对Record象
* @param {Number} index 被移出的record的索引值
*/
remove : true,
/**
* @event update
* Fires when a Record has been updated
* @param {Store} this
* @param {Ext.data.Record} record The Record that was updated
* @param {String} operation The update operation being performed. Value may be one of:
* <pre><code>
Ext.data.Record.EDIT
Ext.data.Record.REJECT
Ext.data.Record.COMMIT
* </code></pre>
*/
/**
* @event update
* 当有record被更新时激发
* @param {Store} this
* @param {Ext.data.Record} record 被更新的记录
* @param {String} operation 更新操作将要执行时的操作. 可能是下列值:
* <pre><code>
Ext.data.Record.EDIT
Ext.data.Record.REJECT
Ext.data.Record.COMMIT
* </code></pre>
*/
update : true,
/**
* @event clear
* Fires when the data cache has been cleared.
* @param {Store} this
*/
/**
* @event clear
* 当数据缓存被清除时激发
* @param {Store} this
*/
clear : true,
/**
* @event beforeload
* Fires before a request is made for a new data object. If the beforeload handler returns false
* the load action will be canceled.
* @param {Store} this
* @param {Object} options The loading options that were specified (see {@link #load} for details)
*/
/**
* @event beforeload
* 在一个请求新数据的请求发起之前触发 ,如果beforeload事件句柄返回false.装载动作将会被取消
* @param {Store} this
* @param {Object} options 指定的loading选项 (从 {@link #load} 查看更多细节)
*/
beforeload : true,
/**
* @event load
* 在一个新的数据集被装载之后激发该事件
* @param {Store} this
* @param {Ext.data.Record[]} records 被载入的records
* @param {Object} options The 指定的loading选项 (从 {@link #load} 查看更多细节)
*/
load : true,
/**
* @event loadexception
* Fires if an exception occurs in the Proxy during loading.
* Called with the signature of the Proxy's "loadexception" event.
*/
/**
* @event loadexception
* 在装载过程中有错误发生在代理中时触发该事件
* 调用代理的"loadexception"事件的签名
*/
loadexception : true
});
if(this.proxy){
this.relayEvents(this.proxy, ["loadexception"]);
}
this.sortToggle = {};
Ext.data.Store.superclass.constructor.call(this);
if(this.inlineData){
this.loadData(this.inlineData);
delete this.inlineData;
}
};
Ext.extend(Ext.data.Store, Ext.util.Observable, {
/**
* @cfg {Ext.data.DataProxy} proxy The Proxy object which provides access to a data object.
*/
/**
* @cfg {Ext.data.DataProxy} proxy 提供访问数据对象的代理对象
*/
/**
* @cfg {Array} data Inline data to be loaded when the store is initialized.
*/
/**
* @cfg {Array} data 当store被初使化时,将被装载的inline 数据.
*/
/**
* @cfg {Ext.data.Reader} reader The Reader object which processes the data object and returns
* an Array of Ext.data.record objects which are cached keyed by their <em>id</em> property.
*/
/**
* @cfg {Ext.data.Reader} 处理数据对象并返回通过他的id属性映射的被缓存的Ext.data.record对象数组的Reader对象.
*/
/**
* @cfg {Object} baseParams An object containing properties which are to be sent as parameters
* on any HTTP request
*/
/**
* @cfg {Object} baseParams 一个包含属性的对象.这些属性在http请求时作为参数被发送出去
*/
/**
* @cfg {Object} sortInfo A config object in the format: {field: "fieldName", direction: "ASC|DESC"}
*/
/**
* @cfg {Object} sortInfo 一个有着类似如下格式的配置对象: {field: "fieldName", direction: "ASC|DESC"}
*/
/**
* @cfg {boolean} remoteSort True if sorting is to be handled by requesting the Proxy to provide a refreshed
* version of the data object in sorted order, as opposed to sorting the Record cache in place (defaults to false).
*/
/**
* @cfg {boolean} remoteSort 如果设置为true,在排序命定时排序被请求的代理(用来提供一个制新了的版本的数据对象)处理.
* 如果不想对Record缓存排序则设为false,默认为false.
*/
remoteSort : false,
/**
* @cfg {boolean} pruneModifiedRecords True to clear all modified record information each time the store is
* loaded or when a record is removed. (defaults to false).
*/
/**
* @cfg {boolean} pruneModifiedRecords 设置为true,则每次当store装载或有record被移除时,清空所有修改了的record信息.
* 默认为false.
*/
pruneModifiedRecords : false,
// private
lastOptions : null,
/**
* Add Records to the Store and fires the add event.
* @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
*/
/**
* 在触发add事件时添加一个Records进Store.
* @param {Ext.data.Record[]} records 被添加到缓存中的Ext.data.Record对象或其数组对象
*/
add : function(records){
records = [].concat(records);
for(var i = 0, len = records.length; i < len; i++){
records[i].join(this);
}
var index = this.data.length;
this.data.addAll(records);
this.fireEvent("add", this, records, index);
},
/**
* Remove a Record from the Store and fires the remove event.
* @param {Ext.data.Record} record Th Ext.data.Record object to remove from the cache.
*/
/**
* 在触发移除事件时从Store中移除一Record对象
* @param {Ext.data.Record} record 被从缓存中移除的Ext.data.Record对象.
*/
remove : function(record){
var index = this.data.indexOf(record);
this.data.removeAt(index);
if(this.pruneModifiedRecords){
this.modified.remove(record);
}
this.fireEvent("remove", this, record, index);
},
/**
* Remove all Records from the Store and fires the clear event.
*/
/**
* 在清除事件触发时从Store移除所有Record
*/
removeAll : function(){
this.data.clear();
if(this.pruneModifiedRecords){
this.modified = [];
}
this.fireEvent("clear", this);
},
/**
* Inserts Records to the Store at the given index and fires the add event.
* @param {Number} index The start index at which to insert the passed Records.
* @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
*/
/**
* 触发添加事件时插入records到指定的store位置
* @param {Number} index The 传入的Records插入的开始位置
* @param {Ext.data.Record[]} records.
*/
insert : function(index, records){
records = [].concat(records);
for(var i = 0, len = records.length; i < len; i++){
this.data.insert(index, records[i]);
records[i].join(this);
}
this.fireEvent("add", this, records, index);
},
/**
* Get the index within the cache of the passed Record.
* @param {Ext.data.Record} record The Ext.data.Record object to to find.
* @return {Number} The index of the passed Record. Returns -1 if not found.
*/
/**
* 获取传入的Record在缓存中的索引
* @param {Ext.data.Record} record 要找寻的Ext.data.Record.
* @return {Number} 被传入的Record的索引,如果未找到返回-1.
*/
indexOf : function(record){
return this.data.indexOf(record);
},
/**
* Get the index within the cache of the Record with the passed id.
* @param {String} id The id of the Record to find.
* @return {Number} The index of the Record. Returns -1 if not found.
*/
/**
* 根据传入的id查询缓存里的Record的索引
* @param {String} id 要找到Record的id.
* @return {Number} 被找到的Record的索引. 如果未找到返回-1.
*/
indexOfId : function(id){
return this.data.indexOfKey(id);
},
/**
* Get the Record with the specified id.
* @param {String} id The id of the Record to find.
* @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
*/
/**
* 根据指定的id找到Record.
* @param {String} id 要找的Record的id
* @return {Ext.data.Record} 返回找到的指定id的Record,如果未找到则返回underfined.
*/
getById : function(id){
return this.data.key(id);
},
/**
* Get the Record at the specified index.
* @param {Number} index The index of the Record to find.
* @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
*/
/**
* 根据指定的索引找到Record.
* @param {Number} index 要找的Record的索引.
* @return {Ext.data.Record} 返回找到的指定索引的Record,如果未找到则返回undefined.
*/
getAt : function(index){
return this.data.itemAt(index);
},
/**
* Returns a range of Records between specified indices.
* @param {Number} startIndex (optional) The starting index (defaults to 0)
* @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
* @return {Ext.data.Record[]} An array of Records
*/
/**
* 返回指定范围里的Records.
* @param {Number} startIndex (可选项) 开始索引 (默认为 0)
* @param {Number} endIndex (可选项) 结束的索引 (默认是Store中最后一个Record的索引)
* @return {Ext.data.Record[]} 返回一个Record数组
*/
getRange : function(start, end){
return this.data.getRange(start, end);
},
// private
storeOptions : function(o){
o = Ext.apply({}, o);
delete o.callback;
delete o.scope;
this.lastOptions = o;
},
/**
* Loads the Record cache from the configured Proxy using the configured Reader.
* <p>
* If using remote paging, then the first load call must specify the <em>start</em>
* and <em>limit</em> properties in the options.params property to establish the initial
* position within the dataset, and the number of Records to cache on each read from the Proxy.
* <p>
* <strong>It is important to note that for remote data sources, loading is asynchronous,
* and this call will return before the new data has been loaded. Perform any post-processing
* in a callback function, or in a "load" event handler.</strong>
* <p>
* @param {Object} options An object containing properties which control loading options:<ul>
* <li>params {Object} An object containing properties to pass as HTTP parameters to a remote data source.</li>
* <li>callback {Function} A function to be called after the Records have been loaded. The callback is
* passed the following arguments:<ul>
* <li>r : Ext.data.Record[]</li>
* <li>options: Options object from the load call</li>
* <li>success: Boolean success indicator</li></ul></li>
* <li>scope {Object} Scope with which to call the callback (defaults to the Store object)</li>
* <li>add {Boolean} indicator to append loaded records rather than replace the current cache.</li>
* </ul>
*/
/**
* 使用配置的Record从配置的代理中装载Record缓存.
* <p>
* 如果使用远程(服务端)分页, 在第一次装载调用时必须在配置项中指定start,和limit属性.
* 参数的属性确定在数据集初使化位置,和每次从代理的缓存中的Record的数目.
* <p>
* <strong>这是很重要的,对于远程数据源,请注意:装载是异步的,而且此次调用将会在新数据被装载之前返回.
* 在回调函数中执行后处理,或者在"load"事件中处理</strong>
* <p>
* @param {Object} options 包含控制装载的可选项作为属性的对象:<ul>
* <li>params {Object} 包含了一组属性的对象.这些属性作为向http参数传入远程数据源.</li>
* <li>callback {Function} 当Record被传入后被调用的参数,该函数传入如下参数:<ul>
* <li>r : Ext.data.Record[]</li>
* <li>options: 来自装载调用的可选项对象</li>
* <li>success: 布尔值的成功指示器</li></ul></li>
* <li>scope {Object} 调用回调函数的作用域 (默认为Store对象)</li>
* <li>add {Boolean} 追加装载的records而不是代替当前缓存的布尔指示器.</li>
* </ul>
*/
load : function(options){
options = options || {};
if(this.fireEvent("beforeload", this, options) !== false){
this.storeOptions(options);
var p = Ext.apply(options.params || {}, this.baseParams);
if(this.sortInfo && this.remoteSort){
var pn = this.paramNames;
p[pn["sort"]] = this.sortInfo.field;
p[pn["dir"]] = this.sortInfo.direction;
}
this.proxy.load(p, this.reader, this.loadRecords, this, options);
}
},
/**
* Reloads the Record cache from the configured Proxy using the configured Reader and
* the options from the last load operation performed.
* @param {Object} options (optional) An object containing properties which may override the options
* used in the last load operation. See {@link #load} for details (defaults to null, in which case
* the most recently used options are reused).
*/
/**
* 使用被配置的reader和可选项从最后一次装载操作任务从配置的proxy中装载record缓存
* @param {Object} options (optional) An object containing properties which may override the options
* used in the last load operation. See {@link #load} for details (defaults to null, in which case
* the most recently used options are reused).
*/
reload : function(options){
this.load(Ext.applyIf(options||{}, this.lastOptions));
},
// private
// Called as a callback by the Reader during a load operation.
// 在装载操作时,被Reader作为回调函数来调用
loadRecords : function(o, options, success){
if(!o || success === false){
if(success !== false){
this.fireEvent("load", this, [], options);
}
if(options.callback){
options.callback.call(options.scope || this, [], options, false);
}
return;
}
var r = o.records, t = o.totalRecords || r.length;
if(!options || options.add !== true){
if(this.pruneModifiedRecords){
this.modified = [];
}
for(var i = 0, len = r.length; i < len; i++){
r[i].join(this);
}
if(this.snapshot){
this.data = this.snapshot;
delete this.snapshot;
}
this.data.clear();
this.data.addAll(r);
this.totalLength = t;
this.applySort();
this.fireEvent("datachanged", this);
}else{
this.totalLength = Math.max(t, this.data.length+r.length);
this.add(r);
}
this.fireEvent("load", this, r, options);
if(options.callback){
options.callback.call(options.scope || this, r, options, true);
}
},
/**
* Loads data from a passed data block. A Reader which understands the format of the data
* must have been configured in the constructor.
* @param {Object} data The data block from which to read the Records. The format of the data expected
* is dependent on the type of Reader that is configured and should correspond to that Reader's readRecords parameter.
* @param {Boolean} append (Optional) True to append the new Records rather than replace the existing cache.
*/
/**
* 从传入的数据块中装载数据,了解数据格式的reader必须被配置在构建器中
* @param {Object} data 从该处读取record的数据块. 预期数据的格式由被配置的reader的类型决定.它应该符合reader的readRecords参数
* @param {Boolean} append (可选项) 设置为true,追加一新记录而不是代替己存在的缓存
*/
loadData : function(o, append){
var r = this.reader.readRecords(o);
this.loadRecords(r, {add: append}, true);
},
/**
* Gets the number of cached records.
* <p>
* <em>If using paging, this may not be the total size of the dataset. If the data object
* used by the Reader contains the dataset size, then the getTotalCount() function returns
* the data set size</em>
*/
/**
* 获取缓存记录的数
* <p>
* <em>如果分页.这里将不再是数据集的总数. 如果Reader使用的数据对象里包含了数据的总数,则可用
* getTotalCount() 方法返回总计录数</em>
*/
getCount : function(){
return this.data.length || 0;
},
/**
* Gets the total number of records in the dataset as returned by the server.
* <p>
* <em>If using paging, for this to be accurate, the data object used by the Reader must contain
* the dataset size</em>
*/
/**
*获取作为服务端返回的数据集中记录的总数.
* <p>
* <em>如果分页,这将要计算.Reader使用的数据对象必须包含数据集的大小</em>
*/
getTotalCount : function(){
return this.totalLength || 0;
},
/**
* Returns the sort state of the Store as an object with two properties:
* <pre><code>
field {String} The name of the field by which the Records are sorted
direction {String} The sort order, "ASC" or "DESC"
* </code></pre>
*/
/**
*以对象的形式返回排序的状态.它包含两属性:
* <pre><code>
field {String} 一个是排序字段
direction {String} 一个是排序方向
* </code></pre>
*/
getSortState : function(){
return this.sortInfo;
},
// private
applySort : function(){
if(this.sortInfo && !this.remoteSort){
var s = this.sortInfo, f = s.field;
var st = this.fields.get(f).sortType;
var fn = function(r1, r2){
var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
};
this.data.sort(s.direction, fn);
if(this.snapshot && this.snapshot != this.data){
this.snapshot.sort(s.direction, fn);
}
}
},
/**
* Sets the default sort column and order to be used by the next load operation.
* @param {String} fieldName The name of the field to sort by.
* @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
/**
* 设置默认的排序列,以便下次load操作时使用
* @param {String} fieldName The name of the field to sort by.
* @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
setDefaultSort : function(field, dir){
this.sortInfo = {field: field, direction: dir ? dir.toUpperCase() : "ASC"};
},
/**
* Sort the Records.
* If remote sorting is used, the sort is performed on the server, and the cache is
* reloaded. If local sorting is used, the cache is sorted internally.
* @param {String} fieldName The name of the field to sort by.
* @param {String} dir (optional) The sort order, "ASC" or "DESC" (defaults to "ASC")
*/
/**
* 为Records排序.
* 如果使用了远程排序, 排序在服务端执行, 然后重新载入缓存.
* 如果只是客户端排序, 只是缓存内部排序.
* @param {String} fieldName 排序字段.
* @param {String} dir (optional) 排序方向.(默认升序 "ASC")
*/
sort : function(fieldName, dir){
var f = this.fields.get(fieldName);
if(!dir){
if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC");
}else{
dir = f.sortDir;
}
}
this.sortToggle[f.name] = dir;
this.sortInfo = {field: f.name, direction: dir};
if(!this.remoteSort){
this.applySort();
this.fireEvent("datachanged", this);
}else{
this.load(this.lastOptions);
}
},
/**
* Calls the specified function for each of the Records in the cache.
* @param {Function} fn The function to call. The Record is passed as the first parameter.
* Returning <em>false</em> aborts and exits the iteration.
* @param {Object} scope (optional) The scope in which to call the function (defaults to the Record).
*/
/**
* 缓存的的每一个record调用的指定函数
* @param {Function} fn 要调用的函数. 该Record作为第一个参数被传入
* 返回 <em>false</em> 中断或退出循环.
* @param {Object} scope (可选项) 调用函数的作用域 (默认为 Record).
*/
each : function(fn, scope){
this.data.each(fn, scope);
},
/**
* Gets all records modified since the last commit. Modified records are persisted across load operations
* (e.g., during paging).
* @return {Ext.data.Record[]} An array of Records containing outstanding modifications.
*/
/**
* 获取所有的自从最后一次提交后被修改的record. 被修改的记录通过load操作来持久化
* (例如,在分页期间).
* @return {Ext.data.Record[]} 包含了显注修改的record数组.
*/
getModifiedRecords : function(){
return this.modified;
},
// private
createFilterFn : function(property, value, anyMatch){
if(!value.exec){ // not a regex
value = String(value);
if(value.length == 0){
return false;
}
value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), "i");
}
return function(r){
return value.test(r.data[property]);
};
},
/**
* Sums the value of <i>property</i> for each record between start and end and returns the result.
* @param {String} property A field on your records
* @param {Number} start The record index to start at (defaults to 0)
* @param {Number} end The last record index to include (defaults to length - 1)
* @return {Number} The sum
*/
/**
* 为每个记录的(开始和结束)属性求和并返回结果.
* @param {String} property 记录的某个字段
* @param {Number} start 该record的开始索引(默认为0)
* @param {Number} end The 该record的结束索引 (默认为 - 1)
* @return {Number} 和
*/
sum : function(property, start, end){
var rs = this.data.items, v = 0;
start = start || 0;
end = (end || end === 0) ? end : rs.length-1;
for(var i = start; i <= end; i++){
v += (rs[i].data[property] || 0);
}
return v;
},
/**
* Filter the records by a specified property.
* @param {String} field A field on your records
* @param {String/RegExp} value Either a string that the field
* should start with or a RegExp to test against the field
* @param {Boolean} anyMatch True to match any part not just the beginning
*/
/**
* 通过指定的属性过滤records
* @param {String} field records的字段
* @param {String/RegExp} value 任意一个字符串(即以该字符串打头的字段)或匹配字段的规则式
* @param {Boolean} anyMatch 设置true,则全文匹配,而不仅是以**打头的匹配
*/
filter : function(property, value, anyMatch){
var fn = this.createFilterFn(property, value, anyMatch);
return fn ? this.filterBy(fn) : this.clearFilter();
},
/**
* Filter by a function. The specified function will be called with each
* record in this data source. If the function returns true the record is included,
* otherwise it is filtered.
* @param {Function} fn The function to be called, it will receive 2 args (record, id)
* @param {Object} scope (optional) The scope of the function (defaults to this)
*/
/**
* 通过函数过滤,该数据源里的所有record将会调用该函数.
* 如果该函数返回true,结果里也包含了record,否则它被过滤掉了
* @param {Function} fn 将被调用的函数,它将接受两个参数 (record, id)
* @param {Object} scope (可选项)该函数的作用域.默认为本函数
*/
filterBy : function(fn, scope){
this.snapshot = this.snapshot || this.data;
this.data = this.queryBy(fn, scope||this);
this.fireEvent("datachanged", this);
},
/**
* Query the records by a specified property.
* @param {String} field A field on your records
* @param {String/RegExp} value Either a string that the field
* should start with or a RegExp to test against the field
* @param {Boolean} anyMatch True to match any part not just the beginning
* @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
*/
/**
* 通过指定的属性查询record
* @param {String} field 你records里的字段名
* @param {String/RegExp} value 任意一个字符串(即以该字符串打头的字段)或匹配字段的规则式
* @param {Boolean} anyMatch 设置true,则全文匹配,而不仅是以**打头的匹配
* @return {MixedCollection} 返回匹配的record的一个 Ext.util.MixedCollection
*/
query : function(property, value, anyMatch){
var fn = this.createFilterFn(property, value, anyMatch);
return fn ? this.queryBy(fn) : this.data.clone();
},
/**
* Query by a function. The specified function will be called with each
* record in this data source. If the function returns true the record is included
* in the results.
* @param {Function} fn The function to be called, it will receive 2 args (record, id)
* @param {Object} scope (optional) The scope of the function (defaults to this)
@return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
**/
/**
* 通过一函数查询. 指定的函数将会被该数据源里的每个record调用.
* 如果该函数返回true,该record被包含在结果中
* @param {Function} fn 将被调用的函数,它将接受两个参数 (record, id)
* @param {Object} scope (可选项)该函数的作用域.默认为本函数
* @return {MixedCollection} 返回匹配的record的一个 Ext.util.MixedCollection
**/
queryBy : function(fn, scope){
var data = this.snapshot || this.data;
return data.filterBy(fn, scope||this);
},
/**
* Collects unique values for a particular dataIndex from this store.
* @param {String} dataIndex The property to collect
* @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
* @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
* @return {Array} An array of the unique values
**/
/**
* 从该store中为精确的数据索引搜集独一无二的值
* @param {String} dataIndex 搜集的一属性
* @param {Boolean} allowNull (可选项) 传入为true,则否许为空或未定义或空字符串值
* @param {Boolean} bypassFilter (可选项) 传入为true,则搜集所有记录,偶数项被过滤掉
* @return {Array} 返回一独一无二的值
**/
collect : function(dataIndex, allowNull, bypassFilter){
var d = (bypassFilter === true && this.snapshot) ?
this.snapshot.items : this.data.items;
var v, sv, r = [], l = {};
for(var i = 0, len = d.length; i < len; i++){
v = d[i].data[dataIndex];
sv = String(v);
if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
l[sv] = true;
r[r.length] = v;
}
}
return r;
},
/**
* Revert to a view of the Record cache with no filtering applied.
* @param {Boolean} suppressEvent If true the filter is cleared silently without notifying listeners
*/
/**
* 不应用过滤回复record缓存的视图
* @param {Boolean} suppressEvent 如果设置为true,该过滤器清空,并且不会通知监听器
*/
clearFilter : function(suppressEvent){
if(this.snapshot && this.snapshot != this.data){
this.data = this.snapshot;
delete this.snapshot;
if(suppressEvent !== true){
this.fireEvent("datachanged", this);
}
}
},
// private
afterEdit : function(record){
if(this.modified.indexOf(record) == -1){
this.modified.push(record);
}
this.fireEvent("update", this, record, Ext.data.Record.EDIT);
},
// private
afterReject : function(record){
this.modified.remove(record);
this.fireEvent("update", this, record, Ext.data.Record.REJECT);
},
// private
afterCommit : function(record){
this.modified.remove(record);
this.fireEvent("update", this, record, Ext.data.Record.COMMIT);
},
/**
* Commit all Records with outstanding changes. To handle updates for changes, subscribe to the
* Store's "update" event, and perform updating when the third parameter is Ext.data.Record.COMMIT.
*/
/**
* 有显注改变时提交所有Record,为了处理更新这些改变.订阅store的update事件.在执行更新时使用第三参数为
* data.Record.COMMIT
*/
commitChanges : function(){
var m = this.modified.slice(0);
this.modified = [];
for(var i = 0, len = m.length; i < len; i++){
m[i].commit();
}
},
/**
* Cancel outstanding changes on all changed records.
*/
rejectChanges : function(){
var m = this.modified.slice(0);
this.modified = [];
for(var i = 0, len = m.length; i < len; i++){
m[i].reject();
}
},
onMetaChange : function(meta, rtype, o){
this.recordType = rtype;
this.fields = rtype.prototype.fields;
delete this.snapshot;
this.sortInfo = meta.sortInfo;
this.modified = [];
this.fireEvent('metachange', this, this.reader.meta);
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
Ext.data.Field = function(config){
if(typeof config == "string"){
config = {name: config};
}
Ext.apply(this, config);
if(!this.type){
this.type = "auto";
}
var st = Ext.data.SortTypes;
// named sortTypes are supported, here we look them up
//支持指定的排序类型,这里我们来查找它们
if(typeof this.sortType == "string"){
this.sortType = st[this.sortType];
}
// set default sortType for strings and dates
// 为strings和dates设置默认的排序类型
if(!this.sortType){
switch(this.type){
case "string":
this.sortType = st.asUCString;
break;
case "date":
this.sortType = st.asDate;
break;
default:
this.sortType = st.none;
}
}
// define once
var stripRe = /[\$,%]/g;
// prebuilt conversion function for this field, instead of
// switching every time we're reading a value
// 为字段预先建立转换函数,来代替每次我们读取值时再选择
if(!this.convert){
var cv, dateFormat = this.dateFormat;
switch(this.type){
case "":
case "auto":
case undefined:
cv = function(v){ return v; };
break;
case "string":
cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
break;
case "int":
cv = function(v){
return v !== undefined && v !== null && v !== '' ?
parseInt(String(v).replace(stripRe, ""), 10) : '';
};
break;
case "float":
cv = function(v){
return v !== undefined && v !== null && v !== '' ?
parseFloat(String(v).replace(stripRe, ""), 10) : '';
};
break;
case "bool":
case "boolean":
cv = function(v){ return v === true || v === "true" || v == 1; };
break;
case "date":
cv = function(v){
if(!v){
return '';
}
if(v instanceof Date){
return v;
}
if(dateFormat){
if(dateFormat == "timestamp"){
return new Date(v*1000);
}
return Date.parseDate(v, dateFormat);
}
var parsed = Date.parse(v);
return parsed ? new Date(parsed) : null;
};
break;
}
this.convert = cv;
}
};
Ext.data.Field.prototype = {
dateFormat: null,
defaultValue: "",
mapping: null,
sortType : null,
sortDir : "ASC"
}; | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.MemoryProxy
* An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor
* to the Reader when its load method is called.
* @constructor
* @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.
*/
/**
* 一个Ext.data.DataProxy的实现类,当它的load方法调用时简单的传入它的构建器指定的数据到Reader
* @构建器
* @param {Object} data Reader用来构建Ext.data.Records 块的数据对象
*/
Ext.data.MemoryProxy = function(data){
Ext.data.MemoryProxy.superclass.constructor.call(this);
this.data = data;
};
Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {
/**
* Load data from the requested source (in this case an in-memory
* data object passed to the constructor), read the data object into
* a block of Ext.data.Records using the passed Ext.data.DataReader implementation, and
* process that block using the passed callback.
* @param {Object} params This parameter is not used by the MemoryProxy class.
* @param {Ext.data.DataReader) reader The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
/**
* 从请求的源装载数据(在这种情况下在内存里的数据对象被传入构建器),使用传入的Ext.data.DataReader的实现
* 将数据对象读入Ext.data.Records块.并使用传入的回调函数处理该块.
* @param {Object} params 这些参数不是MemoryProxy 类用到的参数.
* @param {Ext.data.DataReader) reader 将数据对象转换成Ext.data.Records块对象的读取器.
* @param {Function} callback 传入到Ext.data.records块的函数.
* 该函数必须被传入 <ul>
* <li>Record 块对象</li>
* <li>来自装载函数的参数</li>
* <li>布尔变量的成功指示器</li>
* </ul>
* @param {Object} scope 回调函数的作用域
* @param {Object} arg 被传处回调函数作为第二参数码的可选参数.
*/
load : function(params, reader, callback, scope, arg){
params = params || {};
var result;
try {
result = reader.readRecords(this.data);
}catch(e){
this.fireEvent("loadexception", this, arg, null, e);
callback.call(scope, null, arg, false);
return;
}
callback.call(scope, result, arg, true);
},
// private
update : function(params, records){
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.XmlReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
* based on mappings in a provided Ext.data.Record constructor.<br><br>
* xmlReader类,继承Ext.data.DataReader类.基于Ext.data.Record的构建器提供的映射,从一xml document
* 中创建一Ext.data.Record对象的数组 的数据读取器
* <p>
* <em>Note that in order for the browser to parse a returned XML document, the Content-Type
* header in the HTTP response must be set to "text/xml".</em>
* 注意:为了浏览器解析返回来的xml document, http response的content-type 头必须被设成text/xml
* <p>
* Example code:
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
{name: 'occupation'} // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.XmlReader({
totalRecords: "results", // The element which contains the total dataset size (optional)
record: "row", // The repeated element which contains row information
id: "id" // The element within the row that provides an ID for the record (optional)
}, RecordDef);
</code></pre>
* <p>
* This would consume an XML file like this:
* <pre><code>
<?xml?>
<dataset>
<results>2</results>
<row>
<id>1</id>
<name>Bill</name>
<occupation>Gardener</occupation>
</row>
<row>
<id>2</id>
<name>Ben</name>
<occupation>Horticulturalist</occupation>
</row>
</dataset>
</code></pre>
* @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
* in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
* paged from the remote server.
* @cfg {String} record The DomQuery path to the repeated element which contains record information.
* @cfg {String} success The DomQuery path to the success attribute used by forms.
* @cfg {String} id The DomQuery path relative from the record element to the element that contains
* a record identifier value.
* @constructor
* Create a new XmlReader
* @param {Object} meta Metadata configuration options
* @param {Mixed} recordType The definition of the data record type to produce. This can be either a valid
* Record subclass created with {@link Ext.data.Record#create}, or an array of objects with which to call
* Ext.data.Record.create. See the {@link Ext.data.Record} class for more details.
*/
/*
* @cfg {String} totalRecords domQuery 路径,据此可以找到数据集里的记录总行数.该属性仅当整个数据集里被一次性
* 拿出(而不是远程肥务器分页后的数据)时有用.
* @cfg {String} record 包含记录信息的多个重复元素的DomQurey路径
* @cfg {String} success 被forms使用的成功属性的DomQuery 路径
* @cfg {String} id 关联记录元素到包含记录标识值元素的domQuery路径
* @构建器
* 创建一新xmlReader
* @param {Object} meta 元数据配置项
* @param {Mixed} recordType 用于产生数据记录类型的定义.这既可以是通过Ext.data.Record的create方法产生的一个有效的Record
* 子类,也可以是一个通过调用Ext.data.Record的create方法产生的对象数组.从Ext.data.Record类可以了解更多细节
*/
Ext.data.XmlReader = function(meta, recordType){
meta = meta || {};
Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response The XHR object which contains the parsed XML document. The response is expected
* to contain a method called 'responseXML' that returns an XML document object.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
/**
* 该方法仅仅被DataProxy用来从远程服务器找回数据
* @param {Object} response 包含了解析的xml document的xhr对象
* 该response 被期望包含一方法调用responseXML来返回xml document对象
* @return {Object} records 被Ext.data.Store作为Ext.data.Records缓存的数据块.
*/
read : function(response){
var doc = response.responseXML;
if(!doc) {
throw {message: "XmlReader.read: XML Document not available"};
}
return this.readRecords(doc);
},
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} doc A parsed XML document.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
/**
* 通过xml document创建一包含Ext.data.Records的数据块
* @param {Object} doc 一个被解析的 XML document.
* @return {Object} 被Ext.data.Store当作Ext.data.Records缓存的数据块
*/
readRecords : function(doc){
/**
* After any data loads/reads, the raw XML Document is available for further custom processing.
* @type XMLDocument
*/
/**
* 当有数据loads或reads后,原始的xml Document对于后面的客户操作不可用!
* @type XMLDocument
*/
this.xmlData = doc;
var root = doc.documentElement || doc;
var q = Ext.DomQuery;
var recordType = this.recordType, fields = recordType.prototype.fields;
var sid = this.meta.id;
var totalRecords = 0, success = true;
if(this.meta.totalRecords){
totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
}
if(this.meta.success){
var sv = q.selectValue(this.meta.success, root, true);
success = sv !== false && sv !== 'false';
}
var records = [];
var ns = q.select(this.meta.record, root);
for(var i = 0, len = ns.length; i < len; i++) {
var n = ns[i];
var values = {};
var id = sid ? q.selectValue(sid, n) : undefined;
for(var j = 0, jlen = fields.length; j < jlen; j++){
var f = fields.items[j];
var v = q.selectValue(f.mapping || f.name, n, f.defaultValue);
v = f.convert(v);
values[f.name] = v;
}
var record = new recordType(values, id);
record.node = n;
records[records.length] = record;
}
return {
success : success,
records : records,
totalRecords : totalRecords || records.length
};
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.SortTypes
* @singleton
* Defines the default sorting (casting?) comparison functions used when sorting data.
*/
/**
* @ Ext.data.SortTypes类
* @单例
* 定义在排序数据时一个默认的排序比较函数
*/
Ext.data.SortTypes = {
/**
* Default sort that does nothing
* @param {Mixed} s The value being converted
* @return {Mixed} The comparison value
*/
/**
* 默认的排序即什么也不做
* @param {Mixed} s 将被转换的值
* @return {Mixed} 用来比较的值
*/
none : function(s){
return s;
},
/**
* The regular expression used to strip tags
* @type {RegExp}
* @property
*/
/**
* 用来去掉标签的规则表达式
* @type {RegExp}
* @property
*/
stripTagsRE : /<\/?[^>]+>/gi,
/**
* Strips all HTML tags to sort on text only
* @param {Mixed} s The value being converted
* @return {String} The comparison value
*/
/**
* 去掉所有html标签来基于纯文本排序
* @param {Mixed} s 将被转换的值
* @return {String} 用来比较的值
*/
asText : function(s){
return String(s).replace(this.stripTagsRE, "");
},
/**
* Strips all HTML tags to sort on text only - Case insensitive
* @param {Mixed} s The value being converted
* @return {String} The comparison value
*/
/**
* 去掉所有html标签来基于无大小写区别的文本的排序
* @param {Mixed} s 将被转换的值
* @return {String} 所比较的值
*/
asUCText : function(s){
return String(s).toUpperCase().replace(this.stripTagsRE, "");
},
/**
* Case insensitive string
* @param {Mixed} s The value being converted
* @return {String} The comparison value
*/
/**
* 无大小写区别的字符串
* @param {Mixed} s 将被转换的值
* @return {String} 所比较的值
*/
asUCString : function(s) {
return String(s).toUpperCase();
},
/**
* Date sorting
* @param {Mixed} s The value being converted
* @return {Number} The comparison value
*/
/**
* 日期排序
* @param {Mixed} s 将被转换的值
* @return {Number} 所比较的值
*/
asDate : function(s) {
if(!s){
return 0;
}
if(s instanceof Date){
return s.getTime();
}
return Date.parse(String(s));
},
/**
* Float sorting
* @param {Mixed} s The value being converted
* @return {Float} The comparison value
*/
/**
* 浮点数的排序
* @param {Mixed} s 将被转换的值
* @return {Float} 所比较的值
*/
asFloat : function(s) {
var val = parseFloat(String(s).replace(/,/g, ""));
if(isNaN(val)) val = 0;
return val;
},
/**
* Integer sorting
* @param {Mixed} s The value being converted
* @return {Number} The comparison value
*/
/**
* 整数的排序
* @param {Mixed} s 将被转换的值
* @return {Number} 所比较的值
*/
asInt : function(s) {
var val = parseInt(String(s).replace(/,/g, ""));
if(isNaN(val)) val = 0;
return val;
}
}; | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.JsonStore
* @extends Ext.data.Store
* Small helper class to make creating Stores for JSON data easier. <br/>
* Ext.data.JsonStore类,继承Ext.data.Store.一小帮助类,使得创建json 数据 store更加容易
<pre><code>
var store = new Ext.data.JsonStore({
url: 'get-images.php',
root: 'images',
fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
});
</code></pre>
* <b>Note: Although they are not listed, this class inherits all of the config options of Store,
* JsonReader and HttpProxy (unless inline data is provided).</b>
* @cfg {Array} fields An array of field definition objects, or field name strings.
* @constructor
* @param {Object} config
*/
/*
* <b>注意: 尽管他们没有列出来.除非内在数据己提供,否则该类继承了所有store,jsonReader,和heepProxy的配置项.</b>
* @cfg {Array} fields 一字段定义的对象,或字段名 数组
* @constructor
* @param {Object} config
*/
Ext.data.JsonStore = function(c){
Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(c, {
proxy: !c.data ? new Ext.data.HttpProxy({url: c.url}) : undefined,
reader: new Ext.data.JsonReader(c, c.fields)
}));
};
Ext.extend(Ext.data.JsonStore, Ext.data.Store); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.Connection
* @extends Ext.util.Observable
* 该类压缩了一个页面到当前域的连接,以响应(来自配置文件中的url或请求时指定的url)请求
* 通过该类产生的请求都是异步的,并且会立刻返回,紧根其后的request调用将得不到数据
* 可以使用在request配置项一个回调函数,或事件临听器来处理返回来的数据.
* The class encapsulates a connection to the page's originating domain, allowing requests to be made
* either to a configured URL, or to a URL specified at request time.<br><br>
* <p>
* Requests made by this class are asynchronous, and will return immediately. No data from
* the server will be available to the statement immediately following the {@link #request} call.
* To process returned data, use a callback in the request options object, or an event listener.</p><br>
* <p>
* 注意:如果你正在上传文件,你将不会有一正常的响应对象送回到你的回调或事件名柄中,因为上传是通过iframe来处理的.
* 这里没有xmlhttpRequest对象.response对象是通过iframe的document的innerTHML作为responseText属性,如果存在,
* 该iframe的xml document作为responseXML属性
* 这意味着一个有效的xml或html document必须被返回,如果json数据是被需要的,这次意味着它将放到
* html document的textarea元素内(通过某种规则可以从responseText重新得到)或放到一个元数据区内(通过标准的dom方法可以重新得到)
*
* Note: If you are doing a file upload, you will not get a normal response object sent back to
* your callback or event handler. Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
* The response object is created using the innerHTML of the IFRAME's document as the responseText
* property and, if present, the IFRAME's XML document as the responseXML property.</p><br>
* This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
* that it be placed either inside a <textarea> in an HTML document and retrieved from the responseText
* using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
* standard DOM methods.
* @constructor 构建器
* @param {Object} config a configuration object. 配置对象
*/
Ext.data.Connection = function(config){
Ext.apply(this, config);
this.addEvents({
/**
* @ beforrequest 事件
* 在一网络请求要求返回数据对象之前触发该事件
* @param {Connection} conn 该Connection对象
* @param {Object} options 传入reauest 方法的配置对象
* @event beforerequest
* Fires before a network request is made to retrieve a data object.
* @param {Connection} conn This Connection object.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
"beforerequest" : true,
/**
* @event requestcomplete
* Fires if the request was successfully completed.
* @param {Connection} conn This Connection object.
* @param {Object} response The XHR object containing the response data.
* See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
/**
* @ requestcomplete 事件
* 当请求成功完成时触发该事件
* @param {Connection} conn 该Connection对象
* @param {Object} response 包含返回数据的XHR对象
* 去 {@link http://www.w3.org/TR/XMLHttpRequest/} 获取更多信息
* @param {Object} options 传入reauest 方法的配置对象
*/
"requestcomplete" : true,
/**
* @event requestexception
* Fires if an error HTTP status was returned from the server.
* See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
* @param {Connection} conn This Connection object.
* @param {Object} response The XHR object containing the response data.
* See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
* @param {Object} options The options config object passed to the {@link #request} method.
*/
/**
* @ requestexception 事件
* 当服务器端返回代表错误的http状态时触发该事件
* 去 {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} 获取更多关于HTTP status codes信息.
* @param {Connection} conn 该Connection对象
* @param {Object} response 包含返回数据的XHR对象
* 去 {@link http://www.w3.org/TR/XMLHttpRequest/} 获取更多信息.
* @param {Object} 传入reauest 方法的配置对象.
*/
"requestexception" : true
});
Ext.data.Connection.superclass.constructor.call(this);
};
Ext.extend(Ext.data.Connection, Ext.util.Observable, {
/**
* @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
*/
/**
* @cfg {String} url (可选项) 被用来向服务发起请求默认的url,默认值为undefined
*/
/**
* @cfg {Object} extraParams (Optional) An object containing properties which are used as
* extra parameters to each request made by this object. (defaults to undefined)
*/
/**
* @cfg {Object} extraParams (可选项) 一个包含属性值的对象(这些属性在该Connection发起的每次请求中作为外部参数)
*/
/**
* @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
* to each request made by this object. (defaults to undefined)
*/
/**
* @cfg {Object} defaultHeaders (可选项) 一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中)
*/
/**
* @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
*/
/**
* @cfg {String} method (可选项) 请求时使用的默认的http方法(默认为undefined;
* 如果存在参数但没有设值.则值为post,否则为get)
*/
/**
* @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
*/
/**
* @cfg {Number} timeout (可选项) 一次请求超时的毫秒数.(默认为30秒钟)
*/
timeout : 30000,
/**
* @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
* @type Boolean
*/
/**
* @cfg {Boolean} autoAbort (可选项) 该request是否应当中断挂起的请求.(默认值为false)
* @type Boolean
*/
autoAbort:false,
/**
* @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
* @type Boolean
*/
/**
* @cfg {Boolean} disableCaching (可选项) 设置为true就会添加一个独一无二的cache-buster参数来获取请求(默认值为true)
* @type Boolean
*/
disableCaching: true,
/**
* 向远程服务器发送一http请求
* @param {Object} options 包含如下属性的一对象<ul>
* <li><b>url</b> {String} (可选项) 发送请求的url.默认为配置的url</li>
* <li><b>params</b> {Object/String/Function} (可选项) 一包含属性的对象(这些属性被用作request的参数)或一个编码后的url字串或一个能调用其中任一一属性的函数.</li>
* <li><b>method</b> {String} (可选项) 该请求所用的http方面,默认值为配置的方法,或者当没有方法被配置时,如果没有发送参数时用get,有参数时用post.</li>
* <li><b>callback</b> {Function} (可选项) 该方法被调用时附上返回的http response 对象.
* 不管成功还是失败,该回调函数都将被调用,该函数中传入了如下参数:<ul>
* <li>options {Object} 该request调用的参数.</li>
* <li>success {Boolean} 请求成功则为true.</li>
* <li>response {Object} 包含返回数据的xhr对象.</li>
* </ul></li>
* <li><b>success</b> {Function} (可选项) 该函数被调用取决于请求成功.
* 该回调函数被传入如下参数:<ul>
* <li>response {Object} 包含了返回数据的xhr对象.</li>
* <li>options {Object} 请求所调用的参数.</li>
* </ul></li>
* <li><b>failure</b> {Function} (可选项) 该函数被调用取决于请求失败.
* 该回调函数被传入如下参数:<ul>
* <li>response {Object} 包含了数据的xhr对象.</li>
* <li>options {Object} 请求所调用的参数.</li>
* </ul></li>
* <li><b>scope</b> {Object} (可选项) 回调函数的作用域: "this" 指代回调函数本身
* 默认值为浏览器窗口</li>
* <li><b>form</b> {Object/String} (可选项) 用来压入参数的一个form对象或 form的标识</li>
* <li><b>isUpload</b> {Boolean} (可选项)如果该form对象是上传form,为true, (通常情况下会自动探测).</li>
* <li><b>headers</b> {Object} (可选项) 为请求所加的请求头.</li>
* <li><b>xmlData</b> {Object} (可选项) 用于发送的xml document.注意:它将会被用来在发送数据中代替参数
* 任务参数将会被追加在url中.</li>
* <li><b>disableCaching</b> {Boolean} (可选项) 设置为True,则添加一个独一无二的 cache-buster参数来获取请求.</li>
* </ul>
* Sends an HTTP request to a remote server.
* @param {Object} options An object which may contain the following properties:<ul>
* <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
* <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
* request, a url encoded string or a function to call to get either.</li>
* <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
* if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
* <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
* The callback is called regardless of success or failure and is passed the following parameters:<ul>
* <li>options {Object} The parameter to the request call.</li>
* <li>success {Boolean} True if the request succeeded.</li>
* <li>response {Object} The XMLHttpRequest object containing the response data.</li>
* </ul></li>
* <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
* The callback is passed the following parameters:<ul>
* <li>response {Object} The XMLHttpRequest object containing the response data.</li>
* <li>options {Object} The parameter to the request call.</li>
* </ul></li>
* <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
* The callback is passed the following parameters:<ul>
* <li>response {Object} The XMLHttpRequest object containing the response data.</li>
* <li>options {Object} The parameter to the request call.</li>
* </ul></li>
* <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
* for the callback function. Defaults to the browser window.</li>
* <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
* <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
* <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
* <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
* params for the post data. Any params will be appended to the URL.</li>
* <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
* </ul>
* @return {Number} transactionId
*/
request : function(o){
if(this.fireEvent("beforerequest", this, o) !== false){
var p = o.params;
if(typeof p == "function"){
p = p.call(o.scope||window, o);
}
if(typeof p == "object"){
p = Ext.urlEncode(o.params);
}
if(this.extraParams){
var extras = Ext.urlEncode(this.extraParams);
p = p ? (p + '&' + extras) : extras;
}
var url = o.url || this.url;
if(typeof url == 'function'){
url = url.call(o.scope||window, o);
}
if(o.form){
var form = Ext.getDom(o.form);
url = url || form.action;
var enctype = form.getAttribute("enctype");
if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
return this.doFormUpload(o, p, url);
}
var f = Ext.lib.Ajax.serializeForm(form);
p = p ? (p + '&' + f) : f;
}
var hs = o.headers;
if(this.defaultHeaders){
hs = Ext.apply(hs || {}, this.defaultHeaders);
if(!o.headers){
o.headers = hs;
}
}
var cb = {
success: this.handleResponse,
failure: this.handleFailure,
scope: this,
argument: {options: o},
timeout : this.timeout
};
var method = o.method||this.method||(p ? "POST" : "GET");
if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
}
if(typeof o.autoAbort == 'boolean'){ // options gets top priority
if(o.autoAbort){
this.abort();
}
}else if(this.autoAbort !== false){
this.abort();
}
if((method == 'GET' && p) || o.xmlData){
url += (url.indexOf('?') != -1 ? '&' : '?') + p;
p = '';
}
this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
return this.transId;
}else{
Ext.callback(o.callback, o.scope, [o, null, null]);
return null;
}
},
/**
* Determine whether this object has a request outstanding.
* @param {Number} transactionId (Optional) defaults to the last transaction
* @return {Boolean} True if there is an outstanding request.
*/
/**
* 确认该对象是否有显注的请求
* @param {Number} transactionId (可选项) 默认是最后一次事务
* @return {Boolean} 如果这是个显注的请求的话,返回true.
*/
isLoading : function(transId){
if(transId){
return Ext.lib.Ajax.isCallInProgress(transId);
}else{
return this.transId ? true : false;
}
},
/**
* Aborts any outstanding request.
* @param {Number} transactionId (Optional) defaults to the last transaction
*/
/**
* 中断任何显注的请求.
* @param {Number} transactionId (或选项) 默认值为最后一次事务
*/
abort : function(transId){
if(transId || this.isLoading()){
Ext.lib.Ajax.abort(transId || this.transId);
}
},
// private
handleResponse : function(response){
this.transId = false;
var options = response.argument.options;
response.argument = options ? options.argument : null;
this.fireEvent("requestcomplete", this, response, options);
Ext.callback(options.success, options.scope, [response, options]);
Ext.callback(options.callback, options.scope, [options, true, response]);
},
// private
handleFailure : function(response, e){
this.transId = false;
var options = response.argument.options;
response.argument = options ? options.argument : null;
this.fireEvent("requestexception", this, response, options, e);
Ext.callback(options.failure, options.scope, [response, options]);
Ext.callback(options.callback, options.scope, [options, false, response]);
},
// private
doFormUpload : function(o, ps, url){
var id = Ext.id();
var frame = document.createElement('iframe');
frame.id = id;
frame.name = id;
frame.className = 'x-hidden';
if(Ext.isIE){
frame.src = Ext.SSL_SECURE_URL;
}
document.body.appendChild(frame);
if(Ext.isIE){
document.frames[id].name = id;
}
var form = Ext.getDom(o.form);
form.target = id;
form.method = 'POST';
form.enctype = form.encoding = 'multipart/form-data';
if(url){
form.action = url;
}
var hiddens, hd;
if(ps){ // add dynamic params
hiddens = [];
ps = Ext.urlDecode(ps, false);
for(var k in ps){
if(ps.hasOwnProperty(k)){
hd = document.createElement('input');
hd.type = 'hidden';
hd.name = k;
hd.value = ps[k];
form.appendChild(hd);
hiddens.push(hd);
}
}
}
function cb(){
var r = { // bogus response object
responseText : '',
responseXML : null
};
r.argument = o ? o.argument : null;
try { //
var doc;
if(Ext.isIE){
doc = frame.contentWindow.document;
}else {
doc = (frame.contentDocument || window.frames[id].document);
}
if(doc && doc.body){
r.responseText = doc.body.innerHTML;
}
if(doc && doc.XMLDocument){
r.responseXML = doc.XMLDocument;
}else {
r.responseXML = doc;
}
}
catch(e) {
// ignore
}
Ext.EventManager.removeListener(frame, 'load', cb, this);
this.fireEvent("requestcomplete", this, r, o);
Ext.callback(o.success, o.scope, [r, o]);
Ext.callback(o.callback, o.scope, [o, true, r]);
setTimeout(function(){document.body.removeChild(frame);}, 100);
}
Ext.EventManager.on(frame, 'load', cb, this);
form.submit();
if(hiddens){ // remove dynamic params
for(var i = 0, len = hiddens.length; i < len; i++){
form.removeChild(hiddens[i]);
}
}
}
});
/**
* @class Ext.Ajax
* @extends Ext.data.Connection
* Global Ajax request class.
* Ext.Ajax类,继承了Ext.data.Connection,全局的ajax请求类
* @singleton单例
*/
Ext.Ajax = new Ext.data.Connection({
// fix up the docs
/**
* @cfg {String} url @hide
*/
/**
* @cfg {String} url @hide
*/
/**
* @cfg {Object} extraParams @hide
*/
/**
* @cfg {Object} 外部参数 @hide
*/
/**
* @cfg {Object} defaultHeaders @hide
*/
/**
* @cfg {Object} 默认请求头 @hide
*/
/**
* @cfg {String} method (Optional) @hide
*/
/**
* @cfg {String} 请求的方法 (可选项) @hide
*/
/**
* @cfg {Number} timeout (Optional) @hide
*/
/**
* @cfg {Number} 超时时间 (可选项) @hide
*/
/**
* @cfg {Boolean} autoAbort (Optional) @hide
*/
/**
* @cfg {Boolean} 自动中断 (可选项) @hide
*/
/**
* @cfg {Boolean} disableCaching (Optional) @hide
*/
/**
* @cfg {Boolean} 不启用缓存 (可选项) @hide
*/
/**
* @property disableCaching
* True to add a unique cache-buster param to GET requests. (defaults to true)
* @type Boolean
*/
/**
* @property disableCaching
* 设置为true使得增加一cache-buster参数来获取请求. (默认为true)
* @type Boolean
*/
/**
* @property url
* The default URL to be used for requests to the server. (defaults to undefined)
* @type String
*/
/**
* @property url
* 默认的被用来向服务器发起请求的url. (默认为 undefined)
* @type String
*/
/**
* @property extraParams
* An object containing properties which are used as
* extra parameters to each request made by this object. (defaults to undefined)
* @type Object
*/
/**
* @property 外部参数
* 一个包含属性的对象(这些属性在该Connection发起的每次请求中作为外部参数)
* @type Object
*/
/**
* @property defaultHeaders
* An object containing request headers which are added to each request made by this object. (defaults to undefined)
* @type Object
*/
/**
* @property 默认的请求头
* 一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中)
* @type Object
*/
/**
* @property method
* The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
* @type String
*/
/**
* @property method
* 请求时使用的默认的http方法(默认为undefined;
* 如果存在参数但没有设值.则值为post,否则为get)
* @type String
*/
/**
* @property timeout
* 请求的超时豪秒数. (默认为30秒)
* @type Number
*/
/**
* @property autoAbort
* Whether a new request should abort any pending requests. (defaults to false)
* @type Boolean
*/
/**
* @property autoAbort
* 该request是否应当中断挂起的请求.(默认值为false)
* @type Boolean
*/
autoAbort : false,
/**
* Serialize the passed form into a url encoded string
* @param {String/HTMLElement} form
* @return {String}
*/
/**
* 续列化传入的form为编码后的url字符串
* @param {String/HTMLElement} form
* @return {String}
*/
serializeForm : function(form){
return Ext.lib.Ajax.serializeForm(form);
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.SimpleStore
* @extends Ext.data.Store
* Small helper class to make creating Stores from Array data easier.
* @cfg {Number} id The array index of the record id. Leave blank to auto generate ids.
* @cfg {Array} fields An array of field definition objects, or field name strings.
* @cfg {Array} data The multi-dimensional array of data
* @constructor
* @param {Object} config
*/
/**
* @Ext.data.SimpleStore类
* @继承Ext.data.Store
* 使得从数组创建stores更为方便的简单帮助类
* @cfg {Number} id 记录索引的数组ID.不填则自动生成
* @cfg {Array} fields 字段定义对象的数组,或字段名字符串.
* @cfg {Array} data 多维数据数组
* @constructor
* @param {Object} config
*/
Ext.data.SimpleStore = function(config){
Ext.data.SimpleStore.superclass.constructor.call(this, {
reader: new Ext.data.ArrayReader({
id: config.id
},
Ext.data.Record.create(config.fields)
),
proxy : new Ext.data.MemoryProxy(config.data)
});
this.load();
};
Ext.extend(Ext.data.SimpleStore, Ext.data.Store); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.JsonReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of Ext.data.Record objects from a JSON response
* based on mappings in a provided Ext.data.Record constructor.
* <p>
* json数据读取器,继承数据读取器,基于Ext.data.Record提供的构造器映射方式,
* 将json response对象构建成Ext.data.Record对象的数组
* Example code:
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
{name: 'occupation'} // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.JsonReader({
totalProperty: "results", // The property which contains the total dataset size (optional)
root: "rows", // The property which contains an Array of row objects
id: "id" // The property within each row object that provides an ID for the record (optional)
}, RecordDef);
</code></pre>
* <p>
* This would consume a JSON file like this:
* <pre><code>
{ 'results': 2, 'rows': [
{ 'id': 1, 'name': 'Bill', occupation: 'Gardener' },
{ 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ]
}
</code></pre>
* @cfg {String} totalProperty 一属性名,通过该属性可以得到数据集中记录总条数
* 该属性仅当整个数据集一口气传过来时需要.而不是被远程主机分过页的
* @cfg {String} 属性名,通过该属性能得到被forms使用的成功属性
* @cfg {String} 一属性的名字,该属性包含一行对象的数组
* @cfg {String} 行对象的一属性的名字,该属性包含记录的标识值
* @构建器
* 创建一新的JsonReader
* @param {Object} meta 元数据配置项
* @param {Object} recordType 字段的定义的数组,或由Ext.daa.Record的create方法创建的一个Ext.data.Record对象
*/
/* @cfg {String}
* in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
* paged from the remote server.
* @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms.
* @cfg {String} root name of the property which contains the Array of row objects.
* @cfg {String} id Name of the property within a row object that contains a record identifier value.
* @constructor
* Create a new JsonReader
* @param {Object} meta Metadata configuration options
* @param {Object} recordType Either an Array of field definition objects,
* or an {@link Ext.data.Record} object created using {@link Ext.data.Record#create}.
*/
Ext.data.JsonReader = function(meta, recordType){
meta = meta || {};
Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* @param {Object} response The XHR object which contains the JSON data in its responseText.
* @return {Object} data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
/**
* 该方法仅当一DataProxy从远程主机被找回时使用
* @param {Object} response 其responseText中包含json 数据的XmlHttpRequest对象
* @return {Object} data 被Ext.data.Store对象当作Ext.data.Records的缓存数据块
*/
read : function(response){
var json = response.responseText;
var o = eval("("+json+")");
if(!o) {
throw {message: "JsonReader.read: Json object not found"};
}
if(o.metaData){
delete this.ef;
this.meta = o.metaData;
this.recordType = Ext.data.Record.create(o.metaData.fields);
this.onMetaChange(this.meta, this.recordType, o);
}
return this.readRecords(o);
},
// private function a store will implement
//私有的方法.store将会来实现
onMetaChange : function(meta, recordType, o){
},
/**
* @ignore
*/
simpleAccess: function(obj, subsc) {
return obj[subsc];
},
/**
* @ignore
*/
getJsonAccessor: function(){
var re = /[\[\.]/;
return function(expr) {
try {
return(re.test(expr))
? new Function("obj", "return obj." + expr)
: function(obj){
return obj[expr];
};
} catch(e){}
return Ext.emptyFn;
};
}(),
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} o An object which contains an Array of row objects in the property specified
* in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
* which contains the total size of the dataset.
* @return {Object} data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
/**
* 从xml document创建一包含Ext.data.Records的数据块
* @param {Object} o 一包含行对象组数的对象(在配置文件中作为root)包含数据集记录总数的随意属性(在配置文件中作为totalProperty)
* @return {Object} data 被Ext.data.Store对象当作Ext.data.Records缓存的一数据块
*/
readRecords : function(o){
/**
* After any data loads, the raw JSON data is available for further custom processing.
* @type Object
*/
/**
* 在数据装载后,原始的json数据对于更远的客户端不可再操作
* @type Object
*/
this.jsonData = o;
var s = this.meta, Record = this.recordType,
f = Record.prototype.fields, fi = f.items, fl = f.length;
// Generate extraction functions for the totalProperty, the root, the id, and for each field
// 为totalProperty ,root,id,及其它字段生成的提取函数
if (!this.ef) {
if(s.totalProperty) {
this.getTotal = this.getJsonAccessor(s.totalProperty);
}
if(s.successProperty) {
this.getSuccess = this.getJsonAccessor(s.successProperty);
}
this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
if (s.id) {
var g = this.getJsonAccessor(s.id);
this.getId = function(rec) {
var r = g(rec);
return (r === undefined || r === "") ? null : r;
};
} else {
this.getId = function(){return null;};
}
this.ef = [];
for(var i = 0; i < fl; i++){
f = fi[i];
var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
this.ef[i] = this.getJsonAccessor(map);
}
}
var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
if(s.totalProperty){
var v = parseInt(this.getTotal(o), 10);
if(!isNaN(v)){
totalRecords = v;
}
}
if(s.successProperty){
var v = this.getSuccess(o);
if(v === false || v === 'false'){
success = false;
}
}
var records = [];
for(var i = 0; i < c; i++){
var n = root[i];
var values = {};
var id = this.getId(n);
for(var j = 0; j < fl; j++){
f = fi[j];
var v = this.ef[j](n);
values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
}
var record = new Record(values, id);
record.json = n;
records[i] = record;
}
return {
success : success,
records : records,
totalRecords : totalRecords
};
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.ArrayReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of Ext.data.Record objects from an Array.
* Each element of that Array represents a row of data fields. The
* fields are pulled into a Record object using as a subscript, the <em>mapping</em> property
* of the field definition if it exists, or the field's ordinal position in the definition.<br>
* <p>
* 数组读到器,继承数据读取器
* 该类作用是将一个数组(该数组中的每个元素代表着一行数据字段,字段被放到Record对象中作为子脚本使用)转换成
* Ext.data.Record的对象数组,字段定义的mapping属性如果存在.或字段在定义中的原始位置
*
* Example code:.
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
{name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
]); //"mapping"仅当有"id"字段出现时(排除了使用原始位置作为索引)需要
var myReader = new Ext.data.ArrayReader({
id: 0 // The subscript within row Array that provides an ID for the Record (optional)
}, RecordDef); //下面的行数组内提供了该记录的id
</code></pre>
* <p>
* This would consume an Array like this:
* <pre><code>
[ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
</code></pre>
* @cfg {String} id (optional) The subscript within row Array that provides an ID for the Record
* @constructor
* Create a new JsonReader
* @param {Object} meta Metadata configuration options.
* @param {Object} recordType Either an Array of field definition objects
* as specified to {@link Ext.data.Record#create},
* or an {@link Ext.data.Record} object
* created using {@link Ext.data.Record#create}.
*/
/*
* @cfg {String} id (可选项) 下面的行数组内提供了该记录的id
* @构建器
* 创建一新的JsonReader
* @param {Object} meta 元数据配置项.
* @param {Object} recordType 既是一字段的字义指定对象的数组,又是通过Ext.data.Record的create方法创建的Ext.data.Record对象
*/
Ext.data.ArrayReader = function(meta, recordType){
Ext.data.ArrayReader.superclass.constructor.call(this, meta, recordType);
};
Ext.extend(Ext.data.ArrayReader, Ext.data.JsonReader, {
/**
* Create a data block containing Ext.data.Records from an XML document.
* @param {Object} o An Array of row objects which represents the dataset.
* @return {Object} data A data block which is used by an Ext.data.Store object as
* a cache of Ext.data.Records.
*/
/**
* 从xml document创建一包含Ext.data.Records的数据块
* @param {Object} o 一代表着数据集的行对象数组
* @return {Object} data 被Ext.data.Store对象当作Ext.data.Records 缓存的数据块
*/
readRecords : function(o){
var sid = this.meta ? this.meta.id : null;
var recordType = this.recordType, fields = recordType.prototype.fields;
var records = [];
var root = o;
for(var i = 0; i < root.length; i++){
var n = root[i];
var values = {};
var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
for(var j = 0, jlen = fields.length; j < jlen; j++){
var f = fields.items[j];
var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
var v = n[k] !== undefined ? n[k] : f.defaultValue;
v = f.convert(v);
values[f.name] = v;
}
var record = new recordType(values, id);
record.json = n;
records[records.length] = record;
}
return {
records : records,
totalRecords : records.length
};
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
// Base class for reading structured data from a data source. This class is intended to be
// extended (see ArrayReader, JsonReader and XmlReader) and should not be created directly.
// 从数据源读取结构化数据的基础类,(从数组读取器.json数据读取器和xml数据读取器可以知道)该类被规定为被继承类而不是被直接创建
Ext.data.DataReader = function(meta, recordType){
this.meta = meta;
this.recordType = recordType instanceof Array ?
Ext.data.Record.create(recordType) : recordType;
};
Ext.data.DataReader.prototype = {
}; | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.HttpProxy
* An implementation of {@link Ext.data.DataProxy} that reads a data object from an {@link Ext.data.Connection} object
* configured to reference a certain URL.<br><br>
* <p>
* <em>Note that this class cannot be used to retrieve data from a domain other than the domain
* from which the running page was served.<br><br>
* <p>
* For cross-domain access to remote data, use an {@link Ext.data.ScriptTagProxy}.</em><br><br>
* <p>
* Be aware that to enable the browser to parse an XML document, the server must set
* the Content-Type header in the HTTP response to "text/xml".
* @constructor
* @param {Object} conn Connection config options to add to each request (e.g. {url: 'foo.php'} or
* an {@link Ext.data.Connection} object. If a Connection config is passed, the singleton {@link Ext.Ajax} object
* will be used to make the request.
*/
/**
* @ Ext.data.HttpProxy 类
* Ext.data.DataProxy类的一个实现类,能从Ext.data.Connection(对某一url有着引用的)对象读取数据 <br><br>
* <p>
* <em>注意:该类不能够被用来从非本域(本域指为提供当前页面服务的域)的其它域外获取数据<br><br>
* <p>
* 使用Ext.data.ScriptTagProxy,从交叉域访问远程数据.</em><br><br>
* <p>
* 必须要明白,为了使浏览器能够解析一xml document,该服务器必须将http 响应头的content-type的值为"text/xml"
* @构建器
* @param {Object} conn 添加入每个请求中的Connection配置项(如{url:'foo.php'}) 或者 一个Ext.data.Connection对象.
* 如果一个Connection配置被传入,该单例Ext.Ajax对象将会被用来创建请求
*/
Ext.data.HttpProxy = function(conn){
Ext.data.HttpProxy.superclass.constructor.call(this);
// is conn a conn config or a real conn?
this.conn = conn;
this.useAjax = !conn || !conn.events;
};
Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {
/**
* Return the {@link Ext.data.Connection} object being used by this Proxy.
* @return {Connection} The Connection object. This object may be used to subscribe to events on
* a finer-grained basis than the DataProxy events.
*/
/**
* 返回该Proxy使用的Ext.data.Connection对象.
* @return {Connection} 该Connection对象.该对象可以被用来订阅事件
*/
getConnection : function(){
return this.useAjax ? Ext.Ajax : this.conn;
},
/**
* Load data from the configured {@link Ext.data.Connection}, read the data object into
* a block of Ext.data.Records using the passed {@link Ext.data.DataReader} implementation, and
* process that block using the passed callback.
* @param {Object} params An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
/**
* 从Ext.data.Connection的配置装载数据,使用传入的Ext.data.DataReader实现类将数据对象读入到
* Ext.data.Records数据块中,并通过传入的回调函数处理该数据块
* @param {Object} params 一个包含请求远程主机的http 参数作为属性的对象
* @param {Ext.data.DataReader} reader 一个能将数据对象转换成Ext.data.Record块的数据读取器
* @param {Function} callback 该函数在传入的Ext.data.Record块中.该函数必须被传入 <ul>
* <li>Record 块对象</li>
* <li>来自装载函数中的参数</li>
* <li>成功指示器</li>
* </ul>
* @param {Object} scope 回调函数的作用域
* @param {Object} arg 一可选参数.被传入回调函中中作为它的第二个参数
*/
load : function(params, reader, callback, scope, arg){
if(this.fireEvent("beforeload", this, params) !== false){
var o = {
params : params || {},
request: {
callback : callback,
scope : scope,
arg : arg
},
reader: reader,
callback : this.loadResponse,
scope: this
};
if(this.useAjax){
Ext.applyIf(o, this.conn);
if(this.activeRequest){
Ext.Ajax.abort(this.activeRequest);
}
this.activeRequest = Ext.Ajax.request(o);
}else{
this.conn.request(o);
}
}else{
callback.call(scope||this, null, arg, false);
}
},
// private
loadResponse : function(o, success, response){
delete this.activeRequest;
if(!success){
this.fireEvent("loadexception", this, o, response);
o.request.callback.call(o.request.scope, null, o.request.arg, false);
return;
}
var result;
try {
result = o.reader.read(response);
}catch(e){
this.fireEvent("loadexception", this, o, response, e);
o.request.callback.call(o.request.scope, null, o.request.arg, false);
return;
}
this.fireEvent("load", this, o, o.request.arg);
o.request.callback.call(o.request.scope, result, o.request.arg, true);
},
// private
update : function(dataSet){
},
// private
updateResponse : function(dataSet){
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.data.ScriptTagProxy
* An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain
* other than the originating domain of the running page.<br><br>
* <p>
* <em>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
* of the running page, you must use this class, rather than DataProxy.</em><br><br>
* <p>
* The content passed back from a server resource requested by a ScriptTagProxy is executable JavaScript
* source code that is used as the source inside a <script> tag.<br><br>
* <p>
* In order for the browser to process the returned data, the server must wrap the data object
* with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
* Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
* depending on whether the callback name was passed:
* <p>
/**
* @ Ext.data.ScriptTagProxy类
* Ext.data.DataProxy实现类,从原始域(原始域指当前运行页所在的域)而是其它域读取数据对象<br><br>
* <p>
* <em>注意:如果你从一非本域运行的页面获取的数据与从本域获取数据不同,你必须使用此类来操作,而不是使用DataProxy.</em><br><br>
* <p>
* 被一ScriptTagProxy请求的从服务器资源传回的内容是可执行的javascript脚本,在<script>标签中被当作源.<br><br>
* <p>
* 为了使浏览器能处理返回的数据,服务器必须用对回调函数的调用来封装数据对象.它的名字为作为参数被scriptTagProxy传入
* 下面是一个java的小程序例子.它将返回数据到scriptTagProxy或httpProxy,取决于是否有回调函数名
* <p>
* <pre><code>
boolean scriptTag = false;
String cb = request.getParameter("callback");
if (cb != null) {
scriptTag = true;
response.setContentType("text/javascript");
} else {
response.setContentType("application/x-json");
}
Writer out = response.getWriter();
if (scriptTag) {
out.write(cb + "(");
}
out.print(dataBlock.toJsonString());
if (scriptTag) {
out.write(");");
}
</pre></code>
*
* @constructor
* @param {Object} config A configuration object.
*/
/*
* @constructor
* @param {Object} config一配置对象
*/
Ext.data.ScriptTagProxy = function(config){
Ext.data.ScriptTagProxy.superclass.constructor.call(this);
Ext.apply(this, config);
this.head = document.getElementsByTagName("head")[0];
};
Ext.data.ScriptTagProxy.TRANS_ID = 1000;
Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
/**
* @cfg {String} url The URL from which to request the data object.
*/
/**
* @cfg {String} url从该处请求数据的url.
*/
/**
* @cfg {Number} timeout (Optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
*/
/**
* @cfg {Number} timeout (可选项) 等待响应的毫秒数.默认为30秒
*/
timeout : 30000,
/**
* @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
* the server the name of the callback function set up by the load call to process the returned data object.
* Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
* javascript output which calls this named function passing the data object as its only parameter.
*/
/**
* @cfg {String} callbackParam (可选项) 传到服务器的参数的名字.通过这名字告诉服各器回调函数的名字,装载时装配该函数来
* 处理返回的数据对象,默认值为"callback". 服务器端处理必须读取该参数值.然后生成javascript输出.该javascript调用
* 该名字的函数作为自己的参数传递数据对象
*/
callbackParam : "callback",
/**
* @cfg {Boolean} nocache (Optional) Defaults to true. Disable cacheing by adding a unique parameter
* name to the request.
*/
/**
* @cfg {Boolean} nocache (可选项) 默认值为true,添加一个独一无二的参数名到请求中来取消缓存
*/
nocache : true,
/**
* Load data from the configured URL, read the data object into
* a block of Ext.data.Records using the passed Ext.data.DataReader implementation, and
* process that block using the passed callback.
* @param {Object} params An object containing properties which are to be used as HTTP parameters
* for the request to the remote server.
* @param {Ext.data.DataReader} reader The Reader object which converts the data
* object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
/**
* 从配置的url中装载数据,使用传入的Ext.data.DataReader实现来读取数据对象到Ext.data.Records块中.
* 并通过传入的回调函数处理该数据块
* @param {Object} params 一包含属性的对象,这些属性被用来当作向远程服务器发送的请求http 参数.
* @param {Ext.data.DataReader} reader 转换数据对象到Ext.data.Records块的Reader对象.
* @param {Function} callback 传入Ext.data.Record的函数.
* 该函数必须被传入<ul>
* <li>记录块对象</li>
* <li>来自load函数的参数</li>
* <li>布尔值的成功指示器</li>
* </ul>
* @param {Object} scope 回调函数的作用域
* @param {Object} arg 被传到回调函数中作为第二参数的可选参数.
*/
load : function(params, reader, callback, scope, arg){
if(this.fireEvent("beforeload", this, params) !== false){
var p = Ext.urlEncode(Ext.apply(params, this.extraParams));
var url = this.url;
url += (url.indexOf("?") != -1 ? "&" : "?") + p;
if(this.nocache){
url += "&_dc=" + (new Date().getTime());
}
var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
var trans = {
id : transId,
cb : "stcCallback"+transId,
scriptId : "stcScript"+transId,
params : params,
arg : arg,
url : url,
callback : callback,
scope : scope,
reader : reader
};
var conn = this;
window[trans.cb] = function(o){
conn.handleResponse(o, trans);
};
url += String.format("&{0}={1}", this.callbackParam, trans.cb);
if(this.autoAbort !== false){
this.abort();
}
trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
var script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", trans.scriptId);
this.head.appendChild(script);
this.trans = trans;
}else{
callback.call(scope||this, null, arg, false);
}
},
// private
isLoading : function(){
return this.trans ? true : false;
},
/**
* Abort the current server request.
*/
/**
* 中断当前的服务器请求
*/
abort : function(){
if(this.isLoading()){
this.destroyTrans(this.trans);
}
},
// private
destroyTrans : function(trans, isLoaded){
this.head.removeChild(document.getElementById(trans.scriptId));
clearTimeout(trans.timeoutId);
if(isLoaded){
window[trans.cb] = undefined;
try{
delete window[trans.cb];
}catch(e){}
}else{
// if hasn't been loaded, wait for load to remove it to prevent script error
// 如果没有被装载,等待装载来移除前面的脚本错误
window[trans.cb] = function(){
window[trans.cb] = undefined;
try{
delete window[trans.cb];
}catch(e){}
};
}
},
// private
handleResponse : function(o, trans){
this.trans = false;
this.destroyTrans(trans, true);
var result;
try {
result = trans.reader.readRecords(o);
}catch(e){
this.fireEvent("loadexception", this, o, trans.arg, e);
trans.callback.call(trans.scope||window, null, trans.arg, false);
return;
}
this.fireEvent("load", this, o, trans.arg);
trans.callback.call(trans.scope||window, result, trans.arg, true);
},
// private
handleFailure : function(trans){
this.trans = false;
this.destroyTrans(trans, false);
this.fireEvent("loadexception", this, null, trans.arg);
trans.callback.call(trans.scope||window, null, trans.arg, false);
}
}); | JavaScript |
/*
* Ext JS Library 1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.DatePicker
* @extends Ext.Component
* 简单的日期拾取器类。
* @constructor
* 创建一个 DatePicker 对象
* @param {Object} config 配置项对象
*/
Ext.DatePicker = function(config){
Ext.DatePicker.superclass.constructor.call(this, config);
this.value = config && config.value ?
config.value.clearTime() : new Date().clearTime();
this.addEvents({
/**
* @event select
* 在日期被选中后触发
* @param {DatePicker} this
* @param {Date} date 选中的日期
*/
select: true
});
if(this.handler){
this.on("select", this.handler, this.scope || this);
}
// build the disabledDatesRE
if(!this.disabledDatesRE && this.disabledDates){
var dd = this.disabledDates;
var re = "(?:";
for(var i = 0; i < dd.length; i++){
re += dd[i];
if(i != dd.length-1) re += "|";
}
this.disabledDatesRE = new RegExp(re + ")");
}
};
Ext.extend(Ext.DatePicker, Ext.Component, {
/**
* @cfg {String} todayText
* 选取当前日期按钮上显示的文本(默认为 "Today")
*/
todayText : "Today",
/**
* @cfg {String} okText
* ok 按钮上显示的文本
*/
okText : " OK ", //   可以给用户更多的点击空间
/**
* @cfg {String} cancelText
* cancel 按钮上显示的文本
*/
cancelText : "Cancel",
/**
* @cfg {String} todayTip
* 选取当前日期按钮上的快捷工具提示(默认为 "{current date} (Spacebar)")
*/
todayTip : "{0} (Spacebar)",
/**
* @cfg {Date} minDate
* 允许的最小日期(JavaScript 日期对象, 默认为 null)
*/
minDate : null,
/**
* @cfg {Date} maxDate
* 允许的最大日期(JavaScript 日期对象, 默认为 null)
*/
maxDate : null,
/**
* @cfg {String} minText
* minDate 效验失败时显示的错误文本(默认为 "This date is before the minimum date")
*/
minText : "This date is before the minimum date",
/**
* @cfg {String} maxText
* maxDate 效验失败时显示的错误文本(默认为 "This date is after the maximum date")
*/
maxText : "This date is after the maximum date",
/**
* @cfg {String} format
* 默认的日期格式化字串, 本地化时可以被覆写。格式化字串必须为 {@link Date#parseDate} 中描述的有效项(默认为 'm/d/y').
*/
format : "m/d/y",
/**
* @cfg {Array} disabledDays
* 一个禁用星期数组, 以 0 开始。例如, [0, 6] 禁用周日和周六(默认为 null).
*/
disabledDays : null,
/**
* @cfg {String} disabledDaysText
* 禁用星期上的快捷工具提示(默认为 "")
*/
disabledDaysText : "",
/**
* @cfg {RegExp} disabledDatesRE
* 一个用来匹配禁用日期的 JavaScript 正则表达式(默认为 null)
*/
disabledDatesRE : null,
/**
* @cfg {String} disabledDatesText
* 禁用日期上的快捷工具提示(默认为 "")
*/
disabledDatesText : "",
/**
* @cfg {Boolean} constrainToViewport
* 设为 true 则将日期拾取器限定在 viewport 内(默认为 true)
*/
constrainToViewport : true,
/**
* @cfg {Array} monthNames
* 一个由月份名称组成的数组, 本地化时可以被覆写(默认为 Date.monthNames)
*/
monthNames : Date.monthNames,
/**
* @cfg {Array} dayNames
* 一个由星期名称组成的数组, 本地化时可以被覆写(默认为 Date.dayNames)
*/
dayNames : Date.dayNames,
/**
* @cfg {String} nextText
* 下一月导航按钮的快捷工具提示(默认为 'Next Month (Control+Right)')
*/
nextText: 'Next Month (Control+Right)',
/**
* @cfg {String} prevText
* 上一月导航按钮的快捷工具提示(默认为 'Previous Month (Control+Left)')
*/
prevText: 'Previous Month (Control+Left)',
/**
* @cfg {String} monthYearText
* 月份选择头部的快捷工具提示(默认为 'Choose a month (Control+Up/Down to move years)')
*/
monthYearText: 'Choose a month (Control+Up/Down to move years)',
/**
* @cfg {Number} startDay
* 指定每周开始的星期索引数, 以 0 开始(默认为 0, 表示以周日开始)
*/
startDay : 0,
/**
* 设置日期字段的值
* @param {Date} value 设置的日期
*/
setValue : function(value){
var old = this.value;
this.value = value.clearTime(true);
if(this.el){
this.update(this.value);
}
},
/**
* 取得日期字段的当前值
* @return {Date} 选中的日期
*/
getValue : function(){
return this.value;
},
// private
focus : function(){
if(this.el){
this.update(this.activeDate);
}
},
// private
onRender : function(container, position){
var m = [
'<table cellspacing="0">',
'<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
'<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
var dn = this.dayNames;
for(var i = 0; i < 7; i++){
var d = this.startDay+i;
if(d > 6){
d = d-7;
}
m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
}
m[m.length] = "</tr></thead><tbody><tr>";
for(var i = 0; i < 42; i++) {
if(i % 7 == 0 && i != 0){
m[m.length] = "</tr><tr>";
}
m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
}
m[m.length] = '</tr></tbody></table></td></tr><tr><td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
var el = document.createElement("div");
el.className = "x-date-picker";
el.innerHTML = m.join("");
container.dom.insertBefore(el, position);
this.el = Ext.get(el);
this.eventEl = Ext.get(el.firstChild);
new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), {
handler: this.showPrevMonth,
scope: this,
preventDefault:true,
stopDefault:true
});
new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), {
handler: this.showNextMonth,
scope: this,
preventDefault:true,
stopDefault:true
});
this.eventEl.on("mousewheel", this.handleMouseWheel, this);
this.monthPicker = this.el.down('div.x-date-mp');
this.monthPicker.enableDisplayMode('block');
var kn = new Ext.KeyNav(this.eventEl, {
"left" : function(e){
e.ctrlKey ?
this.showPrevMonth() :
this.update(this.activeDate.add("d", -1));
},
"right" : function(e){
e.ctrlKey ?
this.showNextMonth() :
this.update(this.activeDate.add("d", 1));
},
"up" : function(e){
e.ctrlKey ?
this.showNextYear() :
this.update(this.activeDate.add("d", -7));
},
"down" : function(e){
e.ctrlKey ?
this.showPrevYear() :
this.update(this.activeDate.add("d", 7));
},
"pageUp" : function(e){
this.showNextMonth();
},
"pageDown" : function(e){
this.showPrevMonth();
},
"enter" : function(e){
e.stopPropagation();
return true;
},
scope : this
});
this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"});
this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this);
this.el.unselectable();
this.cells = this.el.select("table.x-date-inner tbody td");
this.textNodes = this.el.query("table.x-date-inner tbody span");
this.mbtn = new Ext.Button(this.el.child("td.x-date-middle", true), {
text: " ",
tooltip: this.monthYearText
});
this.mbtn.on('click', this.showMonthPicker, this);
this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
var today = (new Date()).dateFormat(this.format);
var todayBtn = new Ext.Button(this.el.child("td.x-date-bottom", true), {
text: String.format(this.todayText, today),
tooltip: String.format(this.todayTip, today),
handler: this.selectToday,
scope: this
});
if(Ext.isIE){
this.el.repaint();
}
this.update(this.value);
},
createMonthPicker : function(){
if(!this.monthPicker.dom.firstChild){
var buf = ['<table border="0" cellspacing="0">'];
for(var i = 0; i < 6; i++){
buf.push(
'<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
'<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
i == 0 ?
'<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
'<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
);
}
buf.push(
'<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
this.okText,
'</button><button type="button" class="x-date-mp-cancel">',
this.cancelText,
'</button></td></tr>',
'</table>'
);
this.monthPicker.update(buf.join(''));
this.monthPicker.on('click', this.onMonthClick, this);
this.monthPicker.on('dblclick', this.onMonthDblClick, this);
this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
this.mpYears = this.monthPicker.select('td.x-date-mp-year');
this.mpMonths.each(function(m, a, i){
i += 1;
if((i%2) == 0){
m.dom.xmonth = 5 + Math.round(i * .5);
}else{
m.dom.xmonth = Math.round((i-1) * .5);
}
});
}
},
showMonthPicker : function(){
this.createMonthPicker();
var size = this.el.getSize();
this.monthPicker.setSize(size);
this.monthPicker.child('table').setSize(size);
this.mpSelMonth = (this.activeDate || this.value).getMonth();
this.updateMPMonth(this.mpSelMonth);
this.mpSelYear = (this.activeDate || this.value).getFullYear();
this.updateMPYear(this.mpSelYear);
this.monthPicker.slideIn('t', {duration:.2});
},
updateMPYear : function(y){
this.mpyear = y;
var ys = this.mpYears.elements;
for(var i = 1; i <= 10; i++){
var td = ys[i-1], y2;
if((i%2) == 0){
y2 = y + Math.round(i * .5);
td.firstChild.innerHTML = y2;
td.xyear = y2;
}else{
y2 = y - (5-Math.round(i * .5));
td.firstChild.innerHTML = y2;
td.xyear = y2;
}
this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
}
},
updateMPMonth : function(sm){
this.mpMonths.each(function(m, a, i){
m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
});
},
selectMPMonth: function(m){
},
onMonthClick : function(e, t){
e.stopEvent();
var el = new Ext.Element(t), pn;
if(el.is('button.x-date-mp-cancel')){
this.hideMonthPicker();
}
else if(el.is('button.x-date-mp-ok')){
this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
else if(pn = el.up('td.x-date-mp-month', 2)){
this.mpMonths.removeClass('x-date-mp-sel');
pn.addClass('x-date-mp-sel');
this.mpSelMonth = pn.dom.xmonth;
}
else if(pn = el.up('td.x-date-mp-year', 2)){
this.mpYears.removeClass('x-date-mp-sel');
pn.addClass('x-date-mp-sel');
this.mpSelYear = pn.dom.xyear;
}
else if(el.is('a.x-date-mp-prev')){
this.updateMPYear(this.mpyear-10);
}
else if(el.is('a.x-date-mp-next')){
this.updateMPYear(this.mpyear+10);
}
},
onMonthDblClick : function(e, t){
e.stopEvent();
var el = new Ext.Element(t), pn;
if(pn = el.up('td.x-date-mp-month', 2)){
this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
else if(pn = el.up('td.x-date-mp-year', 2)){
this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
},
hideMonthPicker : function(disableAnim){
if(this.monthPicker){
if(disableAnim === true){
this.monthPicker.hide();
}else{
this.monthPicker.slideOut('t', {duration:.2});
}
}
},
// private
showPrevMonth : function(e){
this.update(this.activeDate.add("mo", -1));
},
// private
showNextMonth : function(e){
this.update(this.activeDate.add("mo", 1));
},
// private
showPrevYear : function(){
this.update(this.activeDate.add("y", -1));
},
// private
showNextYear : function(){
this.update(this.activeDate.add("y", 1));
},
// private
handleMouseWheel : function(e){
var delta = e.getWheelDelta();
if(delta > 0){
this.showPrevMonth();
e.stopEvent();
} else if(delta < 0){
this.showNextMonth();
e.stopEvent();
}
},
// private
handleDateClick : function(e, t){
e.stopEvent();
if(t.dateValue && !Ext.fly(t.parentNode).hasClass("x-date-disabled")){
this.setValue(new Date(t.dateValue));
this.fireEvent("select", this, this.value);
}
},
// private
selectToday : function(){
this.setValue(new Date().clearTime());
this.fireEvent("select", this, this.value);
},
// private
update : function(date){
var vd = this.activeDate;
this.activeDate = date;
if(vd && this.el){
var t = date.getTime();
if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
this.cells.removeClass("x-date-selected");
this.cells.each(function(c){
if(c.dom.firstChild.dateValue == t){
c.addClass("x-date-selected");
setTimeout(function(){
try{c.dom.firstChild.focus();}catch(e){}
}, 50);
return false;
}
});
return;
}
}
var days = date.getDaysInMonth();
var firstOfMonth = date.getFirstDateOfMonth();
var startingPos = firstOfMonth.getDay()-this.startDay;
if(startingPos <= this.startDay){
startingPos += 7;
}
var pm = date.add("mo", -1);
var prevStart = pm.getDaysInMonth()-startingPos;
var cells = this.cells.elements;
var textEls = this.textNodes;
days += startingPos;
// convert everything to numbers so it's fast
var day = 86400000;
var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
var today = new Date().clearTime().getTime();
var sel = date.clearTime().getTime();
var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
var ddMatch = this.disabledDatesRE;
var ddText = this.disabledDatesText;
var ddays = this.disabledDays ? this.disabledDays.join("") : false;
var ddaysText = this.disabledDaysText;
var format = this.format;
var setCellClass = function(cal, cell){
cell.title = "";
var t = d.getTime();
cell.firstChild.dateValue = t;
if(t == today){
cell.className += " x-date-today";
cell.title = cal.todayText;
}
if(t == sel){
cell.className += " x-date-selected";
setTimeout(function(){
try{cell.firstChild.focus();}catch(e){}
}, 50);
}
// disabling
if(t < min) {
cell.className = " x-date-disabled";
cell.title = cal.minText;
return;
}
if(t > max) {
cell.className = " x-date-disabled";
cell.title = cal.maxText;
return;
}
if(ddays){
if(ddays.indexOf(d.getDay()) != -1){
cell.title = ddaysText;
cell.className = " x-date-disabled";
}
}
if(ddMatch && format){
var fvalue = d.dateFormat(format);
if(ddMatch.test(fvalue)){
cell.title = ddText.replace("%0", fvalue);
cell.className = " x-date-disabled";
}
}
};
var i = 0;
for(; i < startingPos; i++) {
textEls[i].innerHTML = (++prevStart);
d.setDate(d.getDate()+1);
cells[i].className = "x-date-prevday";
setCellClass(this, cells[i]);
}
for(; i < days; i++){
intDay = i - startingPos + 1;
textEls[i].innerHTML = (intDay);
d.setDate(d.getDate()+1);
cells[i].className = "x-date-active";
setCellClass(this, cells[i]);
}
var extraDays = 0;
for(; i < 42; i++) {
textEls[i].innerHTML = (++extraDays);
d.setDate(d.getDate()+1);
cells[i].className = "x-date-nextday";
setCellClass(this, cells[i]);
}
this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
if(!this.internalRender){
var main = this.el.dom.firstChild;
var w = main.offsetWidth;
this.el.setWidth(w + this.el.getBorderWidth("lr"));
Ext.fly(main).setWidth(w);
this.internalRender = true;
// opera does not respect the auto grow header center column
// then, after it gets a width opera refuses to recalculate
// without a second pass
if(Ext.isOpera && !this.secondPass){
main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
this.secondPass = true;
this.update.defer(10, this, [date]);
}
}
}
}); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.Button
* @extends Ext.util.Observable
* 简单的按钮类
* @cfg {String} text 按钮的文本
* @cfg {String} icon 要显示要按钮上的图片的路径 (要显示的图片将会被设置成背景图片
* 这是按钮默认的CSS属性, 所以你若想得到一个图标与文字混合的按钮, 设置cls:"x-btn-text-icon")
* @cfg {Function} handler 当按钮被单击时调用一个函数(可以代替单击事件)
* @cfg {Object} scope handler的作用范围
* @cfg {Number} minWidth 按钮最小的宽度 (用于给一系列的按钮一个共同的宽度)
* @cfg {String/Object} tooltip 按钮的提示小标签 - 可以是一个字符串或者QuickTips配置对象
* @cfg {Boolean} hidden 设置为True,一开始便隐藏 (默认为false)
* @cfg {Boolean} disabled 设置为True,按钮一开始就不可用 (默认为false)
* @cfg {Boolean} pressed 设置为True,按钮一开始就被按下 (只有enableToggle = true 时才有效)
* @cfg {String} toggleGroup toggle按扭的按钮组名称(一个组中,只会有一个按钮被按下, 并且只有
* enableToggle = true 时才起作用)
* @cfg {Boolean/Object} repeat 设置为true,当按钮被按下时会反复激发单击事件。它也可以是一个
{@link Ext.util.ClickRepeater} 配置对象(默认为false).
* @constructor
* 创建一个新的按钮
* @param {String/HTMLElement/Element} renderTo 需要添加按钮的elemnet对象
* @param {Object} config 配置对象
*/
Ext.Button = function(renderTo, config){
Ext.apply(this, config);
this.addEvents({
/**
* @event click
* 当按钮被单击的时候执行
* @param {Button} this
* @param {EventObject} e 单击事件
*/
"click" : true,
/**
* @event toggle
* 当按钮的"pressed"状态发生改变时执行(只有当enableToggle = true)
* @param {Button} this
* @param {Boolean} pressed
*/
"toggle" : true,
/**
* @event mouseover
* 当鼠标在按钮上方的时候执行
* @param {Button} this
* @param {Event} e 事件对象
*/
'mouseover' : true,
/**
* @event mouseout
* 当鼠标离开按钮的时候执行
* @param {Button} this
* @param {Event} e The event object
*/
'mouseout': true
});
if(this.menu){
this.menu = Ext.menu.MenuMgr.get(this.menu);
}
if(renderTo){
this.render(renderTo);
}
Ext.Button.superclass.constructor.call(this);
};
Ext.extend(Ext.Button, Ext.util.Observable, {
/**
* 只读. 如果按钮隐藏则为true
* @type Boolean
*/
hidden : false,
/**
* 只读. 如果按钮不可用则为true
* @type Boolean
*/
disabled : false,
/**
* 只读. 当按钮被按下时为true(只有enableToggle = true时可用)
* @type Boolean
*/
pressed : false,
/**
* @cfg {Number} tabIndex
* DOM模型中按钮的tabIndex(默认为 undefined)
*/
tabIndex : undefined,
/**
* @cfg {Boolean} enableToggle
* 设置为true则按钮允许pressed/不pressed时为toggling(默认为false)
*/
enableToggle: false,
/**
* @cfg {Mixed} menu
* 由一个菜单对象、id或config组成的标准的菜单属性(默认为undefined).
*/
menu : undefined,
/**
* @cfg {String} menuAlign
* The position to align the menu to (see {@link Ext.Element#alignTo} for more details, defaults to 'tl-bl?').
*/
menuAlign : "tl-bl?",
/**
* @cfg {String} iconCls
* 一个可以设置这个按钮的icon背景图片的css类(默认为undefined).
*/
iconCls : undefined,
/**
* @cfg {String} type
* 按钮的类型,符合DOM的input元素不的type属性规范。可以是任何一个"submit," "reset" or "button" (默认).
*/
type : 'button',
// private
menuClassTarget: 'tr',
/**
* @cfg {String} clickEvent
* The type of event to map to the button's event handler (默认为 'click')
*/
clickEvent : 'click',
/**
* @cfg {Boolean} handleMouseEvents
* False to disable visual cues on mouseover, mouseout and mousedown (defaults to true)
*/
handleMouseEvents : true,
/**
* @cfg {String} tooltipType
* tooltip的类型。 可以是任何一个 "qtip" (默认) 快速提示 or "title" for title attribute.
*/
tooltipType : 'qtip',
/**
* @cfg {String} cls
* A CSS class to apply to the button's main element.
*/
/**
* @cfg {Ext.Template} template (Optional)
* An {@link Ext.Template} with which to create the Button's main element. This Template must
* contain numeric substitution parameter 0 if it is to display the text property. Changing the template could
* require code modifications if required elements (e.g. a button) aren't present.
*/
// private
render : function(renderTo){
var btn;
if(this.hideParent){
this.parentEl = Ext.get(renderTo);
}
if(!this.dhconfig){
if(!this.template){
if(!Ext.Button.buttonTemplate){
// hideous table template ->丑恶的表格模板
Ext.Button.buttonTemplate = new Ext.Template(
'<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>',
'<td class="x-btn-left"><i> </i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i> </i></td>',
"</tr></tbody></table>");
}
this.template = Ext.Button.buttonTemplate;
}
btn = this.template.append(renderTo, [this.text || ' ', this.type], true);
var btnEl = btn.child("button:first");
btnEl.on('focus', this.onFocus, this);
btnEl.on('blur', this.onBlur, this);
if(this.cls){
btn.addClass(this.cls);
}
if(this.icon){
btnEl.setStyle('background-image', 'url(' +this.icon +')');
}
if(this.iconCls){
btnEl.addClass(this.iconCls);
if(!this.cls){
btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon');
}
}
if(this.tabIndex !== undefined){
btnEl.dom.tabIndex = this.tabIndex;
}
if(this.tooltip){
if(typeof this.tooltip == 'object'){
Ext.QuickTips.tips(Ext.apply({
target: btnEl.id
}, this.tooltip));
} else {
btnEl.dom[this.tooltipType] = this.tooltip;
}
}
}else{
btn = Ext.DomHelper.append(Ext.get(renderTo).dom, this.dhconfig, true);
}
this.el = btn;
if(this.id){
this.el.dom.id = this.el.id = this.id;
}
if(this.menu){
this.el.child(this.menuClassTarget).addClass("x-btn-with-menu");
this.menu.on("show", this.onMenuShow, this);
this.menu.on("hide", this.onMenuHide, this);
}
btn.addClass("x-btn");
if(Ext.isIE && !Ext.isIE7){
this.autoWidth.defer(1, this);
}else{
this.autoWidth();
}
if(this.handleMouseEvents){
btn.on("mouseover", this.onMouseOver, this);
btn.on("mouseout", this.onMouseOut, this);
btn.on("mousedown", this.onMouseDown, this);
}
btn.on(this.clickEvent, this.onClick, this);
//btn.on("mouseup", this.onMouseUp, this);
if(this.hidden){
this.hide();
}
if(this.disabled){
this.disable();
}
Ext.ButtonToggleMgr.register(this);
if(this.pressed){
this.el.addClass("x-btn-pressed");
}
if(this.repeat){
var repeater = new Ext.util.ClickRepeater(btn,
typeof this.repeat == "object" ? this.repeat : {}
);
repeater.on("click", this.onClick, this);
}
},
/**
* 返回按钮下面的元素
* @return {Ext.Element} The element
*/
getEl : function(){
return this.el;
},
/**
* 销毁按钮对象并且移除所有的监听器.
*/
destroy : function(){
Ext.ButtonToggleMgr.unregister(this);
this.el.removeAllListeners();
this.purgeListeners();
this.el.remove();
},
// private
autoWidth : function(){
if(this.el){
this.el.setWidth("auto");
if(Ext.isIE7 && Ext.isStrict){
var ib = this.el.child('button');
if(ib && ib.getWidth() > 20){
ib.clip();
ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr'));
}
}
if(this.minWidth){
if(this.hidden){
this.el.beginMeasure();
}
if(this.el.getWidth() < this.minWidth){
this.el.setWidth(this.minWidth);
}
if(this.hidden){
this.el.endMeasure();
}
}
}
},
/**
* 分配这个按钮的点击处理程序
* @param {Function} handler 当按钮被点击时就调用此函数
* @param {Object} scope (optional) Scope for the function passed in
*/
setHandler : function(handler, scope){
this.handler = handler;
this.scope = scope;
},
/**
* 设置这个按钮的Text
* @param {String} text 按钮的Text
*/
setText : function(text){
this.text = text;
if(this.el){
this.el.child("td.x-btn-center button.x-btn-text").update(text);
}
this.autoWidth();
},
/**
* 取得按钮的Text
* @return {String} 按钮的text
*/
getText : function(){
return this.text;
},
/**
* 显示这个按钮
*/
show: function(){
this.hidden = false;
if(this.el){
this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "");
}
},
/**
* 隐藏这个按钮
*/
hide: function(){
this.hidden = true;
if(this.el){
this[this.hideParent? 'parentEl' : 'el'].setStyle("display", "none");
}
},
/**
* 为隐藏或显示提供方便的函数
* @param {Boolean} visible设置为 True 显示, false 则隐藏
*/
setVisible: function(visible){
if(visible) {
this.show();
}else{
this.hide();
}
},
/**
* 如果它的状态为passed,它将变为passed状态,否则当前的装态为toggled。
* @param {Boolean} state (可选的) 强制一个独特的状态
*/
toggle : function(state){
state = state === undefined ? !this.pressed : state;
if(state != this.pressed){
if(state){
this.el.addClass("x-btn-pressed");
this.pressed = true;
this.fireEvent("toggle", this, true);
}else{
this.el.removeClass("x-btn-pressed");
this.pressed = false;
this.fireEvent("toggle", this, false);
}
if(this.toggleHandler){
this.toggleHandler.call(this.scope || this, this, state);
}
}
},
/**
* 使按钮得到焦点
*/
focus : function(){
this.el.child('button:first').focus();
},
/**
* 使按钮不可用
*/
disable : function(){
if(this.el){
this.el.addClass("x-btn-disabled");
}
this.disabled = true;
},
/**
* 使按钮可用
*/
enable : function(){
if(this.el){
this.el.removeClass("x-btn-disabled");
}
this.disabled = false;
},
/**
* 为设置按钮可用/不可用提供方便设置的函数
* @param {Boolean} enabled True 为可用, false 为不可用
*/
setDisabled : function(v){
this[v !== true ? "enable" : "disable"]();
},
// private
onClick : function(e){
if(e){
e.preventDefault();
}
if(e.button != 0){
return;
}
if(!this.disabled){
if(this.enableToggle){
this.toggle();
}
if(this.menu && !this.menu.isVisible()){
this.menu.show(this.el, this.menuAlign);
}
this.fireEvent("click", this, e);
if(this.handler){
this.el.removeClass("x-btn-over");
this.handler.call(this.scope || this, this, e);
}
}
},
// private
onMouseOver : function(e){
if(!this.disabled){
this.el.addClass("x-btn-over");
this.fireEvent('mouseover', this, e);
}
},
// private
onMouseOut : function(e){
if(!e.within(this.el, true)){
this.el.removeClass("x-btn-over");
this.fireEvent('mouseout', this, e);
}
},
// private
onFocus : function(e){
if(!this.disabled){
this.el.addClass("x-btn-focus");
}
},
// private
onBlur : function(e){
this.el.removeClass("x-btn-focus");
},
// private
onMouseDown : function(e){
if(!this.disabled && e.button == 0){
this.el.addClass("x-btn-click");
Ext.get(document).on('mouseup', this.onMouseUp, this);
}
},
// private
onMouseUp : function(e){
if(e.button == 0){
this.el.removeClass("x-btn-click");
Ext.get(document).un('mouseup', this.onMouseUp, this);
}
},
// private
onMenuShow : function(e){
this.el.addClass("x-btn-menu-active");
},
// private
onMenuHide : function(e){
this.el.removeClass("x-btn-menu-active");
}
});
// 用于按钮的私有类
Ext.ButtonToggleMgr = function(){
var groups = {};
function toggleGroup(btn, state){
if(state){
var g = groups[btn.toggleGroup];
for(var i = 0, l = g.length; i < l; i++){
if(g[i] != btn){
g[i].toggle(false);
}
}
}
}
return {
register : function(btn){
if(!btn.toggleGroup){
return;
}
var g = groups[btn.toggleGroup];
if(!g){
g = groups[btn.toggleGroup] = [];
}
g.push(btn);
btn.on("toggle", toggleGroup);
},
unregister : function(btn){
if(!btn.toggleGroup){
return;
}
var g = groups[btn.toggleGroup];
if(g){
g.remove(btn);
btn.un("toggle", toggleGroup);
}
}
};
}(); | JavaScript |
/**
* @class Ext.BoxComponent
* @extends Ext.Component
* 任何使用矩形容器的作可视化组件{@link Ext.Component}的基类。
* 所有的容器类都应从BoxComponent继承,从而每个嵌套的Ext布局容器都会紧密地协调工作。
* @constructor
* @param {Ext.Element/String/Object} config 配置选项
*/
Ext.BoxComponent = function(config){
Ext.BoxComponent.superclass.constructor.call(this, config);
this.addEvents({
/**
* @event resize
* 当组件调节过大小后触发。
* @param {Ext.Component} this
* @param {Number} adjWidth 矩形调整过后的宽度
* @param {Number} adjHeight 矩形调整过后的高度
* @param {Number} rawWidth 原来设定的宽度
* @param {Number} rawHeight 原来设定的高度
*/
resize : true,
/**
* @event move
* 当组件被移动过之后触发。
* @param {Ext.Component} this
* @param {Number} x 新x位置
* @param {Number} y 新y位置
*/
move : true
});
};
Ext.extend(Ext.BoxComponent, Ext.Component, {
// private, set in afterRender to signify that the component has been rendered
boxReady : false,
// private, used to defer height settings to subclasses
deferHeight: false,
/**
* 设置组件的宽度和高度。
* 该方法会触发resize事件。
* 该方法既可接受单独的数字类型的参数,也可以传入一个size的对象,如 {width:10, height:20}。
* @param {Number/Object} width 要设置的宽度,或一个size对象,格式是{width, height}
* @param {Number} height 要设置的高度(如第一参数是size对象的那第二个参数经不需要了)
* @return {Ext.BoxComponent} this
*/
setSize : function(w, h){
// support for standard size objects
if(typeof w == 'object'){
h = w.height;
w = w.width;
}
// not rendered
if(!this.boxReady){
this.width = w;
this.height = h;
return this;
}
// prevent recalcs when not needed
if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
return this;
}
this.lastSize = {width: w, height: h};
var adj = this.adjustSize(w, h);
var aw = adj.width, ah = adj.height;
if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
var rz = this.getResizeEl();
if(!this.deferHeight && aw !== undefined && ah !== undefined){
rz.setSize(aw, ah);
}else if(!this.deferHeight && ah !== undefined){
rz.setHeight(ah);
}else if(aw !== undefined){
rz.setWidth(aw);
}
this.onResize(aw, ah, w, h);
this.fireEvent('resize', this, aw, ah, w, h);
}
return this;
},
/**
* 返回当前组件所属元素的大小。
* @return {Object} 包含元素大小的对象,格式为{width: (元素宽度), height:(元素高度)}
*/
getSize : function(){
return this.el.getSize();
},
/**
* 对组件所在元素当前的XY位置
* @param {Boolean} local (可选的)如为真返回的是元素的left和top而非XY(默认为false)
* @return {Array} 元素的XY位置(如[100, 200])
*/
getPosition : function(local){
if(local === true){
return [this.el.getLeft(true), this.el.getTop(true)];
}
return this.xy || this.el.getXY();
},
/**
* 返回对组件所在元素的测量矩形大小。
* @param {Boolean} local (可选的) 如为真返回的是元素的left和top而非XY(默认为false)
* @returns {Object} 格式为{x, y, width, height}的对象(矩形)
*/
getBox : function(local){
var s = this.el.getSize();
if(local){
s.x = this.el.getLeft(true);
s.y = this.el.getTop(true);
}else{
var xy = this.xy || this.el.getXY();
s.x = xy[0];
s.y = xy[1];
}
return s;
},
/**
* 对组件所在元素的测量矩形大小,然后根据此值设置组件的大小。
* @param {Object} box 格式为{x, y, width, height}的对象
* @returns {Ext.BoxComponent} this
*/
updateBox : function(box){
this.setSize(box.width, box.height);
this.setPagePosition(box.x, box.y);
return this;
},
// protected
getResizeEl : function(){
return this.resizeEl || this.el;
},
// protected
getPositionEl : function(){
return this.positionEl || this.el;
},
/**
* 设置组件的left和top值。
* 要设置基于页面的XY位置,可使用{@link #setPagePosition}。
* 该方法触发move事件。
* @param {Number} left 新left
* @param {Number} top 新top
* @returns {Ext.BoxComponent} this
*/
setPosition : function(x, y){
this.x = x;
this.y = y;
if(!this.boxReady){
return this;
}
var adj = this.adjustPosition(x, y);
var ax = adj.x, ay = adj.y;
var el = this.getPositionEl();
if(ax !== undefined || ay !== undefined){
if(ax !== undefined && ay !== undefined){
el.setLeftTop(ax, ay);
}else if(ax !== undefined){
el.setLeft(ax);
}else if(ay !== undefined){
el.setTop(ay);
}
this.onPosition(ax, ay);
this.fireEvent('move', this, ax, ay);
}
return this;
},
/**
* 设置组件页面上的left和top值。
* 要设置left、top的位置,可使用{@link #setPosition}。
* 该方法触发move事件。
* @param {Number} x 新x位置
* @param {Number} y 新y位置
* @returns {Ext.BoxComponent} this
*/
setPagePosition : function(x, y){
this.pageX = x;
this.pageY = y;
if(!this.boxReady){
return;
}
if(x === undefined || y === undefined){ // cannot translate undefined points
return;
}
var p = this.el.translatePoints(x, y);
this.setPosition(p.left, p.top);
return this;
},
// private
onRender : function(ct, position){
Ext.BoxComponent.superclass.onRender.call(this, ct, position);
if(this.resizeEl){
this.resizeEl = Ext.get(this.resizeEl);
}
if(this.positionEl){
this.positionEl = Ext.get(this.positionEl);
}
},
// private
afterRender : function(){
Ext.BoxComponent.superclass.afterRender.call(this);
this.boxReady = true;
this.setSize(this.width, this.height);
if(this.x || this.y){
this.setPosition(this.x, this.y);
}
if(this.pageX || this.pageY){
this.setPagePosition(this.pageX, this.pageY);
}
},
/**
* 强制重新计算组件的大小尺寸,这个尺寸是基于所属元素当前的高度和宽度。
* @returns {Ext.BoxComponent} this
*/
syncSize : function(){
delete this.lastSize;
this.setSize(this.el.getWidth(), this.el.getHeight());
return this;
},
/**
* 组件大小调节过后调用的函数,这是个空函数,可由一个子类来实现,执行一些调节大小过后的自定义逻辑。
* @param {Number} x 新X值
* @param {Number} y 新y值
* @param {Number} adjWidth 矩形调整过后的宽度
* @param {Number} adjHeight 矩形调整过后的高度
* @param {Number} rawWidth 原本设定的宽度
* @param {Number} rawHeight 原本设定的高度
*/
onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){
},
/**
* 组件移动过后调用的函数,这是个空函数,可由一个子类来实现,执行一些移动过后的自定义逻辑。
* @param {Number} x 新X值
* @param {Number} y 新y值
*/
onPosition : function(x, y){
},
// private
adjustSize : function(w, h){
if(this.autoWidth){
w = 'auto';
}
if(this.autoHeight){
h = 'auto';
}
return {width : w, height: h};
},
// private
adjustPosition : function(x, y){
return {x : x, y: y};
}
}); | JavaScript |
/**
* @class Ext.Editor
* @extends Ext.Component
* 一个基础性的字段编辑器,内建按需的显示、隐藏控制和一些内建的调节大小及事件句柄逻辑。
* @constructor
* 创建一个新的编辑器
* @param {Ext.form.Field} field 字段对象(或后代descendant)
* @param {Object} config 配置项对象
*/
Ext.Editor = function(field, config){
Ext.Editor.superclass.constructor.call(this, config);
this.field = field;
this.addEvents({
/**
* @event beforestartedit
* 编辑器开始初始化,但在修改值之前触发。若事件句柄返回false则取消整个编辑事件。
* @param {Editor} this
* @param {Ext.Element} boundEl 编辑器绑定的所属元素
* @param {Mixed} value 正被设置的值
*/
"beforestartedit" : true,
/**
* @event startedit
* 当编辑器显示时触发
* @param {Ext.Element} boundEl 编辑器绑定的所属元素
* @param {Mixed} value 原始字段值
*/
"startedit" : true,
/**
* @event beforecomplete
* 修改已提交到字段,但修改未真正反映在所属的字段上之前触发。
* 若事件句柄返回false则取消整个编辑事件。
* 注意如果值没有变动的话并且ignoreNoChange = true的情况下,
* 编辑依然会结束但因为没有真正的编辑所以不会触发事件。
* @param {Editor} this
* @param {Mixed} value 当前字段的值
* @param {Mixed} startValue 原始字段的值
*/
"beforecomplete" : true,
/**
* @event complete
* 当编辑完成过后,任何的改变写入到所属字段时触发。
* @param {Editor} this
* @param {Mixed} value 当前字段的值
* @param {Mixed} startValue 原始字段的值
*/
"complete" : true,
/**
* @event specialkey
* 用于导航的任意键被按下触发(arrows、 tab、 enter、esc等等)
* 你可检查{@link Ext.EventObject#getKey}以确定哪个键被按了。
* @param {Ext.form.Field} this
* @param {Ext.EventObject} e 事件对象
*/
"specialkey" : true
});
};
Ext.extend(Ext.Editor, Ext.Component, {
/**
* @cfg {Boolean/String} autosize
* True表示为编辑器的大小尺寸自适应到所属的字段,设置“width”表示单单适应宽度,
* 设置“height”表示单单适应高度(默认为fasle)
*/
/**
* @cfg {Boolean} revertInvalid
* True表示为当用户完成编辑但字段验证失败后,自动恢复原始值,然后取消这次编辑(默认为true)
*/
/**
* @cfg {Boolean} ignoreNoChange
* True表示为如果用户完成一次编辑但值没有改变时,中止这次编辑的操作(不保存,不触发事件)(默认为false)。
* 只对字符类型的值有效,其它编辑的数据类型将会被忽略。
*/
/**
* @cfg {Boolean} hideEl
* False表示为当编辑器显示时,保持绑定的元素可见(默认为true)。
*/
/**
* @cfg {Mixed} value
* 所属字段的日期值(默认为"")
*/
value : "",
/**
* @cfg {String} alignment
* 对齐的位置(参见{@link Ext.Element#alignTo}了解详细,默认为"c-c?")。
*/
alignment: "c-c?",
/**
* @cfg {Boolean/String} shadow属性为"sides"是四边都是向上阴影, "frame"表示四边外发光, "drop"表示
* 从右下角开始投影(默认为"frame")
*/
shadow : "frame",
/**
* @cfg {Boolean} constrain 表示为约束编辑器到视图
*/
constrain : false,
/**
* @cfg {Boolean} completeOnEnter True表示为回车按下之后就完成编辑(默认为false)
*/
completeOnEnter : false,
/**
* @cfg {Boolean} cancelOnEsc True表示为escape键按下之后便取消编辑(默认为false)
*/
cancelOnEsc : false,
/**
* @cfg {Boolean} updateEl True表示为当更新完成之后同时更新绑定元素的innerHTML(默认为false)
*/
updateEl : false,
// private
onRender : function(ct, position){
this.el = new Ext.Layer({
shadow: this.shadow,
cls: "x-editor",
parentEl : ct,
shim : this.shim,
shadowOffset:4,
id: this.id,
constrain: this.constrain
});
this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden");
if(this.field.msgTarget != 'title'){
this.field.msgTarget = 'qtip';
}
this.field.render(this.el);
if(Ext.isGecko){
this.field.el.dom.setAttribute('autocomplete', 'off');
}
this.field.on("specialkey", this.onSpecialKey, this);
if(this.swallowKeys){
this.field.el.swallowEvent(['keydown','keypress']);
}
this.field.show();
this.field.on("blur", this.onBlur, this);
if(this.field.grow){
this.field.on("autosize", this.el.sync, this.el, {delay:1});
}
},
onSpecialKey : function(field, e){
if(this.completeOnEnter && e.getKey() == e.ENTER){
e.stopEvent();
this.completeEdit();
}else if(this.cancelOnEsc && e.getKey() == e.ESC){
this.cancelEdit();
}else{
this.fireEvent('specialkey', field, e);
}
},
/**
* 进入编辑状态并显示编辑器
* @param {String/HTMLElement/Element} el 要编辑的元素
* @param {String} value (optional) 编辑器初始化的值,如不设置该值便是元素的innerHTML
*/
startEdit : function(el, value){
if(this.editing){
this.completeEdit();
}
this.boundEl = Ext.get(el);
var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
if(!this.rendered){
this.render(this.parentEl || document.body);
}
if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
return;
}
this.startValue = v;
this.field.setValue(v);
if(this.autoSize){
var sz = this.boundEl.getSize();
switch(this.autoSize){
case "width":
this.setSize(sz.width, "");
break;
case "height":
this.setSize("", sz.height);
break;
default:
this.setSize(sz.width, sz.height);
}
}
this.el.alignTo(this.boundEl, this.alignment);
this.editing = true;
if(Ext.QuickTips){
Ext.QuickTips.disable();
}
this.show();
},
/**
* 设置编辑器高、宽
* @param {Number} width 新宽度
* @param {Number} height 新高度
*/
setSize : function(w, h){
this.field.setSize(w, h);
if(this.el){
this.el.sync();
}
},
/**
* 按照当前的最齐设置,把编辑器重新对齐到所绑定的字段。
*/
realign : function(){
this.el.alignTo(this.boundEl, this.alignment);
},
/**
* 结束编辑状态,提交变化的内容到所属的字段,并隐藏编辑器。
* @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false)
*/
completeEdit : function(remainVisible){
if(!this.editing){
return;
}
var v = this.getValue();
if(this.revertInvalid !== false && !this.field.isValid()){
v = this.startValue;
this.cancelEdit(true);
}
if(String(v) === String(this.startValue) && this.ignoreNoChange){
this.editing = false;
this.hide();
return;
}
if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
this.editing = false;
if(this.updateEl && this.boundEl){
this.boundEl.update(v);
}
if(remainVisible !== true){
this.hide();
}
this.fireEvent("complete", this, v, this.startValue);
}
},
// private
onShow : function(){
this.el.show();
if(this.hideEl !== false){
this.boundEl.hide();
}
this.field.show();
if(Ext.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
this.fixIEFocus = true;
this.deferredFocus.defer(50, this);
}else{
this.field.focus();
}
this.fireEvent("startedit", this.boundEl, this.startValue);
},
deferredFocus : function(){
if(this.editing){
this.field.focus();
}
},
/**
* 取消编辑状态并返回到原始值,不作任何的修改,
* @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false)
*/
cancelEdit : function(remainVisible){
if(this.editing){
this.setValue(this.startValue);
if(remainVisible !== true){
this.hide();
}
}
},
// private
onBlur : function(){
if(this.allowBlur !== true && this.editing){
this.completeEdit();
}
},
// private
onHide : function(){
if(this.editing){
this.completeEdit();
return;
}
this.field.blur();
if(this.field.collapse){
this.field.collapse();
}
this.el.hide();
if(this.hideEl !== false){
this.boundEl.show();
}
if(Ext.QuickTips){
Ext.QuickTips.enable();
}
},
/**
* 设置编辑器的数据。
* @param {Mixed} value 所属field可支持的任意值
*/
setValue : function(v){
this.field.setValue(v);
},
/**
* 获取编辑器的数据。
* @return {Mixed} 数据值
*/
getValue : function(){
return this.field.getValue();
}
}); | JavaScript |
/**
* @class Ext.Layer
* @extends Ext.Element
* 一个由{@link Ext.Element}扩展的对象,支持阴影和shim,受视图限制和自动修复阴影/shim位置。
* @cfg {Boolean} shim False表示为禁用iframe的shim,在某些浏览器里需用到(默认为true)
* @cfg {String/Boolean} shadow True表示为创建元素的阴影,采用样式类"x-layer-shadow",或者你可以传入一个字符串指定一个CSS样式类,False表示为关闭阴影。
* @cfg {Object} dh DomHelper配置格式的对象,来创建元素(默认为{tag: "div", cls: "x-layer"})
* @cfg {Boolean} constrain False表示为不受视图的限制(默认为true)
* @cfg {String} cls 元素要添加的CSS样式类
* @cfg {Number} zindex 开始的z-index(默认为1100)
* @cfg {Number} shadowOffset 阴影偏移的像素值(默认为3)
* @constructor
* @param {Object} config 配置项对象
* @param {String/HTMLElement} existingEl (可选的)使用现有的DOM的元素。 如找不到就创建一个。
*/
(function(){
Ext.Layer = function(config, existingEl){
config = config || {};
var dh = Ext.DomHelper;
var cp = config.parentEl, pel = cp ? Ext.getDom(cp) : document.body;
if(existingEl){
this.dom = Ext.getDom(existingEl);
}
if(!this.dom){
var o = config.dh || {tag: "div", cls: "x-layer"};
this.dom = dh.append(pel, o);
}
if(config.cls){
this.addClass(config.cls);
}
this.constrain = config.constrain !== false;
this.visibilityMode = Ext.Element.VISIBILITY;
if(config.id){
this.id = this.dom.id = config.id;
}else{
this.id = Ext.id(this.dom);
}
this.zindex = config.zindex || this.getZIndex();
this.position("absolute", this.zindex);
if(config.shadow){
this.shadowOffset = config.shadowOffset || 4;
this.shadow = new Ext.Shadow({
offset : this.shadowOffset,
mode : config.shadow
});
}else{
this.shadowOffset = 0;
}
this.useShim = config.shim !== false && Ext.useShims;
this.useDisplay = config.useDisplay;
this.hide();
};
var supr = Ext.Element.prototype;
// shims are shared among layer to keep from having 100 iframes
var shims = [];
Ext.extend(Ext.Layer, Ext.Element, {
getZIndex : function(){
return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000;
},
getShim : function(){
if(!this.useShim){
return null;
}
if(this.shim){
return this.shim;
}
var shim = shims.shift();
if(!shim){
shim = this.createShim();
shim.enableDisplayMode('block');
shim.dom.style.display = 'none';
shim.dom.style.visibility = 'visible';
}
var pn = this.dom.parentNode;
if(shim.dom.parentNode != pn){
pn.insertBefore(shim.dom, this.dom);
}
shim.setStyle('z-index', this.getZIndex()-2);
this.shim = shim;
return shim;
},
hideShim : function(){
if(this.shim){
this.shim.setDisplayed(false);
shims.push(this.shim);
delete this.shim;
}
},
disableShadow : function(){
if(this.shadow){
this.shadowDisabled = true;
this.shadow.hide();
this.lastShadowOffset = this.shadowOffset;
this.shadowOffset = 0;
}
},
enableShadow : function(show){
if(this.shadow){
this.shadowDisabled = false;
this.shadowOffset = this.lastShadowOffset;
delete this.lastShadowOffset;
if(show){
this.sync(true);
}
}
},
// private
// this code can execute repeatedly in milliseconds (i.e. during a drag) so
// code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls)
sync : function(doShow){
var sw = this.shadow;
if(!this.updating && this.isVisible() && (sw || this.useShim)){
var sh = this.getShim();
var w = this.getWidth(),
h = this.getHeight();
var l = this.getLeft(true),
t = this.getTop(true);
if(sw && !this.shadowDisabled){
if(doShow && !sw.isVisible()){
sw.show(this);
}else{
sw.realign(l, t, w, h);
}
if(sh){
if(doShow){
sh.show();
}
// fit the shim behind the shadow, so it is shimmed too
var a = sw.adjusts, s = sh.dom.style;
s.left = (Math.min(l, l+a.l))+"px";
s.top = (Math.min(t, t+a.t))+"px";
s.width = (w+a.w)+"px";
s.height = (h+a.h)+"px";
}
}else if(sh){
if(doShow){
sh.show();
}
sh.setSize(w, h);
sh.setLeftTop(l, t);
}
}
},
// private
destroy : function(){
this.hideShim();
if(this.shadow){
this.shadow.hide();
}
this.removeAllListeners();
var pn = this.dom.parentNode;
if(pn){
pn.removeChild(this.dom);
}
Ext.Element.uncache(this.id);
},
remove : function(){
this.destroy();
},
// private
beginUpdate : function(){
this.updating = true;
},
// private
endUpdate : function(){
this.updating = false;
this.sync(true);
},
// private
hideUnders : function(negOffset){
if(this.shadow){
this.shadow.hide();
}
this.hideShim();
},
// private
constrainXY : function(){
if(this.constrain){
var vw = Ext.lib.Dom.getViewWidth(),
vh = Ext.lib.Dom.getViewHeight();
var s = Ext.get(document).getScroll();
var xy = this.getXY();
var x = xy[0], y = xy[1];
var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset;
// only move it if it needs it
var moved = false;
// first validate right/bottom
if((x + w) > vw+s.left){
x = vw - w - this.shadowOffset;
moved = true;
}
if((y + h) > vh+s.top){
y = vh - h - this.shadowOffset;
moved = true;
}
// then make sure top/left isn't negative
if(x < s.left){
x = s.left;
moved = true;
}
if(y < s.top){
y = s.top;
moved = true;
}
if(moved){
if(this.avoidY){
var ay = this.avoidY;
if(y <= ay && (y+h) >= ay){
y = ay-h-5;
}
}
xy = [x, y];
this.storeXY(xy);
supr.setXY.call(this, xy);
this.sync();
}
}
},
isVisible : function(){
return this.visible;
},
// private
showAction : function(){
this.visible = true; // track visibility to prevent getStyle calls
if(this.useDisplay === true){
this.setDisplayed("");
}else if(this.lastXY){
supr.setXY.call(this, this.lastXY);
}else if(this.lastLT){
supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]);
}
},
// private
hideAction : function(){
this.visible = false;
if(this.useDisplay === true){
this.setDisplayed(false);
}else{
this.setLeftTop(-10000,-10000);
}
},
// overridden Element method
setVisible : function(v, a, d, c, e){
if(v){
this.showAction();
}
if(a && v){
var cb = function(){
this.sync(true);
if(c){
c();
}
}.createDelegate(this);
supr.setVisible.call(this, true, true, d, cb, e);
}else{
if(!v){
this.hideUnders(true);
}
var cb = c;
if(a){
cb = function(){
this.hideAction();
if(c){
c();
}
}.createDelegate(this);
}
supr.setVisible.call(this, v, a, d, cb, e);
if(v){
this.sync(true);
}else if(!a){
this.hideAction();
}
}
},
storeXY : function(xy){
delete this.lastLT;
this.lastXY = xy;
},
storeLeftTop : function(left, top){
delete this.lastXY;
this.lastLT = [left, top];
},
// private
beforeFx : function(){
this.beforeAction();
return Ext.Layer.superclass.beforeFx.apply(this, arguments);
},
// private
afterFx : function(){
Ext.Layer.superclass.afterFx.apply(this, arguments);
this.sync(this.isVisible());
},
// private
beforeAction : function(){
if(!this.updating && this.shadow){
this.shadow.hide();
}
},
// overridden Element method
setLeft : function(left){
this.storeLeftTop(left, this.getTop(true));
supr.setLeft.apply(this, arguments);
this.sync();
},
setTop : function(top){
this.storeLeftTop(this.getLeft(true), top);
supr.setTop.apply(this, arguments);
this.sync();
},
setLeftTop : function(left, top){
this.storeLeftTop(left, top);
supr.setLeftTop.apply(this, arguments);
this.sync();
},
setXY : function(xy, a, d, c, e){
this.fixDisplay();
this.beforeAction();
this.storeXY(xy);
var cb = this.createCB(c);
supr.setXY.call(this, xy, a, d, cb, e);
if(!a){
cb();
}
},
// private
createCB : function(c){
var el = this;
return function(){
el.constrainXY();
el.sync(true);
if(c){
c();
}
};
},
// overridden Element method
setX : function(x, a, d, c, e){
this.setXY([x, this.getY()], a, d, c, e);
},
// overridden Element method
setY : function(y, a, d, c, e){
this.setXY([this.getX(), y], a, d, c, e);
},
// overridden Element method
setSize : function(w, h, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
supr.setSize.call(this, w, h, a, d, cb, e);
if(!a){
cb();
}
},
// overridden Element method
setWidth : function(w, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
supr.setWidth.call(this, w, a, d, cb, e);
if(!a){
cb();
}
},
// overridden Element method
setHeight : function(h, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
supr.setHeight.call(this, h, a, d, cb, e);
if(!a){
cb();
}
},
// overridden Element method
setBounds : function(x, y, w, h, a, d, c, e){
this.beforeAction();
var cb = this.createCB(c);
if(!a){
this.storeXY([x, y]);
supr.setXY.call(this, [x, y]);
supr.setSize.call(this, w, h, a, d, cb, e);
cb();
}else{
supr.setBounds.call(this, x, y, w, h, a, d, cb, e);
}
return this;
},
/**
* 设置层的z-index和调整全部的阴影和垫片(shim) z-indexes。
* 层本身的z-index是会自动+2,所以它总会是在其他阴影和垫片上面(这时阴影元素会分配z-index+1,垫片的就是原本传入的z-index)。
* @param {Number} zindex 要设置的新z-index
* @return {this} The Layer
*/
setZIndex : function(zindex){
this.zindex = zindex;
this.setStyle("z-index", zindex + 2);
if(this.shadow){
this.shadow.setZIndex(zindex + 1);
}
if(this.shim){
this.shim.setStyle("z-index", zindex);
}
}
});
})(); | JavaScript |
/*
* Ext JS Library 1.1.1
* Copyright(c) 2006-2007, Ext JS, LLC.
* licensing@extjs.com
*
* http://www.extjs.com/license
*/
/**
* @class Ext.TabPanel
* @extends Ext.util.Observable
* 一个轻量级的tab容器。
* <br><br>
* Usage:
* <pre><code>
// basic tabs 1, built from existing content
var tabs = new Ext.TabPanel("tabs1");
tabs.addTab("script", "View Script");
tabs.addTab("markup", "View Markup");
tabs.activate("script");
//更多高级的tabs, 用javascript创建
var jtabs = new Ext.TabPanel("jtabs");
jtabs.addTab("jtabs-1", "Normal Tab", "My content was added during construction.");
//设置更新管理器 UpdateManager
var tab2 = jtabs.addTab("jtabs-2", "Ajax Tab 1");
var updater = tab2.getUpdateManager();
updater.setDefaultUrl("ajax1.htm");
tab2.on('activate', updater.refresh, updater, true);
//使用setUrl设置Ajax加载
var tab3 = jtabs.addTab("jtabs-3", "Ajax Tab 2");
tab3.setUrl("ajax2.htm", null, true);
//使tab不可用
var tab4 = jtabs.addTab("tabs1-5", "Disabled Tab", "Can't see me cause I'm disabled");
tab4.disable();
jtabs.activate("jtabs-1");
* </code></pre>
* @constructor
* 创建一个新的TabPanel.
* @param {String/HTMLElement/Ext.Element} container 这是一个id, DOM元素 或者 Ext.Element 将被渲染的容器。
* @param {Object/Boolean} config 这是一个配置TabPanel的配置对象, 或者设置为true使得tabs渲染在下方。
*/
Ext.TabPanel = function(container, config){
/**
* The container element for this TabPanel.
* @type Ext.Element
*/
this.el = Ext.get(container, true);
if(config){
if(typeof config == "boolean"){
this.tabPosition = config ? "bottom" : "top";
}else{
Ext.apply(this, config);
}
}
if(this.tabPosition == "bottom"){
this.bodyEl = Ext.get(this.createBody(this.el.dom));
this.el.addClass("x-tabs-bottom");
}
this.stripWrap = Ext.get(this.createStrip(this.el.dom), true);
this.stripEl = Ext.get(this.createStripList(this.stripWrap.dom), true);
this.stripBody = Ext.get(this.stripWrap.dom.firstChild.firstChild, true);
if(Ext.isIE){
Ext.fly(this.stripWrap.dom.firstChild).setStyle("overflow-x", "hidden");
}
if(this.tabPosition != "bottom"){
/** The body element that contains {@link Ext.TabPanelItem} bodies.
* @type Ext.Element
*/
this.bodyEl = Ext.get(this.createBody(this.el.dom));
this.el.addClass("x-tabs-top");
}
this.items = [];
this.bodyEl.setStyle("position", "relative");
this.active = null;
this.activateDelegate = this.activate.createDelegate(this);
this.addEvents({
/**
* @event tabchange
* 当激活的tab改变时执行
* @param {Ext.TabPanel} this
* @param {Ext.TabPanelItem} activePanel 新激活的tab
*/
"tabchange": true,
/**
* @event beforetabchange
* Fires before the active tab changes, set cancel to true on the "e" parameter to cancel the change
* @param {Ext.TabPanel} this
* @param {Object} e Set cancel to true on this object to cancel the tab change
* @param {Ext.TabPanelItem} tab The tab being changed to
*/
"beforetabchange" : true
});
Ext.EventManager.onWindowResize(this.onResize, this);
this.cpad = this.el.getPadding("lr");
this.hiddenCount = 0;
Ext.TabPanel.superclass.constructor.call(this);
};
Ext.extend(Ext.TabPanel, Ext.util.Observable, {
/*
*@cfg {String} tabPosition "top" 或者 "bottom" (默认为 "top")
*/
tabPosition : "top",
/*
*@cfg {Number} currentTabWidth tab当前的宽度 (默认为 0)
*/
currentTabWidth : 0,
/*
*@cfg {Number} minTabWidth tab的最小宽度值 (默认为 40) (当 {@link #resizeTabs} 为false时该配置被忽略)
*/
minTabWidth : 40,
/*
*@cfg {Number} maxTabWidth tab的最大宽度值 (默认为 250) (当{@link #resizeTabs} 为false时该配置被忽略)
*/
maxTabWidth : 250,
/*
*@cfg {Number} preferredTabWidth The preferred (default) width of a tab (defaults to 175) (ignored if {@link #resizeTabs} is not true)
*/
preferredTabWidth : 175,
/*
*@cfg {Boolean} resizeTabs True to enable dynamic tab resizing (defaults to false)
*/
resizeTabs : false,
/*
*@cfg {Boolean} monitorResize Set this to true to turn on window resize monitoring (ignored if {@link #resizeTabs} is not true) (defaults to true)
*/
monitorResize : true,
/**
* Creates a new {@link Ext.TabPanelItem} by looking for an existing element with the provided id -- if it's not found it creates one.
* @param {String} id The id of the div to use <b>or create</b>
* @param {String} text The text for the tab
* @param {String} content (optional) Content to put in the TabPanelItem body
* @param {Boolean} closable (optional) True to create a close icon on the tab
* @return {Ext.TabPanelItem} The created TabPanelItem
*/
addTab : function(id, text, content, closable){
var item = new Ext.TabPanelItem(this, id, text, closable);
this.addTabItem(item);
if(content){
item.setContent(content);
}
return item;
},
/**
* Returns the {@link Ext.TabPanelItem} with the specified id/index
* @param {String/Number} id The id or index of the TabPanelItem to fetch.
* @return {Ext.TabPanelItem}
*/
getTab : function(id){
return this.items[id];
},
/**
* Hides the {@link Ext.TabPanelItem} with the specified id/index
* @param {String/Number} id The id or index of the TabPanelItem to hide.
*/
hideTab : function(id){
var t = this.items[id];
if(!t.isHidden()){
t.setHidden(true);
this.hiddenCount++;
this.autoSizeTabs();
}
},
/**
* "Unhides" the {@link Ext.TabPanelItem} with the specified id/index.
* @param {String/Number} id The id or index of the TabPanelItem to unhide.
*/
unhideTab : function(id){
var t = this.items[id];
if(t.isHidden()){
t.setHidden(false);
this.hiddenCount--;
this.autoSizeTabs();
}
},
/**
* 添加一个现存的 {@link Ext.TabPanelItem}.
* @param {Ext.TabPanelItem} item 添加一个 TabPanelItem
*/
addTabItem : function(item){
this.items[item.id] = item;
this.items.push(item);
if(this.resizeTabs){
item.setWidth(this.currentTabWidth || this.preferredTabWidth);
this.autoSizeTabs();
}else{
item.autoSize();
}
},
/**
* Removes a {@link Ext.TabPanelItem}.
* @param {String/Number} id The id or index of the TabPanelItem to remove.
*/
removeTab : function(id){
var items = this.items;
var tab = items[id];
if(!tab) return;
var index = items.indexOf(tab);
if(this.active == tab && items.length > 1){
var newTab = this.getNextAvailable(index);
if(newTab)newTab.activate();
}
this.stripEl.dom.removeChild(tab.pnode.dom);
if(tab.bodyEl.dom.parentNode == this.bodyEl.dom){ // if it was moved already prevent error
this.bodyEl.dom.removeChild(tab.bodyEl.dom);
}
items.splice(index, 1);
delete this.items[tab.id];
tab.fireEvent("close", tab);
tab.purgeListeners();
this.autoSizeTabs();
},
getNextAvailable : function(start){
var items = this.items;
var index = start;
// look for a next tab that will slide over to
// replace the one being removed
while(index < items.length){
var item = items[++index];
if(item && !item.isHidden()){
return item;
}
}
// if one isn't found select the previous tab (on the left)
index = start;
while(index >= 0){
var item = items[--index];
if(item && !item.isHidden()){
return item;
}
}
return null;
},
/**
* Disables a {@link Ext.TabPanelItem}. It cannot be the active tab, if it is this call is ignored.
* @param {String/Number} id The id or index of the TabPanelItem to disable.
*/
disableTab : function(id){
var tab = this.items[id];
if(tab && this.active != tab){
tab.disable();
}
},
/**
* Enables a {@link Ext.TabPanelItem} that is disabled.
* @param {String/Number} id The id or index of the TabPanelItem to enable.
*/
enableTab : function(id){
var tab = this.items[id];
tab.enable();
},
/**
* Activates a {@link Ext.TabPanelItem}. The currently active one will be deactivated.
* @param {String/Number} id The id or index of the TabPanelItem to activate.
* @return {Ext.TabPanelItem} The TabPanelItem.
*/
activate : function(id){
var tab = this.items[id];
if(!tab){
return null;
}
if(tab == this.active || tab.disabled){
return tab;
}
var e = {};
this.fireEvent("beforetabchange", this, e, tab);
if(e.cancel !== true && !tab.disabled){
if(this.active){
this.active.hide();
}
this.active = this.items[id];
this.active.show();
this.fireEvent("tabchange", this, this.active);
}
return tab;
},
/**
* Gets the active {@link Ext.TabPanelItem}.
* @return {Ext.TabPanelItem} The active TabPanelItem or null if none are active.
*/
getActiveTab : function(){
return this.active;
},
/**
* Updates the tab body element to fit the height of the container element
* for overflow scrolling
* @param {Number} targetHeight (optional) Override the starting height from the elements height
*/
syncHeight : function(targetHeight){
var height = (targetHeight || this.el.getHeight())-this.el.getBorderWidth("tb")-this.el.getPadding("tb");
var bm = this.bodyEl.getMargins();
var newHeight = height-(this.stripWrap.getHeight()||0)-(bm.top+bm.bottom);
this.bodyEl.setHeight(newHeight);
return newHeight;
},
onResize : function(){
if(this.monitorResize){
this.autoSizeTabs();
}
},
/**
* Disables tab resizing while tabs are being added (if {@link #resizeTabs} is false this does nothing)
*/
beginUpdate : function(){
this.updating = true;
},
/**
* Stops an update and resizes the tabs (if {@link #resizeTabs} is false this does nothing)
*/
endUpdate : function(){
this.updating = false;
this.autoSizeTabs();
},
/**
* Manual call to resize the tabs (if {@link #resizeTabs} is false this does nothing)
*/
autoSizeTabs : function(){
var count = this.items.length;
var vcount = count - this.hiddenCount;
if(!this.resizeTabs || count < 1 || vcount < 1 || this.updating) return;
var w = Math.max(this.el.getWidth() - this.cpad, 10);
var availWidth = Math.floor(w / vcount);
var b = this.stripBody;
if(b.getWidth() > w){
var tabs = this.items;
this.setTabWidth(Math.max(availWidth, this.minTabWidth)-2);
if(availWidth < this.minTabWidth){
/*if(!this.sleft){ // incomplete scrolling code
this.createScrollButtons();
}
this.showScroll();
this.stripClip.setWidth(w - (this.sleft.getWidth()+this.sright.getWidth()));*/
}
}else{
if(this.currentTabWidth < this.preferredTabWidth){
this.setTabWidth(Math.min(availWidth, this.preferredTabWidth)-2);
}
}
},
/**
* Returns the number of tabs in this TabPanel.
* @return {Number}
*/
getCount : function(){
return this.items.length;
},
/**
* Resizes all the tabs to the passed width
* @param {Number} The new width
*/
setTabWidth : function(width){
this.currentTabWidth = width;
for(var i = 0, len = this.items.length; i < len; i++) {
if(!this.items[i].isHidden())this.items[i].setWidth(width);
}
},
/**
* Destroys this TabPanel
* @param {Boolean} removeEl (optional) True to remove the element from the DOM as well (defaults to undefined)
*/
destroy : function(removeEl){
Ext.EventManager.removeResizeListener(this.onResize, this);
for(var i = 0, len = this.items.length; i < len; i++){
this.items[i].purgeListeners();
}
if(removeEl === true){
this.el.update("");
this.el.remove();
}
}
});
/**
* @class Ext.TabPanelItem
* @extends Ext.util.Observable
* Represents an individual item (tab plus body) in a TabPanel.
* @param {Ext.TabPanel} tabPanel The {@link Ext.TabPanel} this TabPanelItem belongs to
* @param {String} id The id of this TabPanelItem
* @param {String} text The text for the tab of this TabPanelItem
* @param {Boolean} closable True to allow this TabPanelItem to be closable (defaults to false)
*/
Ext.TabPanelItem = function(tabPanel, id, text, closable){
/**
* The {@link Ext.TabPanel} this TabPanelItem belongs to
* @type Ext.TabPanel
*/
this.tabPanel = tabPanel;
/**
* The id for this TabPanelItem
* @type String
*/
this.id = id;
/** @private */
this.disabled = false;
/** @private */
this.text = text;
/** @private */
this.loaded = false;
this.closable = closable;
/**
* The body element for this TabPanelItem.
* @type Ext.Element
*/
this.bodyEl = Ext.get(tabPanel.createItemBody(tabPanel.bodyEl.dom, id));
this.bodyEl.setVisibilityMode(Ext.Element.VISIBILITY);
this.bodyEl.setStyle("display", "block");
this.bodyEl.setStyle("zoom", "1");
this.hideAction();
var els = tabPanel.createStripElements(tabPanel.stripEl.dom, text, closable);
/** @private */
this.el = Ext.get(els.el, true);
this.inner = Ext.get(els.inner, true);
this.textEl = Ext.get(this.el.dom.firstChild.firstChild.firstChild, true);
this.pnode = Ext.get(els.el.parentNode, true);
this.el.on("mousedown", this.onTabMouseDown, this);
this.el.on("click", this.onTabClick, this);
/** @private */
if(closable){
var c = Ext.get(els.close, true);
c.dom.title = this.closeText;
c.addClassOnOver("close-over");
c.on("click", this.closeClick, this);
}
this.addEvents({
/**
* @event activate
* Fires when this tab becomes the active tab.
* @param {Ext.TabPanel} tabPanel The parent TabPanel
* @param {Ext.TabPanelItem} this
*/
"activate": true,
/**
* @event beforeclose
* Fires before this tab is closed. To cancel the close, set cancel to true on e (e.cancel = true).
* @param {Ext.TabPanelItem} this
* @param {Object} e Set cancel to true on this object to cancel the close.
*/
"beforeclose": true,
/**
* @event close
* Fires when this tab is closed.
* @param {Ext.TabPanelItem} this
*/
"close": true,
/**
* @event deactivate
* Fires when this tab is no longer the active tab.
* @param {Ext.TabPanel} tabPanel The parent TabPanel
* @param {Ext.TabPanelItem} this
*/
"deactivate" : true
});
this.hidden = false;
Ext.TabPanelItem.superclass.constructor.call(this);
};
Ext.extend(Ext.TabPanelItem, Ext.util.Observable, {
purgeListeners : function(){
Ext.util.Observable.prototype.purgeListeners.call(this);
this.el.removeAllListeners();
},
/**
* Shows this TabPanelItem -- this <b>does not</b> deactivate the currently active TabPanelItem.
*/
show : function(){
this.pnode.addClass("on");
this.showAction();
if(Ext.isOpera){
this.tabPanel.stripWrap.repaint();
}
this.fireEvent("activate", this.tabPanel, this);
},
/**
* Returns true if this tab is the active tab.
* @return {Boolean}
*/
isActive : function(){
return this.tabPanel.getActiveTab() == this;
},
/**
* Hides this TabPanelItem -- if you don't activate another TabPanelItem this could look odd.
*/
hide : function(){
this.pnode.removeClass("on");
this.hideAction();
this.fireEvent("deactivate", this.tabPanel, this);
},
hideAction : function(){
this.bodyEl.hide();
this.bodyEl.setStyle("position", "absolute");
this.bodyEl.setLeft("-20000px");
this.bodyEl.setTop("-20000px");
},
showAction : function(){
this.bodyEl.setStyle("position", "relative");
this.bodyEl.setTop("");
this.bodyEl.setLeft("");
this.bodyEl.show();
},
/**
* Set the tooltip for the tab.
* @param {String} tooltip The tab's tooltip
*/
setTooltip : function(text){
if(Ext.QuickTips && Ext.QuickTips.isEnabled()){
this.textEl.dom.qtip = text;
this.textEl.dom.removeAttribute('title');
}else{
this.textEl.dom.title = text;
}
},
onTabClick : function(e){
e.preventDefault();
this.tabPanel.activate(this.id);
},
onTabMouseDown : function(e){
e.preventDefault();
this.tabPanel.activate(this.id);
},
getWidth : function(){
return this.inner.getWidth();
},
setWidth : function(width){
var iwidth = width - this.pnode.getPadding("lr");
this.inner.setWidth(iwidth);
this.textEl.setWidth(iwidth-this.inner.getPadding("lr"));
this.pnode.setWidth(width);
},
/**
* Show or hide the tab
* @param {Boolean} hidden True to hide or false to show.
*/
setHidden : function(hidden){
this.hidden = hidden;
this.pnode.setStyle("display", hidden ? "none" : "");
},
/**
* Returns true if this tab is "hidden"
* @return {Boolean}
*/
isHidden : function(){
return this.hidden;
},
/**
* Returns the text for this tab
* @return {String}
*/
getText : function(){
return this.text;
},
autoSize : function(){
//this.el.beginMeasure();
this.textEl.setWidth(1);
this.setWidth(this.textEl.dom.scrollWidth+this.pnode.getPadding("lr")+this.inner.getPadding("lr"));
//this.el.endMeasure();
},
/**
* Sets the text for the tab (Note: this also sets the tooltip text)
* @param {String} text The tab's text and tooltip
*/
setText : function(text){
this.text = text;
this.textEl.update(text);
this.setTooltip(text);
if(!this.tabPanel.resizeTabs){
this.autoSize();
}
},
/**
* Activates this TabPanelItem -- this <b>does</b> deactivate the currently active TabPanelItem.
*/
activate : function(){
this.tabPanel.activate(this.id);
},
/**
* Disables this TabPanelItem -- this does nothing if this is the active TabPanelItem.
*/
disable : function(){
if(this.tabPanel.active != this){
this.disabled = true;
this.pnode.addClass("disabled");
}
},
/**
* Enables this TabPanelItem if it was previously disabled.
*/
enable : function(){
this.disabled = false;
this.pnode.removeClass("disabled");
},
/**
* Sets the content for this TabPanelItem.
* @param {String} content The content
* @param {Boolean} loadScripts true to look for and load scripts
*/
setContent : function(content, loadScripts){
this.bodyEl.update(content, loadScripts);
},
/**
* Gets the {@link Ext.UpdateManager} for the body of this TabPanelItem. Enables you to perform Ajax updates.
* @return {Ext.UpdateManager} The UpdateManager
*/
getUpdateManager : function(){
return this.bodyEl.getUpdateManager();
},
/**
* Set a URL to be used to load the content for this TabPanelItem.
* @param {String/Function} url The URL to load the content from, or a function to call to get the URL
* @param {String/Object} params (optional) The string params for the update call or an object of the params. See {@link Ext.UpdateManager#update} for more details. (Defaults to null)
* @param {Boolean} loadOnce (optional) Whether to only load the content once. If this is false it makes the Ajax call every time this TabPanelItem is activated. (Defaults to false)
* @return {Ext.UpdateManager} The UpdateManager
*/
setUrl : function(url, params, loadOnce){
if(this.refreshDelegate){
this.un('activate', this.refreshDelegate);
}
this.refreshDelegate = this._handleRefresh.createDelegate(this, [url, params, loadOnce]);
this.on("activate", this.refreshDelegate);
return this.bodyEl.getUpdateManager();
},
/** @private */
_handleRefresh : function(url, params, loadOnce){
if(!loadOnce || !this.loaded){
var updater = this.bodyEl.getUpdateManager();
updater.update(url, params, this._setLoaded.createDelegate(this));
}
},
/**
* Forces a content refresh from the URL specified in the {@link #setUrl} method.
* Will fail silently if the setUrl method has not been called.
* This does not activate the panel, just updates its content.
*/
refresh : function(){
if(this.refreshDelegate){
this.loaded = false;
this.refreshDelegate();
}
},
/** @private */
_setLoaded : function(){
this.loaded = true;
},
/** @private */
closeClick : function(e){
var o = {};
e.stopEvent();
this.fireEvent("beforeclose", this, o);
if(o.cancel !== true){
this.tabPanel.removeTab(this.id);
}
},
/**
* The text displayed in the tooltip for the close icon.
* @type String
*/
closeText : "Close this tab"
});
/** @private */
Ext.TabPanel.prototype.createStrip = function(container){
var strip = document.createElement("div");
strip.className = "x-tabs-wrap";
container.appendChild(strip);
return strip;
};
/** @private */
Ext.TabPanel.prototype.createStripList = function(strip){
// div wrapper for retard IE
strip.innerHTML = '<div class="x-tabs-strip-wrap"><table class="x-tabs-strip" cellspacing="0" cellpadding="0" border="0"><tbody><tr></tr></tbody></table></div>';
return strip.firstChild.firstChild.firstChild.firstChild;
};
/** @private */
Ext.TabPanel.prototype.createBody = function(container){
var body = document.createElement("div");
Ext.id(body, "tab-body");
Ext.fly(body).addClass("x-tabs-body");
container.appendChild(body);
return body;
};
/** @private */
Ext.TabPanel.prototype.createItemBody = function(bodyEl, id){
var body = Ext.getDom(id);
if(!body){
body = document.createElement("div");
body.id = id;
}
Ext.fly(body).addClass("x-tabs-item-body");
bodyEl.insertBefore(body, bodyEl.firstChild);
return body;
};
/** @private */
Ext.TabPanel.prototype.createStripElements = function(stripEl, text, closable){
var td = document.createElement("td");
stripEl.appendChild(td);
if(closable){
td.className = "x-tabs-closable";
if(!this.closeTpl){
this.closeTpl = new Ext.Template(
'<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
'<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span>' +
'<div unselectable="on" class="close-icon"> </div></em></span></a>'
);
}
var el = this.closeTpl.overwrite(td, {"text": text});
var close = el.getElementsByTagName("div")[0];
var inner = el.getElementsByTagName("em")[0];
return {"el": el, "close": close, "inner": inner};
} else {
if(!this.tabTpl){
this.tabTpl = new Ext.Template(
'<a href="#" class="x-tabs-right"><span class="x-tabs-left"><em class="x-tabs-inner">' +
'<span unselectable="on"' + (this.disableTooltips ? '' : ' title="{text}"') +' class="x-tabs-text">{text}</span></em></span></a>'
);
}
var el = this.tabTpl.overwrite(td, {"text": text});
var inner = el.getElementsByTagName("em")[0];
return {"el": el, "inner": inner};
}
}; | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.