code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * @class Ext.form.Url * @extends Ext.form.Text * Wraps an HTML5 url field. See {@link Ext.form.FormPanel FormPanel} for example usage. * @xtype urlfield */ Ext.form.Url = Ext.extend(Ext.form.Text, { inputType: Ext.is.Android ? 'text' : 'url', autoCapitalize: false }); Ext.reg('urlfield', Ext.form.Url); /** * @class Ext.form.UrlField * @extends Ext.form.Url * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.UrlField = Ext.extend(Ext.form.Url, { constructor: function() { console.warn("Ext.form.UrlField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Url instead"); Ext.form.UrlField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.TextArea * @extends Ext.form.Field * <p>Wraps a textarea. See {@link Ext.form.FormPanel FormPanel} for example usage.</p> * @xtype textareafield */ Ext.form.TextArea = Ext.extend(Ext.form.Text, { ui: 'textarea', /** * @cfg {Integer} maxRows The maximum number of lines made visible by the input. */ maxRows: undefined, autoCapitalize: false, renderTpl: [ '<tpl if="label"><label <tpl if="fieldEl">for="{inputId}"</tpl> class="x-form-label"><span>{label}</span></label></tpl>', '<tpl if="fieldEl"><div class="x-form-field-container">', '<textarea id="{inputId}" type="{type}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="maxRows != undefined">rows="{maxRows}" </tpl>', '<tpl if="maxlength">maxlength="{maxlength}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoCapitalize">autocapitalize="{autoCapitalize}" </tpl>', '<tpl if="autoFocus">autofocus="{autoFocus}" </tpl>', '></textarea>', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div></tpl>' ], // @private onRender: function() { this.renderData.maxRows = this.maxRows; Ext.form.TextArea.superclass.onRender.apply(this, arguments); } }); Ext.reg('textareafield', Ext.form.TextArea); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('textarea', Ext.form.TextArea);
JavaScript
/** * @class Ext.form.DatePicker * @extends Ext.form.Field * <p>Specialized field which has a button which when pressed, shows a {@link Ext.DatePicker}.</p> * @xtype datepickerfield */ Ext.form.DatePicker = Ext.extend(Ext.form.Field, { ui: 'select', /** * @cfg {Object/Ext.DatePicker} picker * An object that is used when creating the internal {@link Ext.DatePicker} component or a direct instance of {@link Ext.DatePicker} * Defaults to null */ picker: null, /** * @cfg {Object/Date} value * Default value for the field and the internal {@link Ext.DatePicker} component. Accepts an object of 'year', * 'month' and 'day' values, all of which should be numbers, or a {@link Date}. * * Example: {year: 1989, day: 1, month: 5} = 1st May 1989 or new Date() */ /** * @cfg {Boolean} destroyPickerOnHide * Whether or not to destroy the picker widget on hide. This save memory if it's not used frequently, * but increase delay time on the next show due to re-instantiation. Defaults to false */ destroyPickerOnHide: false, // @cfg {Number} tabIndex @hide tabIndex: -1, // @cfg {Boolean} useMask @hide useMask: true, // @private initComponent: function() { this.addEvents( /** * @event change * Fires when a date is selected * @param {Ext.form.DatePicker} this * @param {Date} date The new date */ 'select' ); Ext.form.Text.superclass.initComponent.apply(this, arguments); }, /** * Get an instance of the internal date picker; will create a new instance if not exist. * @return {Ext.DatePicker} datePicker */ getDatePicker: function() { if (!this.datePicker) { if (this.picker instanceof Ext.DatePicker) { this.datePicker = this.picker; } else { this.datePicker = new Ext.DatePicker(Ext.apply(this.picker || {})); } this.datePicker.setValue(this.value || null); this.datePicker.on({ scope : this, change: this.onPickerChange, hide : this.onPickerHide }); } return this.datePicker; }, /** * @private * Listener to the tap event on the internal {@link #button}. Shows the internal {@link #datePicker} component when the button has been tapped. */ onMaskTap: function() { if (this.disabled) { return; } this.getDatePicker().show(); }, /** * Called when the picker changes its value * @param {Ext.DatePicker} picker The date picker * @param {Object} value The new value from the date picker * @private */ onPickerChange : function(picker, value) { this.setValue(value); this.fireEvent('select', this, this.getValue()); }, /** * Destroys the picker when it is hidden, if * {@link Ext.form.DatePicker#destroyPickerOnHide destroyPickerOnHide} is set to true * @private */ onPickerHide: function() { if (this.destroyPickerOnHide && this.datePicker) { this.datePicker.destroy(); } }, // inherit docs setValue: function(value, animated) { var datePicker = this.getDatePicker(); datePicker.setValue(value, animated); this.value = datePicker.getValue(); if (this.rendered) { this.fieldEl.dom.value = this.getValue(true); } return this; }, /** * Returns the value of the field, which will be a {@link Date} unless the <tt>format</tt> parameter is true. * @param {Boolean} format True to format the value with <tt>Ext.util.Format.defaultDateFormat</tt> */ getValue: function(format) { var value = this.value || null; return (format && Ext.isDate(value)) ? value.format(Ext.util.Format.defaultDateFormat) : value; }, // @private onDestroy: function() { if (this.datePicker) { this.datePicker.destroy(); } Ext.form.DatePicker.superclass.onDestroy.call(this); } }); Ext.reg('datepickerfield', Ext.form.DatePicker); /** * @class Ext.form.DatePickerField * @extends Ext.form.DatePicker * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.DatePickerField = Ext.extend(Ext.form.DatePicker, { constructor: function() { console.warn("Ext.form.DatePickerField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.DatePicker instead"); Ext.form.DatePickerField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.Hidden * @extends Ext.form.Field * <p>Wraps a hidden field. See {@link Ext.form.FormPanel FormPanel} for example usage.</p> * @xtype hiddenfield */ Ext.form.Hidden = Ext.extend(Ext.form.Field, { ui: 'hidden', inputType: 'hidden', tabIndex: -1 }); Ext.reg('hiddenfield', Ext.form.Hidden); /** * @class Ext.form.HiddenField * @extends Ext.form.Hidden * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.HiddenField = Ext.extend(Ext.form.Hidden, { constructor: function() { console.warn("Ext.form.HiddenField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Hidden instead"); Ext.form.HiddenField.superclass.constructor.apply(this, arguments); } }); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('hidden', Ext.form.Hidden);
JavaScript
/** * @class Ext.form.Password * @extends Ext.form.Field * <p>Wraps an HTML5 password field. See {@link Ext.form.FormPanel FormPanel} for example usage.</p> * @xtype passwordfield */ Ext.form.Password = Ext.extend(Ext.form.Text, { inputType: 'password', autoCapitalize : false }); Ext.reg('passwordfield', Ext.form.Password); /** * @class Ext.form.PasswordField * @extends Ext.form.Password * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.PasswordField = Ext.extend(Ext.form.Password, { constructor: function() { console.warn("Ext.form.PasswordField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Password instead"); Ext.form.PasswordField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.Radio * @extends Ext.form.Checkbox * <p>Single radio field. Same as Checkbox, but provided as a convenience for automatically setting the input type. * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.</p> * @constructor * Creates a new Radio * @param {Object} config Configuration options * @xtype radiofield */ Ext.form.Radio = Ext.extend(Ext.form.Checkbox, { inputType: 'radio', ui: 'radio', /** * @cfg {Boolean} useClearIcon @hide */ /** * Returns the selected value if this radio is part of a group (other radio fields with the same name, in the same FormPanel), * @return {String} */ getGroupValue: function() { var field, fields = this.getSameGroupFields(); for (var i=0; i<fields.length; i++) { field = fields[i]; if (field.isChecked()) { return field.getValue(); } } return null; }, /** * Set the matched radio field's status (that has the same value as the given string) to checked * @param {String} value The value of the radio field to check * @return {String} */ setGroupValue: function(value) { var field, fields = this.getSameGroupFields(); for (var i=0; i<fields.length; i++) { field = fields[i]; if (field.getValue() == value) { field.check(); return; } } } }); Ext.reg('radiofield', Ext.form.Radio); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('radio', Ext.form.Radio);
JavaScript
/** * @class Ext.form.FormPanel * @extends Ext.Panel * <p>Simple form panel which enables easy getting and setting of field values. Can load model instances. Example usage:</p> <pre><code> var form = new Ext.form.FormPanel({ items: [ { xtype: 'textfield', name : 'first', label: 'First name' }, { xtype: 'textfield', name : 'last', label: 'Last name' }, { xtype: 'numberfield', name : 'age', label: 'Age' }, { xtype: 'urlfield', name : 'url', label: 'Website' } ] }); </code></pre> * <p>Loading model instances:</p> <pre><code> Ext.regModel('User', { fields: [ {name: 'first', type: 'string'}, {name: 'last', type: 'string'}, {name: 'age', type: 'int'}, {name: 'url', type: 'string'} ] }); var user = Ext.ModelMgr.create({ first: 'Ed', last : 'Spencer', age : 24, url : 'http://extjs.com' }, 'User'); form.load(user); </code></pre> * @xtype form */ Ext.form.FormPanel = Ext.extend(Ext.Panel, { /** * @cfg {Boolean} standardSubmit * Wether or not we want to perform a standard form submit. Defaults to false */ standardSubmit: false, componentCls: 'x-form', /** * @cfg {String} url * The default Url for submit actions */ url: undefined, /** * @cfg {Object} baseParams * Optional hash of params to be sent (when standardSubmit configuration is false) on every submit. */ baseParams : undefined, /** * @cfg {Object} waitTpl * The defined {@link #waitMsg} template. Used for precise control over the masking agent used * to mask the FormPanel (or other Element) during form Ajax/submission actions. For more options, see * {@link #showMask} method. */ waitTpl: new Ext.XTemplate( '<div class="{cls}">{message}&hellip;</div>' ), getElConfig: function() { return Ext.apply(Ext.form.FormPanel.superclass.getElConfig.call(this), { tag: 'form' }); }, // @private initComponent : function() { this.addEvents( /** * @event submit * Fires upon successful (Ajax-based) form submission * @param {Ext.FormPanel} this This FormPanel * @param {Object} result The result object as returned by the server */ 'submit', /** * @event beforesubmit * Fires immediately preceding any Form submit action. * Implementations may adjust submitted form values or options prior to execution. * A return value of <tt>false</tt> from this listener will abort the submission * attempt (regardless of standardSubmit configuration) * @param {Ext.FormPanel} this This FormPanel * @param {Object} values A hash collection of the qualified form values about to be submitted * @param {Object} options Submission options hash (only available when standardSubmit is false) */ 'beforesubmit', /** * @event exception * Fires when either the Ajax HTTP request reports a failure OR the server returns a success:false * response in the result payload. * @param {Ext.FormPanel} this This FormPanel * @param {Object} result Either a failed Ext.data.Connection request object or a failed (logical) server * response payload. */ 'exception' ); Ext.form.FormPanel.superclass.initComponent.call(this); }, // @private afterRender : function() { Ext.form.FormPanel.superclass.afterRender.call(this); this.el.on('submit', this.onSubmit, this); }, // @private onSubmit : function(e, t) { if (!this.standardSubmit || this.fireEvent('beforesubmit', this, this.getValues(true)) === false) { if (e) { e.stopEvent(); } } }, /** * Performs a Ajax-based submission of form values (if standardSubmit is false) or otherwise * executes a standard HTML Form submit action. * @param {Object} options Unless otherwise noted, options may include the following: * <ul> * <li><b>url</b> : String * <div class="sub-desc"> * The url for the action (defaults to the form's {@link #url url}.) * </div></li> * * <li><b>method</b> : String * <div class="sub-desc"> * The form method to use (defaults to the form's method, or POST if not defined) * </div></li> * * <li><b>params</b> : String/Object * <div class="sub-desc"> * The params to pass * (defaults to the FormPanel's baseParams, or none if not defined) * Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}. * </div></li> * * <li><b>headers</b> : Object * <div class="sub-desc"> * Request headers to set for the action * (defaults to the form's default headers) * </div></li> * * <li><b>autoAbort</b> : Boolean * <div class="sub-desc"> * <tt>true</tt> to abort any pending Ajax request prior to submission (defaults to false) * Note: Has no effect when standardSubmit is enabled. * </div></li> * * <li><b>submitDisabled</b> : Boolean * <div class="sub-desc"> * <tt>true</tt> to submit all fields regardless of disabled state (defaults to false) * Note: Has no effect when standardSubmit is enabled. * </div></li> * * <li><b>waitMsg</b> : String/Config * <div class="sub-desc"> * If specified, the value is applied to the {@link #waitTpl} if defined, and rendered to the * {@link #waitMsgTarget} prior to a Form submit action. * </div></li> * * <li><b>success</b> : Function * <div class="sub-desc"> * The callback that will be invoked after a successful response * * The function is passed the following parameters: * o * form : Ext.FormPanel The form that requested the action o * result : The result object returned by the server as a result of the submit request. * </div></li> * * <li><b>failure</b> : Function * <div class="sub-desc"> * The callback that will be invoked after a * failed transaction attempt. The function is passed the following parameters: * form : The Ext.FormPanel that requested the submit. * result : The failed response or result object returned by the server which performed the operation. * </div></li> * * <li><b>scope</b> : Object * <div class="sub-desc"> * The scope in which to call the callback functions (The this reference for the callback functions). * </div></li> * </ul> * * @return {Ext.data.Connection} request Object */ submit: function(options) { var form = this.el.dom || {}, formValues options = Ext.apply({ url : this.url || form.action, submitDisabled : false, method : form.method || 'post', autoAbort : false, params : null, waitMsg : null, headers : null, success : null, failure : null }, options || {}); formValues = this.getValues(this.standardSubmit || !options.submitDisabled); if (this.standardSubmit) { if (form) { if (options.url && Ext.isEmpty(form.action)) { form.action = options.url; } form.method = (options.method || form.method).toLowerCase(); if (this.fireEvent('beforesubmit', this, formValues, options) !== false) { form.submit(); } } return null; } if (this.fireEvent('beforesubmit', this, formValues, options ) !== false) { if (options.waitMsg) { this.showMask(options.waitMsg); } return Ext.Ajax.request({ url : options.url, method : options.method, rawData : Ext.urlEncode(Ext.apply( Ext.apply({}, this.baseParams || {}), options.params || {}, formValues )), autoAbort : options.autoAbort, headers : Ext.apply( {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, options.headers || {}), scope : this, callback : function(options, success, response) { this.hideMask(); if (success) { response = Ext.decode(response.responseText); success = !!response.success; if (success) { if (typeof options.success == 'function') { options.scope ? options.success.call(options.scope, this, response) : options.success(this, response); } this.fireEvent('submit', this, response); return; } } if (typeof options.failure == 'function') { options.scope ? options.failure.call(options.scope, this, response) : options.failure(this, response); } this.fireEvent('exception', this, response); } }); } }, /** * Loads matching fields from a model instance into this form * @param {Ext.data.Model} instance The model instance * @return {Ext.form.FormPanel} this */ loadRecord: function(instance) { if (instance && instance.data) { this.setValues(instance.data); /** * The Model instance currently loaded into this form (if any). Read only * @property record * @type Ext.data.Model */ this.record = instance; } return this; }, /** * @private * Backwards-compatibility for a poorly-named function */ loadModel: function() { return this.loadRecord.apply(this, arguments); }, /** * Returns the Model instance currently loaded into this form (if any) * @return {Ext.data.Model} The Model instance */ getRecord: function() { return this.record; }, /** * Updates a model instance with the current values of this form * @param {Ext.data.Model} instance The model instance * @param {Boolean} enabled <tt>true</tt> to update the Model with values from enabled fields only * @return {Ext.form.FormPanel} this */ updateRecord: function(instance, enabled) { var fields, values, name; if(instance && (fields = instance.fields)){ values = this.getValues(enabled); for (name in values) { if(values.hasOwnProperty(name) && fields.containsKey(name)){ instance.set(name, values[name]); } } } return this; }, //<deprecated since="0.99"> updateModel: function() { console.warn("FormPanel: updateModel has been deprecated. Please use updateRecord."); this.updateRecord.apply(this, arguments); }, //</deprecated> /** * Sets the values of form fields in bulk. Example usage: <pre><code> myForm.setValues({ name: 'Ed', crazy: true, username: 'edspencer' }); </code></pre> If there groups of checkbox fields with the same name, pass their values in an array. For example: <pre><code> myForm.setValues({ name: 'Jacky', crazy: false, hobbies: [ 'reading', 'cooking', 'gaming' ] }); </code></pre> * @param {Object} values field name => value mapping object * @return {Ext.form.FormPanel} this */ setValues: function(values) { var fields = this.getFields(), name, field; values = values || {}; for (name in values) { if (values.hasOwnProperty(name)) { if (Ext.isArray(fields[name])) { fields[name].forEach(function(field) { if (Ext.isArray(values[name])) { field.setChecked((values[name].indexOf(field.getValue()) != -1)); } else { field.setChecked((values[name] == field.getValue())); } }); } else { field = fields[name]; field.setValue(values[name]); } } } return this; }, /** * Returns an object containing the value of each field in the form, keyed to the field's name. * For groups of checkbox fields with the same name, it will be arrays of values. For examples: <pre><code> { name: "Jacky Nguyen", // From a TextField favorites: [ 'pizza', 'noodle', 'cake' ] } </code></pre> * @param {Boolean} enabled <tt>true</tt> to return only enabled fields * @return {Object} Object mapping field name to its value */ getValues: function(enabled) { var fields = this.getFields(), field, values = {}, name; for (name in fields) { if (fields.hasOwnProperty(name)) { if (Ext.isArray(fields[name])) { values[name] = []; fields[name].forEach(function(field) { if (field.isChecked() && !(enabled && field.disabled)) { if (field instanceof Ext.form.Radio) { values[name] = field.getValue(); } else { values[name].push(field.getValue()); } } }); } else { field = fields[name]; if (!(enabled && field.disabled)) { if (field instanceof Ext.form.Checkbox) { values[name] = (field.isChecked()) ? field.getValue() : null; } else { values[name] = field.getValue(); } } } } } return values; }, /** * Resets all fields in the form back to their original values * @return {Ext.form.FormPanel} this This form */ reset: function() { this.getFieldsAsArray().forEach(function(field) { field.reset(); }); return this; }, /** * A convenient method to enable all fields in this forms * @return {Ext.form.FormPanel} this This form */ enable: function() { this.getFieldsAsArray().forEach(function(field) { field.enable(); }); return this; }, /** * A convenient method to disable all fields in this forms * @return {Ext.form.FormPanel} this This form */ disable: function() { this.getFieldsAsArray().forEach(function(field) { field.disable(); }); return this; }, getFieldsAsArray: function() { var fields = []; var getFieldsFrom = function(item) { if (item.isField) { fields.push(item); } if (item.isContainer) { item.items.each(getFieldsFrom); } }; this.items.each(getFieldsFrom); return fields; }, /** * @private * Returns all {@link Ext.Field field} instances inside this form * @param byName return only fields that match the given name, otherwise return all fields. * @return {Object/Array} All field instances, mapped by field name; or an array if byName is passed */ getFields: function(byName) { var fields = {}, itemName; var getFieldsFrom = function(item) { if (item.isField) { itemName = item.getName(); if ((byName && itemName == byName) || typeof byName == 'undefined') { if (fields.hasOwnProperty(itemName)) { if (!Ext.isArray(fields[itemName])) { fields[itemName] = [fields[itemName]]; } fields[itemName].push(item); } else { fields[itemName] = item; } } } if (item.isContainer) { item.items.each(getFieldsFrom); } }; this.items.each(getFieldsFrom); return (byName) ? (fields[byName] || []) : fields; }, getFieldsFromItem: function() { }, /** * Shows a generic/custom mask over a designated Element. * @param {String/Object} cfg Either a string message or a configuration object supporting * the following options: <pre><code> { message : 'Please Wait', transparent : false, target : Ext.getBody(), //optional target Element cls : 'form-mask', customImageUrl : 'trident.jpg' } </code></pre>This object is passed to the {@link #waitTpl} for use with a custom masking implementation. * @param {String/Element} target The target Element instance or Element id to use * as the masking agent for the operation (defaults the container Element of the component) * @return {Ext.form.FormPanel} this */ showMask : function(cfg, target) { cfg = Ext.isString(cfg) ? {message : cfg} : cfg; if (cfg && this.waitTpl) { this.maskTarget = target = Ext.get(target || cfg.target) || this.el; target && target.mask(this.waitTpl.apply(cfg)); } return this; }, /** * Hides a previously shown wait mask (See {@link #showMask}) * @return {Ext.form.FormPanel} this */ hideMask : function(){ if(this.maskTarget){ this.maskTarget.unmask(); delete this.maskTarget; } return this; } }); /** * (Shortcut to {@link #loadRecord} method) Loads matching fields from a model instance into this form * @param {Ext.data.Model} instance The model instance * @return {Ext.form.FormPanel} this */ Ext.form.FormPanel.prototype.load = Ext.form.FormPanel.prototype.loadModel; Ext.reg('formpanel', Ext.form.FormPanel); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('form', Ext.form.FormPanel);
JavaScript
/** * @class Ext.form.Field * @extends Ext.Container * <p>Base class for form fields that provides default event handling, sizing, value handling and other functionality. Ext.form.Field * is not used directly in applications, instead the subclasses such as {@link Ext.form.Text} should be used.</p> * @constructor * Creates a new Field * @param {Object} config Configuration options * @xtype field */ Ext.form.Field = Ext.extend(Ext.Component, { /** * Set to true on all Ext.form.Field subclasses. This is used by {@link Ext.form.FormPanel#getValues} to determine which * components inside a form are fields. * @property isField * @type Boolean */ isField: true, /** * <p>The label Element associated with this Field. <b>Only available if a {@link #label} is specified.</b></p> * @type Ext.Element * @property labelEl */ /** * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered, * not those which are built via applyTo (defaults to undefined). */ /** * @cfg {Mixed} value A value to initialize this field with (defaults to undefined). */ /** * @cfg {String} name The field's HTML name attribute (defaults to ''). * <b>Note</b>: this property must be set if this field is to be automatically included with * {@link Ext.form.BasicForm#submit form submit()}. */ /** * @cfg {String} cls A custom CSS class to apply to the field's underlying element (defaults to ''). */ /** * @cfg {String} fieldCls The default CSS class for the field (defaults to 'x-form-field') */ fieldCls: 'x-form-field', baseCls: 'x-field', /** * @cfg {String} inputCls Optional CSS class that will be added to the actual <input> element (or whichever different element is * defined by {@link inputAutoEl}). Defaults to undefined. */ inputCls: undefined, /** * @cfg {Boolean} disabled True to disable the field (defaults to false). * <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>, * disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p> */ disabled: false, renderTpl: [ '<tpl if="label"><div class="x-form-label"><span>{label}</span></div></tpl>', '<tpl if="fieldEl">', '<div class="x-form-field-container"><input id="{inputId}" type="{inputType}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="maxlength">maxlength="{maxlength}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoCapitalize">autocapitalize="{autoCapitalize}" </tpl>', '<tpl if="autoCorrect">autocorrect="{autoCorrect}" </tpl> />', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div>', '<tpl if="useClearIcon"><div class="x-field-clear-container"><div class="x-field-clear x-hidden-visibility">&#215;</div><div></tpl>', '</tpl>', ], // @private isFormField: true, /** * @cfg {Boolean} autoCreateField True to automatically create the field input element on render. This is true by default, but should * be set to false for any Ext.Field subclasses that don't need an HTML input (e.g. Ext.Slider and similar) */ autoCreateField: true, /** * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password, file (defaults * to 'text'). The types 'file' and 'password' must be used to render those field types currently -- there are * no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText} * is not supported and should be avoided. */ inputType: 'text', /** * @cfg {String} label The label to associate with this field. Defaults to <tt>null</tt>. */ label: null, labelWidth: 100, // Currently unsupported /** * @cfg {String} labelAlign The location to render the label of the field. Acceptable values are 'top' and 'left', defaults to 'left' */ labelAlign: 'left', /** * @cfg {Boolean} required True to make this field required. Note: this only causes a visual indication. Doesn't prevent user from submitting the form. */ required: false, useMask: false, // @private initComponent: function() { //<deprecated since="0.99"> if (Ext.isDefined(this.fieldLabel)) { console.warn("[Ext.form.Field] fieldLabel has been deprecated. Please use label instead."); this.label = this.fieldLabel; } if (Ext.isDefined(this.fieldClass)) { console.warn("[Ext.form.Field] fieldClass has been deprecated. Please use fieldCls instead."); this.fieldCls = this.fieldClass; } if (Ext.isDefined(this.focusClass)) { console.warn("[Ext.form.Field] focusClass has been deprecated. Please use focusCls instead."); this.focusCls = this.focusClass; } if (Ext.isDefined(this.inputValue)) { console.warn("[Ext.form.Field] inputValue has been deprecated. Please use value instead."); this.value = this.inputValue; } //</deprecated> Ext.form.Field.superclass.initComponent.call(this); }, /** * Returns the {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName} * attribute of the field if available. * @return {String} name The field {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName} */ getName: function() { return this.name || this.id || ''; }, /** * @private */ applyRenderSelectors: function() { this.renderSelectors = Ext.applyIf(this.renderSelectors || {}, { mask: '.x-field-mask', labelEl: 'label', fieldEl: '.' + Ext.util.Format.trim(this.renderData.fieldCls).replace(/ /g, '.') }); Ext.form.Field.superclass.applyRenderSelectors.call(this); }, initRenderData: function() { Ext.form.Field.superclass.initRenderData.apply(this, arguments); Ext.applyIf(this.renderData, { disabled : this.disabled, fieldCls : 'x-input-' + this.inputType + (this.inputCls ? ' ' + this.inputCls: ''), fieldEl : !this.fieldEl && this.autoCreateField, inputId : Ext.id(), label : this.label, labelAlign : 'x-label-align-' + this.labelAlign, name : this.getName(), required : this.required, style : this.style, tabIndex : this.tabIndex, inputType : this.inputType, useMask : this.useMask }); return this.renderData; }, onRender: function() { Ext.form.Field.superclass.onRender.apply(this, arguments); var cls = []; if (this.required) { cls.push('x-field-required'); } if (this.label) { cls.push('x-label-align-' + this.labelAlign); } this.el.addCls(cls); }, initEvents: function() { Ext.form.Field.superclass.initEvents.call(this); if (this.fieldEl) { if (this.useMask && this.mask) { this.mon(this.mask, { click: this.onMaskTap, scope: this }); } } }, isDisabled: function() { return this.disabled; }, // @private onEnable: function() { this.fieldEl.dom.disabled = false; }, // @private onDisable: function() { this.fieldEl.dom.disabled = true; }, // @private initValue: function() { this.setValue(this.value || '', true); /** * The original value of the field as configured in the {@link #value} configuration, or * as loaded by the last form load operation if the form's {@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad} * setting is <code>true</code>. * @type mixed * @property originalValue */ this.originalValue = this.getValue(); }, /** * <p>Returns true if the value of this Field has been changed from its original value. * Will return false if the field is disabled or has not been rendered yet.</p> * <p>Note that if the owning {@link Ext.form.BasicForm form} was configured with * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad} * then the <i>original value</i> is updated when the values are loaded by * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#setValues setValues}.</p> * @return {Boolean} True if this field has been changed from its original value (and * is not disabled), false otherwise. */ isDirty: function() { if (this.disabled || !this.rendered) { return false; } return String(this.getValue()) !== String(this.originalValue); }, // @private afterRender: function() { Ext.form.Field.superclass.afterRender.call(this); this.initValue(); }, onMaskTap: function(e) { if (this.disabled) { return; } if (this.mask) { this.hideMask(); this.maskCorrectionTimer = Ext.defer(this.showMask, 1000, this); } }, showMask: function(e) { if (this.mask) { this.mask.setStyle('display', 'block'); } }, hideMask: function(e) { if (this.mask) { this.mask.setStyle('display', 'none'); } }, /** * Resets the current field value to the originally loaded value and clears any validation messages. * See {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad} */ reset: function() { this.setValue(this.originalValue); }, /** * Returns the field data value * @return {Mixed} value The field value */ getValue: function(){ if (!this.rendered || !this.fieldEl) { return this.value; } return this.fieldEl.getValue(); }, /** * Set the field data value * @param {Mixed} value The value to set * @return {Ext.form.Field} this */ setValue: function(value){ this.value = value; if (this.rendered && this.fieldEl) { this.fieldEl.dom.value = (Ext.isEmpty(value) ? '' : value); } return this; } }); Ext.reg('field', Ext.form.Field);
JavaScript
/** * @class Ext.form.Slider * @extends Ext.form.Field * <p>Form component allowing a user to move a 'thumb' along a slider axis to choose a value. Sliders can equally be used outside * of the context of a form. Example usage:</p> <pre><code> new Ext.form.FormPanel({ items: [ { xtype : 'slider', label : 'Volume', value : 5, minValue: 0, maxValue: 10 } ] }); </code></pre> * Or as a standalone component: <pre><code> var slider = new Ext.form.Slider({ value: 5, minValue: 0, maxValue: 10 }); slider.setValue(8); //will update the value and move the thumb; slider.getValue(); //returns 8 </code></pre> * @xtype slider */ Ext.form.Slider = Ext.extend(Ext.form.Field, { ui: 'slider', /** * @cfg {Boolean} useClearIcon @hide */ /** * @cfg {String} inputCls Overrides {@link Ext.form.Field}'s inputCls. Defaults to 'x-slider' */ inputCls: 'x-slider', inputType: 'slider', /** * @cfg {Number} minValue The lowest value any thumb on this slider can be set to (defaults to 0) */ minValue: 0, /** * @cfg {Number} maxValue The highest value any thumb on this slider can be set to (defaults to 100) */ maxValue: 100, /** * @cfg {Number} animate When set to a number greater than 0, it will be the animation duration in ms, defaults to 200 */ animate: 200, /** * @cfg {Number} value The value to initialize the thumb at (defaults to 0) */ value: 0, /** * @private * @cfg {Number} trackWidth The current track width. Used when the field is hidden so setValue will continue to work (needs * the fieldEls width). */ trackWidth: null, monitorOrientation: true, tabIndex: -1, renderTpl: [ '<tpl if="label">', '<label <tpl if="fieldEl">for="{inputId}"</tpl> class="x-form-label"><span>{label}</span></label>', '</tpl>', '<tpl if="fieldEl">', '<div id="{inputId}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}"</tpl>', '<tpl if="style">style="{style}" </tpl>', '/></tpl>' ], /** * @cfg {Number} increment The increment by which to snap each thumb when its value changes. Defaults to 1. Any thumb movement * will be snapped to the nearest value that is a multiple of the increment (e.g. if increment is 10 and the user tries to move * the thumb to 67, it will be snapped to 70 instead) */ increment: 1, /** * @cfg {Array} values The values to initialize each thumb with. One thumb will be created for each value. This configuration * should always be defined but if it is not then it will be treated as though [0] was passed. * * This is intentionally doc'd as private and is not fully supported/implemented yet. * @private */ /** * @cfg {Array} thumbs Optional array of Ext.form.Slider.Thumb instances. Usually {@link values} should be used instead */ // @private constructor: function(config) { this.addEvents( /** * @event beforechange * Fires before the value of a thumb is changed. Return false to cancel the change * @param {Ext.form.Slider} slider The slider instance * @param {Ext.form.Slider.Thumb} thumb The thumb instance * @param {Number} newValue The value that the thumb will be set to * @param {Number} oldValue The previous value */ 'beforechange', /** * @event change * Fires when the value of a thumb is changed. * @param {Ext.form.Slider} slider The slider instance * @param {Ext.form.Slider.Thumb} thumb The thumb instance * @param {Number} newValue The value that the thumb will be set to * @param {Number} oldValue The previous value */ 'change', /** * @event drag * Fires while the thumb is actively dragging. * @param {Ext.form.Slider} slider The slider instance * @param {Ext.form.Slider.Thumb} thumb The thumb instance * @param {Number} value The value of the thumb. */ 'drag', /** * @event dragend * Fires when the thumb is finished dragging. * @param {Ext.form.Slider} slider The slider instance * @param {Ext.form.Slider.Thumb} thumb The thumb instance * @param {Number} value The value of the thumb. */ 'dragend' ); Ext.form.Slider.superclass.constructor.call(this, config); }, // @private initComponent: function() { var me = this; //TODO: This will be removed once multi-thumb support is in place - at that point a 'values' config will be accepted //to create the multiple thumbs me.values = [me.value]; Ext.form.Slider.superclass.initComponent.apply(me, arguments); if (me.thumbs == undefined) { var thumbs = [], values = me.values, length = values.length, i, Thumb = me.getThumbClass(); for (i = 0; i < length; i++) { thumbs[thumbs.length] = new Thumb({ value: values[i], slider: me, listeners: { scope : me, drag : me.onDrag, dragend: me.onThumbDragEnd } }); } me.thumbs = thumbs; } }, onOrientationChange: function() { Ext.form.Slider.superclass.onOrientationChange.apply(this, arguments); var thumb = this.getThumb(); if (thumb.dragObj) { thumb.dragObj.updateBoundary(); this.moveThumb(thumb, this.getPixelValue(thumb.getValue(), thumb), 0); } }, getThumbClass: function() { return Ext.form.Slider.Thumb; }, /** * Sets the new value of the slider, constraining it within {@link minValue} and {@link maxValue}, and snapping to the nearest * {@link increment} if set * @param {Number} value The new value * @param {Boolean} moveThumb Whether or not to move the thumb as well * @param {Number} animate Animation duration, 0 for no animation * @return {Number} The value the thumb was set to */ setValue: function(value, moveThumb, animate) { //TODO: this should accept a second argument referencing which thumb to move var me = this, thumb = me.getThumb(), oldValue = thumb.getValue(), newValue = me.constrain(value); if (me.fireEvent('beforechange', me, thumb, newValue, oldValue) !== false) { if (moveThumb) { me.moveThumb(thumb, me.getPixelValue(newValue, thumb), animate); } thumb.setValue(newValue); me.doComponentLayout(); me.fireEvent('change', me, thumb, newValue, oldValue); } }, /** * @private * Takes a desired value of a thumb and returns the nearest snap value. e.g if minValue = 0, maxValue = 100, increment = 10 and we * pass a value of 67 here, the returned value will be 70. The returned number is constrained within {@link minValue} and {@link maxValue}, * so in the above example 68 would be returned if {@link maxValue} was set to 68. * @param {Number} value The value to snap * @return {Number} The snapped value */ constrain: function(value) { var increment = this.increment, div = Math.floor(Math.abs(value / increment)), lower = this.minValue + (div * increment), higher = Math.min(lower + increment, this.maxValue), dLower = value - lower, dHigher = higher - value; return (dLower < dHigher) ? lower: higher; }, /** * Returns the current value of the Slider's thumb * @return {Number} The thumb value */ getValue: function() { //TODO: should return values from multiple thumbs return this.getThumb().getValue(); }, /** * Returns the Thumb instance bound to this Slider * @return {Ext.form.Slider.Thumb} The thumb instance */ getThumb: function() { //TODO: This function is implemented this way to make the addition of multi-thumb support simpler. This function //should be updated to accept a thumb index return this.thumbs[0]; }, /** * @private * Maps a pixel value to a slider value. If we have a slider that is 200px wide, where minValue is 100 and maxValue is 500, * passing a pixelValue of 38 will return a mapped value of 176 * @param {Number} pixelValue The pixel value, relative to the left edge of the slider * @return {Number} The value based on slider units */ getSliderValue: function(pixelValue, thumb) { var trackWidth = thumb.dragObj.offsetBoundary.right, range = this.maxValue - this.minValue, ratio; this.trackWidth = (trackWidth > 0) ? trackWidth : this.trackWidth; ratio = range / this.trackWidth; return this.minValue + (ratio * (pixelValue)); }, /** * @private * might represent), this returns the pixel on the rendered slider that the thumb should be positioned at * @param {Number} value The internal slider value * @return {Number} The pixel value, rounded and relative to the left edge of the scroller */ getPixelValue: function(value, thumb) { var trackWidth = thumb.dragObj.offsetBoundary.right, range = this.maxValue - this.minValue, ratio; this.trackWidth = (trackWidth > 0) ? trackWidth : this.trackWidth; ratio = this.trackWidth / range; return (ratio * (value - this.minValue)); }, /** * @private * Creates an Ext.form.Slider.Thumb instance for each configured {@link values value}. Assumes that this.el is already present */ renderThumbs: function() { var thumbs = this.thumbs, length = thumbs.length, i; for (i = 0; i < length; i++) { thumbs[i].render(this.fieldEl); } }, /** * @private * Updates a thumb after it has been dragged */ onThumbDragEnd: function(draggable) { var value = this.getThumbValue(draggable), me = this; me.setValue(value, true); me.fireEvent('dragend', me, draggable.thumb, me.constrain(value)); }, /** * @private * Get the value for a draggable thumb. */ getThumbValue: function(draggable) { var thumb = draggable.thumb; return this.getSliderValue(-draggable.getOffset().x, thumb); }, /** * @private * Fires drag events so the user can interact. */ onDrag: function(draggable){ var value = this.getThumbValue(draggable); this.fireEvent('drag', this, draggable.thumb, this.constrain(value)); }, /** * @private * Updates the value of the nearest thumb on tap events */ onTap: function(e) { if (!this.disabled) { var sliderBox = this.fieldEl.getPageBox(), leftOffset = e.pageX - sliderBox.left, thumb = this.getNearest(leftOffset), halfThumbWidth = thumb.dragObj.size.width / 2; this.setValue(this.getSliderValue(leftOffset - halfThumbWidth, thumb), true, this.animate); } }, /** * @private * Moves the thumb element. Should only ever need to be called from within {@link setValue} * @param {Ext.form.Slider.Thumb} thumb The thumb to move * @param {Number} pixel The pixel the thumb should be centered on * @param {Boolean} animate True to animate the movement */ moveThumb: function(thumb, pixel, animate) { thumb.dragObj.setOffset(new Ext.util.Offset(pixel, 0), animate); }, // inherit docs afterRender: function(ct) { var me = this; me.renderThumbs(); Ext.form.Slider.superclass.afterRender.apply(me, arguments); me.fieldEl.on({ scope: me, tap : me.onTap }); }, /** * @private * Finds and returns the nearest {@link Ext.form.Slider.Thumb thumb} to the given value. * @param {Number} value The value * @return {Ext.form.Slider.Thumb} The nearest thumb */ getNearest: function(value) { //TODO: Implemented this way to enable multi-thumb support later return this.thumbs[0]; }, /** * @private * Loops through each of the sliders {@link #thumbs} and calls disable/enable on each of them depending * on the param specified. * @param {Boolean} disable True to disable, false to enable */ setThumbsDisabled: function(disable) { var thumbs = this.thumbs, ln = thumbs.length, i = 0; for (; i < ln; i++) { thumbs[i].dragObj[disable ? 'disable' : 'enable'](); } }, /** * Disables the slider by calling the internal {@link #setThumbsDisabled} method */ disable: function() { Ext.form.Slider.superclass.disable.call(this); this.setThumbsDisabled(true); }, /** * Enables the slider by calling the internal {@link #setThumbsDisabled} method. */ enable: function() { Ext.form.Slider.superclass.enable.call(this); this.setThumbsDisabled(false); } }); Ext.reg('slider', Ext.form.Slider); /** * @class Ext.form.Slider.Thumb * @extends Ext.form.Field * @xtype thumb * @ignore * Utility class used by Ext.form.Slider - should never need to be used directly. */ Ext.form.Slider.Thumb = Ext.extend(Ext.form.Field, { isField: false, baseCls: 'x-thumb', autoCreateField: false, draggable: true, /** * @cfg {Number} value The value to initialize this thumb with (defaults to 0) */ value: 0, /** * @cfg {Ext.form.Slider} slider The Slider that this thumb is attached to. Required */ // inherit docs onRender: function() { this.draggable = { direction: 'horizontal', constrain: this.slider.fieldEl, revert: false, useCssTransform: true, thumb: this }; Ext.form.Slider.Thumb.superclass.onRender.apply(this, arguments); }, // inherit docs setValue: function(newValue) { this.value = newValue; }, // inherit docs getValue: function() { return this.value; } }); Ext.reg('sliderthumb', Ext.form.Slider.Thumb); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('thumb', Ext.form.Slider.Thumb);
JavaScript
/** * @class Ext.form.Email * @extends Ext.form.Text * <p>Wraps an HTML5 email field. See {@link Ext.form.FormPanel FormPanel} for example usage.</p> * @xtype emailfield */ Ext.form.Email = Ext.extend(Ext.form.Text, { inputType: Ext.is.Android ? 'text' : 'email', autoCapitalize: false }); Ext.reg('emailfield', Ext.form.Email); /** * @class Ext.form.EmailField * @extends Ext.form.Email * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.EmailField = Ext.extend(Ext.form.Email, { constructor: function() { console.warn("Ext.form.EmailField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Email instead"); Ext.form.EmailField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.FieldSet * @extends Ext.Container * <p>Simple FieldSet, can contain fields as items. FieldSets do not add any behavior, other than an optional title, and * are just used to group similar fields together. Example usage (within a form):</p> <pre><code> new Ext.form.FormPanel({ items: [ { xtype: 'fieldset', title: 'About Me', items: [ { xtype: 'textfield', name : 'firstName', label: 'First Name' }, { xtype: 'textfield', name : 'lastName', label: 'Last Name' } ] } ] }); </code></pre> * @xtype fieldset */ Ext.form.FieldSet = Ext.extend(Ext.Panel, { componentCls: 'x-form-fieldset', // @private initComponent : function() { this.componentLayout = this.getLayout(); Ext.form.FieldSet.superclass.initComponent.call(this); }, /** * @cfg {String} title Optional fieldset title, rendered just above the grouped fields */ /** * @cfg {String} instructions Optional fieldset instructions, rendered just below the grouped fields */ // @private afterLayout : function(layout) { Ext.form.FieldSet.superclass.afterLayout.call(this, layout); if (this.title && !this.titleEl) { this.setTitle(this.title); } else if (this.titleEl) { this.el.insertFirst(this.titleEl); } if (this.instructions && !this.instructionsEl) { this.setInstructions(this.instructions); } else if (this.instructionsEl) { this.el.appendChild(this.instructionsEl); } }, /** * Sets the title of the current fieldset. * @param {String} title The new title * @return {Ext.form.FieldSet} this */ setTitle: function(title){ if (this.rendered) { if (!this.titleEl) { this.titleEl = this.el.insertFirst({ cls: this.componentCls + '-title' }); } this.titleEl.setHTML(title); } else { this.title = title; } return this; }, /** * Sets the instructions of the current fieldset. * @param {String} instructions The new instructions * @return {Ext.form.FieldSet} this */ setInstructions: function(instructions){ if (this.rendered) { if (!this.instructionsEl) { this.instructionsEl = this.el.createChild({ cls: this.componentCls + '-instructions' }); } this.instructionsEl.setHTML(instructions); } else { this.instructions = instructions; } return this; } }); Ext.reg('fieldset', Ext.form.FieldSet);
JavaScript
/** * @class Ext.form.Number * @extends Ext.form.Field * <p>Wraps an HTML5 number field. See {@link Ext.form.FormPanel FormPanel} for example usage.</p> * @xtype numberfield */ Ext.form.Number = Ext.extend(Ext.form.Text, { ui: 'number', inputType: Ext.is.Android ? 'text' : 'number', minValue : undefined, maxValue : undefined, stepValue : undefined, renderTpl: [ '<tpl if="label"><label <tpl if="fieldEl">for="{inputId}"</tpl> class="x-form-label"><span>{label}</span></label></tpl>', '<tpl if="fieldEl"><div class="x-form-field-container">', '<input id="{inputId}" type="{inputType}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="minValue != undefined">min="{minValue}" </tpl>', '<tpl if="maxValue != undefined">max="{maxValue}" </tpl>', '<tpl if="stepValue != undefined">step="{stepValue}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoCapitalize">autocapitalize="{autoCapitalize}" </tpl>', '<tpl if="autoFocus">autofocus="{autoFocus}" </tpl>', '/>', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div></tpl>', '<tpl if="useClearIcon"><div class="x-field-clear-container"><div class="x-field-clear x-hidden-visibility">&#215;</div><div></tpl>' ], // @private onRender : function() { Ext.apply(this.renderData, { maxValue : this.maxValue, minValue : this.minValue, stepValue : this.stepValue }); Ext.form.Number.superclass.onRender.apply(this, arguments); } }); Ext.reg('numberfield', Ext.form.Number); /** * @class Ext.form.NumberField * @extends Ext.form.Number * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.NumberField = Ext.extend(Ext.form.Number, { constructor: function() { console.warn("Ext.form.NumberField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Number instead"); Ext.form.NumberField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.Toggle * @extends Ext.form.Slider * <p>Specialized Slider with a single thumb and only two values. By default the toggle component can * be switched between the values of 0 and 1.</p> * @xtype togglefield */ Ext.form.Toggle = Ext.extend(Ext.form.Slider, { minValue: 0, maxValue: 1, ui: 'toggle', inputType: 'toggle', /** * @cfg {Boolean} useClearIcon @hide */ /** * @cfg {String} minValueCls CSS class added to the field when toggled to its minValue */ minValueCls: 'x-toggle-off', /** * @cfg {String} maxValueCls CSS class added to the field when toggled to its maxValue */ maxValueCls: 'x-toggle-on', /** * Toggles between the minValue (0 by default) and the maxValue (1 by default) */ toggle: function() { var me = this, thumb = me.thumbs[0], value = thumb.getValue(); me.setValue(value == me.minValue ? me.maxValue : me.minValue, true); }, // inherit docs setValue: function(value) { var me = this; Ext.form.Toggle.superclass.setValue.apply(me, arguments); var fieldEl = me.fieldEl; if (me.constrain(value) === me.minValue) { fieldEl.addCls(me.minValueCls); fieldEl.removeCls(me.maxValueCls); } else { fieldEl.addCls(me.maxValueCls); fieldEl.removeCls(me.minValueCls); } }, /** * @private * Listener to the tap event, just toggles the value */ onTap: function() { if (!this.disabled) { this.toggle(); } }, getThumbClass: function() { return Ext.form.Toggle.Thumb; } }); Ext.reg('togglefield', Ext.form.Toggle); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('toggle', Ext.form.Toggle); /** * @class Ext.form.Toggle.Thumb * @extends Ext.form.Slider.Thumb * @private * @ignore */ Ext.form.Toggle.Thumb = Ext.extend(Ext.form.Slider.Thumb, { onRender: function() { Ext.form.Toggle.Thumb.superclass.onRender.apply(this, arguments); Ext.DomHelper.append(this.el, [{ cls: 'x-toggle-thumb-off', html: '<span>OFF</span>' },{ cls: 'x-toggle-thumb-on', html: '<span>ON</span>' },{ cls: 'x-toggle-thumb-thumb' }]); } });
JavaScript
/** * @class Ext.form.Text * @extends Ext.form.Field * <p>Simple text input field. See {@link Ext.form.FormPanel FormPanel} for example usage.</p> * @xtype textfield */ Ext.form.Text = Ext.extend(Ext.form.Field, { ui: 'text', /** * @cfg {String} focusCls The CSS class to use when the field receives focus (defaults to 'x-field-focus') */ focusCls: 'x-field-focus', /** * @cfg {Integer} maxLength The maximum number of permitted input characters (defaults to 0). */ maxLength: 0, /** * @cfg {String} placeHolder A string value displayed in the input (if supported) when the control is empty. */ placeHolder: undefined, /** * True to set the field's DOM element autocomplete attribute to "on", false to set to "off". Defaults to undefined, leaving the attribute unset * @cfg {Boolean} autoComplete */ autoComplete: undefined, /** * True to set the field's DOM element autocapitalize attribute to "on", false to set to "off". Defaults to undefined, leaving the attribute unset * @cfg {Boolean} autoCapitalize */ autoCapitalize: undefined, /** * True to set the field DOM element autocorrect attribute to "on", false to set to "off". Defaults to undefined, leaving the attribute unset. * @cfg {Boolean} autoCorrect */ autoCorrect: undefined, /** * @property {Boolean} <tt>True</tt> if the field currently has focus. */ isFocused: false, // @private isClearIconVisible: false, useMask: Ext.is.iOS, initComponent: function() { this.addEvents( /** * @event focus * Fires when this field receives input focus. * @param {Ext.form.Text} this This field * @param {Ext.EventObject} e */ 'focus', /** * @event blur * Fires when this field loses input focus. * @param {Ext.form.Text} this This field * @param {Ext.EventObject} e */ 'blur', /** * @event keyup * Fires when a key is released on the input element. * @param {Ext.form.Text} this This field * @param {Ext.EventObject} e */ 'keyup', /** * @event change * Fires just before the field blurs if the field value has changed. * @param {Ext.form.Text} this This field * @param {Mixed} newValue The new value * @param {Mixed} oldValue The original value */ 'change' ); Ext.form.Text.superclass.initComponent.apply(this, arguments); }, applyRenderSelectors: function() { this.renderSelectors = Ext.applyIf(this.renderSelectors || {}, { clearIconEl: '.x-field-clear', clearIconContainerEl: '.x-field-clear-container' }); Ext.form.Text.superclass.applyRenderSelectors.call(this); }, initRenderData: function() { var renderData = Ext.form.Text.superclass.initRenderData.call(this), autoComplete = this.autoComplete, autoCapitalize = this.autoCapitalize, autoCorrect = this.autoCorrect; Ext.applyIf(renderData, { placeHolder : this.placeHolder, maxlength : this.maxLength, useClearIcon : this.useClearIcon }); var testArray = [true, 'on']; if (autoComplete !== undefined) { renderData.autoComplete = (testArray.indexOf(autoComplete) !== -1) ? 'on': 'off'; } if (autoCapitalize !== undefined) { renderData.autoCapitalize = (testArray.indexOf(autoCapitalize) !== -1) ? 'on': 'off'; } if (autoCorrect !== undefined) { renderData.autoCorrect = (testArray.indexOf(autoCorrect) !== -1) ? 'on': 'off'; } this.renderData = renderData; return renderData; }, initEvents: function() { Ext.form.Text.superclass.initEvents.call(this); if (this.fieldEl) { this.mon(this.fieldEl, { focus: this.onFocus, blur: this.onBlur, keyup: this.onKeyUp, paste: this.updateClearIconVisibility, mousedown: this.onBeforeFocus, scope: this }); if(this.clearIconEl){ this.mon(this.clearIconContainerEl, { scope: this, tap: this.onClearTap }); } } }, // @private onEnable: function() { Ext.form.Text.superclass.onEnable.apply(this, arguments); this.disabled = false; this.updateClearIconVisibility(); }, // @private onDisable: function() { Ext.form.Text.superclass.onDisable.apply(this, arguments); this.blur(); this.hideClearIcon(); }, onClearTap: function() { if (!this.disabled) { this.setValue(''); } }, updateClearIconVisibility: function() { var value = this.getValue(); if (!value) { value = ''; } if (value.length < 1){ this.hideClearIcon(); } else { this.showClearIcon(); } return this; }, showClearIcon: function() { if (!this.disabled && this.fieldEl && this.clearIconEl && !this.isClearIconVisible) { this.isClearIconVisible = true; this.fieldEl.addCls('x-field-clearable'); this.clearIconEl.removeCls('x-hidden-visibility'); } return this; }, hideClearIcon: function() { if (this.fieldEl && this.clearIconEl && this.isClearIconVisible) { this.isClearIconVisible = false; this.fieldEl.removeCls('x-field-clearable'); this.clearIconEl.addCls('x-hidden-visibility'); } return this; }, // @private afterRender: function() { Ext.form.Text.superclass.afterRender.call(this); this.updateClearIconVisibility(); }, // @private onBeforeFocus: function(e) { this.fireEvent('beforefocus', e); }, beforeFocus: Ext.emptyFn, // @private onFocus: function(e) { if (this.mask) { if (this.maskCorrectionTimer) { clearTimeout(this.maskCorrectionTimer); } this.hideMask(); } this.beforeFocus(); if (this.focusCls) { this.el.addCls(this.focusCls); } if (!this.isFocused) { this.isFocused = true; /** * <p>The value that the Field had at the time it was last focused. This is the value that is passed * to the {@link #change} event which is fired if the value has been changed when the Field is blurred.</p> * <p><b>This will be undefined until the Field has been visited.</b> Compare {@link #originalValue}.</p> * @type mixed * @property startValue */ this.startValue = this.getValue(); this.fireEvent('focus', this, e); } }, // @private beforeBlur: Ext.emptyFn, // @private onBlur: function(e) { this.beforeBlur(); if (this.focusCls) { this.el.removeCls(this.focusCls); } this.isFocused = false; var value = this.getValue(); if (String(value) != String(this.startValue)){ this.fireEvent('change', this, value, this.startValue); } this.fireEvent('blur', this, e); this.updateClearIconVisibility(); this.showMask(); this.afterBlur(); }, // @private afterBlur: Ext.emptyFn, /** * Attempts to set the field as the active input focus. * @return {Ext.form.Text} this */ focus: function(){ if (this.rendered && this.fieldEl && this.fieldEl.dom.focus) { this.fieldEl.dom.focus(); } return this; }, /** * Attempts to forcefully blur input focus for the field. * @return {Ext.form.Text} this */ blur: function(){ if(this.rendered && this.fieldEl && this.fieldEl.dom.blur) { this.fieldEl.dom.blur(); } return this; }, setValue: function() { Ext.form.Text.superclass.setValue.apply(this, arguments); this.updateClearIconVisibility(); }, onKeyUp: function(e) { this.updateClearIconVisibility(); if (e.browserEvent.keyCode === 13) { this.blur(); } else { this.fireEvent('keyup', this, e); } } /** * @cfg {Integer} maxLength Maximum number of character permit by the input. */ }); Ext.reg('textfield', Ext.form.Text); /** * @class Ext.form.TextField * @extends Ext.form.Text * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.TextField = Ext.extend(Ext.form.Text, { constructor: function() { console.warn("Ext.form.TextField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Text instead"); Ext.form.TextField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.Select * @extends Ext.form.Field * Simple Select field wrapper. Example usage: <pre><code> new Ext.form.Select({ options: [ {text: 'First Option', value: 'first'}, {text: 'Second Option', value: 'second'}, {text: 'Third Option', value: 'third'} ] }); </code></pre> * @xtype selectfield */ Ext.form.Select = Ext.extend(Ext.form.Text, { ui: 'select', /** * @cfg {Boolean} useClearIcon @hide */ /** * @cfg {String/Integer} valueField The underlying {@link Ext.data.Field#name data value name} (or numeric Array index) to bind to this * Select control. (defaults to 'value') */ valueField: 'value', /** * @cfg {String/Integer} displayField The underlying {@link Ext.data.Field#name data value name} (or numeric Array index) to bind to this * Select control. This resolved value is the visibly rendered value of the available selection options. * (defaults to 'text') */ displayField: 'text', /** * @cfg {Ext.data.Store} store (Optional) store instance used to provide selection options data. */ /** * @cfg {Array} options (Optional) An array of select options. <pre><code> [ {text: 'First Option', value: 'first'}, {text: 'Second Option', value: 'second'}, {text: 'Third Option', value: 'third'} ] </code></pre> * Note: option object member names should correspond with defined {@link #valueField valueField} and {@link #displayField displayField} values. * This config will be ignore if a {@link #store store} instance is provided */ // @cfg {Number} tabIndex @hide tabIndex: -1, // @cfg {Boolean} useMask @hide useMask: true, // @private initComponent: function() { var options = this.options; if (this.store) { this.store = Ext.StoreMgr.lookup(this.store); } else { this.store = new Ext.data.Store({ fields: [this.valueField, this.displayField] }); if (options && Ext.isArray(options) && options.length > 0) { this.setOptions(this.options); } } Ext.form.Select.superclass.initComponent.call(this); this.addEvents( /** * @event change * Fires when an option selection has changed * @param {Ext.form.Select} this * @param {Mixed} value */ 'change' ); }, getPicker: function() { if (!this.picker) { this.picker = new Ext.Picker({ slots: [{ align : 'center', name : this.name, valueField : this.valueField, displayField: this.displayField, value : this.getValue(), store : this.store }], listeners: { change: this.onPickerChange, scope: this } }); } return this.picker; }, getListPanel: function() { if (!this.listPanel) { this.listPanel = new Ext.Panel({ floating : true, stopMaskTapEvent : true, hideOnMaskTap : true, cls : 'x-select-overlay', scroll : 'vertical', items: { xtype: 'list', store: this.store, itemId: 'list', scroll: false, itemTpl : [ '<span class="x-list-label">{' + this.displayField + '}</span>', '<span class="x-list-selected"></span>' ], listeners: { select : this.onListSelect, scope : this } } }); } return this.listPanel; }, onMaskTap: function() { if (this.disabled) { return; } this.showComponent(); }, showComponent: function() { if (Ext.is.Phone) { this.getPicker().show(); } else { var listPanel = this.getListPanel(), index = this.store.find(this.valueField, this.value); listPanel.showBy(this.el, 'fade', false); listPanel.down('#list').getSelectionModel().select(index != -1 ? index: 0, false, true); } }, onListSelect: function(selModel, selected) { if (selected) { this.setValue(selected.get(this.valueField)); this.fireEvent('change', this, this.getValue()); } this.listPanel.hide({ type: 'fade', out: true, scope: this }); }, onPickerChange: function(picker, value) { var currentValue = this.getValue(), newValue = value[this.name]; if (newValue != currentValue) { this.setValue(newValue); this.fireEvent('change', this, newValue); } }, // Inherited docs setValue: function(value) { var record = value ? this.store.findRecord(this.valueField, value) : this.store.getAt(0); if (record && this.rendered) { this.fieldEl.dom.value = record.get(this.displayField); this.value = record.get(this.valueField); } else { this.value = value; } // Temporary fix, the picker should sync with the store automatically by itself if (this.picker) { var pickerValue = {}; pickerValue[this.name] = this.value; this.picker.setValue(pickerValue); } return this; }, // Inherited docs getValue: function(){ return this.value; }, /** * Updates the underlying &lt;options&gt; list with new values. * @param {Array} options An array of options configurations to insert or append. * @param {Boolean} append <tt>true</tt> to append the new options existing values. <pre><code> selectBox.setOptions( [ {text: 'First Option', value: 'first'}, {text: 'Second Option', value: 'second'}, {text: 'Third Option', value: 'third'} ]).setValue('third'); </code></pre> * Note: option object member names should correspond with defined {@link #valueField valueField} and * {@link #displayField displayField} values. * @return {Ext.form.Select} this */ setOptions: function(options, append) { if (!options) { this.store.clearData(); this.setValue(null); } else { this.store.loadData(options, append); } }, destroy: function() { Ext.form.Select.superclass.destroy.apply(this, arguments); if (this.listPanel) { this.listPanel.destroy(); } if (this.picker) { this.picker.destroy(); } } }); Ext.reg('selectfield', Ext.form.Select); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('select', Ext.form.Select);
JavaScript
/** * @class Ext.form.Search * @extends Ext.form.Field * Wraps an HTML5 search field. See {@link Ext.form.FormPanel FormPanel} for example usage. * @xtype searchfield */ Ext.form.Search = Ext.extend(Ext.form.Text, { inputType: Ext.is.Android ? 'text' : 'search' /** * @cfg {Boolean} useClearIcon @hide */ }); Ext.reg('searchfield', Ext.form.Search); /** * @class Ext.form.SearchField * @extends Ext.form.Search * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.SearchField = Ext.extend(Ext.form.Search, { constructor: function() { console.warn("Ext.form.SearchField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Search instead"); Ext.form.SearchField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.Spinner * @extends Ext.form.Field * <p>Wraps an HTML5 number field. Example usage: * <pre><code> new Ext.form.Spinner({ minValue: 0, maxValue: 100, incrementValue: 2, cycle: true }); </code></pre> * @xtype spinnerfield */ Ext.form.Spinner = Ext.extend(Ext.form.Number, { /** * @cfg {Boolean} useClearIcon @hide */ componentCls: 'x-spinner', /** * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY) */ minValue: Number.NEGATIVE_INFINITY, /** * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE) */ maxValue: Number.MAX_VALUE, /** * @cfg {Number} incrementValue Value that is added or subtracted from the current value when a spinner is used. * Defaults to <tt>1</tt>. */ incrementValue: 1, /** * @cfg {Boolean} accelerateOnTapHold True if autorepeating should start slowly and accelerate. * Defaults to <tt>true</tt>. */ accelerateOnTapHold: true, // @private defaultValue: 0, /** * @cfg {Boolean} cycle When set to true, it will loop the values of a minimum or maximum is reached. * If the maximum value is reached, the value will be set to the minimum. * If the minimum value is reached, the value will be set to the maximum. * Defaults to <tt>false</tt>. */ cycle: false, /** * @cfg {Boolean} disableInput True to disable the input field, meaning that only the spinner buttons * can be used. Defaults to <tt>false</tt>. */ disableInput: false, /** * @cfg {Boolean} useClearIcon @hide */ useClearIcon: false, /** * @cfg {Boolean} autoCapitalize @hide */ autoCapitalize: false, renderTpl: [ '<tpl if="label"><label <tpl if="fieldEl">for="{inputId}"</tpl> class="x-form-label"><span>{label}</span></label></tpl>', '<tpl if="fieldEl">', '<div class="{componentCls}-body">', '<div class="{componentCls}-down"><span>-</span></div>', '<div class="x-form-field-container">', '<input id="{inputId}" type="{type}" name="{name}" class="{fieldCls}"', '<tpl if="tabIndex">tabIndex="{tabIndex}" </tpl>', '<tpl if="placeHolder">placeholder="{placeHolder}" </tpl>', '<tpl if="style">style="{style}" </tpl>', '<tpl if="minValue != undefined">min="{minValue}" </tpl>', '<tpl if="maxValue != undefined">max="{maxValue}" </tpl>', '<tpl if="stepValue != undefined">step="{stepValue}" </tpl>', '<tpl if="autoComplete">autocomplete="{autoComplete}" </tpl>', '<tpl if="autoFocus">autofocus="{autoFocus}" </tpl>', '/>', '<tpl if="useMask"><div class="x-field-mask"></div></tpl>', '</div>', '<div class="{componentCls}-up"><span>+</span></div>', '</div>', '</tpl>' ], initComponent: function() { //<deprecated since=0.99> if (Ext.isDefined(this.accelerate)) { console.warn("Spinner: accelerate has been removed. Please use accelerateOnTapHold."); this.accelerate = this.accelerateOnTapHold; } //</deprecated> this.addEvents( /** * @event spin * Fires when the value is changed via either spinner buttons * @param {Ext.form.Spinner} this * @param {Number} value * @param {String} direction 'up' or 'down' */ 'spin', /** * @event spindown * Fires when the value is changed via the spinner down button * @param {Ext.form.Spinner} this * @param {Number} value */ 'spindown', /** * @event spinup * Fires when the value is changed via the spinner up button * @param {Ext.form.Spinner} this * @param {Number} value */ 'spinup' ); Ext.form.Spinner.superclass.initComponent.call(this); }, // @private onRender: function() { this.renderData.disableInput = this.disableInput; Ext.applyIf(this.renderSelectors, { spinUpEl: '.x-spinner-up', spinDownEl: '.x-spinner-down' }); Ext.form.Spinner.superclass.onRender.apply(this, arguments); this.downRepeater = this.createRepeater(this.spinDownEl, this.onSpinDown); this.upRepeater = this.createRepeater(this.spinUpEl, this.onSpinUp); }, initValue: function() { if (isNaN(this.defaultValue)) { this.defaultValue = 0; } if (!this.value) { this.value = this.defaultValue; } Ext.form.Spinner.superclass.initValue.apply(this, arguments); }, // @private createRepeater: function(el, fn){ var repeat = new Ext.util.TapRepeater(el, { accelerate: this.accelerateOnTapHold }); this.mon(repeat, { tap: fn, touchstart: this.onTouchStart, touchend: this.onTouchEnd, preventDefault: true, scope: this }); return repeat; }, // @private onSpinDown: function() { if (!this.disabled) { this.spin(true); } }, // @private onSpinUp: function() { if (!this.disabled) { this.spin(false); } }, onKeyUp: function(e) { // var value = parseInt(this.getValue()); // // if (isNaN(value)) { // value = this.defaultValue; // } // // this.setValue(value); Ext.form.Spinner.superclass.onKeyUp.apply(this, arguments); }, // @private onTouchStart: function(btn) { if (!this.disabled) { btn.el.addCls('x-button-pressed'); } }, // @private onTouchEnd: function(btn) { btn.el.removeCls('x-button-pressed'); }, // @private spin: function(down) { var value = parseFloat(this.getValue()), increment = this.incrementValue, cycle = this.cycle, min = this.minValue, max = this.maxValue, direction = down ? 'down': 'up'; if (down){ value -= increment; } else{ value += increment; } value = (isNaN(value)) ? this.defaultValue: value; if (value < min) { value = cycle ? max: min; } else if (value > max) { value = cycle ? min: max; } this.setValue(value); this.fireEvent('spin' + direction, this, value); this.fireEvent('spin', this, value, direction); }, // @private destroy: function() { Ext.destroy(this.downRepeater, this.upRepeater); Ext.form.Spinner.superclass.destroy.call(this, arguments); } }); Ext.reg('spinnerfield', Ext.form.Spinner); /** * @class Ext.form.SpinnerField * @extends Ext.form.Spinner * @private * @hidden * DEPRECATED - remove this in 1.0. See RC1 Release Notes for details */ Ext.form.SpinnerField = Ext.extend(Ext.form.Spinner, { constructor: function() { console.warn("Ext.form.SpinnerField has been deprecated and will be removed in Sencha Touch 1.0. Please use Ext.form.Spinner instead"); Ext.form.SpinnerField.superclass.constructor.apply(this, arguments); } });
JavaScript
/** * @class Ext.form.Checkbox * @extends Ext.form.Field * Simple Checkbox class. Can be used as a direct replacement for traditional checkbox fields. * @constructor * @param {Object} config Optional config object * @xtype checkboxfield */ Ext.form.Checkbox = Ext.extend(Ext.form.Field, { ui: 'checkbox', inputType: 'checkbox', /** * @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>) */ checked: false, /** * @cfg {String} value The string value to submit if the item is in a checked state. */ value: '', // @private constructor: function(config) { this.addEvents( /** * @event check * Fires when the checkbox is checked. * @param {Ext.form.Checkbox} this This checkbox */ 'check', /** * @event uncheck * Fires when the checkbox is unchecked. * @param {Ext.form.Checkbox} this This checkbox */ 'uncheck' ); Ext.form.Checkbox.superclass.constructor.call(this, config); }, renderTpl: [ '<tpl if="label"><label <tpl if="fieldEl">for="{inputId}"</tpl> class="x-form-label"><span>{label}</span></label></tpl>', '<tpl if="fieldEl"><input id="{inputId}" type="{inputType}" name="{name}" class="{fieldCls}" tabIndex="-1" ', '<tpl if="checked"> checked </tpl>', '<tpl if="style">style="{style}" </tpl> value="{inputValue}" />', '</tpl>' ], // @private onRender: function() { var isChecked = this.getBooleanIsChecked(this.checked); Ext.apply(this.renderData, { inputValue : this.value || '', checked : isChecked }); Ext.form.Checkbox.superclass.onRender.apply(this, arguments); if (this.fieldEl) { this.mon(this.fieldEl, { change: this.onChange, scope: this }); this.setChecked(isChecked); this.originalState = this.isChecked(); } }, // @private onChange: function() { if (this.isChecked()) { this.fireEvent('check', this); } else { this.fireEvent('uncheck', this); } }, /** * Returns the checked state of the checkbox. * @return {Boolean} True if checked, else otherwise */ isChecked: function() { return this.fieldEl.dom.checked || false; }, /** * Set the checked state of the checkbox. * @return {Ext.form.Checkbox} this This checkbox */ setChecked: function(checked) { this.fieldEl.dom.checked = this.getBooleanIsChecked(checked); return this; }, /** * Set the checked state of the checkbox to true * @return {Ext.form.Checkbox} this This checkbox */ check: function() { return this.setChecked(true); }, /** * Set the checked state of the checkbox to false * @return {Ext.form.Checkbox} this This checkbox */ uncheck: function() { return this.setChecked(false); }, // Inherited reset: function() { Ext.form.Checkbox.superclass.reset.apply(this, arguments); this.setChecked(this.originalState); return this; }, //@private getBooleanIsChecked: function(value) { return /^(true|1|on)/i.test(String(value)); }, getSameGroupFields: function() { var parent = this.el.up('form'), formComponent = Ext.getCmp(parent.id), fields = []; if (formComponent) { fields = formComponent.getFields(this.getName()); } return fields; }, /** * Returns an array of values from the checkboxes in the group that are checked, * @return {Array} */ getGroupValues: function() { var values = []; this.getSameGroupFields().forEach(function(field) { if (field.isChecked()) { values.push(field.getValue()); } }); return values; }, /** * Set the status of all matched checkboxes in the same group to checked * @param {Array} values An array of values * @return {Ext.form.Checkbox} This checkbox */ setGroupValues: function(values) { this.getSameGroupFields().forEach(function(field) { field.setChecked((values.indexOf(field.getValue()) !== -1)); }); return this; } }); Ext.reg('checkboxfield', Ext.form.Checkbox); //DEPRECATED - remove this in 1.0. See RC1 Release Notes for details Ext.reg('checkbox', Ext.form.Checkbox);
JavaScript
/** * @class Ext.Panel * @extends Ext.lib.Panel * <p>Panel is a container that has specific functionality and structural components that make * it the perfect building block for application-oriented user interfaces.</p> * <p>Panels are, by virtue of their inheritance from {@link Ext.Container}, capable * of being configured with a {@link Ext.Container#layout layout}, and containing child Components.</p> * <p>When either specifying child {@link Ext.Component#items items} of a Panel, or dynamically {@link Ext.Container#add adding} Components * to a Panel, remember to consider how you wish the Panel to arrange those child elements, and whether * those child elements need to be sized using one of Ext's built-in <code><b>{@link Ext.Container#layout layout}</b></code> schemes. By * default, Panels use the {@link Ext.layout.ContainerLayout ContainerLayout} scheme. This simply renders * child components, appending them one after the other inside the Container, and <b>does not apply any sizing</b> * at all.</p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #fullscreen}</li> * <li>{@link #layout}</li> * <li>{@link #items}</li> * <li>{@link #dockedItems}</li> * <li>{@link #html}</li> * </ul> * * <h2>Useful Methods</h2> * <ul class="list"> * <li>{@link #show}</li> * <li>{@link #hide}</li> * <li>{@link #showBy}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Panel/screenshot.png" /></p> * * <h2>Example code:</h2> * <pre><code> var panel = new Ext.Panel({ fullscreen: true, dockedItems: [ { dock : 'top', xtype: 'toolbar', title: 'Standard Titlebar' }, { dock : 'top', xtype: 'toolbar', ui : 'light', items: [ { text: 'Test Button' } ] } ], html: 'Testing' });</code></pre> * * @constructor * Create a new Panel * @param {Object} config The config object * @xtype panel */ Ext.Panel = Ext.extend(Ext.lib.Panel, { // inherited scroll: false, /** * @cfg {Boolean} fullscreen * Force the component to take up 100% width and height available. Defaults to false. * Setting this configuration immediately sets the monitorOrientation config to true. */ fullscreen: false }); Ext.reg('panel', Ext.Panel);
JavaScript
/** * @class Ext.SegmentedButton * @extends Ext.Container * <p>SegmentedButton is a container for a group of {@link Ext.Button}s. Generally a SegmentedButton would be * a child of a {@link Ext.Toolbar} and would be used to switch between different views.</p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #allowMultiple}</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.SegmentedButton/screenshot.png" /></p> * * <h2>Example usage:</h2> * <pre><code> var segmentedButton = new Ext.SegmentedButton({ allowMultiple: true, items: [ { text: 'Option 1' }, { text : 'Option 2', pressed: true, handler: tappedFn }, { text: 'Option 3' } ], listeners: { toggle: function(container, button, pressed){ console.log("User toggled the '" + button.text + "' button: " + (pressed ? 'on' : 'off')); } } });</code></pre> * @constructor * @param {Object} config The config object * @xtype buttons */ Ext.SegmentedButton = Ext.extend(Ext.Container, { defaultType: 'button', componentCls: 'x-segmentedbutton', pressedCls: 'x-button-pressed', /** * @cfg {Boolean} allowMultiple * Allow multiple pressed buttons (defaults to false). */ allowMultiple: false, /** * @cfg {Boolean} allowDepress * Allow to depress a pressed button. (defaults to true when allowMultiple is true) */ // @private initComponent : function() { this.layout = Ext.apply({}, this.layout || {}, { type: 'hbox', align: 'stretch' }); Ext.SegmentedButton.superclass.initComponent.call(this); if (this.allowDepress === undefined) { this.allowDepress = this.allowMultiple; } this.addEvents( /** * @event toggle * Fires when any child button's pressed state has changed. * @param {Ext.SegmentedButton} this * @param {Ext.Button} button The button whose state has changed * @param {Boolean} pressed The new button state. */ 'toggle' ); }, // @private initEvents : function() { Ext.SegmentedButton.superclass.initEvents.call(this); this.mon(this.el, { tap: this.onTap, capture: true, scope: this }); }, // @private afterLayout : function(layout) { var me = this; Ext.SegmentedButton.superclass.afterLayout.call(me, layout); if (!me.initialized) { me.items.each(function(item, index) { me.setPressed(item, !!item.pressed, true); }); if (me.allowMultiple) { me.pressedButtons = me.getPressedButtons(); } me.initialized = true; } }, // @private onTap : function(e, t) { if (!this.disabled && (t = e.getTarget('.x-button'))) { this.setPressed(t.id, this.allowDepress ? undefined : true); } }, /** * Gets the pressed button(s) * @returns {Array/Button} The pressed button or an array of pressed buttons (if allowMultiple is true) */ getPressed : function() { return this.allowMultiple ? this.getPressedButtons() : this.pressedButton; }, /** * Activates a button * @param {Number/String/Button} position/id/button. The button to activate. * @param {Boolean} pressed if defined, sets the pressed state of the button, * otherwise the pressed state is toggled * @param {Boolean} suppressEvents true to suppress toggle events during the action. * If allowMultiple is true, then setPressed will toggle the button state. */ setPressed : function(btn, pressed, suppressEvents) { var me = this; btn = me.getComponent(btn); if (!btn || !btn.isButton || btn.disabled) { if (!me.allowMultiple && me.pressedButton) { me.setPressed(me.pressedButton, false); } return; } if (!Ext.isBoolean(pressed)) { pressed = !btn.pressed; } if (pressed) { if (!me.allowMultiple) { if (me.pressedButton && me.pressedButton !== btn) { me.pressedButton.el.removeCls(me.pressedCls); me.pressedButton.pressed = false; if (suppressEvents !== true) { me.fireEvent('toggle', me, me.pressedButton, false); } } me.pressedButton = btn; } btn.el.addCls(me.pressedCls); btn.pressed = true; btn.preventCancel = true; if (me.initialized && suppressEvents !== true) { me.fireEvent('toggle', me, btn, true); } } else if (!pressed) { if (!me.allowMultiple && btn === me.pressedButton) { me.pressedButton = null; } if (btn.pressed) { btn.el.removeCls(me.pressedCls); btn.pressed = false; if (suppressEvents !== true) { me.fireEvent('toggle', me, btn, false); } } } if (me.allowMultiple && me.initialized) { me.pressedButtons = me.getPressedButtons(); } }, // @private getPressedButtons : function(toggleEvents) { var pressed = this.items.filterBy(function(item) { return item.isButton && !item.disabled && item.pressed; }); return pressed.items; }, /** * Disables all buttons */ disable : function() { this.items.each(function(item) { item.disable(); }); Ext.SegmentedButton.superclass.disable.apply(this, arguments); }, /** * Enables all buttons */ enable : function() { this.items.each(function(item) { item.enable(); }, this); Ext.SegmentedButton.superclass.enable.apply(this, arguments); } }); Ext.reg('segmentedbutton', Ext.SegmentedButton);
JavaScript
/** * @class Ext.Component * @extends Ext.lib.Component * <p>Base class for all Ext components. All subclasses of Component may participate in the automated * Ext component lifecycle of creation, rendering and destruction which is provided by the {@link Ext.Container Container} class. * Components may be added to a Container through the {@link Ext.Container#items items} config option at the time the Container is created, * or they may be added dynamically via the {@link Ext.Container#add add} method.</p> * <p>The Component base class has built-in support for basic hide/show and enable/disable behavior.</p> * <p>All Components are registered with the {@link Ext.ComponentMgr} on construction so that they can be referenced at any time via * {@link Ext#getCmp}, passing the {@link #id}.</p> * <p>All user-developed visual widgets that are required to participate in automated lifecycle and size management should subclass Component (or * {@link Ext.BoxComponent} if managed box model handling is required, ie height and width management).</p> * <p>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>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 ------------- ------------------ button {@link Ext.Button} component {@link Ext.Component} container {@link Ext.Container} dataview {@link Ext.DataView} panel {@link Ext.Panel} slider {@link Ext.form.Slider} toolbar {@link Ext.Toolbar} spacer {@link Ext.Spacer} tabpanel {@link Ext.TabPanel} Form components --------------------------------------- formpanel {@link Ext.form.FormPanel} checkboxfield {@link Ext.form.Checkbox} selectfield {@link Ext.form.Select} field {@link Ext.form.Field} fieldset {@link Ext.form.FieldSet} hiddenfield {@link Ext.form.Hidden} numberfield {@link Ext.form.Number} radiofield {@link Ext.form.Radio} textareafield {@link Ext.form.TextArea} textfield {@link Ext.form.Text} togglefield {@link Ext.form.Toggle} </pre> * @constructor * @param {Ext.Element/String/Object} config The configuration options may be specified as either: * <div class="mdetail-params"><ul> * <li><b>an element</b> : * <p class="sub-desc">it is set as the internal element and its id used as the component id</p></li> * <li><b>a string</b> : * <p class="sub-desc">it is assumed to be the id of an existing element and is used as the component id</p></li> * <li><b>anything else</b> : * <p class="sub-desc">it is assumed to be a standard config object and is applied to the component</p></li> * </ul></div> * @xtype component */ Ext.Component = Ext.extend(Ext.lib.Component, { /** * @cfg {Object/String/Boolean} showAnimation * The type of animation you want to use when this component is shown. If you set this * this hide animation will automatically be the opposite. */ showAnimation: null, /** * @cfg {Boolean} monitorOrientation * Monitor Orientation change */ monitorOrientation: false, /** * @cfg {Boolean} floatingCls * The class that is being added to this component when its floating. * (defaults to x-floating) */ floatingCls: 'x-floating', /** * @cfg {Boolean} hideOnMaskTap * True to automatically bind a tap listener to the mask that hides the window. * Defaults to true. Note: if you set this property to false you have to programmaticaly * hide the overlay. */ hideOnMaskTap: true, /** * @cfg {Boolean} stopMaskTapEvent * True to stop the event that fires when you click outside the floating component. * Defalts to true. */ stopMaskTapEvent: true, /** * @cfg {Boolean} centered * Center the Component. Defaults to false. */ centered: false, /** * @cfg {Boolean} modal * True to make the Component modal and mask everything behind it when displayed, false to display it without * restricting access to other UI elements (defaults to false). */ modal: false, /** * @cfg {Mixed} scroll * Configure the component to be scrollable. Acceptable values are: * <ul> * <li>'horizontal', 'vertical', 'both' to enabling scrolling for that direction.</li> * <li>A {@link Ext.util.Scroller Scroller} configuration.</li> * <li>false to explicitly disable scrolling.</li> * </ul> * * Enabling scrolling immediately sets the monitorOrientation config to true (for {@link Ext.Panel Panel}) */ // @private initComponent : function() { this.addEvents( /** * @event beforeorientationchange * Fires before the orientation changes, if the monitorOrientation * configuration is set to true. Return false to stop the orientation change. * @param {Ext.Panel} this * @param {String} orientation 'landscape' or 'portrait' * @param {Number} width * @param {Number} height */ 'beforeorientationchange', /** * @event orientationchange * Fires when the orientation changes, if the monitorOrientation * configuration is set to true. * @param {Ext.Panel} this * @param {String} orientation 'landscape' or 'portrait' * @param {Number} width * @param {Number} height */ 'orientationchange' ); if (this.fullscreen || this.floating) { this.monitorOrientation = true; this.autoRender = true; } if (this.fullscreen) { this.width = window.innerWidth; this.height = window.innerHeight; this.cls = (this.cls || '') + ' x-fullscreen'; this.renderTo = document.body; } }, onRender : function() { Ext.Component.superclass.onRender.apply(this, arguments); if (this.monitorOrientation) { this.el.addCls('x-' + Ext.Viewport.orientation); } if (this.floating) { this.setFloating(true); } if (this.draggable) { this.setDraggable(this.draggable); } if (this.scroll) { this.setScrollable(this.scroll); } }, afterRender : function() { if (this.fullscreen) { this.layoutOrientation(Ext.Viewport.orientation, this.width, this.height); } Ext.Component.superclass.afterRender.call(this); }, initEvents : function() { Ext.Component.superclass.initEvents.call(this); if (this.monitorOrientation) { Ext.EventManager.onOrientationChange(this.setOrientation, this); } }, // Template method that can be overriden to perform logic after the panel has layed out itself // e.g. Resized the body and positioned all docked items. afterComponentLayout : function() { var scrollEl = this.scrollEl, scroller = this.scroller, parentEl; if (scrollEl) { parentEl = scrollEl.parent(); if (scroller.horizontal) { scrollEl.setStyle('min-width', parentEl.getWidth(true) + 'px'); scrollEl.setHeight(parentEl.getHeight(true) || null); } if (scroller.vertical) { scrollEl.setStyle('min-height', parentEl.getHeight(true) + 'px'); scrollEl.setWidth(parentEl.getWidth(true) || null); } scroller.updateBoundary(true); } if (this.fullscreen && Ext.is.iPad) { Ext.repaint(); } }, layoutOrientation: Ext.emptyFn, // Inherit docs update: function(){ // We override this here so we can call updateBoundary once the update happens. Ext.Component.superclass.update.apply(this, arguments); var scroller = this.scroller; if (scroller && scroller.updateBoundary){ scroller.updateBoundary(true); } }, /** * Show the component. * @param {Object/String/Boolean} animation (optional) Defaults to false. */ show : function(animation) { var rendered = this.rendered; if ((this.hidden || !rendered) && this.fireEvent('beforeshow', this) !== false) { if (this.anchorEl) { this.anchorEl.hide(); } if (!rendered && this.autoRender) { this.render(Ext.isBoolean(this.autoRender) ? Ext.getBody() : this.autoRender); } this.hidden = false; if (this.rendered) { this.onShow(animation); this.fireEvent('show', this); } } return this; }, /** * Show this component relative another component or element. * @param {Mixed} alignTo Element or Component * @param {Object/String/Boolean} animation * @param {Boolean} allowOnSide true to allow this element to be aligned on the left or right. * @returns {Ext.Component} this */ showBy : function(alignTo, animation, allowSides, anchor) { if (!this.floating) { return this; } if (alignTo.isComponent) { alignTo = alignTo.el; } else { alignTo = Ext.get(alignTo); } this.x = 0; this.y = 0; this.show(animation); if (anchor !== false) { if (!this.anchorEl) { this.anchorEl = this.el.createChild({ cls: 'x-anchor' }); } this.anchorEl.show(); } this.alignTo(alignTo, allowSides, 20); }, alignTo : function(alignTo, allowSides, offset) { // We are going to try and position this component to the alignTo element. var alignBox = alignTo.getPageBox(), constrainBox = { width: window.innerWidth, height: window.innerHeight }, size = this.getSize(), newSize = { width: Math.min(size.width, constrainBox.width), height: Math.min(size.height, constrainBox.height) }, position, index = 2, positionMap = [ 'tl-bl', 't-b', 'tr-br', 'l-r', 'l-r', 'r-l', 'bl-tl', 'b-t', 'br-tr' ], anchorEl = this.anchorEl, offsets = [0, offset], targetBox, cls, onSides = false, arrowOffsets = [0, 0], alignCenterX = alignBox.left + (alignBox.width / 2), alignCenterY = alignBox.top + (alignBox.height / 2); if (alignCenterX <= constrainBox.width * (1/3)) { index = 1; arrowOffsets[0] = 25; } else if (alignCenterX >= constrainBox.width * (2/3)) { index = 3; arrowOffsets[0] = -30; } if (alignCenterY >= constrainBox.height * (2/3)) { index += 6; offsets = [0, -offset]; arrowOffsets[1] = -10; } // If the alignTo element is vertically in the middle part of the screen // we position it left or right. else if (allowSides !== false && alignCenterY >= constrainBox.height * (1/3)) { index += 3; offsets = (index <= 5) ? [offset, 0] : [-offset, 0]; arrowOffsets = (index <= 5) ? [10, 0] : [-10, 0]; onSides = true; } else { arrowOffsets[1] = 10; } position = positionMap[index-1]; targetBox = this.el.getAlignToXY(alignTo, position, offsets); // If the window is going to be aligned on the left or right of the alignTo element // we make sure the height is smaller then the window height, and the width if (onSides) { if (targetBox[0] < 0) { newSize.width = alignBox.left - offset; } else if (targetBox[0] + newSize.width > constrainBox.width) { newSize.width = constrainBox.width - alignBox.right - offset; } } else { if (targetBox[1] < 0) { newSize.height = alignBox.top - offset; } else if (targetBox[1] + newSize.height > constrainBox.height) { newSize.height = constrainBox.height - alignBox.bottom - offset; } } if (newSize.width != size.width) { this.setSize(newSize.width); } else if (newSize.height != size.height) { this.setSize(undefined, newSize.height); } targetBox = this.el.getAlignToXY(alignTo, position, offsets); this.setPosition(targetBox[0], targetBox[1]); if (anchorEl) { // we are at the top anchorEl.removeCls(['x-anchor-bottom', 'x-anchor-left', 'x-anchor-right', 'x-anchor-top']); if (offsets[1] == offset) { cls = 'x-anchor-top'; } else if (offsets[1] == -offset) { cls = 'x-anchor-bottom'; } else if (offsets[0] == offset) { cls = 'x-anchor-left'; } else { cls = 'x-anchor-right'; } targetBox = anchorEl.getAlignToXY(alignTo, position, arrowOffsets); anchorEl.setXY(targetBox); anchorEl.addCls(cls); } return position; }, /** * Show this component centered of its parent or the window * This only applies when the component is floating. * @param {Boolean} centered True to center, false to remove centering * @returns {Ext.Component} this */ setCentered : function(centered, update) { this.centered = centered; if (this.rendered && update) { var x, y; if (!this.ownerCt) { x = (Ext.Element.getViewportWidth() / 2) - (this.getWidth() / 2); y = (Ext.Element.getViewportHeight() / 2) - (this.getHeight() / 2); } else { x = (this.ownerCt.getTargetEl().getWidth() / 2) - (this.getWidth() / 2); y = (this.ownerCt.getTargetEl().getHeight() / 2) - (this.getHeight() / 2); } this.setPosition(x, y); } return this; }, /** * Hide the component * @param {Object/String/Boolean} animation (optional) Defaults to false. */ hide : function(animation) { if (!this.hidden && this.fireEvent('beforehide', this) !== false) { this.hidden = true; if (this.rendered) { this.onHide(animation, true); } } return this; }, // @private onShow : function(animation) { this.el.show(); Ext.Component.superclass.onShow.call(this, animation); if (animation === undefined || animation === true) { animation = this.showAnimation; } if (this.floating) { this.el.dom.parentNode || this.el.appendTo(document.body); if (animation) { this.el.setStyle('opacity', 0.01); } if (this.centered) { this.setCentered(true, true); } else { this.setPosition(this.x, this.y); } if (this.modal) { this.el.parent().mask(null, 'x-mask-gray'); } if (this.hideOnMaskTap) { Ext.getDoc().on('touchstart', this.onFloatingTouchStart, this, {capture: true}); } } if (animation) { //this.el.setStyle('opacity', 0.01); Ext.Anim.run(this, animation, { out: false, autoClear: true }); this.showAnimation = animation; } }, // @private onFloatingTouchStart : function(e, t) { var doc = Ext.getDoc(); if (!this.el.contains(t)) { doc.on('touchend', function(e) { this.hide(); if (this.stopMaskTapEvent || Ext.fly(t).hasCls('x-mask')) { e.stopEvent(); } }, this, {single: true, capture: true}); e.stopEvent(); } }, // @private onHide : function(animation, fireHideEvent) { if (animation === undefined || animation === true) { animation = this.showAnimation; } if (this.hideOnMaskTap && this.floating) { Ext.getDoc().un('touchstart', this.onFloatingTouchStart, this); } if (animation) { Ext.Anim.run(this, animation, { out: true, reverse: true, autoClear: true, scope: this, fireHideEvent: fireHideEvent, after: this.doHide }); } else { this.doHide(null, {fireHideEvent: fireHideEvent}); } }, // private doHide : function(el, options) { var parent = this.el.parent(); this.el.hide(); if (parent && this.floating && this.modal) { parent.unmask(); } if (options && options.fireHideEvent) { this.fireEvent('hide', this); } }, /** * Sets a Component as scrollable. * @param {Mixed} config * Acceptable values are a Ext.Scroller configuration, 'horizontal', 'vertical', 'both', and false */ setScrollable : function(config) { if (!this.rendered) { this.scroll = config; return; } Ext.destroy(this.scroller); this.scroller = null; if (config !== false) { var direction = Ext.isObject(config) ? config.direction: config; config = Ext.apply({}, Ext.isObject(config) ? config: {}, { // momentum: true, direction: direction }); if (!this.scrollEl) { this.scrollEl = this.getTargetEl().createChild(); this.originalGetTargetEl = this.getTargetEl; this.getTargetEl = function() { return this.scrollEl; }; } this.scroller = (new Ext.util.ScrollView(this.scrollEl, config)).scroller; } else { this.getTargetEl = this.originalGetTargetEl; } }, /** * Sets a Component as floating. * @param {Boolean} floating * @param {Boolean} autoShow */ setFloating : function(floating, autoShow) { this.floating = !!floating; this.hidden = true; if (this.rendered) { if (floating !== false) { this.el.addCls(this.floatingCls); if (autoShow) { this.show(); } } else { this.el.removeCls(this.floatingCls); Ext.getDoc().un('touchstart', this.onFloatingTouchStart, this); } } else if (floating !== false) { this.autoRender = true; } }, /** * Sets a Component as draggable. * @param {Boolean/Mixed} draggable On first call, this can be a config object for {@link Ext.util.Draggable}. * Afterwards, if set to false, the existing draggable object will be disabled * @param {Boolean} autoShow */ setDraggable : function(draggable, autoShow) { this.isDraggable = draggable; if (this.rendered) { if (draggable === false) { if (this.dragObj) { this.dragObj.disable(); } } else { if (autoShow) { this.show(); } if (this.dragObj) { this.dragObj.enable(); } else { this.dragObj = new Ext.util.Draggable(this.el, Ext.apply({}, this.isDraggable || {})); this.relayEvents(this.dragObj, ['dragstart', 'beforedragend' ,'drag', 'dragend']); } } } }, /** * Sets the orientation for the Panel. * @param {String} orientation 'landscape' or 'portrait' * @param {Number/String} width New width of the Panel. * @param {Number/String} height New height of the Panel. */ setOrientation : function(orientation, w, h) { if (this.fireEvent('beforeorientationchange', this, orientation, w, h) !== false) { if (this.orientation != orientation) { this.el.removeCls('x-' + this.orientation); this.el.addCls('x-' + orientation); } this.orientation = orientation; this.layoutOrientation(orientation, w, h); if (this.fullscreen) { this.setSize(w, h); } if (this.floating && this.centered) { this.setCentered(true, true); } this.onOrientationChange(orientation, w, h); this.fireEvent('orientationchange', this, orientation, w, h); } }, // @private onOrientationChange : Ext.emptyFn, beforeDestroy : function() { if (this.floating && this.modal && !this.hidden) { this.el.parent().unmask(); } Ext.destroy(this.scroller); Ext.Component.superclass.beforeDestroy.call(this); }, onDestroy : function() { if (this.monitorOrientation && Ext.EventManager.orientationEvent) { Ext.EventManager.orientationEvent.removeListener(this.setOrientation, this); } Ext.Component.superclass.onDestroy.call(this); } }); // @xtype box Ext.BoxComponent = Ext.Component; Ext.reg('component', Ext.Component); Ext.reg('box', Ext.BoxComponent);
JavaScript
/** * @class Ext.NestedList * @extends Ext.Panel * * <p>NestedList provides a miller column interface to navigate between nested sets * and provide a clean interface with limited screen real-estate.</p> * * <pre><code> // store with data var data = { text: 'Groceries', items: [{ text: 'Drinks', items: [{ text: 'Water', items: [{ text: 'Sparkling', leaf: true },{ text: 'Still', leaf: true }] },{ text: 'Coffee', leaf: true },{ text: 'Espresso', leaf: true },{ text: 'Redbull', leaf: true },{ text: 'Coke', leaf: true },{ text: 'Diet Coke', leaf: true }] },{ text: 'Fruit', items: [{ text: 'Bananas', leaf: true },{ text: 'Lemon', leaf: true }] },{ text: 'Snacks', items: [{ text: 'Nuts', leaf: true },{ text: 'Pretzels', leaf: true },{ text: 'Wasabi Peas', leaf: true }] },{ text: 'Empty Category', items: [] }] }; Ext.regModel('ListItem', { fields: [{name: 'text', type: 'string'}] }); var store = new Ext.data.TreeStore({ model: 'ListItem', root: data, proxy: { type: 'ajax', reader: { type: 'tree', root: 'items' } } }); var nestedList = new Ext.NestedList({ fullscreen: true, title: 'Groceries', displayField: 'text', store: store });</code></pre> * * @xtype nestedlist */ Ext.NestedList = Ext.extend(Ext.Panel, { componentCls: 'x-nested-list', /** * @cfg {String} layout * @hide */ layout: 'card', /** * @cfg {String} tpl * @hide */ /** * @cfg {String} defaultType * @hide */ // Putting this in getSubList otherwise users would have to explicitly // specify the xtype to create in getDetailCard //defaultType: 'list', /** * @cfg {String} cardSwitchAnimation * Animation to be used during transitions of cards. * Any valid value from Ext.anims can be used ('fade', 'slide', 'flip', 'cube', 'pop', 'wipe'). * Defaults to 'slide'. */ cardSwitchAnimation: 'slide', /** * @type Ext.Button */ backButton: null, /** * @cfg {String} backText * The label to display for the back button. Defaults to "Back". */ backText: 'Back', /** * @cfg {Boolean} useTitleAsBackText */ useTitleAsBackText: true, /** * @cfg {Boolean} updateTitleText * Update the title with the currently selected category. Defaults to true. */ updateTitleText: true, /** * @cfg {String} displayField * Display field to use when setting item text and title. * This configuration is ignored when overriding getItemTextTpl or * getTitleTextTpl for the item text or title. (Defaults to 'text') */ displayField: 'text', /** * @cfg {String} loadingText * Loading text to display when a subtree is loading. */ loadingText: 'Loading...', /** * @cfg {String} emptyText * Empty text to display when a subtree is empty. */ emptyText: 'No items available.', /** * @cfg {Boolean/Function} onItemDisclosure * Maps to the Ext.List onItemDisclosure configuration for individual lists. (Defaults to false) */ onItemDisclosure: false, /** * @cfg {Boolean/Number} clearSelectionDelay * Number of milliseconds to show the highlight when going back in a list. (Defaults to 200). * Passing false will keep the prior list selection. */ clearSelectionDelay: 200, /** * @cfg {Boolean} allowDeselect * Set to true to alow the user to deselect leaf items via interaction. * Defaults to false. */ allowDeselect: false, /** * Override this method to provide custom template rendering of individual * nodes. The template will receive all data within the Record and will also * receive whether or not it is a leaf node. * @param {Ext.data.Record} node */ getItemTextTpl: function(node) { return '{' + this.displayField + '}'; }, /** * Override this method to provide custom template rendering of titles/back * buttons when useTitleAsBackText is enabled. * @param {Ext.data.Record} node */ getTitleTextTpl: function(node) { return '{' + this.displayField + '}'; }, // private renderTitleText: function(node) { // caching this on the record/node // could store in an internal cache via id // so that we could clean it up if (!node.titleTpl) { node.titleTpl = new Ext.XTemplate(this.getTitleTextTpl(node)); } var record = node.getRecord(); if (record) { return node.titleTpl.applyTemplate(record.data); } else if (node.isRoot) { return this.title || this.backText; // <debug> } else { throw new Error("No RecordNode passed into renderTitleText"); } // </debug> }, /** * @property toolbar * Ext.Toolbar shared across each of the lists. * This will only exist when useToolbar is true which * is the default. */ useToolbar: true, /** * @property store * Ext.data.TreeStore */ /** * @cfg {Ext.data.TreeStore} store * The {@link Ext.data.TreeStore} to bind this NestedList to. */ /** * Implement getDetailCard to provide a final card for leaf nodes when useDetailCard * is enabled. getDetailCard will be passed the currentRecord and the parentRecord. * The default implementation will return false * @param {Ext.data.Record} record * @param {Ext.data.Record} parentRecord */ getDetailCard: function(recordNode, parentNode) { return false; }, initComponent : function() { //<deprecated since=0.99> if (Ext.isDefined(this.clearSelectionDefer)) { console.warn("NestedList: clearSelectionDefer has been removed. Please use clearSelectionDelay."); this.clearSelectionDelay = this.clearSelectionDefer; } if (Ext.isDefined(this.disclosure)) { console.warn("NestedList: disclosure has been removed. Please use onItemDisclosure"); this.onItemDisclosure = this.disclosure; } //</deprecated> var store = Ext.StoreMgr.lookup(this.store), rootNode = store.getRootNode(), title = rootNode.getRecord() ? this.renderTitleText(rootNode) : this.title || ''; this.store = store; if (this.useToolbar) { // Add the back button this.backButton = new Ext.Button({ text: this.backText, ui: 'back', handler: this.onBackTap, scope: this, // First stack doesn't show back hidden: true }); if (!this.toolbar || !this.toolbar.isComponent) { /** * @cfg {Object} toolbar * Configuration for the Ext.Toolbar that is created within the Ext.NestedList. */ this.toolbar = Ext.apply({}, this.toolbar || {}, { dock: 'top', xtype: 'toolbar', ui: 'light', title: title, items: [] }); this.toolbar.items.unshift(this.backButton); this.toolbar = new Ext.Toolbar(this.toolbar); this.dockedItems = this.dockedItems || []; this.dockedItems.push(this.toolbar); } else { this.toolbar.insert(0, this.backButton); } } this.items = [this.getSubList(rootNode)]; Ext.NestedList.superclass.initComponent.call(this); this.on('itemtap', this.onItemTap, this); this.addEvents( /** * @event itemtap * Fires when a node is tapped on * @param {Ext.List} list The Ext.List that is currently active * @param {Number} index The index of the item that was tapped * @param {Ext.Element} item The item element * @param {Ext.EventObject} e The event object */ /** * @event itemdoubletap * Fires when a node is double tapped on * @param {Ext.List} list The Ext.List that is currently active * @param {Number} index The index of the item that was tapped * @param {Ext.Element} item The item element * @param {Ext.EventObject} e The event object */ /** * @event containertap * Fires when a tap occurs and it is not on a template node. * @param {Ext.List} list The Ext.List that is currently active * @param {Ext.EventObject} e The raw event object */ /** * @event selectionchange * Fires when the selected nodes change. * @param {Ext.List} list The Ext.List that is currently active * @param {Array} selections Array of the selected nodes */ /** * @event beforeselect * Fires before a selection is made. If any handlers return false, the selection is cancelled. * @param {Ext.List} list The Ext.List that is currently active * @param {HTMLElement} node The node to be selected * @param {Array} selections Array of currently selected nodes */ // new events. /** * @event listchange * Fires when the user taps a list item * @param {Ext.NestedList} this * @param {Object} listitem */ 'listchange', /** * @event leafitemtap * Fires when the user taps a leaf list item * @param {Ext.List} subList The subList the item is on * @param {Number} subIdx The id of the item tapped * @param {Ext.Element} el The element of the item tapped * @param {Ext.EventObject} e The event * @param {Ext.Panel} card The next card to be shown */ 'leafitemtap' ); }, /** * @private * Returns the list config for a specified node. * @param {HTMLElement} node The node for the list config */ getListConfig: function(node) { var itemId = node.internalId, emptyText = this.emptyText; return { itemId: itemId, xtype: 'list', autoDestroy: true, recordNode: node, store: this.store.getSubStore(node), loadingText: this.loadingText, onItemDisclosure: this.onItemDisclosure, displayField: this.displayField, singleSelect: true, clearSelectionOnDeactivate: false, bubbleEvents: [ 'itemtap', 'containertap', 'beforeselect', 'itemdoubletap', 'selectionchange' ], itemTpl: '<span<tpl if="leaf == true"> class="x-list-item-leaf"</tpl>>' + this.getItemTextTpl(node) + '</span>', deferEmptyText: true, allowDeselect: this.allowDeselect, refresh: function() { if (this.hasSkippedEmptyText) { this.emptyText = emptyText; } Ext.List.prototype.refresh.apply(this, arguments); } }; }, /** * Returns the subList for a specified node * @param {HTMLElement} node The node for the subList */ getSubList: function(node) { var items = this.items, list, itemId = node.internalId; // can be invoked prior to items being transformed into // a MixedCollection if (items && items.get) { list = items.get(itemId); } if (list) { return list; } else { return this.getListConfig(node); } }, addNextCard: function(recordNode, swapTo) { var nextList, parentNode = recordNode ? recordNode.parentNode : null, card; if (recordNode.leaf) { card = this.getDetailCard(recordNode, parentNode); if (card) { nextList = this.add(card); } } else { nextList = this.getSubList(recordNode); nextList = this.add(nextList); } return nextList; }, setActivePath: function(path) { // a forward leading slash indicates to go // to root, otherwise its relative to current // position var gotoRoot = path.substr(0, 1) === "/", j = 0, ds = this.store, tree = ds.tree, node, card, lastCard, pathArr, pathLn; if (gotoRoot) { path = path.substr(1); } pathArr = Ext.toArray(path.split('/')); pathLn = pathArr.length; if (gotoRoot) { // clear all but first item var items = this.items, itemsArray = this.items.items, i = items.length; for (; i > 1; i--) { this.remove(itemsArray[i - 1], true); } // verify last item left matches first item in pathArr // <debug> var rootNode = itemsArray[0].recordNode; if (rootNode.id !== pathArr[0]) { throw new Error("rootNode doesn't match!"); } // </debug> // skip the 0 item rather than remove/add j = 1; } // loop through the path and add cards for (; j < pathLn; j++) { if (pathArr[j] !== "") { node = tree.getNodeById(pathArr[j]); // currently adding cards and not verifying // that they are true child nodes of the current parent // this would be some good debug tags. card = this.addNextCard(node); // leaf nodes may or may not have a card // therefore we need a temp var (lastCard) if (card) { lastCard = card; } } } // <debug> if (!lastCard) { throw new Error("Card was not found when trying to add to NestedList."); } // </debug> this.setActiveItem(lastCard, false); this.syncToolbar(); }, syncToolbar: function(card) { var list = card || this.getActiveItem(), depth = this.items.indexOf(list), recordNode = list.recordNode, parentNode = recordNode ? recordNode.parentNode : null, backBtn = this.backButton, backBtnText = this.useTitleAsBackText && parentNode ? this.renderTitleText(parentNode) : this.backText, backToggleMth = (depth !== 0) ? 'show' : 'hide'; if (backBtn) { backBtn[backToggleMth](); if (parentNode) { backBtn.setText(backBtnText); } } if (this.toolbar && this.updateTitleText) { this.toolbar.setTitle(recordNode && recordNode.getRecord() ? this.renderTitleText(recordNode) : this.title || ''); this.toolbar.doLayout(); } }, /** * Called when an list item has been tapped * @param {Ext.List} subList The subList the item is on * @param {Number} subIdx The id of the item tapped * @param {Ext.Element} el The element of the item tapped * @param {Ext.EventObject} e The event */ onItemTap: function(subList, subIdx, el, e) { var store = subList.getStore(), record = store.getAt(subIdx), recordNode = record.node, parentNode = recordNode ? recordNode.parentNode : null, displayField = this.displayField, backToggleMth, nextDepth, nextList; nextList = this.addNextCard(recordNode); if (recordNode.leaf) { this.fireEvent("leafitemtap", subList, subIdx, el, e, nextList); } if (nextList) { // depth should be based off record // and TreeStore rather than items. nextDepth = this.items.indexOf(nextList); this.setActiveItem(nextList, { type: this.cardSwitchAnimation }); this.syncToolbar(nextList); } }, /** * Called when the {@link #backButton} has been tapped */ onBackTap: function() { var currList = this.getActiveItem(), currIdx = this.items.indexOf(currList); if (currIdx != 0) { var prevDepth = currIdx - 1, prevList = this.items.getAt(prevDepth), recordNode = prevList.recordNode, record = recordNode.getRecord(), parentNode = recordNode ? recordNode.parentNode : null, backBtn = this.backButton, backToggleMth = (prevDepth !== 0) ? 'show' : 'hide', backBtnText; this.on('cardswitch', function(newCard, oldCard) { var selModel = prevList.getSelectionModel(); this.remove(currList); if (this.clearSelectionDelay) { Ext.defer(selModel.deselectAll, this.clearSelectionDelay, selModel); } }, this, {single: true}); this.setActiveItem(prevList, { type: this.cardSwitchAnimation, reverse: true, scope: this }); this.syncToolbar(prevList); } } }); Ext.reg('nestedlist', Ext.NestedList);
JavaScript
/** * @class Ext.Carousel * @extends Ext.Panel * * <p>A customized Panel which provides the ability to slide back and forth between * different child items.</p> * * <h2>Useful Properties</h2> * <ul class="list"> * <li>{@link #ui} (defines the style of the carousel)</li> * <li>{@link #direction} (defines the direction of the carousel)</li> * <li>{@link #indicator} (defines if the indicator show be shown)</li> * </ul> * * <h2>Useful Methods</h2> * <ul class="list"> * <li>{@link #next} (moves to the next card)</li> * <li>{@link #prev} (moves to the previous card)</li> * <li>{@link #setActiveItem} (moves to the passed card)</li> * </ul> * * <h2>Screenshot:</h2> * <p><img src="doc_resources/Ext.Carousel/screenshot.png" /></p> * * <h2>Example code:</h2> <pre><code> var carousel = new Ext.Carousel({ items: [ { html: '&lt;p&gt;Navigate the carousel on this page by swiping left/right.&lt;/p&gt;', cls : 'card card1' }, { html: '&lt;p&gt;Clicking on either side of the indicators below&lt;/p&gt;', cls : 'card card2' }, { html: 'Card #3', cls : 'card card3' } ] }); var panel = new Ext.Panel({ cls: 'cards', layout: { type : 'vbox', align: 'stretch' }, defaults: { flex: 1 }, items: [ carousel, { xtype : 'carousel', ui : 'light', direction: 'vertical', items: [ { html: '&lt;p&gt;Carousels can be vertical and given a ui of "light" or "dark".&lt;/p&gt;', cls : 'card card1' }, { html: 'Card #2', cls : 'card card2' }, { html: 'Card #3', cls : 'card card3' } ] } ] }); </code></pre> * @xtype carousel */ Ext.Carousel = Ext.extend(Ext.Panel, { /** * @cfg {String} baseCls * The base CSS class to apply to the Carousel's element (defaults to <code>'x-carousel'</code>). */ baseCls: 'x-carousel', /** * @cfg {Boolean} indicator * Provides an indicator while toggling between child items to let the user * know where they are in the card stack. */ indicator: true, /** * @cfg {String} ui * Style options for Carousel. Default is 'dark'. 'light' is also available. */ ui: 'dark', /** * @cfg {String} direction * The direction of the Carousel. Default is 'horizontal'. 'vertical' also available. */ direction: 'horizontal', // @private horizontal: false, // @private vertical: false, // @private initComponent: function() { this.layout = { type: 'card', // This will set the size of all cards in this container on each layout sizeAllCards: true, // This will prevent the hiding of items on card switch hideInactive: false, itemCls: 'x-carousel-item', targetCls: 'x-carousel-body', setOwner : function(owner) { Ext.layout.CardLayout.superclass.setOwner.call(this, owner); } }; if (this.indicator) { var cfg = Ext.isObject(this.indicator) ? this.indicator : {}; this.indicator = new Ext.Carousel.Indicator(Ext.apply({}, cfg, { direction: this.direction, carousel: this, ui: this.ui })); } if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } Ext.Carousel.superclass.initComponent.call(this); }, // @private afterRender: function() { Ext.Carousel.superclass.afterRender.call(this); // Bind the required listeners this.mon(this.body, { dragstart: this.onDragStart, drag: this.onDrag, dragThreshold: 6, dragend: this.onDragEnd, direction: this.direction, disableLocking: true, scope: this }); this.el.addCls(this.baseCls + '-' + this.direction); }, onDragStart : function(e) { var gesture = e.gesture, type = e.type; // If the gesture is locked, it means that a scroller or other inner element is listening for drag events // and locking the gesture. In this case we want to check if we are at the boundaries of that scroller. // If so, then we perform the carousel's behavior, else let the inner dragging thingy do its thingy. if (gesture.isLocked(type)) { var lockingGesture = gesture.getLockingGesture(type), lockingTarget = lockingGesture.target, scrollEl = Ext.get(lockingTarget).down('.x-scroller'), scroller = scrollEl && scrollEl.getScrollParent(); if (scroller && ((scroller.vertical && this.vertical) || (scroller.horizontal && this.vertical))) { this.inScrollBounds = false; this.checkScrollBounds = scroller; } else { e.gesture.stop(); } } else { e.gesture.disableLocking = false; e.gesture.lock(); } }, /** * The afterLayout method on the carousel just makes sure the active card * is still into view. It also makes sure the indicator is pointing to * the right card. * @private */ afterLayout : function() { Ext.Carousel.superclass.afterLayout.apply(this, arguments); this.currentSize = this.body.getSize(); this.currentScroll = {x: 0, y: 0}; this.updateCardPositions(); var activeItem = this.layout.getActiveItem(); if (activeItem && this.indicator) { this.indicator.onBeforeCardSwitch(this, activeItem, null, this.items.indexOf(activeItem)); } }, /** * The onDrag method sets the currentScroll object. It also slows down the drag * if we are at the bounds of the carousel. * @private */ onDrag : function(e) { this.currentScroll = { x: e.deltaX, y: e.deltaY }; var scroller = this.checkScrollBounds; if (scroller) { var offset = scroller.getNewOffsetFromTouchPoint(Ext.util.Point.fromEvent(e)); if ( (this.vertical && !scroller.offsetBoundary.isOutOfBound('y', offset.y)) || (this.horizontal && !scroller.offsetBoundary.isOutOfBound('x', offset.x)) ) { if (this.outOfScrollBounds) { this.outOfScrollBounds = false; this.checkDragEnd = false; scroller.onStart(e); } return; } else { if (!this.outOfScrollBounds) { this.checkDragEnd = true; this.outOfScrollBounds = true; scroller.scrollView.hideIndicators(); Ext.apply(e.gesture, { startX: e.pageX, startY: e.pageY, startTime: e.time }); return; } } } // Slow the drag down in the bounce var activeIndex = this.items.items.indexOf(this.layout.activeItem); // If this is a horizontal carousel if (this.horizontal) { if ( // And we are on the first card and dragging left (activeIndex == 0 && e.deltaX > 0) || // Or on the last card and dragging right (activeIndex == this.items.length - 1 && e.deltaX < 0) ) { if (scroller) { // If there is a scroller, then we let the scroller handle the bounce return; } else { // Then slow the drag down this.currentScroll.x = e.deltaX / 2; } } else if (scroller) { scroller.isDragging = false; } } // If this is a vertical carousel else if (this.vertical) { if ( // And we are on the first card and dragging up (activeIndex == 0 && e.deltaY > 0) || // Or on the last card and dragging down (activeIndex == this.items.length - 1 && e.deltaY < 0) ) { if (scroller) { // If there is a scroller, then we let the scroller handle the bounce return; } else { // Then slow the drag down this.currentScroll.y = e.deltaY / 2; } } else if (scroller) { scroller.isDragging = false; } } // This will update all the cards to their correct position based on the current drag this.updateCardPositions(); }, /** * This will update all the cards to their correct position based on the current drag. * It can be passed true to animate the position updates. * @private */ updateCardPositions : function(animate) { var cards = this.items.items, ln = cards.length, cardOffset, i, card, el, style; // Now we loop over the items and position the active item // in the middle of the strip, and the two items on either // side to the left and right. for (i = 0; i < ln; i++) { card = cards[i]; // This means the items is within 2 cards of the active item if (this.isCardInRange(card)) { if (card.hidden) { card.show(); } el = card.el; style = el.dom.style; if (animate) { if (card === this.layout.activeItem) { el.on('webkitTransitionEnd', this.onTransitionEnd, this, {single: true}); } style.webkitTransitionDuration = '300ms'; } else { style.webkitTransitionDuration = '0ms'; } cardOffset = this.getCardOffset(card); if (this.horizontal) { Ext.Element.cssTransform(el, {translate: [cardOffset, 0]}); } else { Ext.Element.cssTransform(el, {translate: [0, cardOffset]}); } } else if (!card.hidden) { // All other items we position far away card.hide(); } } }, /** * Returns the amount of pixels from the current drag to a card. * @private */ getCardOffset : function(card) { var cardOffset = this.getCardIndexOffset(card), currentSize = this.currentSize, currentScroll = this.currentScroll; return this.horizontal ? (cardOffset * currentSize.width) + currentScroll.x : (cardOffset * currentSize.height) + currentScroll.y; }, /** * Returns the difference between the index of the active card and the passed card. * @private */ getCardIndexOffset : function(card) { return this.items.items.indexOf(card) - this.getActiveIndex(); }, /** * Returns true if the passed card is within 2 cards from the active card. * @private */ isCardInRange : function(card) { return Math.abs(this.getCardIndexOffset(card)) <= 2; }, /** * Returns the index of the currently active card. * @return {Number} The index of the currently active card. */ getActiveIndex : function() { return this.items.indexOf(this.layout.activeItem); }, /** * This determines if we are going to the next card, the previous card, or back to the active card. * @private */ onDragEnd : function(e, t) { e.gesture.disableLocking = true; if (this.checkScrollBounds && !this.outOfScrollBounds) { return; } var previousDelta, deltaOffset; if (this.horizontal) { deltaOffset = e.deltaX; previousDelta = e.previousDeltaX; } else { deltaOffset = e.deltaY; previousDelta = e.previousDeltaY; } // We have gone to the right if (deltaOffset < 0 && Math.abs(deltaOffset) > 3 && previousDelta <= 0 && this.layout.getNext()) { this.next(); } // We have gone to the left else if (deltaOffset > 0 && Math.abs(deltaOffset) > 3 && previousDelta >= 0 && this.layout.getPrev()) { this.prev(); } else { // drag back to current active card this.scrollToCard(this.layout.activeItem); } }, /** * Here we make sure that the card we are switching to is not translated * by the carousel anymore. This is only if we are switching card using * the setActiveItem of setActiveItem methods and thus customDrag is not set * to true. * @private */ onBeforeCardSwitch : function(newCard) { if (!this.customDrag && this.items.indexOf(newCard) != -1) { var style = newCard.el.dom.style; style.webkitTransitionDuration = null; style.webkitTransform = null; } return Ext.Carousel.superclass.onBeforeCardSwitch.apply(this, arguments); }, /** * This is an internal function that is called in onDragEnd that goes to * the next or previous card. * @private */ scrollToCard : function(newCard) { this.currentScroll = {x: 0, y: 0}; this.oldCard = this.layout.activeItem; if (newCard != this.oldCard && this.isCardInRange(newCard) && this.onBeforeCardSwitch(newCard, this.oldCard, this.items.indexOf(newCard), true) !== false) { this.layout.activeItem = newCard; if (this.horizontal) { this.currentScroll.x = -this.getCardOffset(newCard); } else { this.currentScroll.y = -this.getCardOffset(newCard); } } this.updateCardPositions(true); }, // @private onTransitionEnd : function(e, t) { this.customDrag = false; this.currentScroll = {x: 0, y: 0}; if (this.oldCard && this.layout.activeItem != this.oldCard) { this.onCardSwitch(this.layout.activeItem, this.oldCard, this.items.indexOf(this.layout.activeItem), true); } delete this.oldCard; }, /** * This function makes sure that all the cards are in correct locations * after a card switch * @private */ onCardSwitch : function(newCard, oldCard, index, animated) { this.currentScroll = {x: 0, y: 0}; this.updateCardPositions(); Ext.Carousel.superclass.onCardSwitch.apply(this, arguments); newCard.fireEvent('activate', newCard); }, /** * Switches the next card */ next: function() { var next = this.layout.getNext(); if (next) { this.customDrag = true; this.scrollToCard(next); } return this; }, /** * Switches the previous card */ prev: function() { var prev = this.layout.getPrev(); if (prev) { this.customDrag = true; this.scrollToCard(prev); } return this; }, /** * Method to determine whether this Sortable is currently disabled. * @return {Boolean} the disabled state of this Sortable. */ isVertical : function() { return this.vertical; }, /** * Method to determine whether this Sortable is currently sorting. * @return {Boolean} the sorting state of this Sortable. */ isHorizontal : function() { return this.horizontal; } }); Ext.reg('carousel', Ext.Carousel); /** * @class Ext.Carousel.Indicator * @extends Ext.Component * @xtype carouselindicator * @private * * A private utility class used by Ext.Carousel to create indicators. */ Ext.Carousel.Indicator = Ext.extend(Ext.Component, { baseCls: 'x-carousel-indicator', initComponent: function() { if (this.carousel.rendered) { this.render(this.carousel.body); this.onBeforeCardSwitch(null, null, this.carousel.items.indexOf(this.carousel.layout.getActiveItem())); } else { this.carousel.on('render', function() { this.render(this.carousel.body); }, this, {single: true}); } Ext.Carousel.Indicator.superclass.initComponent.call(this); }, // @private onRender: function() { Ext.Carousel.Indicator.superclass.onRender.apply(this, arguments); for (var i = 0, ln = this.carousel.items.length; i < ln; i++) { this.createIndicator(); } this.mon(this.carousel, { beforecardswitch: this.onBeforeCardSwitch, add: this.onCardAdd, remove: this.onCardRemove, scope: this }); this.mon(this.el, { tap: this.onTap, scope: this }); this.el.addCls(this.baseCls + '-' + this.direction); }, // @private onTap: function(e, t) { var box = this.el.getPageBox(), centerX = box.left + (box.width / 2), centerY = box.top + (box.height / 2); if ( (this.carousel.direction == 'horizontal' && e.pageX > centerX) || (this.carousel.direction == 'vertical' && e.pageY > centerY) ) { this.carousel.next(); } else { this.carousel.prev(); } }, // @private createIndicator: function() { this.indicators = this.indicators || []; this.indicators.push(this.el.createChild({ tag: 'span' })); }, // @private onBeforeCardSwitch: function(carousel, card, old, index) { if (Ext.isNumber(index) && index != -1 && this.indicators[index]) { this.indicators[index].radioCls('x-carousel-indicator-active'); } }, // @private onCardAdd: function() { this.createIndicator(); }, // @private onCardRemove: function() { this.indicators.pop().remove(); } }); Ext.reg('carouselindicator', Ext.Carousel.Indicator);
JavaScript
Ext.applyIf(Ext.Element, { /** * Returns the calculated CSS 2D transform offset values (translate x and y) * @param {Ext.Element/Element} el the element * @return {Ext.util.Offset} instance of Ext.util.Offset, with x and y properties */ getComputedTransformOffset: function(el) { if (el instanceof Ext.Element) el = el.dom; var cssMatrix = new WebKitCSSMatrix(window.getComputedStyle(el).webkitTransform); if (typeof cssMatrix.m41 != 'undefined') { return new Ext.util.Offset(cssMatrix.m41, cssMatrix.m42); } else if (typeof cssMatrix.d != 'undefined') { return new Ext.util.Offset(cssMatrix.d, cssMatrix.e); } return new Ext.util.Offset(0, 0); }, /** * Transform an element using CSS 3 * @param {Ext.Element/Element} el the element * @param {Object} transforms an object with all transformation to be applied. The keys are transformation method names, * the values are arrays of params or a single number if there's only one param e.g: * { * translate: [0, 1, 2], * scale: 0.5, * skew: -25, * rotate: 7 * } */ cssTransform: function(el, transforms) { if (el instanceof Ext.Element) el = el.dom; var m = new WebKitCSSMatrix(); Ext.iterate(transforms, function(n, v) { v = Ext.isArray(v) ? v : [v]; m = m[n].apply(m, v); }); // To enable hardware accelerated transforms on iOS (v3 only, fixed in v4?) we have to build the string manually // Other than that simply apply the matrix works perfectly on all the rest of devices if (Ext.supports.CSS3DTransform) { el.style.webkitTransform = 'matrix3d(' + m.m11+', '+m.m12+', '+m.m13+', '+m.m14+', '+ m.m21+', '+m.m22+', '+m.m23+', '+m.m24+', '+ m.m31+', '+m.m32+', '+m.m33+', '+m.m34+', '+ m.m41+', '+m.m42+', '+m.m43+', '+m.m44+ ')'; } else { el.style.webkitTransform = m; } } });
JavaScript
/** * @class Ext.Anim * @extends Object * <p>Ext.Anim is used to excute animations defined in {@link Ext.anims}. The {@link #run} method can take any of the * properties defined below.</p> * * <h2>Example usage:</h2> * <code><pre> Ext.Anim.run(this, 'fade', { out: false, autoClear: true }); * </pre></code> * * <p>Animations are disabled on Android and Blackberry by default using the {@link #disableAnimations} property.</p> * @singleton */ Ext.Anim = Ext.extend(Object, { isAnim: true, /** * @cfg {Boolean} disableAnimations * True to disable animations. By default, animations are disabled on Android and Blackberry */ disableAnimations: false, // disableAnimations: (Ext.is.Android || Ext.is.Blackberry) ? true : false, defaultConfig: { /** * @cfg {Object} from * An object of CSS values which the animation begins with. If you define a CSS property here, you must also * define it in the {@link #to} config. */ from: {}, /** * @cfg {Object} to * An object of CSS values which the animation ends with. If you define a CSS property here, you must also * define it in the {@link #from} config. */ to: {}, /** * @cfg {Number} duration * Time in milliseconds for the animation to last. * (Defaults to 250). */ duration: 250, /** * @cfg {Number} delay Time to delay before starting the animation. * (Defaults to 0). */ delay: 0, /** * @cfg {String} easing * Valid values are 'ease', 'linear', ease-in', 'ease-out', 'ease-in-out' or a cubic-bezier curve as defined by CSS. * (Defaults to 'ease-in-out'). */ easing: 'ease-in-out', /** * @cfg {Boolean} autoClear * True to remove all custom CSS defined in the {@link #to} config when the animation is over. * (Defaults to true). */ autoClear: true, /** * @cfg {Boolean} out * True if you want the animation to slide out of the screen. * (Defaults to true). */ out: true, /** * @cfg {String} direction * Valid values are 'left', 'right', 'up', 'down' and null. * (Defaults to null). */ direction: null, /** * @cfg {Boolean} reverse * True to reverse the animation direction. For example, if the animation direction was set to 'left', it would * then use 'right'. * (Defaults to false). */ reverse: false }, /** * @cfg {Function} before * Code to execute before starting the animation. */ /** * @cfg {Scope} scope * Scope to run the {@link before} function in. */ opposites: { 'left': 'right', 'right': 'left', 'up': 'down', 'down': 'up' }, constructor: function(config) { config = Ext.apply({}, config || {}, this.defaultConfig); this.config = config; Ext.Anim.superclass.constructor.call(this); this.running = []; }, initConfig : function(el, runConfig) { var me = this, runtime = {}, config = Ext.apply({}, runConfig || {}, me.config); config.el = el = Ext.get(el); if (config.reverse && me.opposites[config.direction]) { config.direction = me.opposites[config.direction]; } if (me.config.before) { me.config.before.call(config, el, config); } if (runConfig.before) { runConfig.before.call(config.scope || config, el, config); } return config; }, run: function(el, config) { el = Ext.get(el); config = config || {}; var me = this, style = el.dom.style, property, after = config.after; config = this.initConfig(el, config); if (this.disableAnimations) { for (property in config.to) { if (!config.to.hasOwnProperty(property)) { continue; } style[property] = config.to[property]; } this.onTransitionEnd(null, el, { config: config, after: after }); return me; } el.un('webkitTransitionEnd', me.onTransitionEnd, me); style.webkitTransitionDuration = '0ms'; for (property in config.from) { if (!config.from.hasOwnProperty(property)) { continue; } style[property] = config.from[property]; } setTimeout(function() { // If this element has been destroyed since the timeout started, do nothing if (!el.dom) { return; } // If this is a 3d animation we have to set the perspective on the parent if (config.is3d === true) { el.parent().setStyle({ // TODO: Ability to set this with 3dConfig '-webkit-perspective': '1200', '-webkit-transform-style': 'preserve-3d' }); } style.webkitTransitionDuration = config.duration + 'ms'; style.webkitTransitionProperty = 'all'; style.webkitTransitionTimingFunction = config.easing; // Bind our listener that fires after the animation ends el.on('webkitTransitionEnd', me.onTransitionEnd, me, { single: true, config: config, after: after }); for (property in config.to) { if (!config.to.hasOwnProperty(property)) { continue; } style[property] = config.to[property]; } }, config.delay || 5); me.running[el.id] = config; return me; }, onTransitionEnd: function(ev, el, o) { el = Ext.get(el); var style = el.dom.style, config = o.config, property, me = this; if (config.autoClear) { for (property in config.to) { if (!config.to.hasOwnProperty(property)) { continue; } style[property] = ''; } } style.webkitTransitionDuration = null; style.webkitTransitionProperty = null; style.webkitTransitionTimingFunction = null; if (config.is3d) { el.parent().setStyle({ '-webkit-perspective': '', '-webkit-transform-style': '' }); } if (me.config.after) { me.config.after.call(config, el, config); } if (o.after) { o.after.call(config.scope || me, el, config); } delete me.running[el.id]; } }); Ext.Anim.seed = 1000; /** * Used to run an animation on a specific element. Use the config argument to customize the animation * @param {Ext.Element/Element} el The element to animate * @param {String} anim The animation type, defined in {@link #Ext.anims} * @param {Object} config The config object for the animation * @method run */ Ext.Anim.run = function(el, anim, config) { if (el.isComponent) { el = el.el; } config = config || {}; if (anim.isAnim) { anim.run(el, config); } else { if (Ext.isObject(anim)) { if (config.before && anim.before) { config.before = Ext.createInterceptor(config.before, anim.before, anim.scope); } if (config.after && anim.after) { config.after = Ext.createInterceptor(config.after, anim.after, anim.scope); } config = Ext.apply({}, config, anim); anim = anim.type; } if (!Ext.anims[anim]) { throw anim + ' is not a valid animation type.'; } else { // add el check to make sure dom exists. if (el && el.dom) { Ext.anims[anim].run(el, config); } } } }; /** * @class Ext.anims * <p>Defines different types of animations. <strong>flip, cube, wipe</strong> animations do not work on Android.</p> * <p>Please refer to {@link Ext.Anim} on how to use animations.</p> * @singleton */ Ext.anims = { /** * Fade Animation */ fade: new Ext.Anim({ before: function(el) { var fromOpacity = 1, toOpacity = 1, curZ = el.getStyle('z-index') == 'auto' ? 0 : el.getStyle('z-index'), zIndex = curZ; if (this.out) { toOpacity = 0; } else { zIndex = curZ + 1; fromOpacity = 0; } this.from = { 'opacity': fromOpacity, 'z-index': zIndex }; this.to = { 'opacity': toOpacity, 'z-index': zIndex }; } }), /** * Slide Animation */ slide: new Ext.Anim({ direction: 'left', cover: false, reveal: false, before: function(el) { var curZ = el.getStyle('z-index') == 'auto' ? 0 : el.getStyle('z-index'), zIndex = curZ + 1, toX = 0, toY = 0, fromX = 0, fromY = 0, elH = el.getHeight(), elW = el.getWidth(); if (this.direction == 'left' || this.direction == 'right') { if (this.out == true) { toX = -elW; } else { fromX = elW; } } else if (this.direction == 'up' || this.direction == 'down') { if (this.out == true) { toY = -elH; } else { fromY = elH; } } if (this.direction == 'right' || this.direction == 'down') { toY *= -1; toX *= -1; fromY *= -1; fromX *= -1; } if (this.cover && this.out) { toX = 0; toY = 0; zIndex = curZ; } else if (this.reveal && !this.out) { fromX = 0; fromY = 0; zIndex = curZ; } this.from = { '-webkit-transform': 'translate3d(' + fromX + 'px, ' + fromY + 'px, 0)', 'z-index': zIndex, 'opacity': 0.99 }; this.to = { '-webkit-transform': 'translate3d(' + toX + 'px, ' + toY + 'px, 0)', 'z-index': zIndex, 'opacity': 1 }; } }), /** * Pop Animation */ pop: new Ext.Anim({ scaleOnExit: true, before: function(el) { var fromScale = 1, toScale = 1, fromOpacity = 1, toOpacity = 1, curZ = el.getStyle('z-index') == 'auto' ? 0 : el.getStyle('z-index'), fromZ = curZ, toZ = curZ; if (!this.out) { fromScale = 0.01; fromZ = curZ + 1; toZ = curZ + 1; fromOpacity = 0; } else { if (this.scaleOnExit) { toScale = 0.01; toOpacity = 0; } else { toOpacity = 0.8; } } this.from = { '-webkit-transform': 'scale(' + fromScale + ')', '-webkit-transform-origin': '50% 50%', 'opacity': fromOpacity, 'z-index': fromZ }; this.to = { '-webkit-transform': 'scale(' + toScale + ')', '-webkit-transform-origin': '50% 50%', 'opacity': toOpacity, 'z-index': toZ }; } }) };
JavaScript
/** * @class Ext.DomHelper * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates * from your DOM building code.</p> * * <p><b><u>DomHelper element specification object</u></b></p> * <p>A specification object is used when creating elements. Attributes of this object * are assumed to be element attributes, except for 4 special attributes: * <div class="mdetail-params"><ul> * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li> * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the * same kind of element definition objects to be created and appended. These can be nested * as deep as you want.</div></li> * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element. * This will end up being either the "class" attribute on a HTML fragment or className * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li> * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li> * </ul></div></p> * * <p><b><u>Insertion methods</u></b></p> * <p>Commonly used insertion methods: * <div class="mdetail-params"><ul> * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li> * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li> * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li> * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li> * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li> * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li> * </ul></div></p> * * <p><b><u>Example</u></b></p> * <p>This is an example, where an unordered list with 3 children items is appended to an existing * element with id <tt>'my-div'</tt>:<br> <pre><code> var dh = Ext.DomHelper; // create shorthand alias // specification object var spec = { id: 'my-ul', tag: 'ul', cls: 'my-list', // append children after creating children: [ // may also specify 'cn' instead of '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'} ] }; var list = dh.append( 'my-div', // the context element 'my-div' can either be the id or the actual node spec // the specification object ); </code></pre></p> * <p>Element creation specification parameters in this class may also be passed as an Array of * specification objects. This can be used to insert multiple sibling nodes into an existing * container very efficiently. For example, to add more list items to the example above:<pre><code> dh.append('my-ul', [ {tag: 'li', id: 'item3', html: 'List Item 3'}, {tag: 'li', id: 'item4', html: 'List Item 4'} ]); * </code></pre></p> * * <p><b><u>Templating</u></b></p> * <p>The real power is in the built-in templating. Instead of creating or appending any elements, * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to * insert new elements. Revisiting the example above, we could utilize templating this time: * <pre><code> // create the node var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'}); // get template var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'}); for(var i = 0; i < 5, i++){ tpl.append(list, [i]); // use template to append to the actual node } * </code></pre></p> * <p>An example using a template:<pre><code> var html = '<a id="{0}" href="{1}" class="nav">{2}</a>'; var tpl = new Ext.DomHelper.createTemplate(html); tpl.append('blog-roll', ['link1', 'http://www.tommymaintz.com/', "Tommy&#39;s Site"]); tpl.append('blog-roll', ['link2', 'http://www.avins.org/', "Jamie&#39;s Site"]); * </code></pre></p> * * <p>The same example using named parameters:<pre><code> var html = '<a id="{id}" href="{url}" class="nav">{text}</a>'; var tpl = new Ext.DomHelper.createTemplate(html); tpl.append('blog-roll', { id: 'link1', url: 'http://www.tommymaintz.com/', text: "Tommy&#39;s Site" }); tpl.append('blog-roll', { id: 'link2', url: 'http://www.avins.org/', text: "Jamie&#39;s Site" }); * </code></pre></p> * * <p><b><u>Compiling Templates</u></b></p> * <p>Templates are applied using regular expressions. The performance is great, but if * you are adding a bunch of DOM elements using the same template, you can increase * performance even further by {@link Ext.Template#compile "compiling"} the template. * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and * broken up at the different variable points and a dynamic function is created and eval'ed. * The generated function performs string concatenation of these parts and the passed * variables instead of using regular expressions. * <pre><code> var html = '<a id="{id}" href="{url}" class="nav">{text}</a>'; var tpl = new Ext.DomHelper.createTemplate(html); tpl.compile(); //... use template like normal * </code></pre></p> * * <p><b><u>Performance Boost</u></b></p> * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead * of DOM can significantly boost performance.</p> * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>, * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification * results in the creation of a text node. Usage:</p> * <pre><code> Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance * </code></pre> * @singleton */ Ext.DomHelper = { emptyTags : /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i, confRe : /tag|children|cn|html$/i, endRe : /end/i, /** * Returns the markup for the passed Element(s) config. * @param {Object} o The DOM object spec (and children) * @return {String} */ markup : function(o) { var b = '', attr, val, key, keyVal, cn; if (typeof o == "string") { b = o; } else if (Ext.isArray(o)) { for (var i=0; i < o.length; i++) { if (o[i]) { b += this.markup(o[i]); } }; } else { b += '<' + (o.tag = o.tag || 'div'); for (attr in o) { if (!o.hasOwnProperty(attr)) { continue; } val = o[attr]; if (!this.confRe.test(attr)) { if (typeof val == "object") { b += ' ' + attr + '="'; for (key in val) { if (!val.hasOwnProperty(key)) { continue; } b += key + ':' + val[key] + ';'; }; b += '"'; } else { b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"'; } } }; // Now either just close the tag or try to add children and close the tag. if (this.emptyTags.test(o.tag)) { b += '/>'; } else { b += '>'; if ((cn = o.children || o.cn)) { b += this.markup(cn); } else if (o.html) { b += o.html; } b += '</' + o.tag + '>'; } } return b; }, /** * Applies a style specification to an element. * @param {String/HTMLElement} el The element to apply styles to * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or * a function which returns such a specification. */ applyStyles : function(el, styles) { if (styles) { var i = 0, len, style; el = Ext.fly(el); if (typeof styles == 'function') { styles = styles.call(); } if (typeof styles == 'string'){ styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); for(len = styles.length; i < len;){ el.setStyle(styles[i++], styles[i++]); } } else if (Ext.isObject(styles)) { el.setStyle(styles); } } }, /** * Inserts an HTML fragment into the DOM. * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd. * @param {HTMLElement} el The context element * @param {String} html The HTML fragment * @return {HTMLElement} The new node */ insertHtml : function(where, el, html) { var hash = {}, hashVal, setStart, range, frag, rangeEl, rs; where = where.toLowerCase(); // add these here because they are used in both branches of the condition. hash['beforebegin'] = ['BeforeBegin', 'previousSibling']; hash['afterend'] = ['AfterEnd', 'nextSibling']; range = el.ownerDocument.createRange(); setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before'); if (hash[where]) { range[setStart](el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, where == 'beforebegin' ? el : el.nextSibling); return el[(where == 'beforebegin' ? 'previous' : 'next') + 'Sibling']; } else { rangeEl = (where == 'afterbegin' ? 'first' : 'last') + 'Child'; if (el.firstChild) { range[setStart](el[rangeEl]); frag = range.createContextualFragment(html); if (where == 'afterbegin') { el.insertBefore(frag, el.firstChild); } else { el.appendChild(frag); } } else { el.innerHTML = html; } return el[rangeEl]; } throw 'Illegal insertion point -> "' + where + '"'; }, /** * Creates new DOM element(s) and inserts them before el. * @param {Mixed} el The context element * @param {Object/String} o The DOM object spec (and children) or raw HTML blob * @param {Boolean} returnElement (optional) true to return a Ext.Element * @return {HTMLElement/Ext.Element} The new node */ insertBefore : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'beforebegin'); }, /** * Creates new DOM element(s) and inserts them after el. * @param {Mixed} el The context element * @param {Object} o The DOM object spec (and children) * @param {Boolean} returnElement (optional) true to return a Ext.Element * @return {HTMLElement/Ext.Element} The new node */ insertAfter : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'afterend', 'nextSibling'); }, /** * Creates new DOM element(s) and inserts them as the first child of el. * @param {Mixed} el The context element * @param {Object/String} o The DOM object spec (and children) or raw HTML blob * @param {Boolean} returnElement (optional) true to return a Ext.Element * @return {HTMLElement/Ext.Element} The new node */ insertFirst : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'afterbegin', 'firstChild'); }, /** * Creates new DOM element(s) and appends them to el. * @param {Mixed} el The context element * @param {Object/String} o The DOM object spec (and children) or raw HTML blob * @param {Boolean} returnElement (optional) true to return a Ext.Element * @return {HTMLElement/Ext.Element} The new node */ append : function(el, o, returnElement) { return this.doInsert(el, o, returnElement, 'beforeend', '', true); }, /** * Creates new DOM element(s) and overwrites the contents of el with them. * @param {Mixed} el The context element * @param {Object/String} o The DOM object spec (and children) or raw HTML blob * @param {Boolean} returnElement (optional) true to return a Ext.Element * @return {HTMLElement/Ext.Element} The new node */ overwrite : function(el, o, returnElement) { el = Ext.getDom(el); el.innerHTML = this.markup(o); return returnElement ? Ext.get(el.firstChild) : el.firstChild; }, doInsert : function(el, o, returnElement, pos, sibling, append) { var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o)); return returnElement ? Ext.get(newNode, true) : newNode; } };
JavaScript
/** * @class Ext.anims */ Ext.apply(Ext.anims, { /** * Flip Animation */ flip: new Ext.Anim({ is3d: true, direction: 'left', before: function(el) { var rotateProp = 'Y', fromScale = 1, toScale = 1, fromRotate = 0, toRotate = 0; if (this.out) { toRotate = -180; toScale = 0.8; } else { fromRotate = 180; fromScale = 0.8; } if (this.direction == 'up' || this.direction == 'down') { rotateProp = 'X'; } if (this.direction == 'right' || this.direction == 'left') { toRotate *= -1; fromRotate *= -1; } this.from = { '-webkit-transform': 'rotate' + rotateProp + '(' + fromRotate + 'deg) scale(' + fromScale + ')', '-webkit-backface-visibility': 'hidden' }; this.to = { '-webkit-transform': 'rotate' + rotateProp + '(' + toRotate + 'deg) scale(' + toScale + ')', '-webkit-backface-visibility': 'hidden' }; } }), /** * Cube Animation */ cube: new Ext.Anim({ is3d: true, direction: 'left', style: 'outer', before: function(el) { var origin = '0% 0%', fromRotate = 0, toRotate = 0, rotateProp = 'Y', fromZ = 0, toZ = 0, fromOpacity = 1, toOpacity = 1, zDepth, elW = el.getWidth(), elH = el.getHeight(), showTranslateZ = true, fromTranslate = ' translateX(0)', toTranslate = ''; if (this.direction == 'left' || this.direction == 'right') { if (this.out) { origin = '100% 100%'; toZ = elW; toOpacity = 0.5; toRotate = -90; } else { origin = '0% 0%'; fromZ = elW; fromOpacity = 0.5; fromRotate = 90; } } else if (this.direction == 'up' || this.direction == 'down') { rotateProp = 'X'; if (this.out) { origin = '100% 100%'; toZ = elH; toRotate = 90; } else { origin = '0% 0%'; fromZ = elH; fromRotate = -90; } } if (this.direction == 'down' || this.direction == 'right') { fromRotate *= -1; toRotate *= -1; origin = (origin == '0% 0%') ? '100% 100%': '0% 0%'; } if (this.style == 'inner') { fromZ *= -1; toZ *= -1; fromRotate *= -1; toRotate *= -1; if (!this.out) { toTranslate = ' translateX(0px)'; origin = '0% 50%'; } else { toTranslate = fromTranslate; origin = '100% 50%'; } } this.from = { '-webkit-transform': 'rotate' + rotateProp + '(' + fromRotate + 'deg)' + (showTranslateZ ? ' translateZ(' + fromZ + 'px)': '') + fromTranslate, '-webkit-transform-origin': origin }; this.to = { '-webkit-transform': 'rotate' + rotateProp + '(' + toRotate + 'deg) translateZ(' + toZ + 'px)' + toTranslate, '-webkit-transform-origin': origin }; }, duration: 250 }), /** * Wipe Animation. * <p>Because of the amount of calculations involved, this animation is best used on small display * changes or specifically for phone environments. Does not currently accept any parameters.</p> */ wipe: new Ext.Anim({ before: function(el) { var curZ = el.getStyle('z-index'), mask = '', toSize = '100%', fromSize = '100%'; if (!this.out) { zIndex = curZ + 1; mask = '-webkit-gradient(linear, left bottom, right bottom, from(transparent), to(#000), color-stop(66%, #000), color-stop(33%, transparent))'; toSize = el.getHeight() * 100 + 'px'; fromSize = el.getHeight(); this.from = { '-webkit-mask-image': mask, '-webkit-mask-size': el.getWidth() * 3 + 'px ' + el.getHeight() + 'px', 'z-index': zIndex, '-webkit-mask-position-x': 0 }; this.to = { '-webkit-mask-image': mask, '-webkit-mask-size': el.getWidth() * 3 + 'px ' + el.getHeight() + 'px', 'z-index': zIndex, '-webkit-mask-position-x': -el.getWidth() * 2 + 'px' }; } }, duration: 500 }) });
JavaScript
/** * @class Ext.CompositeElement * <p>This class encapsulates a <i>collection</i> of DOM elements, providing methods to filter * members, or to perform collective actions upon the whole set.</p> * * Example:<pre><code> var els = Ext.select("#some-el div.some-class"); // or select directly from an existing element var el = Ext.get('some-el'); el.select('div.some-class'); els.setWidth(100); // all elements become 100 width els.hide(true); // all elements fade out and hide // or els.setWidth(100).hide(true); </code> */ Ext.CompositeElement = function(els, root) { /** * <p>The Array of DOM elements which this CompositeElement encapsulates. Read-only.</p> * <p>This will not <i>usually</i> be accessed in developers' code, but developers wishing * to augment the capabilities of the CompositeElement class may use it when adding * methods to the class.</p> * <p>For example to add the <code>nextAll</code> method to the class to <b>add</b> all * following siblings of selected elements, the code would be</p><code><pre> Ext.override(Ext.CompositeElement, { nextAll: function() { var els = this.elements, i, l = els.length, n, r = [], ri = -1; // Loop through all elements in this Composite, accumulating // an Array of all siblings. for (i = 0; i < l; i++) { for (n = els[i].nextSibling; n; n = n.nextSibling) { r[++ri] = n; } } // Add all found siblings to this Composite return this.add(r); } });</pre></code> * @type Array * @property elements */ this.elements = []; this.add(els, root); this.el = new Ext.Element.Flyweight(); }; Ext.CompositeElement.prototype = { isComposite: true, // private getElement : function(el) { // Set the shared flyweight dom property to the current element var e = this.el; e.dom = el; e.id = el.id; return e; }, // private transformElement : function(el) { return Ext.getDom(el); }, /** * Returns the number of elements in this Composite. * @return Number */ getCount : function() { return this.elements.length; }, /** * Adds elements to this Composite object. * @param {Mixed} els Either an Array of DOM elements to add, or another Composite object who's elements should be added. * @return {CompositeElement} This Composite object. */ add : function(els, root) { var me = this, elements = me.elements; if (!els) { return this; } if (typeof els == 'string') { els = Ext.Element.selectorFunction(els, root); } else if (els.isComposite) { els = els.elements; } else if (!Ext.isIterable(els)) { els = [els]; } for (var i = 0, len = els.length; i < len; ++i) { elements.push(me.transformElement(els[i])); } return me; }, invoke : function(fn, args) { var me = this, els = me.elements, len = els.length, e, i; for (i = 0; i < len; i++) { e = els[i]; if (e) { Ext.Element.prototype[fn].apply(me.getElement(e), args); } } return me; }, /** * Returns a flyweight Element of the dom element object at the specified index * @param {Number} index * @return {Ext.Element} */ item : function(index) { var me = this, el = me.elements[index], out = null; if (el){ out = me.getElement(el); } return out; }, // fixes scope with flyweight addListener : function(eventName, handler, scope, opt) { var els = this.elements, len = els.length, i, e; for (i = 0; i<len; i++) { e = els[i]; if (e) { Ext.EventManager.on(e, eventName, handler, scope || e, opt); } } return this; }, /** * <p>Calls the passed function for each element in this composite.</p> * @param {Function} fn The function to call. The function is passed the following parameters:<ul> * <li><b>el</b> : Element<div class="sub-desc">The current Element in the iteration. * <b>This is the flyweight (shared) Ext.Element instance, so if you require a * a reference to the dom node, use el.dom.</b></div></li> * <li><b>c</b> : Composite<div class="sub-desc">This Composite object.</div></li> * <li><b>idx</b> : Number<div class="sub-desc">The zero-based index in the iteration.</div></li> * </ul> * @param {Object} scope (optional) The scope (<i>this</i> reference) in which the function is executed. (defaults to the Element) * @return {CompositeElement} this */ each : function(fn, scope) { var me = this, els = me.elements, len = els.length, i, e; for (i = 0; i<len; i++) { e = els[i]; if (e) { e = this.getElement(e); if(fn.call(scope || e, e, me, i)){ break; } } } return me; }, /** * Clears this Composite and adds the elements passed. * @param {Mixed} els Either an array of DOM elements, or another Composite from which to fill this Composite. * @return {CompositeElement} this */ fill : function(els) { var me = this; me.elements = []; me.add(els); return me; }, /** * Filters this composite to only elements that match the passed selector. * @param {String/Function} selector A string CSS selector or a comparison function. * The comparison function will be called with the following arguments:<ul> * <li><code>el</code> : Ext.Element<div class="sub-desc">The current DOM element.</div></li> * <li><code>index</code> : Number<div class="sub-desc">The current index within the collection.</div></li> * </ul> * @return {CompositeElement} this */ filter : function(selector) { var els = [], me = this, elements = me.elements, fn = Ext.isFunction(selector) ? selector : function(el){ return el.is(selector); }; me.each(function(el, self, i){ if(fn(el, i) !== false){ els[els.length] = me.transformElement(el); } }); me.elements = els; return me; }, /** * Returns the first Element * @return {Ext.Element} */ first : function() { return this.item(0); }, /** * Returns the last Element * @return {Ext.Element} */ last : function() { return this.item(this.getCount()-1); }, /** * Returns true if this composite contains the passed element * @param {Mixed} el The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection. * @return Boolean */ contains : function(el) { return this.indexOf(el) != -1; }, /** * Find the index of the passed element within the composite collection. * @param {Mixed} el The id of an element, or an Ext.Element, or an HtmlElement to find within the composite collection. * @return Number The index of the passed Ext.Element in the composite collection, or -1 if not found. */ indexOf : function(el) { return this.elements.indexOf(this.transformElement(el)); }, /** * Removes all elements. */ clear : function() { this.elements = []; } }; Ext.CompositeElement.prototype.on = Ext.CompositeElement.prototype.addListener; (function(){ var fnName, ElProto = Ext.Element.prototype, CelProto = Ext.CompositeElement.prototype; for (fnName in ElProto) { if (Ext.isFunction(ElProto[fnName])) { (function(fnName) { CelProto[fnName] = CelProto[fnName] || function(){ return this.invoke(fnName, arguments); }; }).call(CelProto, fnName); } } })(); if(Ext.DomQuery) { Ext.Element.selectorFunction = Ext.DomQuery.select; } /** * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or * {@link Ext.CompositeElement CompositeElement} object. * @param {String/Array} selector The CSS selector or an array of elements * @param {HTMLElement/String} root (optional) The root element of the query or id of the root * @return {CompositeElement} * @member Ext.Element * @method select */ Ext.Element.select = function(selector, root, composite) { var els; composite = (composite === false) ? false : true; if (typeof selector == "string") { els = Ext.Element.selectorFunction(selector, root); } else if (selector.length !== undefined) { els = selector; } else { throw new Error("Invalid selector"); } return composite ? new Ext.CompositeElement(els) : els; }; /** * Selects elements based on the passed CSS selector to enable {@link Ext.Element Element} methods * to be applied to many related elements in one statement through the returned {@link Ext.CompositeElement CompositeElement} or * {@link Ext.CompositeElement CompositeElement} object. * @param {String/Array} selector The CSS selector or an array of elements * @param {HTMLElement/String} root (optional) The root element of the query or id of the root * @return {CompositeElement} * @member Ext * @method select */ Ext.select = Ext.Element.select; // Backwards compatibility with desktop Ext.CompositeElementLite = Ext.CompositeElement; /** * @class Ext.CompositeElementLite */ Ext.apply(Ext.CompositeElementLite.prototype, { addElements : function(els, root){ if(!els){ return this; } if(typeof els == "string"){ els = Ext.Element.selectorFunction(els, root); } var yels = this.elements; Ext.each(els, function(e) { yels.push(Ext.get(e)); }); return this; }, /** * Removes the specified element(s). * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite * or an array of any of those. * @param {Boolean} removeDom (optional) True to also remove the element from the document * @return {CompositeElement} this */ removeElement : function(keys, removeDom){ var me = this, els = this.elements, el; Ext.each(keys, function(val){ if ((el = (els[val] || els[val = me.indexOf(val)]))) { if(removeDom){ if(el.dom){ el.remove(); }else{ Ext.removeNode(el); } } els.splice(val, 1); } }); return this; }, /** * Replaces the specified element with the passed element. * @param {Mixed} el The id of an element, the Element itself, the index of the element in this composite * to replace. * @param {Mixed} replacement The id of an element or the Element itself. * @param {Boolean} domReplace (Optional) True to remove and replace the element in the document too. * @return {CompositeElement} this */ replaceElement : function(el, replacement, domReplace){ var index = !isNaN(el) ? el : this.indexOf(el), d; if(index > -1){ replacement = Ext.getDom(replacement); if(domReplace){ d = this.elements[index]; d.parentNode.insertBefore(replacement, d); Ext.removeNode(d); } this.elements.splice(index, 1, replacement); } return this; } });
JavaScript
/** * @class Ext.Element */ Ext.Element.addMethods({ /** * Gets the current Y position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @return {Number} The Y position of the element */ getY : function(el) { return this.getXY(el)[1]; }, /** * Gets the current X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @return {Number} The X position of the element */ getX : function(el) { return this.getXY(el)[0]; }, /** * Gets the current position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @return {Array} The XY position of the element */ getXY : function() { // @FEATUREDETECT var point = window.webkitConvertPointFromNodeToPage(this.dom, new WebKitPoint(0, 0)); return [point.x, point.y]; }, /** * 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(), e = Ext.fly(el, '_internal').getXY(); return [o[0]-e[0],o[1]-e[1]]; }, /** * Sets the position of the element in page coordinates, regardless of how the element is positioned. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Array} pos Contains X & Y [x, y] values for new position (coordinates are page-based) * @return {Ext.Element} this */ setXY : function(pos) { var me = this; if(arguments.length > 1) { pos = [pos, arguments[1]]; } // me.position(); var pts = me.translatePoints(pos), style = me.dom.style; for (pos in pts) { if (!pts.hasOwnProperty(pos)) { continue; } if(!isNaN(pts[pos])) style[pos] = pts[pos] + "px"; } return me; }, /** * Sets the X position of the element based on page coordinates. Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @param {Number} The X position of the element * @return {Ext.Element} this */ setX : function(x){ return this.setXY([x, this.getY()]); }, /** * 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) { return this.setXY([this.getX(), y]); }, /** * Sets the element's left position directly using CSS style (instead of {@link #setX}). * @param {String} left The left CSS property value * @return {Ext.Element} this */ setLeft : function(left) { this.setStyle('left', Ext.Element.addUnits(left)); return this; }, /** * Sets the element's top position directly using CSS style (instead of {@link #setY}). * @param {String} top The top CSS property value * @return {Ext.Element} this */ setTop : function(top) { this.setStyle('top', Ext.Element.addUnits(top)); return this; }, /** * Sets the element's top and left positions directly using CSS style (instead of {@link #setXY}) * @param {String} top The top CSS property value * @param {String} left The left CSS property value */ setTopLeft: function(top, left) { var addUnits = Ext.Element.addUnits; this.setStyle('top', addUnits(top)); this.setStyle('left', addUnits(left)); return this; }, /** * Sets the element's CSS right style. * @param {String} right The right CSS property value * @return {Ext.Element} this */ setRight : function(right) { this.setStyle('right', Ext.Element.addUnits(right)); return this; }, /** * Sets the element's CSS bottom style. * @param {String} bottom The bottom CSS property value * @return {Ext.Element} this */ setBottom : function(bottom) { this.setStyle('bottom', Ext.Element.addUnits(bottom)); return this; }, /** * Gets the left X coordinate * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} */ getLeft : function(local) { return parseInt(this.getStyle('left'), 10) || 0; }, /** * Gets the right X coordinate of the element (element X position + element width) * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} */ getRight : function(local) { return parseInt(this.getStyle('right'), 10) || 0; }, /** * Gets the top Y coordinate * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} */ getTop : function(local) { return parseInt(this.getStyle('top'), 10) || 0; }, /** * Gets the bottom Y coordinate of the element (element Y position + element height) * @param {Boolean} local True to get the local css position instead of page coordinate * @return {Number} */ getBottom : function(local) { return parseInt(this.getStyle('bottom'), 10) || 0; }, /** * Sets the element's box. Use getBox() on another element to get a box obj. If animate is true then width, height, x and y will be animated concurrently. * @param {Object} box The box to fill {x, y, width, height} * @return {Ext.Element} this */ setBox : function(left, top, width, height) { var undefined; if (Ext.isObject(left)) { width = left.width; height = left.height; top = left.top; left = left.left; } if (left !== undefined) { this.setLeft(left); } if (top !== undefined) { this.setTop(top); } if (width !== undefined) { this.setWidth(width); } if (height !== undefined) { this.setHeight(height); } return this; }, /** * Return an object defining the area of this Element which can be passed to {@link #setBox} to * set another Element's size/location to match this element. * @param {Boolean} contentBox (optional) If true a box for the content of the element is returned. * @param {Boolean} local (optional) If true the element's left and top are returned instead of page x/y. * @return {Object} box An object in the format<pre><code> { x: &lt;Element's X position>, y: &lt;Element's Y position>, width: &lt;Element's width>, height: &lt;Element's height>, bottom: &lt;Element's lower bound>, right: &lt;Element's rightmost bound> } </code></pre> * The returned object may also be addressed as an Array where index 0 contains the X position * and index 1 contains the Y position. So the result may also be used for {@link #setXY} */ getBox : function(contentBox, local) { var me = this, dom = me.dom, width = dom.offsetWidth, height = dom.offsetHeight, xy, box, l, r, t, b; if (!local) { xy = me.getXY(); } else if (contentBox) { xy = [0,0]; } else { xy = [parseInt(me.getStyle("left"), 10) || 0, parseInt(me.getStyle("top"), 10) || 0]; } if (!contentBox) { box = { x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: width, height: height }; } else { l = me.getBorderWidth.call(me, "l") + me.getPadding.call(me, "l"); r = me.getBorderWidth.call(me, "r") + me.getPadding.call(me, "r"); t = me.getBorderWidth.call(me, "t") + me.getPadding.call(me, "t"); b = me.getBorderWidth.call(me, "b") + me.getPadding.call(me, "b"); box = { x: xy[0] + l, y: xy[1] + t, 0: xy[0] + l, 1: xy[1] + t, width: width - (l + r), height: height - (t + b) }; } box.left = box.x; box.top = box.y; box.right = box.x + box.width; box.bottom = box.y + box.height; return box; }, /** * Return an object defining the area of this Element which can be passed to {@link #setBox} to * set another Element's size/location to match this element. * @param {Boolean} asRegion(optional) If true an Ext.util.Region will be returned * @return {Object} box An object in the format<pre><code> { x: &lt;Element's X position>, y: &lt;Element's Y position>, width: &lt;Element's width>, height: &lt;Element's height>, bottom: &lt;Element's lower bound>, right: &lt;Element's rightmost bound> } </code></pre> * The returned object may also be addressed as an Array where index 0 contains the X position * and index 1 contains the Y position. So the result may also be used for {@link #setXY} */ getPageBox : function(getRegion) { var me = this, el = me.dom, w = el.offsetWidth, h = el.offsetHeight, xy = me.getXY(), t = xy[1], r = xy[0] + w, b = xy[1] + h, l = xy[0]; if (!el) { return new Ext.util.Region(); } if (getRegion) { return new Ext.util.Region(t, r, b, l); } else { return { left: l, top: t, width: w, height: h, right: r, bottom: b }; } }, /** * Translates the passed page coordinates into left/top css values for this element * @param {Number/Array} x The page x or an array containing [x, y] * @param {Number} y (optional) The page y, required if x is not an array * @return {Object} An object with left and top properties. e.g. {left: (value), top: (value)} */ translatePoints : function(x, y) { y = isNaN(x[1]) ? y : x[1]; x = isNaN(x[0]) ? x : x[0]; var me = this, relative = me.isStyle('position', 'relative'), o = me.getXY(), l = parseInt(me.getStyle('left'), 10), t = parseInt(me.getStyle('top'), 10); l = !isNaN(l) ? l : (relative ? 0 : me.dom.offsetLeft); t = !isNaN(t) ? t : (relative ? 0 : me.dom.offsetTop); return {left: (x - o[0] + l), top: (y - o[1] + t)}; } });
JavaScript
/** * @class Ext.DomQuery * Provides functionality to select elements on the page based on a CSS selector. * <p> All selectors, attribute filters and pseudos below can be combined infinitely in any order. For example "div.foo:nth-child(odd)[@foo=bar].bar:first" would be a perfectly valid selector. </p> <h4>Element Selectors:</h4> <ul class="list"> <li> <b>*</b> any element</li> <li> <b>E</b> an element with the tag E</li> <li> <b>E F</b> All descendent elements of E that have the tag F</li> <li> <b>E > F</b> or <b>E/F</b> all direct children elements of E that have the tag F</li> <li> <b>E + F</b> all elements with the tag F that are immediately preceded by an element with the tag E</li> <li> <b>E ~ F</b> all elements with the tag F that are preceded by a sibling element with the tag E</li> </ul> <h4>Attribute Selectors:</h4> <p>The use of &#64; and quotes are optional. For example, div[&#64;foo='bar'] is also a valid attribute selector.</p> <ul class="list"> <li> <b>E[foo]</b> has an attribute "foo"</li> <li> <b>E[foo=bar]</b> has an attribute "foo" that equals "bar"</li> <li> <b>E[foo^=bar]</b> has an attribute "foo" that starts with "bar"</li> <li> <b>E[foo$=bar]</b> has an attribute "foo" that ends with "bar"</li> <li> <b>E[foo*=bar]</b> has an attribute "foo" that contains the substring "bar"</li> <li> <b>E[foo%=2]</b> has an attribute "foo" that is evenly divisible by 2</li> <li> <b>E[foo!=bar]</b> has an attribute "foo" that does not equal "bar"</li> </ul> <h4>Pseudo Classes:</h4> <ul class="list"> <li> <b>E:first-child</b> E is the first child of its parent</li> <li> <b>E:last-child</b> E is the last child of its parent</li> <li> <b>E:nth-child(<i>n</i>)</b> E is the <i>n</i>th child of its parent (1 based as per the spec)</li> <li> <b>E:nth-child(odd)</b> E is an odd child of its parent</li> <li> <b>E:nth-child(even)</b> E is an even child of its parent</li> <li> <b>E:only-child</b> E is the only child of its parent</li> <li> <b>E:checked</b> E is an element that is has a checked attribute that is true (e.g. a radio or checkbox) </li> <li> <b>E:first</b> the first E in the resultset</li> <li> <b>E:last</b> the last E in the resultset</li> <li> <b>E:nth(<i>n</i>)</b> the <i>n</i>th E in the resultset (1 based)</li> <li> <b>E:odd</b> shortcut for :nth-child(odd)</li> <li> <b>E:even</b> shortcut for :nth-child(even)</li> <li> <b>E:contains(foo)</b> E's innerHTML contains the substring "foo"</li> <li> <b>E:nodeValue(foo)</b> E contains a textNode with a nodeValue that equals "foo"</li> <li> <b>E:not(S)</b> an E element that does not match simple selector S</li> <li> <b>E:has(S)</b> an E element that has a descendent that matches simple selector S</li> <li> <b>E:next(S)</b> an E element whose next sibling matches simple selector S</li> <li> <b>E:prev(S)</b> an E element whose previous sibling matches simple selector S</li> <li> <b>E:any(S1|S2|S2)</b> an E element which matches any of the simple selectors S1, S2 or S3//\\</li> </ul> <h4>CSS Value Selectors:</h4> <ul class="list"> <li> <b>E{display=none}</b> css value "display" that equals "none"</li> <li> <b>E{display^=none}</b> css value "display" that starts with "none"</li> <li> <b>E{display$=none}</b> css value "display" that ends with "none"</li> <li> <b>E{display*=none}</b> css value "display" that contains the substring "none"</li> <li> <b>E{display%=2}</b> css value "display" that is evenly divisible by 2</li> <li> <b>E{display!=none}</b> css value "display" that does not equal "none"</li> </ul> * @singleton */ Ext.DomQuery = { /** * Selects a group of elements. * @param {String} selector The selector/xpath query (can be a comma separated list of selectors) * @param {Node/String} root (optional) The start of the query (defaults to document). * @return {Array} An Array of DOM elements which match the selector. If there are * no matches, and empty Array is returned. */ select : function(q, root) { var results = [], nodes, i, j, qlen, nlen; root = root || document; if (typeof root == 'string') { root = document.getElementById(root); } q = q.split(","); for (i = 0, qlen = q.length; i < qlen; i++) { if (typeof q[i] == 'string') { nodes = root.querySelectorAll(q[i]); for (j = 0, nlen = nodes.length; j < nlen; j++) { results.push(nodes[j]); } } } return results; }, /** * Selects a single element. * @param {String} selector The selector/xpath query * @param {Node} root (optional) The start of the query (defaults to document). * @return {HtmlElement} The DOM element which matched the selector. */ selectNode : function(q, root) { return Ext.DomQuery.select(q, root)[0]; }, /** * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child) * @param {String/HTMLElement/Array} el An element id, element or array of elements * @param {String} selector The simple selector to test * @return {Boolean} */ is : function(el, q) { if (typeof el == "string") { el = document.getElementById(el); } return Ext.DomQuery.select(q).indexOf(el) !== -1; } }; Ext.Element.selectorFunction = Ext.DomQuery.select; Ext.query = Ext.DomQuery.select;
JavaScript
(function() { /** * @class Ext.Element */ Ext.Element.classReCache = {}; var El = Ext.Element, view = document.defaultView; El.addMethods({ marginRightRe: /marginRight/i, trimRe: /^\s+|\s+$/g, spacesRe: /\s+/, /** * Adds one or more CSS classes to the element. Duplicate classes are automatically filtered out. * @param {String/Array} className The CSS class to add, or an array of classes * @return {Ext.Element} this */ addCls: function(className) { var me = this, i, len, v, cls = []; if (!Ext.isArray(className)) { if (className && !this.hasCls(className)) { me.dom.className += " " + className; } } else { for (i = 0, len = className.length; i < len; i++) { v = className[i]; if (v && !me.hasCls(v)) { cls.push(v); } } if (cls.length) { me.dom.className += " " + cls.join(" "); } } return me; }, //<debug> addClass : function() { throw new Error("Component: addClass has been deprecated. Please use addCls."); }, //</debug> /** * Removes one or more CSS classes from the element. * @param {String/Array} className The CSS class to remove, or an array of classes * @return {Ext.Element} this */ removeCls: function(className) { var me = this, i, idx, len, cls, elClasses; if (!Ext.isArray(className)) { className = [className]; } if (me.dom && me.dom.className) { elClasses = me.dom.className.replace(this.trimRe, '').split(this.spacesRe); for (i = 0, len = className.length; i < len; i++) { cls = className[i]; if (typeof cls == 'string') { cls = cls.replace(this.trimRe, ''); idx = elClasses.indexOf(cls); if (idx != -1) { elClasses.splice(idx, 1); } } } me.dom.className = elClasses.join(" "); } return me; }, //<debug> removeClass : function() { throw new Error("Component: removeClass has been deprecated. Please use removeCls."); }, //</debug> /** * Puts a mask over this element to disable user interaction. * This method can only be applied to elements which accept child nodes. * @param {String} msg (optional) A message to display in the mask. This can be html. * @param {String} msgCls (optional) A css class to apply to the msg element * @param {Boolean} transparent (optional) False to show make the mask gray with opacity. (defaults to true) * @return {Element} The mask element */ mask: function(msg, msgCls, transparent) { var me = this, dom = me.dom, el = Ext.Element.data(dom, 'mask'), mask, size, cls = ''; me.addCls('x-masked'); if (me.getStyle("position") == "static") { me.addCls('x-masked-relative'); } if (el) { el.remove(); } if (Ext.isString(msgCls) && !Ext.isEmpty(msgCls)) { cls = ' ' + msgCls; } else { if (msgCls) { cls = ' x-mask-gray'; } } mask = me.createChild({ cls: 'x-mask' + ((transparent !== false) ? '' : ' x-mask-gray'), html: msg ? ('<div class="' + (msgCls || 'x-mask-message') + '">' + msg + '</div>') : '' }); size = me.getSize(); Ext.Element.data(dom, 'mask', mask); if (dom === document.body) { size.height = window.innerHeight; if (me.orientationHandler) { Ext.EventManager.unOrientationChange(me.orientationHandler, me); } me.orientationHandler = function() { size = me.getSize(); size.height = window.innerHeight; mask.setSize(size); }; Ext.EventManager.onOrientationChange(me.orientationHandler, me); } mask.setSize(size); if (Ext.is.iPad) { Ext.repaint(); } }, /** * Removes a previously applied mask. */ unmask: function() { var me = this, dom = me.dom, mask = Ext.Element.data(dom, 'mask'); if (mask) { mask.remove(); Ext.Element.data(dom, 'mask', undefined); } me.removeCls(['x-masked', 'x-masked-relative']); if (dom === document.body) { Ext.EventManager.unOrientationChange(me.orientationHandler, me); delete me.orientationHandler; } }, /** * Adds one or more CSS classes to this element and removes the same class(es) from all siblings. * @param {String/Array} className The CSS class to add, or an array of classes * @return {Ext.Element} this */ radioCls: function(className) { var cn = this.dom.parentNode.childNodes, v; className = Ext.isArray(className) ? className: [className]; for (var i = 0, len = cn.length; i < len; i++) { v = cn[i]; if (v && v.nodeType == 1) { Ext.fly(v, '_internal').removeCls(className); } }; return this.addCls(className); }, //<debug> radioClass : function() { throw new Error("Component: radioClass has been deprecated. Please use radioCls."); }, //</debug> /** * Toggles the specified CSS class on this element (removes it if it already exists, otherwise adds it). * @param {String} className The CSS class to toggle * @return {Ext.Element} this */ toggleCls: function(className) { return this.hasCls(className) ? this.removeCls(className) : this.addCls(className); }, //<debug> toggleClass : function() { throw new Error("Component: toggleClass has been deprecated. Please use toggleCls."); }, //</debug> /** * Checks if the specified CSS class exists on this element's DOM node. * @param {String} className The CSS class to check for * @return {Boolean} True if the class exists, else false */ hasCls: function(className) { return className && (' ' + this.dom.className + ' ').indexOf(' ' + className + ' ') != -1; }, //<debug> hasClass : function() { throw new Error("Element: hasClass has been deprecated. Please use hasCls."); return this.hasCls.apply(this, arguments); }, //</debug> /** * Replaces a CSS class on the element with another. If the old name does not exist, the new name will simply be added. * @param {String} oldClassName The CSS class to replace * @param {String} newClassName The replacement CSS class * @return {Ext.Element} this */ replaceCls: function(oldClassName, newClassName) { return this.removeCls(oldClassName).addCls(newClassName); }, //<debug> replaceClass : function() { throw new Error("Component: replaceClass has been deprecated. Please use replaceCls."); }, //</debug> isStyle: function(style, val) { return this.getStyle(style) == val; }, /** * 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(prop) { var dom = this.dom, result, display, cs, platform = Ext.is, style = dom.style; prop = El.normalize(prop); cs = (view) ? view.getComputedStyle(dom, '') : dom.currentStyle; result = (cs) ? cs[prop] : null; // Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343 if (result && !platform.correctRightMargin && this.marginRightRe.test(prop) && style.position != 'absolute' && result != '0px') { display = style.display; style.display = 'inline-block'; result = view.getComputedStyle(dom, null)[prop]; style.display = display; } result || (result = style[prop]); // Webkit returns rgb values for transparent. if (!platform.correctTransparentColor && result == 'rgba(0, 0, 0, 0)') { result = 'transparent'; } return result; }, /** * Wrapper for setting style properties, also takes single object parameter of multiple styles. * @param {String/Object} property The style property to be set, or an object of multiple styles. * @param {String} value (optional) The value to apply to the given property, or null if an object was passed. * @return {Ext.Element} this */ setStyle: function(prop, value) { var tmp, style; if (typeof prop == 'string') { tmp = {}; tmp[prop] = value; prop = tmp; } for (style in prop) { if (prop.hasOwnProperty(style)) { this.dom.style[El.normalize(style)] = prop[style]; } } return this; }, /** * Applies a style specification to an element. * @param {String/HTMLElement} el The element to apply styles to * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or * a function which returns such a specification. */ applyStyles: function(styles) { if (styles) { var i, len, dom = this.dom; if (typeof styles == 'function') { styles = styles.call(); } if (typeof styles == 'string') { styles = Ext.util.Format.trim(styles).split(/\s*(?::|;)\s*/); for (i = 0, len = styles.length; i < len;) { dom.style[El.normalize(styles[i++])] = styles[i++]; } } else if (typeof styles == 'object') { this.setStyle(styles); } } }, /** * Returns the offset height of the element * @param {Boolean} contentHeight (optional) true to get the height minus borders and padding * @return {Number} The element's height */ getHeight: function(contentHeight) { var dom = this.dom, height = contentHeight ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight; return height > 0 ? height: 0; }, /** * Returns the offset width of the element * @param {Boolean} contentWidth (optional) true to get the width minus borders and padding * @return {Number} The element's width */ getWidth: function(contentWidth) { var dom = this.dom, width = contentWidth ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth; return width > 0 ? width: 0; }, /** * Set the width of this Element. * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS width style. Animation may <b>not</b> be used. * </ul></div> * @return {Ext.Element} this */ setWidth: function(width) { var me = this; me.dom.style.width = El.addUnits(width); return me; }, /** * Set the height of this Element. * <pre><code> // change the height to 200px and animate with default configuration Ext.fly('elementId').setHeight(200, true); // change the height to 150px and animate with a custom configuration Ext.fly('elId').setHeight(150, { duration : .5, // animation will have a duration of .5 seconds // will change the content to "finished" callback: function(){ this.{@link #update}("finished"); } }); * </code></pre> * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels.)</li> * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li> * </ul></div> * @return {Ext.Element} this */ setHeight: function(height) { var me = this; me.dom.style.height = El.addUnits(height); return me; }, /** * Set the size of this Element. If animation is true, both width and height will be animated concurrently. * @param {Mixed} width The new width. This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new width in this Element's {@link #defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS width style. Animation may <b>not</b> be used. * <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li> * </ul></div> * @param {Mixed} height The new height. This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new height in this Element's {@link #defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li> * </ul></div> * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this */ setSize: function(width, height) { var me = this, style = me.dom.style; if (Ext.isObject(width)) { // in case of object from getSize() height = width.height; width = width.width; } style.width = El.addUnits(width); style.height = El.addUnits(height); return me; }, /** * Gets the width of the border(s) for the specified side(s) * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, * passing <tt>'lr'</tt> would get the border <b><u>l</u></b>eft width + the border <b><u>r</u></b>ight width. * @return {Number} The width of the sides passed added together */ getBorderWidth: function(side) { return this.sumStyles(side, El.borders); }, /** * Gets the size of the padding(s) for the specified side(s) * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, * passing <tt>'lr'</tt> would get the padding <b><u>l</u></b>eft + the padding <b><u>r</u></b>ight. * @return {Number} The padding of the sides passed added together */ getPadding: function(side) { return this.sumStyles(side, El.paddings); }, /** * Gets the size of the margins(s) for the specified side(s) * @param {String} side Can be t, l, r, b or any combination of those to add multiple values. For example, * passing <tt>'lr'</tt> would get the margin <b><u>l</u></b>eft + the margin <b><u>r</u></b>ight. * @return {Number} The margin of the sides passed added together */ getMargin: function(side) { return this.sumStyles(side, El.margins); }, /** * <p>Returns the dimensions of the element available to lay content out in.<p> * <p>If the element (or any ancestor element) has CSS style <code>display : none</code>, the dimensions will be zero.</p> */ getViewSize: function() { var doc = document, dom = this.dom; if (dom == doc || dom == doc.body) { return { width: El.getViewportWidth(), height: El.getViewportHeight() }; } else { return { width: dom.clientWidth, height: dom.clientHeight }; } }, /** * Returns the size of the element. * @param {Boolean} contentSize (optional) true to get the width/size minus borders and padding * @return {Object} An object containing the element's size {width: (element width), height: (element height)} */ getSize: function(contentSize) { var dom = this.dom; return { width: Math.max(0, contentSize ? (dom.clientWidth - this.getPadding("lr")) : dom.offsetWidth), height: Math.max(0, contentSize ? (dom.clientHeight - this.getPadding("tb")) : dom.offsetHeight) }; }, /** * Forces the browser to repaint this element * @return {Ext.Element} this */ repaint: function() { var dom = this.dom; this.addCls("x-repaint"); dom.style.background = 'transparent none'; setTimeout(function() { dom.style.background = null; Ext.get(dom).removeCls("x-repaint"); }, 1); return this; }, /** * Retrieves the width of the element accounting for the left and right * margins. */ getOuterWidth: function() { return this.getWidth() + this.getMargin('lr'); }, /** * Retrieves the height of the element account for the top and bottom * margins. */ getOuterHeight: function() { return this.getHeight() + this.getMargin('tb'); }, // private sumStyles: function(sides, styles) { var val = 0, m = sides.match(/\w/g), len = m.length, s, i; for (i = 0; i < len; i++) { s = m[i] && parseFloat(this.getStyle(styles[m[i]])) || 0; if (s) { val += Math.abs(s); } } return val; } }); })();
JavaScript
/** * @class Ext.Element */ Ext.Element.addMethods({ /** * Gets the x,y coordinates specified by the anchor position on the element. * @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo} * for details on supported anchor positions. * @param {Object} size (optional) An object containing the size to use for calculating anchor position * {width: (target width), height: (target height)} (defaults to the element's current size) * @return {Array} [x, y] An array containing the element's x and y coordinates */ getAnchorXY: function(anchor, local, size) { //Passing a different size is useful for pre-calculating anchors, //especially for anchored animations that change the el size. anchor = (anchor || "tl").toLowerCase(); size = size || {}; var me = this, vp = me.dom == document.body || me.dom == document, width = size.width || vp ? window.innerWidth: me.getWidth(), height = size.height || vp ? window.innerHeight: me.getHeight(), xy, rnd = Math.round, myXY = me.getXY(), extraX = vp ? 0: !local ? myXY[0] : 0, extraY = vp ? 0: !local ? myXY[1] : 0, hash = { c: [rnd(width * 0.5), rnd(height * 0.5)], t: [rnd(width * 0.5), 0], l: [0, rnd(height * 0.5)], r: [width, rnd(height * 0.5)], b: [rnd(width * 0.5), height], tl: [0, 0], bl: [0, height], br: [width, height], tr: [width, 0] }; xy = hash[anchor]; return [xy[0] + extraX, xy[1] + extraY]; }, /** * 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 (optional, defaults to "tl-bl?") The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @return {Array} [x, y] */ getAlignToXY: function(el, position, offsets) { el = Ext.get(el); //<debug> if (!el || !el.dom) { throw new Error("Element.alignToXY with an element that doesn't exist"); } //</debug> offsets = offsets || [0, 0]; if (!position || position == '?') { position = 'tl-bl?'; } else if (! (/-/).test(position) && position !== "") { position = 'tl-' + position; } position = position.toLowerCase(); var me = this, matches = position.match(/^([a-z]+)-([a-z]+)(\?)?$/), dw = window.innerWidth, dh = window.innerHeight, p1 = "", p2 = "", a1, a2, x, y, swapX, swapY, p1x, p1y, p2x, p2y, width, height, region, constrain; if (!matches) { throw "Element.alignTo with an invalid alignment " + position; } p1 = matches[1]; p2 = matches[2]; constrain = !!matches[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 a1 = me.getAnchorXY(p1, true); a2 = el.getAnchorXY(p2, false); x = a2[0] - a1[0] + offsets[0]; y = a2[1] - a1[1] + offsets[1]; if (constrain) { width = me.getWidth(); height = me.getHeight(); region = el.getPageBox(); //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. p1y = p1.charAt(0); p1x = p1.charAt(p1.length - 1); p2y = p2.charAt(0); p2x = p2.charAt(p2.length - 1); swapY = ((p1y == "t" && p2y == "b") || (p1y == "b" && p2y == "t")); swapX = ((p1x == "r" && p2x == "l") || (p1x == "l" && p2x == "r")); if (x + width > dw) { x = swapX ? region.left - width: dw - width; } if (x < 0) { x = swapX ? region.right: 0; } if (y + height > dh) { y = swapY ? region.top - height: dh - height; } if (y < 0) { y = swapY ? region.bottom: 0; } } return [x, y]; } /** * Anchors an element to another element and realigns it when the window is resized. * @param {Mixed} element The element to align to. * @param {String} position The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter * is a number, it is used as the buffer delay (defaults to 50ms). * @param {Function} callback The function to call after the animation finishes * @return {Ext.Element} this */ // anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){ // var me = this, // dom = me.dom, // scroll = !Ext.isEmpty(monitorScroll), // action = function(){ // Ext.fly(dom).alignTo(el, alignment, offsets, animate); // Ext.callback(callback, Ext.fly(dom)); // }, // anchor = this.getAnchor(); // // // previous listener anchor, remove it // this.removeAnchor(); // Ext.apply(anchor, { // fn: action, // scroll: scroll // }); // // Ext.EventManager.onWindowResize(action, null); // // if(scroll){ // Ext.EventManager.on(window, 'scroll', action, null, // {buffer: !isNaN(monitorScroll) ? monitorScroll : 50}); // } // action.call(me); // align immediately // return me; // }, /** * Remove any anchor to this element. See {@link #anchorTo}. * @return {Ext.Element} this */ // removeAnchor : function(){ // var me = this, // anchor = this.getAnchor(); // // if(anchor && anchor.fn){ // Ext.EventManager.removeResizeListener(anchor.fn); // if(anchor.scroll){ // Ext.EventManager.un(window, 'scroll', anchor.fn); // } // delete anchor.fn; // } // return me; // }, // // // private // getAnchor : function(){ // var data = Ext.Element.data, // dom = this.dom; // if (!dom) { // return; // } // var anchor = data(dom, '_anchor'); // // if(!anchor){ // anchor = data(dom, '_anchor', {}); // } // return anchor; // }, /** * Aligns this element with another element relative to the specified anchor points. If the other element is the * document it aligns it to the viewport. * The position parameter is optional, and can be specified in any one of the following formats: * <ul> * <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li> * <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point. * The element being aligned will position its top-left corner (tl) to that point. <i>This method has been * deprecated in favor of the newer two anchor syntax below</i>.</li> * <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the * element's anchor point, and the second value is used as the target's anchor point.</li> * </ul> * In addition to the anchor points, the position parameter also supports the "?" character. If "?" is passed at the end of * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to * the viewport if necessary. Note that the element being aligned might be swapped to align to a different position than * that specified in order to enforce the viewport constraints. * Following are all of the supported anchor positions: <pre> Value Description ----- ----------------------------- tl The top left corner (default) t The center of the top edge tr The top right corner l The center of the left edge c In the center of the element r The center of the right edge bl The bottom left corner b The center of the bottom edge br The bottom right corner </pre> Example Usage: <pre><code> // align el to other-el using the default positioning ("tl-bl", non-constrained) el.alignTo("other-el"); // align the top left corner of el with the top right corner of other-el (constrained to viewport) el.alignTo("other-el", "tr?"); // align the bottom right corner of el with the center left edge of other-el el.alignTo("other-el", "br-l?"); // align the center of el with the bottom left corner of other-el and // adjust the x position by -6 pixels (and the y position by 0) el.alignTo("other-el", "c-bl", [-6, 0]); </code></pre> * @param {Mixed} element The element to align to. * @param {String} position (optional, defaults to "tl-bl?") The position to align to. * @param {Array} offsets (optional) Offset the positioning by [x, y] * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this */ // alignTo : function(element, position, offsets, animate){ // var me = this; // return me.setXY(me.getAlignToXY(element, position, offsets), // me.preanim && !!animate ? me.preanim(arguments, 3) : false); // }, // // // private ==> used outside of core // adjustForConstraints : function(xy, parent, offsets){ // return this.getConstrainToXY(parent || document, false, offsets, xy) || xy; // }, // // // private ==> used outside of core // getConstrainToXY : function(el, local, offsets, proposedXY){ // 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, // vb = vy + vh, // xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]), // x = xy[0], y = xy[1], // offset = this.getConstrainOffset(), // w = this.dom.offsetWidth + offset, // h = this.dom.offsetHeight + offset; // // // only move it if it needs it // var moved = false; // // // first validate right/bottom // if((x + w) > vr){ // x = vr - w; // moved = true; // } // if((y + h) > vb){ // y = vb - h; // moved = true; // } // // then make sure top/left isn't negative // if(x < vx){ // x = vx; // moved = true; // } // if(y < vy){ // y = vy; // moved = true; // } // return moved ? [x, y] : false; // }; // }(), // // // private, used internally // getConstrainOffset : function(){ // return 0; // }, // // /** // * 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) { // return this.alignTo(centerIn || document, 'c-c'); // } });
JavaScript
/** * @class Ext.Element */ Ext.Element.addMethods({ /** * Gets the Scroller instance of the first parent that has one. * @return {Ext.util.Scroller/null} The first parent scroller */ getScrollParent : function() { var parent = this.dom, scroller; while (parent && parent != document.body) { if (parent.id && (scroller = Ext.ScrollManager.get(parent.id))) { return scroller; } parent = parent.parentNode; } return null; } });
JavaScript
/** * @class Ext */ Ext.apply(Ext, { /** * The version of the framework * @type String */ version : '1.0.0RC', versionDetail : { major : 1, minor : 0, patch : '0RC' }, /** * Sets up a page for use on a mobile device. * @param {Object} config * * Valid configurations are: * <ul> * <li>fullscreen - Boolean - Sets an appropriate meta tag for Apple devices to run in full-screen mode.</li> * <li>tabletStartupScreen - String - Startup screen to be used on an iPad. The image must be 768x1004 and in portrait orientation.</li> * <li>phoneStartupScreen - String - Startup screen to be used on an iPhone or iPod touch. The image must be 320x460 and in * portrait orientation.</li> * <li>icon - Default icon to use. This will automatically apply to both tablets and phones. These should be 72x72.</li> * <li>tabletIcon - String - An icon for only tablets. (This config supersedes icon.) These should be 72x72.</li> * <li>phoneIcon - String - An icon for only phones. (This config supersedes icon.) These should be 57x57.</li> * <li>glossOnIcon - Boolean - Add gloss on icon on iPhone, iPad and iPod Touch</li> * <li>statusBarStyle - String - Sets the status bar style for fullscreen iPhone OS web apps. Valid options are default, black, * or black-translucent.</li> * <li>onReady - Function - Function to be run when the DOM is ready.<li> * <li>scope - Scope - Scope for the onReady configuraiton to be run in.</li> * </ul> */ setup: function(config) { if (config && typeof config == 'object') { if (config.addMetaTags !== false) { this.addMetaTags(config); } if (Ext.isFunction(config.onReady)) { var me = this; Ext.onReady(function() { var args = arguments; if (config.fullscreen !== false) { Ext.Viewport.init(function() { config.onReady.apply(me, args); }); } else { config.onReady.apply(this, args); } }, config.scope); } } }, /** * Return the dom node for the passed String (id), dom node, or Ext.Element. * Here are some examples: * <pre><code> // gets dom node based on id var elDom = Ext.getDom('elId'); // gets dom node based on the dom node var elDom1 = Ext.getDom(elDom); // If we don&#39;t know if we are working with an // Ext.Element or a dom node use Ext.getDom function(el){ var dom = Ext.getDom(el); // do something with the dom node } </code></pre> * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc) * when this method is called to be successful. * @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); }, /** * <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference. * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval} is * <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node * will be ignored if passed in.</p> * @param {HTMLElement} node The node to remove */ removeNode : function(node) { if (node && node.parentNode && node.tagName != 'BODY') { Ext.EventManager.removeAll(node); node.parentNode.removeChild(node); delete Ext.cache[node.id]; } }, /** * @private * Creates meta tags for a given config object. This is usually just called internally from Ext.setup - see * that method for full usage. Extracted into its own function so that Ext.Application and other classes can * call it without invoking all of the logic inside Ext.setup. * @param {Object} config The meta tag configuration object */ addMetaTags: function(config) { if (!Ext.isObject(config)) { return; } var head = Ext.get(document.getElementsByTagName('head')[0]), tag, precomposed; /** * The viewport meta tag. This disables user scaling. This is supported * on most Android phones and all iOS devices and will probably be supported * on most future devices (like Blackberry, Palm etc). */ if (!Ext.is.Desktop) { tag = Ext.get(document.createElement('meta')); tag.set({ name: 'viewport', content: 'width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0;' }); head.appendChild(tag); } /** * We want to check now for iOS specific meta tags. Unfortunately most * of these are not supported on devices other then iOS. */ if (Ext.is.iOS) { /** * On iOS, if you save to home screen, you can decide if you want * to launch the app fullscreen (without address bar). You can also * change the styling of the status bar at the top of the screen. */ if (config.fullscreen !== false) { tag = Ext.get(document.createElement('meta')); tag.set({ name: 'apple-mobile-web-app-capable', content: 'yes' }); head.appendChild(tag); if (Ext.isString(config.statusBarStyle)) { tag = Ext.get(document.createElement('meta')); tag.set({ name: 'apple-mobile-web-app-status-bar-style', content: config.statusBarStyle }); head.appendChild(tag); } } /** * iOS allows you to specify a startup screen. This is displayed during * the startup of your app if you save to your homescreen. Since we could * be dealing with an iPad or iPhone/iPod, we have a tablet startup screen * and a phone startup screen. */ if (config.tabletStartupScreen && Ext.is.iPad) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-startup-image', href: config.tabletStartupScreen }); head.appendChild(tag); } if (config.phoneStartupScreen && !Ext.is.iPad) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-startup-image', href: config.phoneStartupScreen }); head.appendChild(tag); } /** * On iOS you can specify the icon used when you save the app to your * homescreen. You can set an icon that will be used for both iPads * and iPhone/iPod, or you can specify specific icons for both. */ if (config.icon) { config.phoneIcon = config.tabletIcon = config.icon; } precomposed = (config.glossOnIcon === false) ? '-precomposed' : ''; if (Ext.is.iPad && Ext.isString(config.tabletIcon)) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-icon' + precomposed, href: config.tabletIcon }); head.appendChild(tag); } else if (!Ext.is.iPad && Ext.isString(config.phoneIcon)) { tag = Ext.get(document.createElement('link')); tag.set({ rel: 'apple-touch-icon' + precomposed, href: config.phoneIcon }); head.appendChild(tag); } } } }); Ext.Viewport = new (Ext.extend(Ext.util.Observable, { constructor: function() { this.addEvents( 'orientationchange', 'resize' ); if (Ext.supports.OrientationChange) { window.addEventListener('orientationchange', Ext.createDelegate(this.onOrientationChange, this), false); } else { window.addEventListener('resize', Ext.createDelegate(this.onResize, this), false); } if (!Ext.desktop) { document.addEventListener('touchstart', Ext.createDelegate(this.onTouchStartCapturing, this), true); document.addEventListener('touchmove', Ext.createDelegate(this.onTouchMoveBubbling, this), false); } this.stretchSizes = {}; }, init: function(fn) { var me = this, stretchSize = Math.max(window.innerHeight, window.innerWidth) * 2; me.updateOrientation(); if (!Ext.is.Desktop) { me.stretchEl = Ext.getBody().createChild({ cls: 'x-body-stretcher', style: 'height: ' + stretchSize + 'px; width:' + (Ext.is.Android ? stretchSize + 'px' : '1px') }); } setTimeout(function() { me.scrollToTop(); setTimeout(function() { // me.updateSize(); Ext.getBody().setStyle('overflow', 'hidden'); if (Ext.is.Android && me.stretchEl) { me.stretchEl.remove(); delete me.stretchEl; } if (fn) { setTimeout(function() { fn(); if (!Ext.is.Android) { me.updateBodySize(); } }, 500); } }, 200); }, 500); if (!Ext.is.Android) { this.on('orientationchange', function() { if (Ext.currentlyFocusedField) { Ext.currentlyFocusedField.blur(); } }); } }, showStretchEl: function() { if (!Ext.is.Android && this.stretchEl) { this.stretchEl.setStyle('display', 'block'); } }, hideStretchEl: function() { if (!Ext.is.Android && this.stretchEl) { this.stretchEl.setStyle('display', 'none'); } }, updateBodySize: function() { // Why Ext.getBody() is undefined in here? WTF! document.body.style.width = window.innerWidth + 'px'; document.body.style.height = window.innerHeight + 'px'; }, updateOrientation: function() { this.lastSize = this.getSize(); this.orientation = this.getOrientation(); }, onTouchStartCapturing: function(e) { var target = e.target; if (!Ext.currentlyFocusedField && !Ext.is.Android) { this.scrollToTop(); } if (Ext.is.Android) { if (target.tagName && (/input|select|textarea/i.test(target.tagName))) { return; } e.preventDefault(); e.stopPropagation(); } }, onTouchMoveBubbling: function(e) { e.preventDefault(); e.stopPropagation(); }, // updateSize: function() { // var size = this.getSize(); // // if (!this.lastSize) { // this.lastSize = size; // return; // } // // if (size.width != this.lastSize.width || size.height != this.lastSize.height) { // this.fireResizeEvent(); // } // // this.lastSize = size; // }, onOrientationChange: function() { var me = this; this.updateOrientation(); this.fireEvent('orientationchange', this, this.orientation); if (!Ext.is.Android) { this.scrollToTop(1, function() { me.updateBodySize(); me.fireResizeEvent(); }, true); } else { this.scrollToTop(100, function() { me.fireResizeEvent(); }); } }, fireResizeEvent: function() { var me = this; var size = me.getSize(); if (Ext.is.Android) { if (this.resizeEventTimer) { clearTimeout(this.resizeEventTimer); } this.resizeEventTimer = setTimeout(function() { me.fireEvent('resize', me, me.getSize()); }, 500); } else { me.fireEvent('resize', me, me.getSize()); } }, onResize: function() { if (this.orientation != this.getOrientation()) { this.onOrientationChange(); } else { var size = this.getSize(); if (Ext.is.Android) { if ((size.width == this.lastSize.width && size.height > this.lastSize.height) || (size.height == this.lastSize.height && size.width > this.lastSize.width)) { this.fireEvent('resize', this, size); } } else { this.fireEvent('resize', this, size); } } }, getSize: function() { return { width: window.innerWidth, height: window.innerHeight }; }, getOffset: function() { return { x: window.pageXOffset, y: window.pageYOffset }; }, scrollToTop: function(delay, fn) { if (delay) { setTimeout(function() { window.scrollTo(0, Ext.is.Android ? -1 : 0); if (fn) { setTimeout(fn, 0); } }, delay); } else { window.scrollTo(0, Ext.is.Android ? -1 : 0); if (fn) { setTimeout(fn, 0); } } }, getOrientation: function() { var size = this.getSize(); if (window.hasOwnProperty('orientation')) { return (window.orientation == 0 || window.orientation == 180) ? 'portrait' : 'landscape'; } else { if (Ext.is.Android) { if ((size.width == this.lastSize.width && size.height < this.lastSize.height) || (size.height == this.lastSize.height && size.width < this.lastSize.width)) { return this.orientation; } } return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; } } })); //Initialize doc classes and feature detections (function() { var initExt = function() { // find the body element var bd = Ext.getBody(), cls = []; if (!bd) { return false; } var Is = Ext.is; if (Is.Phone) { cls.push('x-phone'); } else if (Is.Tablet) { cls.push('x-tablet'); } else if (Is.Desktop) { cls.push('x-desktop'); } if (Is.iPad) { cls.push('x-ipad'); } if (Is.iOS) { cls.push('x-ios'); } if (Is.Android) { cls.push('x-android'); } if (Is.Standalone) { cls.push('x-standalone'); } if (cls.length) { bd.addCls(cls); } return true; }; if (!initExt()) { Ext.onReady(initExt); } })();
JavaScript
/** * @class Ext.Element * <p>Encapsulates a DOM element, adding simple DOM manipulation facilities, normalizing for browser differences.</p> * <p>All instances of this class inherit the methods of {@link Ext.Fx} making visual effects easily available to all DOM elements.</p> * <p>Note that the events documented in this class are not Ext events, they encapsulate browser events. To * access the underlying browser event, see {@link Ext.EventObject#browserEvent}. Some older * browsers may not support the full range of events. Which events are supported is beyond the control of ExtJs.</p> * Usage:<br> <pre><code> // by id var el = Ext.get("my-div"); // by DOM element reference var el = Ext.get(myDivElement); </code></pre> * <b>Animations</b><br /> * <p>When an element is manipulated, by default there is no animation.</p> * <pre><code> var el = Ext.get("my-div"); // no animation el.setWidth(100); * </code></pre> * <p>Many of the functions for manipulating an element have an optional "animate" parameter. This * parameter can be specified as boolean (<tt>true</tt>) for default animation effects.</p> * <pre><code> // default animation el.setWidth(100, true); * </code></pre> * * <p>To configure the effects, an object literal with animation options to use as the Element animation * configuration object can also be specified. Note that the supported Element animation configuration * options are a subset of the {@link Ext.Fx} animation options specific to Fx effects. The supported * Element animation configuration options are:</p> <pre> Option Default Description --------- -------- --------------------------------------------- {@link Ext.Fx#duration duration} .35 The duration of the animation in seconds {@link Ext.Fx#easing easing} easeOut The easing method {@link Ext.Fx#callback callback} none A function to execute when the anim completes {@link Ext.Fx#scope scope} this The scope (this) of the callback function </pre> * * <pre><code> // Element animation options object var opt = { {@link Ext.Fx#duration duration}: 1, {@link Ext.Fx#easing easing}: 'elasticIn', {@link Ext.Fx#callback callback}: this.foo, {@link Ext.Fx#scope scope}: this }; // animation with some options set el.setWidth(100, opt); * </code></pre> * <p>The Element animation object being used for the animation will be set on the options * object as "anim", which allows you to stop or manipulate the animation. Here is an example:</p> * <pre><code> // using the "anim" property to get the Anim object if(opt.anim.isAnimated()){ opt.anim.stop(); } * </code></pre> * <p>Also see the <tt>{@link #animate}</tt> method for another animation technique.</p> * <p><b> Composite (Collections of) Elements</b></p> * <p>For working with collections of Elements, see {@link Ext.CompositeElement}</p> * @constructor Create a new Element directly. * @param {String/HTMLElement} element * @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class). */ (function() { var El = Ext.Element = Ext.extend(Object, { /** * The default unit to append to CSS values where a unit isn't provided (defaults to px). * @type String */ defaultUnit : "px", constructor : function(element, forceNew) { var dom = typeof element == 'string' ? document.getElementById(element) : element, id; if (!dom) { return null; } id = dom.id; if (!forceNew && id && Ext.cache[id]) { return Ext.cache[id].el; } /** * The DOM element * @type HTMLElement */ this.dom = dom; /** * The DOM element ID * @type String */ this.id = id || Ext.id(dom); return this; }, /** * Sets the passed attributes as attributes of this element (a style attribute can be a string, object or function) * @param {Object} o The object with the attributes * @param {Boolean} useSet (optional) false to override the default setAttribute to use expandos. * @return {Ext.Element} this */ set : function(o, useSet) { var el = this.dom, attr, value; for (attr in o) { if (o.hasOwnProperty(attr)) { value = o[attr]; if (attr == 'style') { this.applyStyles(value); } else if (attr == 'cls') { el.className = value; } else if (useSet !== false) { el.setAttribute(attr, value); } else { el[attr] = value; } } } return this; }, /** * Returns true if this element matches the passed simple selector (e.g. div.some-class or span:first-child) * @param {String} selector The simple selector to test * @return {Boolean} True if this element matches the selector, else false */ is : function(simpleSelector) { return Ext.DomQuery.is(this.dom, simpleSelector); }, /** * Returns the value of the "value" attribute * @param {Boolean} asNumber true to parse the value as a number * @return {String/Number} */ getValue : function(asNumber){ var val = this.dom.value; return asNumber ? parseInt(val, 10) : val; }, /** * Appends an event handler to this element. The shorthand version {@link #on} is equivalent. * @param {String} eventName The name of event to handle. * @param {Function} fn The handler function the event invokes. This function is passed * the following parameters:<ul> * <li><b>evt</b> : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li> * <li><b>el</b> : HtmlElement<div class="sub-desc">The DOM element which was the target of the event. * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li> * <li><b>o</b> : Object<div class="sub-desc">The options object from the addListener call.</div></li> * </ul> * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed. * <b>If omitted, defaults to this Element.</b>. * @param {Object} options (optional) An object containing handler configuration properties. * This may contain any of the following properties:<ul> * <li><b>scope</b> Object : <div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the handler function is executed. * <b>If omitted, defaults to this Element.</b></div></li> * <li><b>delegate</b> String: <div class="sub-desc">A simple selector to filter the target or look for a descendant of the target. See below for additional details.</div></li> * <li><b>stopEvent</b> Boolean: <div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li> * <li><b>preventDefault</b> Boolean: <div class="sub-desc">True to prevent the default action</div></li> * <li><b>stopPropagation</b> Boolean: <div class="sub-desc">True to prevent event propagation</div></li> * <li><b>normalized</b> Boolean: <div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li> * <li><b>target</b> Ext.Element: <div class="sub-desc">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.</div></li> * <li><b>delay</b> Number: <div class="sub-desc">The number of milliseconds to delay the invocation of the handler after the event fires.</div></li> * <li><b>single</b> Boolean: <div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li> * <li><b>buffer</b> Number: <div class="sub-desc">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.</div></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. Using the options argument, it is possible to combine different * types of listeners:<br> * <br> * A 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('tap', this.onTap, this, { single: true, delay: 100, stopEvent : true });</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({ 'tap' : { fn: this.onTap, scope: this }, 'doubletap' : { fn: this.onDoubleTap, scope: this }, 'swipe' : { fn: this.onSwipe, scope: this } });</code></pre> * <p> * Or a shorthand syntax:<br> * Code:<pre><code></p> el.on({ 'tap' : this.onTap, 'doubletap' : this.onDoubleTap, 'swipe' : this.onSwipe, scope: this }); * </code></pre></p> * <p><b>delegate</b></p> * <p>This is a configuration option that you can pass along when registering a handler for * an event to assist with event delegation. Event delegation is a technique that is used to * reduce memory consumption and prevent exposure to memory-leaks. By registering an event * for a container element as opposed to each element within a container. By setting this * configuration option to a simple selector, the target element will be filtered to look for * a descendant of the target. * For example:<pre><code> // using this markup: &lt;div id='elId'> &lt;p id='p1'>paragraph one&lt;/p> &lt;p id='p2' class='clickable'>paragraph two&lt;/p> &lt;p id='p3'>paragraph three&lt;/p> &lt;/div> // utilize event delegation to registering just one handler on the container element: el = Ext.get('elId'); el.on( 'tap', function(e,t) { // handle click console.info(t.id); // 'p2' }, this, { // filter the target element to be a descendant with the class 'tappable' delegate: '.tappable' } ); * </code></pre></p> * @return {Ext.Element} this */ addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); return this; }, /** * Removes an event handler from this element. The shorthand version {@link #un} is equivalent. * <b>Note</b>: if a <i>scope</i> was explicitly specified when {@link #addListener adding} the * listener, the same scope must be specified here. * Example: * <pre><code> el.removeListener('tap', this.handlerFn); // or el.un('tap', this.handlerFn); </code></pre> * @param {String} eventName The name of the event from which to remove the handler. * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b> * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added, * then this must refer to the same object. * @return {Ext.Element} this */ removeListener : function(eventName, fn, scope) { Ext.EventManager.un(this.dom, eventName, fn, scope); return this; }, /** * Removes all previous added listeners from this element * @return {Ext.Element} this */ removeAllListeners : function(){ Ext.EventManager.removeAll(this.dom); return this; }, /** * Recursively removes all previous added listeners from this element and its children * @return {Ext.Element} this */ purgeAllListeners : function() { Ext.EventManager.purgeElement(this, true); return this; }, /** * <p>Removes this element's dom reference. Note that event and cache removal is handled at {@link Ext#removeNode}</p> */ remove : function() { var me = this, dom = me.dom; if (dom) { delete me.dom; Ext.removeNode(dom); } }, isAncestor : function(c) { var p = this.dom; c = Ext.getDom(c); if (p && c) { return p.contains(c); } return false; }, /** * Determines if this element is a descendent of the passed in Element. * @param {Mixed} element An Ext.Element, HTMLElement or string linking to an id of an Element. * @returns {Boolean} */ isDescendent : function(p) { return Ext.fly(p, '_internal').isAncestor(this); }, /** * Returns true if this element is an ancestor of the passed element * @param {HTMLElement/String} el The element to check * @return {Boolean} True if this element is an ancestor of el, else false */ contains : function(el) { return !el ? false : this.isAncestor(el); }, /** * Returns the value of an attribute from the element's underlying DOM node. * @param {String} name The attribute name * @param {String} namespace (optional) The namespace in which to look for the attribute * @return {String} The attribute value */ getAttribute : function(name, ns) { var d = this.dom; return d.getAttributeNS(ns, name) || d.getAttribute(ns + ":" + name) || d.getAttribute(name) || d[name]; }, /** * Set the innerHTML of this element * @param {String} html The new HTML * @return {Ext.Element} this */ setHTML : function(html) { if(this.dom) { this.dom.innerHTML = html; } return this; }, /** * Returns the innerHTML of an Element or an empty string if the element's * dom no longer exists. */ getHTML : function() { return this.dom ? this.dom.innerHTML : ''; }, /** * Hide this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this */ hide : function() { this.setVisible(false); return this; }, /** * Show this element - Uses display mode to determine whether to use "display" or "visibility". See {@link #setVisible}. * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object * @return {Ext.Element} this */ show : function() { this.setVisible(true); return this; }, /** * Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use * the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property. * @param {Boolean} visible Whether the element is visible * @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object * @return {Ext.Element} this */ setVisible : function(visible, animate) { var me = this, dom = me.dom, mode = this.getVisibilityMode(); switch (mode) { case El.VISIBILITY: this.removeCls(['x-hidden-display', 'x-hidden-offsets']); this[visible ? 'removeCls' : 'addCls']('x-hidden-visibility'); break; case El.DISPLAY: this.removeCls(['x-hidden-visibility', 'x-hidden-offsets']); this[visible ? 'removeCls' : 'addCls']('x-hidden-display'); break; case El.OFFSETS: this.removeCls(['x-hidden-visibility', 'x-hidden-display']); this[visible ? 'removeCls' : 'addCls']('x-hidden-offsets'); break; } return me; }, getVisibilityMode: function() { var dom = this.dom, mode = El.data(dom, 'visibilityMode'); if (mode === undefined) { El.data(dom, 'visibilityMode', mode = El.DISPLAY); } return mode; }, setDisplayMode : function(mode) { El.data(this.dom, 'visibilityMode', mode); return this; } }); var Elp = El.prototype; /** * Visibility mode constant for use with {@link #setVisibilityMode}. Use visibility to hide element * @static * @type Number */ El.VISIBILITY = 1; /** * Visibility mode constant for use with {@link #setVisibilityMode}. Use display to hide element * @static * @type Number */ El.DISPLAY = 2; /** * Visibility mode constant for use with {@link #setVisibilityMode}. Use offsets to hide element * @static * @type Number */ El.OFFSETS = 3; El.addMethods = function(o){ Ext.apply(Elp, o); }; Elp.on = Elp.addListener; Elp.un = Elp.removeListener; // Alias for people used to Ext JS and Ext Core Elp.update = Elp.setHTML; /** * Retrieves Ext.Element objects. * <p><b>This method does not retrieve {@link Ext.Component Component}s.</b> 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. Automatically fixes if an * object was recreated with the same id via AJAX or DOM.</p> * @param {Mixed} el The id of the node, a DOM Node or an existing Element. * @return {Element} The Element object (or null if no matching element was found) * @static * @member Ext.Element * @method get */ El.get = function(el){ var extEl, dom, id; if(!el){ return null; } if (typeof el == "string") { // element id if (!(dom = document.getElementById(el))) { return null; } if (Ext.cache[el] && Ext.cache[el].el) { extEl = Ext.cache[el].el; extEl.dom = dom; } else { extEl = El.addToCache(new El(dom)); } return extEl; } else if (el.tagName) { // dom element if(!(id = el.id)){ id = Ext.id(el); } if (Ext.cache[id] && Ext.cache[id].el) { extEl = Ext.cache[id].el; extEl.dom = el; } else { extEl = El.addToCache(new El(el)); } return extEl; } else if (el instanceof El) { if(el != El.docEl){ // refresh dom element in case no longer valid, // catch case where it hasn't been appended el.dom = document.getElementById(el.id) || el.dom; } 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(!El.docEl){ var F = function(){}; F.prototype = Elp; El.docEl = new F(); El.docEl.dom = document; El.docEl.id = Ext.id(document); } return El.docEl; } return null; }; // private El.addToCache = function(el, id){ id = id || el.id; Ext.cache[id] = { el: el, data: {}, events: {} }; return el; }; // private method for getting and setting element data El.data = function(el, key, value) { el = El.get(el); if (!el) { return null; } var c = Ext.cache[el.id].data; if (arguments.length == 2) { return c[key]; } else { return (c[key] = value); } }; // 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.collectorThreadId); } else { var id, dom, EC = Ext.cache; for (id in EC) { if (!EC.hasOwnProperty(id)) { continue; } if(EC[id].skipGarbageCollection){ continue; } dom = EC[id].el.dom; if(!dom || !dom.parentNode || (!dom.offsetParent && !document.getElementById(id))){ if(Ext.enableListenerCollection){ Ext.EventManager.removeAll(dom); } delete EC[id]; } } } }; //El.collectorThreadId = setInterval(El.garbageCollect, 20000); // dom is optional El.Flyweight = function(dom) { this.dom = dom; }; var F = function(){}; F.prototype = Elp; El.Flyweight.prototype = new F; El.Flyweight.prototype.isFlyweight = true; El._flyweights = {}; /** * <p>Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element - * the dom node can be overwritten by other code. Shorthand of {@link Ext.Element#fly}</p> * <p>Use this to make one-time references to DOM elements which are not going to be accessed again either by * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link Ext#get} * will be more appropriate to take advantage of the caching provided by the Ext.Element class.</p> * @param {String/HTMLElement} el The dom node or id * @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts * (e.g. internally Ext uses "_global") * @return {Element} The shared Element object (or null if no matching element was found) * @member Ext.Element * @method fly */ El.fly = function(el, named) { var ret = null; named = named || '_global'; el = Ext.getDom(el); if (el) { (El._flyweights[named] = El._flyweights[named] || new El.Flyweight()).dom = el; ret = El._flyweights[named]; } return ret; }; /** * Retrieves Ext.Element objects. * <p><b>This method does not retrieve {@link Ext.Component Component}s.</b> 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. Automatically fixes if an * object was recreated with the same id via AJAX or DOM.</p> * Shorthand of {@link Ext.Element#get} * @param {Mixed} el The id of the node, a DOM Node or an existing Element. * @return {Element} The Element object (or null if no matching element was found) * @member Ext * @method get */ Ext.get = El.get; /** * <p>Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element - * the dom node can be overwritten by other code. Shorthand of {@link Ext.Element#fly}</p> * <p>Use this to make one-time references to DOM elements which are not going to be accessed again either by * application code, or by Ext's classes. If accessing an element which will be processed regularly, then {@link Ext#get} * will be more appropriate to take advantage of the caching provided by the Ext.Element class.</p> * @param {String/HTMLElement} el The dom node or id * @param {String} named (optional) Allows for creation of named reusable flyweights to prevent conflicts * (e.g. internally Ext uses "_global") * @return {Element} The shared Element object (or null if no matching element was found) * @member Ext * @method fly */ Ext.fly = El.fly; /*Ext.EventManager.on(window, 'unload', function(){ delete Ext.cache; delete El._flyweights; });*/ })();
JavaScript
/** * @class Ext.History * @extends Ext.util.Observable * @ignore * @private * * Mobile-optimized port of Ext.History. Note - iPad on iOS < 4.2 does not have HTML5 History support so we still * have to poll for changes. */ Ext.History = new Ext.util.Observable({ constructor: function() { Ext.History.superclass.constructor.call(this, config); this.addEvents( /** * @event change */ 'change' ); }, /** * @private * Initializes event listeners */ init: function() { var me = this; me.setToken(window.location.hash); if (Ext.supports.History) { window.addEventListener('hashchange', this.onChange); } else { setInterval(function() { var newToken = me.cleanToken(window.location.hash), oldToken = me.getToken(); if (newToken != oldToken) { me.onChange(); } }, 50); } }, /** * @private * Event listener for the hashchange event */ onChange: function() { var me = Ext.History, newToken = me.cleanToken(window.location.hash); if (me.token != newToken) { me.fireEvent('change', newToken); } me.setToken(newToken); }, /** * Sets a new token, stripping of the leading # if present. Does not fire the 'change' event * @param {String} token The new token * @return {String} The cleaned token */ setToken: function(token) { return this.token = this.cleanToken(token); }, /** * @private * Cleans a token by stripping off the leading # if it is present * @param {String} token The unclean token * @return {String} The clean token */ cleanToken: function(token) { return token[0] == '#' ? token.substr(1) : token; }, /** * Returns the current history token * @return {String} The current token */ getToken: function() { return this.token; }, /** * Adds a token to the history stack by updation the address bar hash * @param {String} token The new token */ add: function(token) { window.location.hash = this.setToken(token); if (!Ext.supports.History) { this.onChange(); } } });
JavaScript
Ext.gesture.Tap = Ext.extend(Ext.gesture.Gesture, { handles: [ 'tapstart', 'tapcancel', 'tap', 'doubletap', 'taphold', 'singletap' ], cancelThreshold: 10, doubleTapThreshold: 800, singleTapThreshold: 400, holdThreshold: 1000, fireClickEvent: false, onTouchStart : function(e, touch) { var me = this; me.startX = touch.pageX; me.startY = touch.pageY; me.fire('tapstart', e, me.getInfo(touch)); if (this.listeners.taphold) { me.timeout = setTimeout(function() { me.fire('taphold', e, me.getInfo(touch)); delete me.timeout; }, me.holdThreshold); } me.lastTouch = touch; }, onTouchMove : function(e, touch) { var me = this; if (me.isCancel(touch)) { me.fire('tapcancel', e, me.getInfo(touch)); if (me.timeout) { clearTimeout(me.timeout); delete me.timeout; } me.stop(); } me.lastTouch = touch; }, onTouchEnd : function(e) { var me = this, info = me.getInfo(me.lastTouch); this.fireTapEvent(e, info); if (me.lastTapTime && e.timeStamp - me.lastTapTime <= me.doubleTapThreshold) { me.lastTapTime = null; e.preventDefault(); me.fire('doubletap', e, info); } else { me.lastTapTime = e.timeStamp; } if (me.listeners && me.listeners.singletap && me.singleTapThreshold && !me.preventSingleTap) { me.fire('singletap', e, info); me.preventSingleTap = true; setTimeout(function() { me.preventSingleTap = false; }, me.singleTapThreshold); } if (me.timeout) { clearTimeout(me.timeout); delete me.timeout; } }, fireTapEvent: function(e, info) { this.fire('tap', e, info); if (e.event) e = e.event; var target = (e.changedTouches ? e.changedTouches[0] : e).target; if (!target.disabled && this.fireClickEvent) { var clickEvent = document.createEvent("MouseEvent"); clickEvent.initMouseEvent('click', e.bubbles, e.cancelable, document.defaultView, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.metaKey, e.button, e.relatedTarget); clickEvent.isManufactured = true; target.dispatchEvent(clickEvent); } }, getInfo : function(touch) { return { pageX: touch.pageX, pageY: touch.pageY }; }, isCancel : function(touch) { var me = this; return ( Math.abs(touch.pageX - me.startX) >= me.cancelThreshold || Math.abs(touch.pageY - me.startY) >= me.cancelThreshold ); } }); Ext.regGesture('tap', Ext.gesture.Tap);
JavaScript
Ext.gesture.Pinch = Ext.extend(Ext.gesture.Gesture, { handles: [ 'pinchstart', 'pinch', 'pinchend' ], touches: 2, onTouchStart : function(e) { var me = this; if (Ext.supports.Touch && e.targetTouches.length >= 2) { me.lock('swipe', 'scroll', 'scrollstart', 'scrollend', 'touchmove', 'touchend', 'touchstart', 'tap', 'tapstart', 'taphold', 'tapcancel', 'doubletap'); me.pinching = true; var targetTouches = e.targetTouches, firstTouch = me.firstTouch = targetTouches[0], secondTouch = me.secondTouch = targetTouches[1]; me.previousDistance = me.startDistance = me.getDistance(); me.previousScale = 1; me.fire('pinchstart', e, { distance: me.startDistance, scale: me.previousScale }); } else if (me.pinching) { me.unlock('swipe', 'scroll', 'scrollstart', 'scrollend', 'touchmove', 'touchend', 'touchstart', 'tap', 'tapstart', 'taphold', 'tapcancel', 'doubletap'); me.pinching = false; } }, onTouchMove : function(e) { if (this.pinching) { this.fire('pinch', e, this.getPinchInfo()); } }, onTouchEnd : function(e) { if (this.pinching) { this.fire('pinchend', e, this.getPinchInfo()); } }, getPinchInfo : function() { var me = this, distance = me.getDistance(), scale = distance / me.startDistance, firstTouch = me.firstTouch, secondTouch = me.secondTouch, info = { scale: scale, deltaScale: scale - 1, previousScale: me.previousScale, previousDeltaScale: scale - me.previousScale, distance: distance, deltaDistance: distance - me.startDistance, startDistance: me.startDistance, previousDistance: me.previousDistance, previousDeltaDistance: distance - me.previousDistance, firstTouch: firstTouch, secondTouch: secondTouch, firstPageX: firstTouch.pageX, firstPageY: firstTouch.pageY, secondPageX: secondTouch.pageX, secondPageY: secondTouch.pageY, // The midpoint between the touches is (x1 + x2) / 2, (y1 + y2) / 2 midPointX: (firstTouch.pageX + secondTouch.pageX) / 2, midPointY: (firstTouch.pageY + secondTouch.pageY) / 2 }; me.previousScale = scale; me.previousDistance = distance; return info; }, getDistance : function() { var me = this; return Math.sqrt( Math.pow(Math.abs(me.firstTouch.pageX - me.secondTouch.pageX), 2) + Math.pow(Math.abs(me.firstTouch.pageY - me.secondTouch.pageY), 2) ); } }); Ext.regGesture('pinch', Ext.gesture.Pinch);
JavaScript
Ext.gesture.Drag = Ext.extend(Ext.gesture.Touch, { handles: ['dragstart', 'drag', 'dragend'], dragThreshold: 5, direction: 'both', horizontal: false, vertical: false, constructor: function() { Ext.gesture.Drag.superclass.constructor.apply(this, arguments); if (this.direction == 'both') { this.horizontal = true; this.vertical = true; } else if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } return this; }, onTouchStart: function(e, touch) { this.startX = this.previousX = touch.pageX; this.startY = this.previousY = touch.pageY; this.startTime = this.previousTime = e.timeStamp; if (!this.dragThreshold) { var info = this.getInfo(touch); if (this.fire('dragstart', e, info)) { this.dragging = true; this.lock('drag', 'dragstart', 'dragend'); this.fire('drag', e, info); } } else { this.dragging = false; } }, onTouchMove: function(e, touch) { var info = this.getInfo(touch); if (!this.dragging) { if (this.isDragging(info) && this.fire('dragstart', e, info)) { this.dragging = true; this.lock('drag', 'dragstart', 'dragend'); this.fire('drag', e, info); } } else { this.fire('drag', e, info); } }, onTouchEnd: function(e) { if (this.dragging) { this.fire('dragend', e, this.lastInfo); } this.dragging = false; }, isDragging: function(info) { return ( (this.horizontal && info.absDeltaX >= this.dragThreshold) || (this.vertical && info.absDeltaY >= this.dragThreshold) ); }, /** * Method to determine whether this Sortable is currently disabled. * @return {Boolean} the disabled state of this Sortable. */ isVertical: function() { return this.vertical; }, /** * Method to determine whether this Sortable is currently sorting. * @return {Boolean} the sorting state of this Sortable. */ isHorizontal: function() { return this.horizontal; } }); Ext.regGesture('drag', Ext.gesture.Drag);
JavaScript
Ext.gesture.Manager = new Ext.AbstractManager({ startEvent: 'touchstart', moveEvent: 'touchmove', endEvent: 'touchend', init: function() { this.targets = []; if (!Ext.supports.Touch) { Ext.apply(this, { startEvent: 'mousedown', moveEvent: 'mousemove', endEvent: 'mouseup' }); } this.followTouches = []; this.currentGestures = []; this.currentTargets = []; document.addEventListener(this.startEvent, Ext.createDelegate(this.onTouchStart, this), true); document.addEventListener(this.endEvent, Ext.createDelegate(this.onTouchEnd, this), true); if (!Ext.is.Desktop) { document.addEventListener('click', Ext.createDelegate(this.onClick, this), true); this.addEventListener(Ext.getBody(), 'tap', Ext.emptyFn, {capture: true, fireClickEvent: true}); } // Not sure if it's even needed // if (Ext.is.Blackberry) { // document.addEventListener('mousedown', this.onMouseDown, false); // } }, onClick: function(e) { var target = e.target; if (!(e.isManufactured == true) || target.disabled == true) { e.stopPropagation(); e.preventDefault(); } }, onMouseDown: function(e) { e.stopPropagation(); e.preventDefault(); }, onTouchStart: function(e) { var targets = [], target = e.target; this.locks = {}; this.currentTargets = [target]; while (target) { if (this.targets.indexOf(target) != -1) { targets.unshift(target); } target = target.parentNode; this.currentTargets.push(target); } this.startEvent = e; this.handleTargets(targets, e); }, /** * This listener is here to always ensure we stop all current gestures * @private */ onTouchEnd: function(e) { var gestures = this.currentGestures.slice(0), ln = gestures.length, i, gesture; this.followTouches = []; this.startedChangedTouch = false; this.currentTargets = []; this.startEvent = null; for (i = 0; i < ln; i++) { gesture = gestures[i]; if (!e.stopped && gesture.listenForEnd) { gesture.onTouchEnd(e, e.changedTouches ? e.changedTouches[0]: e); gesture.lastMovePoint = null; } this.stopGesture(gesture); } }, startGesture: function(gesture) { var me = this; gesture.started = true; if (gesture.listenForMove) { gesture.onTouchMoveWrap = function(e) { var point = Ext.util.Point.fromEvent(e); if (!gesture.lastMovePoint) { gesture.lastMovePoint = point; } else { if (gesture.lastMovePoint.equals(point)) { return; } else { gesture.lastMovePoint.copyFrom(point); } } if (!e.stopped) { gesture.onTouchMove(e, e.changedTouches ? e.changedTouches[0]: e); } }; gesture.target.addEventListener(me.moveEvent, gesture.onTouchMoveWrap, !!gesture.capture); } this.currentGestures.push(gesture); }, stopGesture: function(gesture) { gesture.started = false; if (gesture.listenForMove) { gesture.target.removeEventListener(this.moveEvent, gesture.onTouchMoveWrap, !!gesture.capture); } this.currentGestures.remove(gesture); }, handleTargets: function(targets, e) { // In handle targets we have to first handle all the capture targets, // then all the bubble targets. var ln = targets.length, i, target; this.startedChangedTouch = false; this.startedTouches = Ext.supports.Touch ? e.touches : [e]; for (i = 0; i < ln; i++) { if (e.stopped) { break; } target = targets[i]; this.handleTarget(target, e, true); } for (i = ln - 1; i >= 0; i--) { if (e.stopped) { break; } target = targets[i]; this.handleTarget(target, e, false); } if (this.startedChangedTouch) { this.followTouches = this.followTouches.concat(Ext.supports.Touch ? Ext.toArray(e.targetTouches) : [e]); } }, handleTarget: function(target, e, capture) { var gestures = Ext.Element.data(target, 'x-gestures') || [], ln = gestures.length, i, gesture; for (i = 0; i < ln; i++) { gesture = gestures[i]; if ( (!!gesture.capture === !!capture) && (this.followTouches.length < gesture.touches) && (Ext.supports.Touch ? (e.targetTouches.length === gesture.touches) : true) ) { this.startedChangedTouch = true; this.startGesture(gesture); if (gesture.listenForStart) { gesture.onTouchStart(e, e.changedTouches ? e.changedTouches[0] : e); } if (e.stopped) { break; } } } }, addEventListener: function(target, eventName, listener, options) { target = Ext.getDom(target); var targets = this.targets, name = this.getGestureName(eventName), gestures = Ext.Element.data(target, 'x-gestures') || [], gesture; // <debug> if (!name) { throw 'Trying to subscribe to unknown event ' + eventName; } // </debug> if (targets.indexOf(target) == -1) { this.targets.push(target); } gesture = this.get(target.id + '-' + name); if (!gesture) { gesture = this.create(Ext.apply({}, options || {}, { target: target, type: name })); gestures.push(gesture); Ext.Element.data(target, 'x-gestures', gestures); } gesture.addListener(eventName, listener); // If there is already a finger down, then instantly start the gesture if (this.startedChangedTouch && this.currentTargets.contains(target) && !gesture.started) { this.startGesture(gesture); if (gesture.listenForStart) { gesture.onTouchStart(this.startEvent, this.startedTouches[0]); } } }, removeEventListener: function(target, eventName, listener) { target = Ext.getDom(target); var name = this.getGestureName(eventName), gestures = Ext.Element.data(target, 'x-gestures') || [], gesture; gesture = this.get(target.id + '-' + name); if (gesture) { gesture.removeListener(eventName, listener); for (name in gesture.listeners) { return; } gesture.destroy(); gestures.remove(gesture); Ext.Element.data(target, 'x-gestures', gestures); } }, getGestureName: function(ename) { return this.names && this.names[ename]; }, registerType: function(type, cls) { var handles = cls.prototype.handles, i, ln; this.types[type] = cls; cls[this.typeName] = type; if (!handles) { handles = cls.prototype.handles = [type]; } this.names = this.names || {}; for (i = 0, ln = handles.length; i < ln; i++) { this.names[handles[i]] = type; } } }); Ext.regGesture = function() { return Ext.gesture.Manager.registerType.apply(Ext.gesture.Manager, arguments); };
JavaScript
Ext.gesture.Gesture = Ext.extend(Object, { listenForStart: true, listenForEnd: true, listenForMove: true, disableLocking: false, touches: 1, constructor: function(config) { config = config || {}; Ext.apply(this, config); this.target = Ext.getDom(this.target); this.listeners = {}; // <debug> if (!this.target) { throw 'Trying to bind a ' + this.type + ' event to element that does\'nt exist: ' + this.target; } // </debug> this.id = this.target.id + '-' + this.type; Ext.gesture.Gesture.superclass.constructor.call(this); Ext.gesture.Manager.register(this); }, addListener: function(name, listener) { this.listeners[name] = this.listeners[name] || []; this.listeners[name].push(listener); }, removeListener: function(name, listener) { var listeners = this.listeners[name]; if (listeners) { listeners.remove(listener); if (listeners.length == 0) { delete this.listeners[name]; } for (name in this.listeners) { if (this.listeners.hasOwnProperty(name)) { return; } } this.listeners = {}; } }, fire: function(type, e, args) { var listeners = this.listeners[type], ln = listeners && listeners.length, i; if (!this.disableLocking && this.isLocked(type)) { return false; } if (ln) { args = Ext.apply(args || {}, { time: e.timeStamp, type: type, gesture: this, target: (e.target.nodeType == 3) ? e.target.parentNode: e.target }); for (i = 0; i < ln; i++) { listeners[i](e, args); } } return true; }, stop: function() { Ext.gesture.Manager.stopGesture(this); }, lock: function() { if (!this.disableLocking) { var args = arguments, ln = args.length, i; for (i = 0; i < ln; i++) { Ext.gesture.Manager.locks[args[i]] = this.id; } } }, unlock: function() { if (!this.disableLocking) { var args = arguments, ln = args.length, i; for (i = 0; i < ln; i++) { if (Ext.gesture.Manager.locks[args[i]] == this.id) { delete Ext.gesture.Manager.locks[args[i]]; } } } }, isLocked : function(type) { var lock = Ext.gesture.Manager.locks[type]; return !!(lock && lock !== this.id); }, getLockingGesture : function(type) { var lock = Ext.gesture.Manager.locks[type]; if (lock) { return Ext.gesture.Manager.get(lock) || null; } return null; }, onTouchStart: Ext.emptyFn, onTouchMove: Ext.emptyFn, onTouchEnd: Ext.emptyFn, destroy: function() { this.stop(); this.listeners = null; Ext.gesture.Manager.unregister(this); } });
JavaScript
Ext.gesture.Touch = Ext.extend(Ext.gesture.Gesture, { handles: ['touchstart', 'touchmove', 'touchend', 'touchdown'], touchDownInterval: 500, onTouchStart: function(e, touch) { this.startX = this.previousX = touch.pageX; this.startY = this.previousY = touch.pageY; this.startTime = this.previousTime = e.timeStamp; this.fire('touchstart', e); this.lastEvent = e; if (this.listeners.touchdown) { this.touchDownIntervalId = setInterval(Ext.createDelegate(this.touchDownHandler, this), this.touchDownInterval); } }, onTouchMove: function(e, touch) { this.fire('touchmove', e, this.getInfo(touch)); this.lastEvent = e; }, onTouchEnd: function(e) { this.fire('touchend', e, this.lastInfo); clearInterval(this.touchDownIntervalId); }, touchDownHandler : function() { this.fire('touchdown', this.lastEvent, this.lastInfo); }, getInfo : function(touch) { var time = (new Date()).getTime(), deltaX = touch.pageX - this.startX, deltaY = touch.pageY - this.startY, info = { startX: this.startX, startY: this.startY, previousX: this.previousX, previousY: this.previousY, pageX: touch.pageX, pageY: touch.pageY, deltaX: deltaX, deltaY: deltaY, absDeltaX: Math.abs(deltaX), absDeltaY: Math.abs(deltaY), previousDeltaX: touch.pageX - this.previousX, previousDeltaY: touch.pageY - this.previousY, time: time, startTime: this.startTime, previousTime: this.previousTime, deltaTime: time - this.startTime, previousDeltaTime: time - this.previousTime }; this.previousTime = info.time; this.previousX = info.pageX; this.previousY = info.pageY; this.lastInfo = info; return info; } }); Ext.regGesture('touch', Ext.gesture.Touch);
JavaScript
Ext.gesture.Swipe = Ext.extend(Ext.gesture.Gesture, { listenForEnd: false, swipeThreshold: 35, swipeTime: 1000, onTouchStart : function(e, touch) { this.startTime = e.timeStamp; this.startX = touch.pageX; this.startY = touch.pageY; this.lock('scroll', 'scrollstart', 'scrollend'); }, onTouchMove : function(e, touch) { var deltaY = touch.pageY - this.startY, deltaX = touch.pageX - this.startX, absDeltaY = Math.abs(deltaY), absDeltaX = Math.abs(deltaX), deltaTime = e.timeStamp - this.startTime; // If the swipeTime is over, we are not gonna check for it again if (absDeltaY - absDeltaX > 3 || deltaTime > this.swipeTime) { this.unlock('scroll', 'scrollstart', 'scrollend'); this.stop(); } else if (absDeltaX > this.swipeThreshold && absDeltaX > absDeltaY) { // If this is a swipe, a scroll is not possible anymore this.fire('swipe', e, { direction: (deltaX < 0) ? 'left' : 'right', distance: absDeltaX, deltaTime: deltaTime, deltaX: deltaX }); this.stop(); } } }); Ext.regGesture('swipe', Ext.gesture.Swipe);
JavaScript
Ext.TouchEventObjectImpl = Ext.extend(Object, { constructor : function(e, args) { if (e) { this.setEvent(e, args); } }, setEvent : function(e, args) { Ext.apply(this, { event: e, time: e.timeStamp }); this.touches = e.touches || [e]; this.changedTouches = e.changedTouches || [e]; this.targetTouches = e.targetTouches || [e]; if (args) { this.target = args.target; Ext.apply(this, args); } else { this.target = e.target; } return this; }, stopEvent : function() { this.stopPropagation(); this.preventDefault(); }, stopPropagation : function() { this.event.stopped = true; }, preventDefault : function() { this.event.preventDefault(); }, getTarget : function(selector, maxDepth, returnEl) { if (selector) { return Ext.fly(this.target).findParent(selector, maxDepth, returnEl); } else { return returnEl ? Ext.get(this.target) : this.target; } } }); Ext.TouchEventObject = new Ext.TouchEventObjectImpl();
JavaScript
/** * @class Ext.ComponentQuery * @extends Object * * Provides searching of Components within Ext.ComponentMgr (globally) or a specific * Ext.Container on the page with a similar syntax to a CSS selector. * * Xtypes can be retrieved by their name with an optional . prefix <ul> <li>component or .component</li> <li>gridpanel or .gridpanel</li> </ul> * * An itemId or id must be prefixed with a #. <ul> <li>#myContainer</li> </ul> * * * Attributes must be wrapped in brackets <ul> <li>component[autoScroll]</li> <li>panel[title="Test"]</li> </ul> * Queries return an array of components. * Here are some example queries. <pre><code> // retrieve all Ext.Panel's on the page by xtype var panelsArray = Ext.ComponentQuery.query('.panel'); // retrieve all Ext.Panels within the container with an id myCt var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt .panel'); // retrieve all direct children which are Ext.Panels within myCt var directChildPanel = Ext.ComponentQuery.query('#myCt > .panel'); // retrieve all gridpanels and listviews var gridsAndLists = Ext.ComponentQuery.query('gridpanel, listview'); </code></pre> * @singleton */ Ext.ComponentQuery = { // Determines leading mode // > for direct child modeRe: /^(\s?[>]\s?|\s|$)/, tokenRe: /^(#)?([\w-\*]+)/, matchers : [{ // Checks for .xtype re: /^\.([\w-]+)/, method: 'getByXType' },{ // checks for [attribute=value] re: /^(?:[\[\{](?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, method: 'getByAttribute' }, { // checks for #cmpId re: /^#([\w-]+)/, method: 'getById' }], // private cache of selectors and matching ComponentQuery.Query objects cache: {}, query: function(selector, root) { var selectors = selector.split(','), ln = selectors.length, i, query, results = [], noDupResults = [], dupMatcher = {}, resultsLn, cmp; for (i = 0; i < ln; i++) { selector = Ext.util.Format.trim(selectors[i]); query = this.cache[selector]; if (!query) { this.cache[selector] = query = this.parse(selector); } results = results.concat(query.execute(root)); } // multiple selectors, potential to find duplicates // lets filter them out. if (ln > 1) { resultsLn = results.length; for (i = 0; i < resultsLn; i++) { cmp = results[i]; if (!dupMatcher[cmp.id]) { noDupResults.push(cmp); dupMatcher[cmp.id] = true; } } results = noDupResults; } return results; }, parse: function(selector) { var matchers = this.matchers, operations = [], ln = matchers.length, lastSelector, tokenMatch, modeMatch, selectorMatch, args, i, matcher; // We are going to parse the beginning of the selector over and // over again, slicing of any portions we converted into an // operation of the selector until it is an empty string. while (selector && lastSelector != selector) { lastSelector = selector; // First we check if we are dealing with a token like #, * or an xtype tokenMatch = selector.match(this.tokenRe); if (tokenMatch) { // If the token is a # we push a getById operation to our stack if (tokenMatch[1] == '#') { operations.push({ method: 'getById', args: [Ext.util.Format.trim(tokenMatch[2])] }); } // If the token is a * or an xtype string, we push a getByXType // operation to the stack. else { operations.push({ method: 'getByXType', args: [Ext.util.Format.trim(tokenMatch[2])] }); } // Now we slice of the part we just converted into an operation selector = selector.replace(tokenMatch[0], ''); } // If the next part of the query is not a space or >, it means we // are going to check for more things that our current selection // has to comply to. while (!(modeMatch = selector.match(this.modeRe))) { // Lets loop over each type of matcher and execute it // on our current selector. for (i = 0; i < ln; i++) { matcher = matchers[i]; selectorMatch = selector.match(matcher.re); // If we have a match, add an operation with the method // associated with this matcher, and pass the regular // expression matches are arguments to the operation. if (selectorMatch) { operations.push({ method: matcher.method, args: selectorMatch.splice(1) }); selector = selector.replace(selectorMatch[0], ''); // dont think the break is required //break; } } } // Now we are going to check for a mode change. This means a space // or a > to determine if we are going to select all the children // of the currently matched items. if (modeMatch[1]) { operations.push({ mode: modeMatch[1] }); selector = selector.replace(modeMatch[1], ''); } } // Now that we have all our operations in an array, we are going // to create a new Query using these operations. return new Ext.ComponentQuery.Query({ operations: operations }); } }; /** * @class Ext.ComponentQuery.Query * @extends Object * @private */ Ext.ComponentQuery.Query = Ext.extend(Object, { constructor: function(cfg) { cfg = cfg || {}; Ext.apply(this, cfg); }, execute : function(root) { var operations = this.operations, ln = operations.length, operation, i, workingItems; // no root, use all Components on the page if (!root) { workingItems = Ext.ComponentMgr.all.items.slice(); } // We are going to loop over our operations and take care of them // one by one. for (i = 0; i < ln; i++) { operation = operations[i]; // The mode operation requires some custom handling. // All other operations essentially filter down our current // working items, while mode replaces our current working // items by getting children from each one of our current // working items. The type of mode determines the type of // children we get. (e.g. > only gets direct children) if (operation.mode) { workingItems = this.getItems(workingItems || [root], operation.mode); } else { workingItems = this.filterItems(workingItems || this.getItems([root]), operation); } // If this is the last operation, it means our current working // items are the final matched items. Thus return them! if (i == ln -1) { return workingItems; } } return []; }, filterItems : function(items, operation) { var matchedItems = [], ln = items.length, i, item, args, matches; // Loop over each item, execute the operation. If the operation // returns true, it means the item should still be in our working // items. for (i = 0; i < ln; i++) { item = items[i]; // We add the item as the first argument to the operation arguments. args = [item].concat(operation.args); // Execute the operation matches = this[operation.method].apply(this, args); if (matches) { matchedItems.push(item); } } return matchedItems; }, getItems: function(items, mode) { var workingItems = [], ln = items.length, item, i; mode = mode ? Ext.util.Format.trim(mode) : ''; for (i = 0; i < ln; i++) { item = items[i]; if (item.getRefItems) { workingItems = workingItems.concat(item.getRefItems(mode != '>')); } } return workingItems; }, // Verfies that a component is of a certain // xtype getByXType : function(cmp, xtype) { return xtype === '*' || cmp.isXType(xtype); }, // Verifies that a component has a certain // property and optionally that its value matches getByAttribute : function(cmp, property, operator, value) { return (value === undefined) ? !!cmp[property] : (cmp[property] == value); }, // Verifies that a component has a certain itemId or id getById : function(cmp, id) { return cmp.getItemId() == id; } });
JavaScript
/** * @class Ext.lib.Container * @extends Ext.Component * Shared Container class */ Ext.lib.Container = Ext.extend(Ext.Component, { /** * @cfg {String/Object} layout * <p><b>*Important</b>: In order for child items to be correctly sized and * positioned, typically a layout manager <b>must</b> be specified through * the <code>layout</code> configuration option.</p> * <br><p>The sizing and positioning of child {@link items} is the responsibility of * the Container's layout manager which creates and manages the type of layout * you have in mind. For example:</p> * <p>If the {@link #layout} configuration is not explicitly specified for * a general purpose container (e.g. Container or Panel) the * {@link Ext.layout.AutoContainerLayout default layout manager} will be used * which does nothing but render child components sequentially into the * Container (no sizing or positioning will be performed in this situation).</p> * <br><p><b><code>layout</code></b> may be specified as either as an Object or * as a String:</p><div><ul class="mdetail-params"> * * <li><u>Specify as an Object</u></li> * <div><ul class="mdetail-params"> * <li>Example usage:</li> * <pre><code> layout: { type: 'vbox', align: 'left' } </code></pre> * * <li><code><b>type</b></code></li> * <br/><p>The layout type to be used for this container. If not specified, * a default {@link Ext.layout.ContainerLayout} will be created and used.</p> * <br/><p>Valid layout <code>type</code> values are:</p> * <div class="sub-desc"><ul class="mdetail-params"> * <li><code><b>{@link Ext.layout.ContainerLayout auto}</b></code> &nbsp;&nbsp;&nbsp; <b>Default</b></li> * <li><code><b>{@link Ext.layout.CardLayout card}</b></code></li> * <li><code><b>{@link Ext.layout.FitLayout fit}</b></code></li> * <li><code><b>{@link Ext.layout.HBoxLayout hbox}</b></code></li> * <li><code><b>{@link Ext.layout.VBoxLayout vbox}</b></code></li> * </ul></div> * * <li>Layout specific configuration properties</li> * <br/><p>Additional layout specific configuration properties may also be * specified. For complete details regarding the valid config options for * each layout type, see the layout class corresponding to the <code>type</code> * specified.</p> * * </ul></div> * * <li><u>Specify as a String</u></li> * <div><ul class="mdetail-params"> * <li>Example usage:</li> * <pre><code> layout: { type: 'vbox', padding: '5', align: 'left' } </code></pre> * <li><code><b>layout</b></code></li> * <br/><p>The layout <code>type</code> to be used for this container (see list * of valid layout type values above).</p><br/> * <br/><p>Additional layout specific configuration properties. For complete * details regarding the valid config options for each layout type, see the * layout class corresponding to the <code>layout</code> specified.</p> * </ul></div></ul></div> */ /** * @cfg {String/Number} activeItem * A string component id or the numeric index of the component that should be initially activated within the * container's layout on render. For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first * item in the container's collection). activeItem only applies to layout styles that can display * items one at a time (like {@link Ext.layout.CardLayout} and * {@link Ext.layout.FitLayout}). Related to {@link Ext.layout.ContainerLayout#activeItem}. */ /** * @cfg {Object/Array} items * <pre><b>** IMPORTANT</b>: be sure to <b>{@link #layout specify a <code>layout</code>} if needed ! **</b></pre> * <p>A single item, or an array of child Components to be added to this container, * for example:</p> * <pre><code> // specifying a single item items: {...}, layout: 'fit', // specify a layout! // specifying multiple items items: [{...}, {...}], layout: 'hbox', // specify a layout! </code></pre> * <p>Each item may be:</p> * <div><ul class="mdetail-params"> * <li>any type of object based on {@link Ext.Component}</li> * <li>a fully instanciated object or</li> * <li>an object literal that:</li> * <div><ul class="mdetail-params"> * <li>has a specified <code>{@link Ext.Component#xtype xtype}</code></li> * <li>the {@link Ext.Component#xtype} specified is associated with the Component * desired and should be chosen from one of the available xtypes as listed * in {@link Ext.Component}.</li> * <li>If an <code>{@link Ext.Component#xtype xtype}</code> is not explicitly * specified, the {@link #defaultType} for that Container is used.</li> * <li>will be "lazily instanciated", avoiding the overhead of constructing a fully * instanciated Component object</li> * </ul></div></ul></div> * <p><b>Notes</b>:</p> * <div><ul class="mdetail-params"> * <li>Ext uses lazy rendering. Child Components will only be rendered * should it become necessary. Items are automatically laid out when they are first * shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</li> * <li>Do not specify <code>{@link Ext.Panel#contentEl contentEl}</code>/ * <code>{@link Ext.Panel#html html}</code> with <code>items</code>.</li> * </ul></div> */ /** * @cfg {Object|Function} defaults * <p>This option is a means of applying default settings to all added items whether added through the {@link #items} * config or via the {@link #add} or {@link #insert} methods.</p> * <p>If an added item is a config object, and <b>not</b> an instantiated Component, then the default properties are * unconditionally applied. If the added item <b>is</b> an instantiated Component, then the default properties are * applied conditionally so as not to override existing properties in the item.</p> * <p>If the defaults option is specified as a function, then the function will be called using this Container as the * scope (<code>this</code> reference) and passing the added item as the first parameter. Any resulting object * from that call is then applied to the item as default properties.</p> * <p>For example, to automatically apply padding to the body of each of a set of * contained {@link Ext.Panel} items, you could pass: <code>defaults: {bodyStyle:'padding:15px'}</code>.</p> * <p>Usage:</p><pre><code> defaults: { // defaults are applied to items, not the container autoScroll:true }, items: [ { xtype: 'panel', // defaults <b>do not</b> have precedence over id: 'panel1', // options in config objects, so the defaults autoScroll: false // will not be applied here, panel1 will be autoScroll:false }, new Ext.Panel({ // defaults <b>do</b> have precedence over options id: 'panel2', // options in components, so the defaults autoScroll: false // will be applied here, panel2 will be autoScroll:true. }) ] </code></pre> */ /** @cfg {Boolean} autoDestroy * If true the container will automatically destroy any contained component that is removed from it, else * destruction must be handled manually (defaults to true). */ autoDestroy : true, /** @cfg {String} defaultType * <p>The default {@link Ext.Component xtype} of child Components to create in this Container when * a child item is specified as a raw configuration object, rather than as an instantiated Component.</p> * <p>Defaults to <code>'panel'</code>.</p> */ defaultType: 'panel', isContainer : true, baseCls: 'x-container', /** * @cfg {Array} bubbleEvents * <p>An array of events that, when fired, should be bubbled to any parent container. * See {@link Ext.util.Observable#enableBubble}. * Defaults to <code>['add', 'remove']</code>. */ bubbleEvents: ['add', 'remove'], // @private initComponent : function(){ this.addEvents( /** * @event afterlayout * Fires when the components in this container are arranged by the associated layout manager. * @param {Ext.Container} this * @param {ContainerLayout} layout The ContainerLayout implementation for this container */ 'afterlayout', /** * @event beforeadd * Fires before any {@link Ext.Component} is added or inserted into the container. * A handler can return false to cancel the add. * @param {Ext.Container} this * @param {Ext.Component} component The component being added * @param {Number} index The index at which the component will be added to the container's items collection */ 'beforeadd', /** * @event beforeremove * Fires before any {@link Ext.Component} is removed from the container. A handler can return * false to cancel the remove. * @param {Ext.Container} this * @param {Ext.Component} component The component being removed */ 'beforeremove', /** * @event add * @bubbles * Fires after any {@link Ext.Component} is added or inserted into the container. * @param {Ext.Container} this * @param {Ext.Component} component The component that was added * @param {Number} index The index at which the component was added to the container's items collection */ 'add', /** * @event remove * @bubbles * Fires after any {@link Ext.Component} is removed from the container. * @param {Ext.Container} this * @param {Ext.Component} component The component that was removed */ 'remove', /** * @event beforecardswitch * Fires before this container switches the active card. This event * is only available if this container uses a CardLayout. Note that * TabPanel and Carousel both get a CardLayout by default, so both * will have this event. * A handler can return false to cancel the card switch. * @param {Ext.Container} this * @param {Ext.Component} newCard The card that will be switched to * @param {Ext.Component} oldCard The card that will be switched from * @param {Number} index The index of the card that will be switched to * @param {Boolean} animated True if this cardswitch will be animated */ 'beforecardswitch', /** * @event cardswitch * Fires after this container switches the active card. If the card * is switched using an animation, this event will fire after the * animation has finished. This event is only available if this container * uses a CardLayout. Note that TabPanel and Carousel both get a CardLayout * by default, so both will have this event. * @param {Ext.Container} this * @param {Ext.Component} newCard The card that has been switched to * @param {Ext.Component} oldCard The card that has been switched from * @param {Number} index The index of the card that has been switched to * @param {Boolean} animated True if this cardswitch was animated */ 'cardswitch' ); // layoutOnShow stack this.layoutOnShow = new Ext.util.MixedCollection(); Ext.lib.Container.superclass.initComponent.call(this); this.initItems(); }, // @private initItems : function() { var items = this.items; /** * The MixedCollection containing all the child items of this container. * @property items * @type Ext.util.MixedCollection */ this.items = new Ext.util.MixedCollection(false, this.getComponentId); if (items) { if (!Ext.isArray(items)) { items = [items]; } this.add(items); } }, // @private afterRender : function() { this.getLayout(); Ext.lib.Container.superclass.afterRender.apply(this, arguments); }, // @private setLayout : function(layout) { var currentLayout = this.layout; if (currentLayout && currentLayout.isLayout && currentLayout != layout) { currentLayout.setOwner(null); } this.layout = layout; layout.setOwner(this); }, /** * Returns the {@link Ext.layout.ContainerLayout layout} instance currently associated with this Container. * If a layout has not been instantiated yet, that is done first * @return {Ext.layout.ContainerLayout} The layout */ getLayout : function() { if (!this.layout || !this.layout.isLayout) { this.setLayout(Ext.layout.LayoutManager.create(this.layout, 'autocontainer')); } return this.layout; }, /** * Force this container's layout to be recalculated. A call to this function is required after adding a new component * to an already rendered container, or possibly after changing sizing/position properties of child components. * @return {Ext.Container} this */ doLayout : function() { var layout = this.getLayout(); if (this.rendered && layout) { layout.layout(); } return this; }, // @private afterLayout : function(layout) { this.fireEvent('afterlayout', this, layout); }, // @private prepareItems : function(items, applyDefaults) { if (!Ext.isArray(items)) { items = [items]; } // Make sure defaults are applied and item is initialized var item, i, ln; for (i = 0, ln = items.length; i < ln; i++) { item = items[i]; if (applyDefaults) { item = this.applyDefaults(item); } items[i] = this.lookupComponent(item); } return items; }, // @private applyDefaults : function(config) { var defaults = this.defaults; if (defaults) { if (Ext.isFunction(defaults)) { defaults = defaults.call(this, config); } if (Ext.isString(config)) { config = Ext.ComponentMgr.get(config); Ext.apply(config, defaults); } else if (!config.isComponent) { Ext.applyIf(config, defaults); } else { Ext.apply(config, defaults); } } return config; }, // @private lookupComponent : function(comp) { if (Ext.isString(comp)) { return Ext.ComponentMgr.get(comp); } else { return this.createComponent(comp); } return comp; }, // @private createComponent : function(config, defaultType) { if (config.isComponent) { return config; } // // add in ownerCt at creation time but then immediately // // remove so that onBeforeAdd can handle it // var component = Ext.create(Ext.apply({ownerCt: this}, config), defaultType || this.defaultType); // // delete component.initialConfig.ownerCt; // delete component.ownerCt; return Ext.create(config, defaultType || this.defaultType); }, // @private - used as the key lookup function for the items collection getComponentId : function(comp) { return comp.getItemId(); }, /** * <p>Adds {@link Ext.Component Component}(s) to this Container.</p> * <br><p><b>Description</b></u> : * <div><ul class="mdetail-params"> * <li>Fires the {@link #beforeadd} event before adding</li> * <li>The Container's {@link #defaults default config values} will be applied * accordingly (see <code>{@link #defaults}</code> for details).</li> * <li>Fires the {@link #add} event after the component has been added.</li> * </ul></div> * <br><p><b>Notes</b></u> : * <div><ul class="mdetail-params"> * <li>If the Container is <i>already rendered</i> when <code>add</code> * is called, you may need to call {@link #doLayout} to refresh the view which causes * any unrendered child Components to be rendered. This is required so that you can * <code>add</code> multiple child components if needed while only refreshing the layout * once. For example:<pre><code> var tb = new {@link Ext.Toolbar}(); tb.render(document.body); // toolbar is rendered tb.add({text:'Button 1'}); // add multiple items ({@link #defaultType} for {@link Ext.Toolbar Toolbar} is 'button') tb.add({text:'Button 2'}); tb.{@link #doLayout}(); // refresh the layout * </code></pre></li> * <li><i>Warning:</i> Containers directly managed by the BorderLayout layout manager * may not be removed or added. See the Notes for {@link Ext.layout.BorderLayout BorderLayout} * for more details.</li> * </ul></div> * @param {...Object/Array} component * <p>Either one or more Components to add or an Array of Components to add. See * <code>{@link #items}</code> for additional information.</p> * @return {Ext.Component/Array} The Components that were added. */ add : function() { var args = Array.prototype.slice.call(arguments), index = -1; if (typeof args[0] == 'number') { index = args.shift(); } var hasMultipleArgs = args.length > 1; if (hasMultipleArgs || Ext.isArray(args[0])) { var items = hasMultipleArgs ? args : args[0], results = [], i, ln, item; for (i = 0, ln = items.length; i < ln; i++) { item = items[i]; if (!item) { throw "Trying to add a null item as a child of Container with itemId/id: " + this.getItemId(); } if (index != -1) { item = this.add(index + i, item); } else { item = this.add(item); } results.push(item); } return results; } var cmp = this.prepareItems(args[0], true)[0]; index = (index !== -1) ? index : this.items.length; if (this.fireEvent('beforeadd', this, cmp, index) !== false && this.onBeforeAdd(cmp) !== false) { this.items.insert(index, cmp); cmp.onAdded(this, index); this.onAdd(cmp, index); this.fireEvent('add', this, cmp, index); } return cmp; }, onAdd : Ext.emptyFn, onRemove : Ext.emptyFn, /** * Inserts a Component into this Container at a specified index. Fires the * {@link #beforeadd} event before inserting, then fires the {@link #add} event after the * Component has been inserted. * @param {Number} index The index at which the Component will be inserted * into the Container's items collection * @param {Ext.Component} component The child Component to insert.<br><br> * Ext uses lazy rendering, and will only render the inserted Component should * it become necessary.<br><br> * A Component config object may be passed in order to avoid the overhead of * constructing a real Component object if lazy rendering might mean that the * inserted Component will not be rendered immediately. To take advantage of * this 'lazy instantiation', set the {@link Ext.Component#xtype} config * property to the registered type of the Component wanted.<br><br> * For a list of all available xtypes, see {@link Ext.Component}. * @return {Ext.Component} component The Component (or config object) that was * inserted with the Container's default config values applied. */ insert : function(index, comp){ return this.add(index, comp); }, // @private onBeforeAdd : function(item) { if (item.ownerCt) { item.ownerCt.remove(item, false); } if (this.hideBorders === true){ item.border = (item.border === true); } }, /** * Removes a component from this container. Fires the {@link #beforeremove} event before removing, then fires * the {@link #remove} event after the component has been removed. * @param {Component/String} component The component reference or id to remove. * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function. * Defaults to the value of this Container's {@link #autoDestroy} config. * @return {Ext.Component} component The Component that was removed. */ remove : function(comp, autoDestroy) { var c = this.getComponent(comp); //<debug> if (!c) { console.warn("Attempted to remove a component that does not exist. Ext.Container: remove takes an argument of the component to remove. cmp.remove() is incorrect usage."); } //</debug> if (c && this.fireEvent('beforeremove', this, c) !== false) { this.doRemove(c, autoDestroy); this.fireEvent('remove', this, c); } return c; }, // @private doRemove : function(component, autoDestroy) { var layout = this.layout, hasLayout = layout && this.rendered; this.items.remove(component); component.onRemoved(); if (hasLayout) { layout.onRemove(component); } this.onRemove(component, autoDestroy); if (autoDestroy === true || (autoDestroy !== false && this.autoDestroy)) { component.destroy(); } if (hasLayout && !autoDestroy) { layout.afterRemove(component); } }, /** * Removes all components from this container. * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function. * Defaults to the value of this Container's {@link #autoDestroy} config. * @return {Array} Array of the destroyed components */ removeAll : function(autoDestroy) { var item, removeItems = this.items.items.slice(), items = [], ln = removeItems.length, i; for (i = 0; i < ln; i++) { item = removeItems[i]; this.remove(item, autoDestroy); if (item.ownerCt !== this) { items.push(item); } } return items; }, // Used by ComponentQuery to retrieve all of the items // which can potentially be considered a child of this Container. // This should be overriden by components which have child items // that are not contained in items. For example dockedItems, menu, etc getRefItems : function(deep) { var items = this.items.items.slice(), ln = items.length, i, item; if (deep) { for (i = 0; i < ln; i++) { item = items[i]; if (item.getRefItems) { items = items.concat(item.getRefItems(true)); } } } return items; }, /** * Examines this container's <code>{@link #items}</code> <b>property</b> * and gets a direct child component of this container. * @param {String/Number} comp This parameter may be any of the following: * <div><ul class="mdetail-params"> * <li>a <b><code>String</code></b> : representing the <code>{@link Ext.Component#itemId itemId}</code> * or <code>{@link Ext.Component#id id}</code> of the child component </li> * <li>a <b><code>Number</code></b> : representing the position of the child component * within the <code>{@link #items}</code> <b>property</b></li> * </ul></div> * <p>For additional information see {@link Ext.util.MixedCollection#get}. * @return Ext.Component The component (if found). */ getComponent : function(comp) { if (Ext.isObject(comp)) { comp = comp.getItemId(); } return this.items.get(comp); }, /** * Retrieves all descendant components which match the passed selector. * Executes an Ext.ComponentQuery.query using this container as its root. * @param {String} selector Selector complying to an Ext.ComponentQuery selector * @return {Array} Ext.Component's which matched the selector */ query : function(selector) { return Ext.ComponentQuery.query(selector, this); }, /** * Retrieves the first direct child of this container which matches the passed selector. * The passed in selector must comply with an Ext.ComponentQuery selector. * @param {String} selector An Ext.ComponentQuery selector * @return Ext.Component */ child : function(selector) { return this.query('> ' + selector)[0] || null; }, /** * Retrieves the first descendant of this container which matches the passed selector. * The passed in selector must comply with an Ext.ComponentQuery selector. * @param {String} selector An Ext.ComponentQuery selector * @return Ext.Component */ down : function(selector) { return this.query(selector)[0] || null; }, // inherit docs show : function() { Ext.lib.Container.superclass.show.apply(this, arguments); var layoutCollection = this.layoutOnShow, ln = layoutCollection.getCount(), i = 0, needsLayout, item; for (; i < ln; i++) { item = layoutCollection.get(i); needsLayout = item.needsLayout; if (Ext.isObject(needsLayout)) { item.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize); } } layoutCollection.clear(); }, // @private beforeDestroy : function() { var items = this.items, c; if (items) { while ((c = items.first())) { this.doRemove(c, true); } } Ext.destroy(this.layout); Ext.lib.Container.superclass.beforeDestroy.call(this); } });
JavaScript
Ext.DataViewSelectionModel = Ext.extend(Ext.AbstractStoreSelectionModel, { deselectOnContainerClick: true, bindComponent: function(view) { this.view = view; this.bind(view.getStore()); var eventListeners = { refresh: this.refresh, scope: this, el: { scope: this } }; eventListeners.el[view.triggerEvent] = this.onItemClick; eventListeners.el[view.triggerCtEvent] = this.onContainerClick; view.on(eventListeners); }, onItemClick: function(e) { var view = this.view, node = view.findTargetByEvent(e); if (node) { this.selectWithEvent(view.getRecord(node), e); } else { return false; } }, onContainerClick: function() { if (this.deselectOnContainerClick) { this.deselectAll(); } }, // Allow the DataView to update the ui onSelectChange: function(record, isSelected, suppressEvent) { var view = this.view; if (isSelected) { view.onItemSelect(record); if (!suppressEvent) { this.fireEvent('select', this, record); } } else { view.onItemDeselect(record); if (!suppressEvent) { this.fireEvent('deselect', this, record); } } } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.AbstractStoreSelectionModel * @extends Ext.util.Observable * * 跟踪有什么记录是选中的、选取的,在一些数据绑定的器件中。是一个抽象的方法不宜直接使用它。 * 数据绑定的器件就是GridPanel、TreePanel和ListView,它们应该有继承AbstractStoreSelectionModel的子类参与组建的数据绑定。 * 抽象方法 onSelectChange及onLastFocusChanged应该在子类中去实现,以提供更新UI组件的功能。 * <br /> * Tracks what records are currently selected in a databound widget. * * This is an abstract class and is not meant to be directly used. * * DataBound UI widgets such as GridPanel, TreePanel, and ListView * should subclass AbstractStoreSelectionModel and provide a way * to binding to the component. * The abstract methods onSelectChange and onLastFocusChanged should * be implemented in these subclasses to update the UI widget. */ Ext.AbstractStoreSelectionModel = Ext.extend(Ext.util.Observable, { // lastSelected /** * @cfg {String} mode * 选择的模式。可以SINGLE、SIMPLE和MULTI三种值的一种。默认是“SINGLE”。 * Modes of selection. * Valid values are SINGLE, SIMPLE, and MULTI. Defaults to 'SINGLE' */ /** * @property selected * 只读的。保存当前已选择记录的MixedCollection对象。 * READ-ONLY A MixedCollection that maintains all of the currently selected * records. */ selected: null, constructor: function(cfg) { cfg = cfg || {}; Ext.apply(this, cfg); this.modes = { SINGLE: true, SIMPLE: true, MULTI: true }; // 设置selectionMode sets this.selectionMode this.setSelectionMode(cfg.mode); // 保存当前选好的记录。 maintains the currently selected records. this.selected = new Ext.util.MixedCollection(); Ext.AbstractStoreSelectionModel.superclass.constructor.call(this, cfg); }, // 绑定Store到selModel。binds the store to the selModel. bind : function(store, initial){ if(!initial && this.store){ if(store !== this.store && this.store.autoDestroy){ this.store.destroy(); }else{ this.store.un("add", this.onStoreAdd, this); this.store.un("clear", this.onStoreClear, this); this.store.un("remove", this.onStoreRemove, this); this.store.un("update", this.onStoreUpdate, this); } } if(store){ store = Ext.StoreMgr.lookup(store); store.on({ add: this.onStoreAdd, clear: this.onStoreClear, remove: this.onStoreRemove, update: this.onStoreUpdate, scope: this }); } this.store = store; if(store && !initial){ this.refresh(); } }, selectAll: function(silent) { var selections = this.store.getRange(); for (var i = 0, ln = selections.length; i < ln; i++) { this.doSelect(selections[i], true, silent); } }, deselectAll: function() { var selections = this.getSelection(); for (var i = 0, ln = selections.length; i < ln; i++) { this.doDeselect(selections[i]); } }, // 决定MULTI, SIMPLE and SINGLE选区模式其不同的逻辑。 // 必须传入事件好让我们知道用户是否按下了ctrl或者shift键。 // Provides differentiation of logic between MULTI, SIMPLE and SINGLE // selection modes. Requires that an event be passed so that we can know // if user held ctrl or shift. selectWithEvent: function(record, e) { switch (this.selectionMode) { case 'MULTI': if (e.ctrlKey && this.isSelected(record)) { this.doDeselect(record, false); } else if (e.shiftKey && this.lastFocused) { this.selectRange(this.lastFocused, record, e.ctrlKey); } else if (e.ctrlKey) { this.doSelect(record, true, false); } else if (this.isSelected(record) && !e.shiftKey && !e.ctrlKey && this.selected.getCount() > 1) { this.doSelect(record, false, false); } else { this.doSelect(record, false); } break; case 'SIMPLE': if (this.isSelected(record)) { this.doDeselect(record); } else { this.doSelect(record, true); } break; case 'SINGLE': this.doSelect(record, false); break; } }, /** * 如选区模型{@link Ext.grid.AbstractSelectionModel#isLocked 不是锁定的},选取多个行。行上限:startRow,行下限:endRow。 * Selects a range of rows if the selection model * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}. * 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 (可选项)true代表保留当前选区。(optional) True to retain existing selections */ selectRange : function(startRecord, endRecord, keepExisting, dir){ var i, startRow = this.store.indexOf(startRecord), endRow = this.store.indexOf(endRecord), tmp, selectedCount = 0, dontDeselect; if (this.isLocked()){ return; } // 交换值。 swap values if (startRow > endRow){ tmp = endRow; endRow = startRow; startRow = tmp; } for (i = startRow; i <= endRow; i++) { if (this.isSelected(this.store.getAt(i))) { selectedCount++; } } if (!dir) { dontDeselect = -1; } else { dontDeselect = (dir == 'up') ? startRow : endRow; } for (i = startRow; i <= endRow; i++){ if (selectedCount == (endRow - startRow + 1)) { if (i != dontDeselect) { this.doDeselect(i, true); } } else { this.doSelect(i, true); } } }, /** * 选取record。传入索引亦可。 * Selects a record instance by record instance or index. * @param {Ext.data.Record/Index} records 记录数组或索引。An array of records or an index * @param {Boolean} keepExisting (可选项)true表示为保留当前选区。 * @param {Boolean} suppressEvent (可选项)true表示为跳过所有selectionchange事件。Set to false to not fire a select event */ select: function(records, keepExisting, suppressEvent) { this.doSelect(records, keepExisting, suppressEvent); }, /** * 反选record。传入索引亦可。 * Deselects a record instance by record instance or index. * @param {Ext.data.Record/Index} records 记录数组或索引。An array of records or an index * @param {Boolean} suppressEvent (可选项)true表示为跳过所有deselect事件。Set to false to not fire a deselect event */ deselect: function(records, suppressEvent) { this.doDeselect(records, suppressEvent); }, doSelect: function(records, keepExisting, suppressEvent) { if (this.locked) { return; } if (typeof records === "number") { records = [this.store.getAt(records)]; } if (this.selectionMode == "SINGLE" && records) { var record = records.length ? records[0] : records; this.doSingleSelect(record, suppressEvent); } else { this.doMultiSelect(records, keepExisting, suppressEvent); } }, doMultiSelect: function(records, keepExisting, suppressEvent) { if (this.locked) { return; } var selected = this.selected, change = false, record; records = !Ext.isArray(records) ? [records] : records; if (!keepExisting && selected.getCount() > 0) { change = true; this.doDeselect(this.getSelection(), true); } for (var i = 0, ln = records.length; i < ln; i++) { record = records[i]; if (keepExisting && this.isSelected(record)) { continue; } change = true; this.lastSelected = record; selected.add(record); if (!suppressEvent) { this.setLastFocused(record); } this.onSelectChange(record, true, suppressEvent); } // 如果有改变的话并且没有跳过事件的指令,就触发selchange事件。fire selchange if there was a change and there is no suppressEvent flag this.maybeFireSelectionChange(change && !suppressEvent); }, // 可以通过索引、记录本身、或记录数组来表示记录。 records can be an index, a record or an array of records doDeselect: function(records, suppressEvent) { if (this.locked) { return; } if (typeof records === "number") { records = [this.store.getAt(records)]; } var change = false, selected = this.selected, record; records = !Ext.isArray(records) ? [records] : records; for (var i = 0, ln = records.length; i < ln; i++) { record = records[i]; if (selected.remove(record)) { if (this.lastSelected == record) { this.lastSelected = selected.last(); } this.onSelectChange(record, false, suppressEvent); change = true; } } // 如果有改变的话并且没有跳过事件的指令,就触发selchange事件。fire selchange if there was a change and there is no suppressEvent flag this.maybeFireSelectionChange(change && !suppressEvent); }, doSingleSelect: function(record, suppressEvent) { if (this.locked) { return; } // 已选择,是否还检查一下beforeselect? // already selected. // should we also check beforeselect? if (this.isSelected(record)) { return; } var selected = this.selected; if (selected.getCount() > 0) { this.doDeselect(this.lastSelected, suppressEvent); } selected.add(record); this.lastSelected = record; this.onSelectChange(record, true, suppressEvent); this.setLastFocused(record); this.maybeFireSelectionChange(!suppressEvent); }, /** * @param {Ext.data.Record} record * 设置送入的record作为最后得到焦点的记录。如果记录已经选择这个方法就没有意义。 * Set a record as the last focused record. This does NOT mean * that the record has been selected. */ setLastFocused: function(record) { var recordBeforeLast = this.lastFocused; this.lastFocused = record; this.onLastFocusChanged(recordBeforeLast, record); }, // fire selection change as long as true is not passed // into maybeFireSelectionChange maybeFireSelectionChange: function(fireEvent) { if (fireEvent) { this.fireEvent('selectionchange', this, this.getSelection()); } }, /** * 返回最后选择的记录。 * Returns the last selected record. */ getLastSelected: function() { return this.lastSelected; }, getLastFocused: function() { return this.lastFocused; }, /** * 返回当前已选择的记录。 * Returns an array of the currently selected records. */ getSelection: function() { return this.selected.getRange(); }, /** * 返回当前的选择模式。可以是SINGLE、SIMPLE和MULTI三种值的一种。 * Returns the current selectionMode. SINGLE, MULTI or SIMPLE. */ getSelectionMode: function() { return this.selectionMode; }, /** * 设置当前的选择模式。参数可以是SINGLE、SIMPLE和MULTI三种值的一种。 * Sets the current selectionMode. SINGLE, MULTI or SIMPLE. */ setSelectionMode: function(selMode) { selMode = selMode ? selMode.toUpperCase() : 'SINGLE'; // 默认SINGLE。 set to mode specified unless it doesnt exist, in that case // use single. this.selectionMode = this.modes[selMode] ? selMode : 'SINGLE'; }, /** * 返回true表示当前选区是锁定的。 * Returns true if the selections are locked. * @return {Boolean} */ isLocked: function() { return this.locked; }, /** * 锁定当前选区,不让人动它。 * Locks the current selection and disables any changes from * happening to the selection. * @param {Boolean} locked */ setLocked: function(locked) { this.locked = !!locked; }, /** * 检查特定行是否选择。 * Returns <tt>true</tt> if the specified row is selected. * @param {Record/Number} record Record对象或者是Record的索引。The record or index of the record to check * @return {Boolean} */ isSelected: function(record) { record = Ext.isNumber(record) ? this.store.getAt(record) : record; return this.selected.indexOf(record) !== -1; }, /** * 返回true的话表示有选择选区。 * Returns true if there is a selected record. * @return {Boolean} */ hasSelection: function() { return this.selected.getCount() > 0; }, refresh: function() { var toBeSelected = [], oldSelections = this.getSelection(), ln = oldSelections.length, selection, change, i = 0; // 在执行刷新之后,必须保证没有记录漏掉,否则的话要重新读取要选择的。 // check to make sure that there are no records // missing after the refresh was triggered, prune // them from what is to be selected if so for (; i < ln; i++) { selection = oldSelections[i]; if (this.store.indexOf(selection) != -1) { toBeSelected.push(selection); } } // 旧选择和新选区不相同,就是有变动。there was a change from the old selected and // the new selection if (this.selected.getCount() != toBeSelected.length) { change = true; } this.clearSelections(); if (toBeSelected.length) { // 再次选取选区。 perform the selection again this.doSelect(toBeSelected, false, true); } this.maybeFireSelectionChange(change); }, clearSelections: function() { // 复位整个选区。 reset the entire selection to nothing this.selected.clear(); this.lastSelected = null; this.setLastFocused(null); }, //当有Store有记录加入。when a record is added to a store onStoreAdd: function() { }, // 当store没有数据时,选区也就没有了(如果有的话)。when a store is cleared remove all selections // (if there were any) onStoreClear: function() { var selected = this.selected; if (selected.getCount > 0) { selected.clear(); this.lastSelected = null; this.setLastFocused(null); this.maybeFireSelectionChange(true); } }, // 如果选中的记录其中有被移除的,就SelectionModel中剔除。prune records from the SelectionModel if // they were selected at the time they were // removed. onStoreRemove: function(store, record) { if (this.locked) { return; } var selected = this.selected; if (selected.remove(record)) { if (this.lastSelected == record) { this.lastSelected = null; } if (this.getLastFocused() == record) { this.setLastFocused(null); } this.maybeFireSelectionChange(true); } }, getCount: function() { return this.selected.getCount(); }, // cleanup. destroy: function() { }, // if records are updated onStoreUpdate: function() { }, // @abstract onSelectChange: function(record, isSelected, suppressEvent) { }, // @abstract onLastFocusChanged: function(oldFocused, newFocused) { }, // @abstract onEditorKey: function(field, e) { }, // @abstract bindComponent: function(cmp) { } });
JavaScript
/** * @class Ext.DataView * @extends Ext.Component * A mechanism for displaying data using custom layout templates and formatting. DataView uses an {@link Ext.XTemplate} * as its internal templating mechanism, and is bound to an {@link Ext.data.Store} * so that as the data in the store changes the view is automatically updated to reflect the changes. The view also * provides built-in behavior for many common events that can occur for its contained items including click, doubleclick, * mouseover, mouseout, etc. as well as a built-in selection model. <b>In order to use these features, an {@link #itemSelector} * config must be provided for the DataView to determine what nodes it will be working with.</b> * * <p>The example below binds a DataView to a {@link Ext.data.Store} and renders it into an {@link Ext.Panel}.</p> * <pre><code> var store = new Ext.data.JsonStore({ url: 'get-images.php', root: 'images', fields: [ 'name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date', dateFormat:'timestamp'} ] }); store.load(); var tpl = new Ext.XTemplate( '&lt;tpl for="."&gt;', '&lt;div class="thumb-wrap" id="{name}"&gt;', '&lt;div class="thumb"&gt;&lt;img src="{url}" title="{name}"&gt;&lt;/div&gt;', '&lt;span class="x-editable"&gt;{shortName}&lt;/span&gt;&lt;/div&gt;', '&lt;/tpl&gt;', '&lt;div class="x-clear"&gt;&lt;/div&gt;' ); var panel = new Ext.Panel({ id:'images-view', frame:true, width:535, autoHeight:true, collapsible:true, layout:'fit', title:'Simple DataView', items: new Ext.DataView({ store: store, tpl: tpl, autoHeight:true, multiSelect: true, overCls:'x-view-over', itemSelector:'div.thumb-wrap', emptyText: 'No images to display' }) }); panel.render(document.body); </code></pre> * @constructor * Create a new DataView * @param {Object} config The config object * @xtype dataview */ // dataview will extend from DataPanel/BoundPanel Ext.DataView = Ext.extend(Ext.Component, { /** * @cfg {String/Array} tpl * @required * The HTML fragment or an array of fragments that will make up the template used by this DataView. This should * be specified in the same format expected by the constructor of {@link Ext.XTemplate}. */ /** * @cfg {Ext.data.Store} store * @required * The {@link Ext.data.Store} to bind this DataView to. */ /** * @cfg {String} itemSelector * @required * <b>This is a required setting</b>. A simple CSS selector (e.g. <tt>div.some-class</tt> or * <tt>span:first-child</tt>) that will be used to determine what nodes this DataView will be * working with. */ /** * @cfg {String} overItemCls * A CSS class to apply to each item in the view on mouseover (defaults to undefined). */ /** * @cfg {String} loadingText * A string to display during data load operations (defaults to undefined). If specified, this text will be * displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's * contents will continue to display normally until the new data is loaded and the contents are replaced. */ loadingText: 'Loading...', /** * @cfg {String} selectedItemCls * A CSS class to apply to each selected item in the view (defaults to 'x-view-selected'). */ selectedItemCls: "x-item-selected", /** * @cfg {String} emptyText * The text to display in the view when there is no data to display (defaults to ''). */ emptyText: "", /** * @cfg {Boolean} deferEmptyText True to defer emptyText being applied until the store's first load */ deferEmptyText: true, /** * @cfg {Boolean} trackOver True to enable mouseenter and mouseleave events */ trackOver: false, /** * @cfg {Boolean} blockRefresh Set this to true to ignore datachanged events on the bound store. This is useful if * you wish to provide custom transition animations via a plugin (defaults to false) */ blockRefresh: false, /** * @cfg {Boolean} disableSelection <p><tt>true</tt> to disable selection within the DataView. Defaults to <tt>false</tt>. * This configuration will lock the selection model that the DataView uses.</p> */ //private last: false, triggerEvent: 'click', triggerCtEvent: 'containerclick', addCmpEvents: function() { }, // private initComponent : function(){ //<debug> var isDef = Ext.isDefined; if (!isDef(this.tpl) || !isDef(this.store) || !isDef(this.itemSelector)) { throw "DataView requires tpl, store and itemSelector configurations to be defined."; } //</debug> Ext.DataView.superclass.initComponent.call(this); if(Ext.isString(this.tpl) || Ext.isArray(this.tpl)){ this.tpl = new Ext.XTemplate(this.tpl); } // backwards compat alias for overClass/selectedClass // TODO: Consider support for overCls generation Ext.Component config if (Ext.isDefined(this.overCls) || Ext.isDefined(this.overClass)) { this.overItemCls = this.overCls || this.overClass; delete this.overCls; delete this.overClass; //<debug> throw "Using the deprecated overCls or overClass configuration. Use overItemCls."; //</debug> } if (Ext.isDefined(this.selectedCls) || Ext.isDefined(this.selectedClass)) { this.selectedItemCls = this.selectedCls || this.selectedClass; delete this.selectedCls; delete this.selectedClass; //<debug> throw "Using the deprecated selectedCls or selectedClass configuration. Use selectedItemCls."; //</debug> } this.addCmpEvents(); this.store = Ext.StoreMgr.lookup(this.store) this.all = new Ext.CompositeElementLite(); this.getSelectionModel().bindComponent(this); }, onRender : function() { Ext.DataView.superclass.onRender.apply(this, arguments); if (this.loadingText) { this.loadMask = new Ext.LoadMask(this.el); } }, getSelectionModel: function(){ if (!this.selModel) { this.selModel = {}; } if (!this.selModel.events) { this.selModel = new Ext.DataViewSelectionModel(this.selModel); } if (!this.selModel.hasRelaySetup) { this.relayEvents(this.selModel, ['selectionchange', 'select', 'deselect']); this.selModel.hasRelaySetup = true; } // lock the selection model if user // has disabled selection if (this.disableSelection) { this.selModel.locked = true; } return this.selModel; }, /** * Refreshes the view by reloading the data from the store and re-rendering the template. */ refresh: function() { if (!this.rendered) { return; } var el = this.getTargetEl(), records = this.store.getRange(); el.update(''); if (records.length < 1) { if (!this.deferEmptyText || this.hasSkippedEmptyText) { el.update(this.emptyText); } this.all.clear(); } else { this.tpl.overwrite(el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, el.dom)); this.updateIndexes(0); } this.hasSkippedEmptyText = true; this.fireEvent('refresh'); }, /** * Function which can be overridden to provide custom formatting for each Record that is used by this * DataView's {@link #tpl template} to render each node. * @param {Array/Object} data The raw data object that was used to create the Record. * @param {Number} recordIndex the index number of the Record being prepared for rendering. * @param {Record} record The Record being prepared for rendering. * @return {Array/Object} The formatted data in a format expected by the internal {@link #tpl template}'s overwrite() method. * (either an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'})) */ prepareData: function(data, index, record) { if (record) { Ext.apply(data, this.prepareAssociatedData(record)); } return data; }, /** * @private * This complex-looking method takes a given Model instance and returns an object containing all data from * all of that Model's *loaded* associations. It does this recursively - for example if we have a User which * hasMany Orders, and each Order hasMany OrderItems, it will return an object like this: * * { * orders: [ * { * id: 123, * status: 'shipped', * orderItems: [ * ... * ] * } * ] * } * * This makes it easy to iterate over loaded associations in a DataView. * * @param {Ext.data.Model} record The Model instance * @param {Array} ids PRIVATE. The set of Model instance internalIds that have already been loaded * @return {Object} The nested data set for the Model's loaded associations */ prepareAssociatedData: function(record, ids) { //we keep track of all of the internalIds of the models that we have loaded so far in here ids = ids || []; var associations = record.associations.items, associationCount = associations.length, associationData = {}, associatedStore, associatedName, associatedRecords, associatedRecord, associatedRecordCount, association, internalId, i, j; for (i = 0; i < associationCount; i++) { association = associations[i]; //this is the hasMany store filled with the associated data associatedStore = record[association.storeName]; //we will use this to contain each associated record's data associationData[association.name] = []; //if it's loaded, put it into the association data if (associatedStore && associatedStore.data.length > 0) { associatedRecords = associatedStore.data.items; associatedRecordCount = associatedRecords.length; //now we're finally iterating over the records in the association. We do this recursively for (j = 0; j < associatedRecordCount; j++) { associatedRecord = associatedRecords[j]; internalId = associatedRecord.internalId; //when we load the associations for a specific model instance we add it to the set of loaded ids so that //we don't load it twice. If we don't do this, we can fall into endless recursive loading failures. if (ids.indexOf(internalId) == -1) { ids.push(internalId); associationData[association.name][j] = associatedRecord.data; Ext.apply(associationData[association.name][j], this.prepareAssociatedData(associatedRecord, ids)); } } } } return associationData; }, /** * <p>Function which can be overridden which returns the data object passed to this * DataView's {@link #tpl template} to render the whole DataView.</p> * <p>This is usually an Array of data objects, each element of which is processed by an * {@link Ext.XTemplate XTemplate} which uses <tt>'&lt;tpl for="."&gt;'</tt> to iterate over its supplied * data object as an Array. However, <i>named</i> properties may be placed into the data object to * provide non-repeating data such as headings, totals etc.</p> * @param {Array} records An Array of {@link Ext.data.Model}s to be rendered into the DataView. * @param {Number} startIndex the index number of the Record being prepared for rendering. * @return {Array} An Array of data objects to be processed by a repeating XTemplate. May also * contain <i>named</i> properties. */ collectData : function(records, startIndex){ var r = [], i = 0, len = records.length; for(; i < len; i++){ r[r.length] = this.prepareData(records[i].data, startIndex + i, records[i]); } return r; }, // private bufferRender : function(records, index){ var div = document.createElement('div'); this.tpl.overwrite(div, this.collectData(records, index)); return Ext.query(this.itemSelector, div); }, // private onUpdate : function(ds, record){ var index = this.store.indexOf(record), original, node; if (index > -1){ original = this.all.elements[index]; node = this.bufferRender([record], index)[0]; this.all.replaceElement(index, node, true); this.updateIndexes(index, index); // Maintain selection after update // TODO: Move to approriate event handler. this.selModel.refresh(); } }, // private onAdd : function(ds, records, index){ if (this.all.getCount() === 0) { this.refresh(); return; } var nodes = this.bufferRender(records, index), n, a = this.all.elements; if (index < this.all.getCount()) { n = this.all.item(index).insertSibling(nodes, 'before', true); a.splice.apply(a, [index, 0].concat(nodes)); } else { n = this.all.last().insertSibling(nodes, 'after', true); a.push.apply(a, nodes); } this.updateIndexes(index); }, // private onRemove : function(ds, record, index){ this.all.removeElement(index, true); this.updateIndexes(index); if (this.store.getCount() === 0){ this.refresh(); } }, /** * Refreshes an individual node's data from the store. * @param {Number} index The item's data index in the store */ refreshNode : function(index){ this.onUpdate(this.store, this.store.getAt(index)); }, // private updateIndexes : function(startIndex, endIndex){ var ns = this.all.elements; startIndex = startIndex || 0; endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1)); for(var i = startIndex; i <= endIndex; i++){ ns[i].viewIndex = i; } }, /** * Returns the store associated with this DataView. * @return {Ext.data.Store} The store */ getStore : function(){ return this.store; }, /** * Changes the data store bound to this view and refreshes it. * @param {Store} store The store to bind to this view */ bindStore : function(store, initial) { if (!initial && this.store) { if (store !== this.store && this.store.autoDestroy) { this.store.destroy(); } else { this.mun(this.store, { scope: this, beforeload: this.onBeforeLoad, datachanged: this.onDataChanged, add: this.onAdd, remove: this.onRemove, update: this.onUpdate, clear: this.refresh }); } if (!store) { if (this.loadMask) { this.loadMask.bindStore(null); } this.store = null; } } if (store) { store = Ext.StoreMgr.lookup(store); this.mon(store, { scope: this, beforeload: this.onBeforeLoad, datachanged: this.onDataChanged, add: this.onAdd, remove: this.onRemove, update: this.onUpdate, clear: this.refresh }); if (this.loadMask) { this.loadMask.bindStore(store); } } this.store = store; if (store) { this.refresh(); } }, /** * @private * Calls this.refresh if this.blockRefresh is not true */ onDataChanged: function() { if (this.blockRefresh !== true) { this.refresh.apply(this, arguments); } }, /** * Returns the template node the passed child belongs to, or null if it doesn't belong to one. * @param {HTMLElement} node * @return {HTMLElement} The template node */ findItemByChild: function(node){ return Ext.fly(node).findParent(this.itemSelector, this.getTargetEl()); }, /** * Returns the template node by the Ext.EventObject or null if it is not found. * @param {Ext.EventObject} e */ findTargetByEvent: function(e) { return e.getTarget(this.itemSelector, this.getTargetEl()); }, /** * Gets the currently selected nodes. * @return {Array} An array of HTMLElements */ getSelectedNodes: function(){ var nodes = [], records = this.selModel.getSelection(), ln = records.length, i = 0; for (; i < ln; i++) { nodes.push(this.getNode(records[i])); } return nodes; }, /** * Gets an array of the records from an array of nodes * @param {Array} nodes The nodes to evaluate * @return {Array} records The {@link Ext.data.Model} objects */ getRecords: function(nodes) { var records = [], i = 0, len = nodes.length; for (; i < len; i++) { records[records.length] = this.store.getAt(nodes[i].viewIndex); } return r; }, /** * Gets a record from a node * @param {HTMLElement} node The node to evaluate * @return {Record} record The {@link Ext.data.Model} object */ getRecord: function(node){ return this.store.getAt(node.viewIndex); }, /** * Returns true if the passed node is selected, else false. * @param {HTMLElement/Number/Ext.data.Model} node The node, node index or record to check * @return {Boolean} True if selected, else false */ isSelected : function(node) { // TODO: El/Idx/Record var r = this.getRecord(node); return this.selModel.isSelected(r); }, /** * Selects a record instance by record instance or index. * @param {Ext.data.Record/Index} records An array of records or an index * @param {Boolean} keepExisting * @param {Boolean} suppressEvent Set to false to not fire a select event */ select: function(records, keepExisting, suppressEvent) { this.selModel.select(records, keepExisting, suppressEvent); }, /** * Deselects a record instance by record instance or index. * @param {Ext.data.Record/Index} records An array of records or an index * @param {Boolean} suppressEvent Set to false to not fire a deselect event */ deselect: function(records, suppressEvent) { this.selModel.deselect(records, suppressEvent); }, /** * Gets a template node. * @param {HTMLElement/String/Number/Ext.data.Model} nodeInfo An HTMLElement template node, index of a template node, * the id of a template node or the record associated with the node. * @return {HTMLElement} The node or null if it wasn't found */ getNode : function(nodeInfo) { if (Ext.isString(nodeInfo)) { return document.getElementById(nodeInfo); } else if (Ext.isNumber(nodeInfo)) { return this.all.elements[nodeInfo]; } else if (nodeInfo instanceof Ext.data.Model) { var idx = this.store.indexOf(nodeInfo); return this.all.elements[idx]; } return nodeInfo; }, /** * Gets a range nodes. * @param {Number} start (optional) The index of the first node in the range * @param {Number} end (optional) The index of the last node in the range * @return {Array} An array of nodes */ getNodes: function(start, end) { var ns = this.all.elements, nodes = [], i; start = start || 0; end = !Ext.isDefined(end) ? Math.max(ns.length - 1, 0) : end; if (start <= end) { for (i = start; i <= end && ns[i]; i++) { nodes.push(ns[i]); } } else { for (i = start; i >= end && ns[i]; i--) { nodes.push(ns[i]); } } return nodes; }, /** * Finds the index of the passed node. * @param {HTMLElement/String/Number/Record} nodeInfo An HTMLElement template node, index of a template node, the id of a template node * or a record associated with a node. * @return {Number} The index of the node or -1 */ indexOf: function(node) { node = this.getNode(node); if (Ext.isNumber(node.viewIndex)) { return node.viewIndex; } return this.all.indexOf(node); }, // private onBeforeLoad: function() { if (this.loadingText) { this.getTargetEl().update(''); this.all.clear(); } }, onDestroy : function() { this.all.clear(); Ext.DataView.superclass.onDestroy.call(this); this.bindStore(null); this.selModel.destroy(); }, // invoked by the selection model to maintain visual UI cues onItemSelect: function(record) { var node = this.getNode(record); Ext.fly(node).addCls(this.selectedItemCls); }, // invoked by the selection model to maintain visual UI cues onItemDeselect: function(record) { var node = this.getNode(record); Ext.fly(node).removeCls(this.selectedItemCls); }, select: function(records, keepExisting, supressEvents) { console.warn("DataView: select will be removed, please access select through a DataView's SelectionModel, ie: view.getSelectionModel().select()"); var sm = this.getSelectionModel(); return sm.select.apply(sm, arguments); }, clearSelections: function() { console.warn("DataView: clearSelections will be removed, please access deselectAll through DataView's SelectionModel, ie: view.getSelectionModel().deselectAll()"); var sm = this.getSelectionModel(); return sm.deselectAll(); } }); Ext.reg('dataview', Ext.DataView); // all of this information is available directly // from the SelectionModel itself, the only added methods // to DataView regarding selection will perform some transformation/lookup // between HTMLElement/Nodes to records and vice versa. Ext.DataView.override({ /** * @cfg {Boolean} multiSelect * True to allow selection of more than one item at a time, false to allow selection of only a single item * at a time or no selection at all, depending on the value of {@link #singleSelect} (defaults to false). */ /** * @cfg {Boolean} singleSelect * True to allow selection of exactly one item at a time, false to allow no selection at all (defaults to false). * Note that if {@link #multiSelect} = true, this value will be ignored. */ /** * @cfg {Boolean} simpleSelect * True to enable multiselection by clicking on multiple items without requiring the user to hold Shift or Ctrl, * false to force the user to hold Ctrl or Shift to select more than on item (defaults to false). */ /** * Gets the number of selected nodes. * @return {Number} The node count */ getSelectionCount : function(){ return this.selModel.getSelection().length; }, /** * Gets an array of the selected records * @return {Array} An array of {@link Ext.data.Model} objects */ getSelectedRecords : function(){ return this.selModel.getSelection(); } });
JavaScript
/** * @class Ext.is * * Determines information about the current platform the application is running on. * * @singleton */ Ext.is = { init : function() { var platforms = this.platforms, ln = platforms.length, i, platform; for (i = 0; i < ln; i++) { platform = platforms[i]; this[platform.identity] = platform.regex.test(platform.string); } /** * @property Desktop True if the browser is running on a desktop machine * @type {Boolean} */ this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android); /** * @property Tablet True if the browser is running on a tablet (iPad) */ this.Tablet = this.iPad; /** * @property Phone True if the browser is running on a phone. * @type {Boolean} */ this.Phone = !this.Desktop && !this.Tablet; /** * @property iOS True if the browser is running on iOS * @type {Boolean} */ this.iOS = this.iPhone || this.iPad || this.iPod; /** * @property Standalone Detects when application has been saved to homescreen. * @type {Boolean} */ this.Standalone = !!window.navigator.standalone; }, /** * @property iPhone True when the browser is running on a iPhone * @type {Boolean} */ platforms: [{ string: navigator.platform, regex: /iPhone/i, identity: 'iPhone' }, /** * @property iPod True when the browser is running on a iPod * @type {Boolean} */ { string: navigator.platform, regex: /iPod/i, identity: 'iPod' }, /** * @property iPad True when the browser is running on a iPad * @type {Boolean} */ { string: navigator.userAgent, regex: /iPad/i, identity: 'iPad' }, /** * @property Blackberry True when the browser is running on a Blackberry * @type {Boolean} */ { string: navigator.userAgent, regex: /Blackberry/i, identity: 'Blackberry' }, /** * @property Android True when the browser is running on an Android device * @type {Boolean} */ { string: navigator.userAgent, regex: /Android/i, identity: 'Android' }, /** * @property Mac True when the browser is running on a Mac * @type {Boolean} */ { string: navigator.platform, regex: /Mac/i, identity: 'Mac' }, /** * @property Windows True when the browser is running on Windows * @type {Boolean} */ { string: navigator.platform, regex: /Win/i, identity: 'Windows' }, /** * @property Linux True when the browser is running on Linux * @type {Boolean} */ { string: navigator.platform, regex: /Linux/i, identity: 'Linux' }] }; Ext.is.init(); /** * @class Ext.supports * * Determines information about features are supported in the current environment * * @singleton */ Ext.supports = { init : function() { var doc = document, div = doc.createElement('div'), tests = this.tests, ln = tests.length, i, test; div.innerHTML = [ '<div style="height:30px;width:50px;">', '<div style="height:20px;width:20px;"></div>', '</div>', '<div style="float:left; background-color:transparent;"></div>' ].join(''); doc.body.appendChild(div); for (i = 0; i < ln; i++) { test = tests[i]; this[test.identity] = test.fn.call(this, doc, div); } doc.body.removeChild(div); }, /** * @property OrientationChange True if the device supports orientation change * @type {Boolean} */ OrientationChange: !Ext.is.Desktop && (((typeof window.orientation != 'undefined') || window.hasOwnProperty('orientation')) && ('onorientationchange' in window)), tests: [ /** * @property Transitions True if the device supports CSS3 Transitions * @type {Boolean} */ { identity: 'Transitions', fn: function(doc, div) { var prefix = [ 'webkit', 'Moz', 'o', 'ms', 'khtml' ], TE = 'TransitionEnd', transitionEndName = [ prefix[0] + TE, 'transitionend', //Moz bucks the prefixing convention prefix[2] + TE, prefix[3] + TE, prefix[4] + TE ], ln = prefix.length, i = 0, out = false; div = Ext.get(div); for (; i < ln; i++) { if (div.getStyle(prefix[i] + "TransitionProperty")) { Ext.supports.CSS3Prefix = prefix[i]; Ext.supports.CSS3TransitionEnd = transitionEndName[i]; out = true; break; } } return out; } }, /** * @property Touch True if the device supports touch * @type {Boolean} */ { identity: 'Touch', fn: function(doc, div) { return (!Ext.is.Desktop && ('ontouchstart' in div)); } }, /** * @property RightMargin True if the device supports right margin * @type {Boolean} */ { identity: 'RightMargin', fn: function(doc, div, view) { view = doc.defaultView; return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px'); } }, /** * @property TransparentColor True if the device supports transparent color * @type {Boolean} */ { identity: 'TransparentColor', fn: function(doc, div, view) { view = doc.defaultView; return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent'); } }, /** * @property SVG True if the device supports SVG * @type {Boolean} */ { identity: 'SVG', fn: function(doc) { return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect; } }, /** * @property Canvas True if the device supports Canvas * @type {Boolean} */ { identity: 'Canvas', fn: function(doc) { return !!doc.createElement('canvas').getContext; } }, /** * @property VML True if the device supports VML * @type {Boolean} */ { identity: 'VML', fn: function(doc) { var d = doc.createElement("div"); d.innerHTML = "<!--[if vml]><br><br><![endif]-->"; return (d.childNodes.length == 2); } }, /** * @property Float True if the device supports CSS float * @type {Boolean} */ { identity: 'Float', fn: function(doc, div) { return !!div.lastChild.style.cssFloat; } }, /** * @property AudioTag True if the device supports the HTML5 audio tag * @type {Boolean} */ { identity: 'AudioTag', fn: function(doc) { return !!doc.createElement('audio').canPlayType; } }, /** * @property History True if the device supports HTML5 history * @type {Boolean} */ { identity: 'History', fn: function() { return !!(window.history && history.pushState); } }, /** * @property CSS3DTransform True if the device supports CSS3DTransform * @type {Boolean} */ { identity: 'CSS3DTransform', fn: function() { return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41')); } }, /** * @property GeoLocation True if the device supports GeoLocation * @type {Boolean} */ { identity: 'GeoLocation', fn: function() { return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined'); } } ] };
JavaScript
/** * @class Ext.ComponentMgr * <p> * 为页面上全体的组件(特指{@link Ext.Component}的子类)以便能够可通过组件的id方便地去访问,(参见{@link Ext.getCmp}方法)。 * Provides a registry of all Components (instances of {@link Ext.Component} or any subclass * thereof) on a page so that they can be easily accessed by {@link Ext.Component component} * {@link Ext.Component#id id} (see {@link #get}, or the convenience method {@link Ext#getCmp Ext.getCmp}).</p> * <p> * 此对象对组件的<i>类classes</i>提供索引检索的功能,这个索引应是如{@link Ext.Component#xtype}般的易记标识码。 * 对于由大量复合配置对象构成的Ext页面,使用<tt>xtype</tt>能避免不必要子组件实例化。<br /> * This object also provides a registry of available Component <i>classes</i> * indexed by a mnemonic code known as the Component's {@link Ext.Component#xtype xtype}. * The <code>{@link Ext.Component#xtype xtype}</code> provides a way to avoid instantiating child Components * when creating a full, nested config object for a complete Ext page.</p> * <p> * 只要xtype正确声明好,就可利用<i>配置项对象(config object)</i>表示一个子组件。 * 这样如遇到组件真是需要显示的时候,与之适合的类型(xtype)就会匹配对应的组件类,达到延时实例化(lazy instantiation)。<br /> * A child Component may be specified simply as a <i>config object</i> * as long as the correct <code>{@link Ext.Component#xtype xtype}</code> is specified so that if and when the Component * needs rendering, the correct type can be looked up for lazy instantiation.</p> * <p> * 全部的xtype列表可参阅{@link Ext.Component}。 * For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p> * @singleton */ Ext.ComponentMgr = new Ext.AbstractManager({ typeName: 'xtype', /** * Creates a new Component from the specified config object using the * config object's {@link Ext.component#xtype xtype} to determine the class to instantiate. * @param {Object} config A configuration object for the Component you wish to create. * @param {Constructor} defaultType The constructor to provide the default Component type if * the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>). * @return {Ext.Component} The newly instantiated Component. */ create : function(config, defaultType){ if (config.isComponent) { return config; } else { var type = config.xtype || defaultType, Class = this.types[type]; if (!Class) { throw "Attempting to create a component with an xtype that has not been registered: " + type } return new Class(config); } return config.render ? config : new (config); }, registerType : function(type, cls) { this.types[type] = cls; cls[this.typeName] = type; cls.prototype[this.typeName] = type; } }); /** * Shorthand for {@link Ext.ComponentMgr#registerType} * @param {String} xtype The {@link Ext.component#xtype mnemonic string} by which the Component class * may be looked up. * @param {Constructor} cls The new Component class. * @member Ext * @method reg */ Ext.reg = function() { return Ext.ComponentMgr.registerType.apply(Ext.ComponentMgr, arguments); }; // this will be called a lot internally, shorthand to keep the bytes down /** * Shorthand for {@link Ext.ComponentMgr#create} * Creates a new Component from the specified config object using the * config object's {@link Ext.component#xtype xtype} to determine the class to instantiate. * @param {Object} config A configuration object for the Component you wish to create. * @param {Constructor} defaultType The constructor to provide the default Component type if * the config object does not contain a <code>xtype</code>. (Optional if the config contains a <code>xtype</code>). * @return {Ext.Component} The newly instantiated Component. * @member Ext * @method create */ Ext.create = function() { return Ext.ComponentMgr.create.apply(Ext.ComponentMgr, arguments); };
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.XmlStore * @extends Ext.data.Store * @private * @ignore * <p> * 一个轻型的辅助类,好让处理XML类型的{@link Ext.data.Store}起来更加轻松。XmlStore可通过{@link Ext.data.XmlReader}自动配置。 * Small helper class to make creating {@link Ext.data.Store}s from XML data easier. * A XmlStore will be automatically configured with a {@link Ext.data.XmlReader}.</p> * <p>如是这样地配置一个Store:A store configuration would be something like:<pre><code> var store = new Ext.data.XmlStore({ // store configs autoDestroy: true, storeId: 'myStore', url: 'sheldon.xml', // 自动转为HttpProxy的代理。automatically configures a HttpProxy // reader configs record: 'Item', // 每条记录都有Item标签。records will have an "Item" tag idPath: 'ASIN', totalRecords: '@TotalResults' fields: [ // 设置与xml文档映射的字段。最紧要的事mapping项,其他的就次要。 // set up the fields mapping into the xml doc // The first needs mapping, the others are very basic {name: 'Author', mapping: 'ItemAttributes > Author'}, 'Title', 'Manufacturer', 'ProductGroup' ] }); * </code></pre></p> * <p>经过配置后,这样的xml会演变成为store对象:This store is configured to consume a returned object of the form:<pre><code> &#60?xml version="1.0" encoding="UTF-8"?> &#60ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15"> &#60Items> &#60Request> &#60IsValid>True&#60/IsValid> &#60ItemSearchRequest> &#60Author>Sidney Sheldon&#60/Author> &#60SearchIndex>Books&#60/SearchIndex> &#60/ItemSearchRequest> &#60/Request> &#60TotalResults>203&#60/TotalResults> &#60TotalPages>21&#60/TotalPages> &#60Item> &#60ASIN>0446355453&#60/ASIN> &#60DetailPageURL> http://www.amazon.com/ &#60/DetailPageURL> &#60ItemAttributes> &#60Author>Sidney Sheldon&#60/Author> &#60Manufacturer>Warner Books&#60/Manufacturer> &#60ProductGroup>Book&#60/ProductGroup> &#60Title>Master of the Game&#60/Title> &#60/ItemAttributes> &#60/Item> &#60/Items> &#60/ItemSearchResponse> * </code></pre> * “对象字面化”的形式也可以用于{@link #data}的配置项。<br /> * An object literal of this form could also be used as the {@link #data} config option.</p> * <p><b>注意:</b>尽管还没有列出,该类可接收来自<b>{@link Ext.data.XmlReader XmlReader}</b>所有的配置项。<br /> * <b>Note:</b> Although not listed here, this class accepts all of the configuration options of * <b>{@link Ext.data.XmlReader XmlReader}</b>.</p> * @constructor * @param {Object} config * @xtype xmlstore */ Ext.data.XmlStore = Ext.extend(Ext.data.Store, { /** * @cfg {Ext.data.DataReader} reader @hide */ constructor: function(config){ config = config || {}; config = config || {}; Ext.applyIf(config, { proxy: { type: 'ajax', reader: 'xml', writer: 'xml' } }); Ext.data.XmlStore.superclass.constructor.call(this, config); } }); Ext.reg('xmlstore', Ext.data.XmlStore);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.data.JsonPStore * @extends Ext.data.Store * @ignore * @private * <p><b>NOTE:</b>该类需要迁移到新的API。 This class is in need of migration to the new API.</p> * <p> * 小型的辅助类使得创建跨域读取JSON数据的{@link Ext.data.Store}更来得容易。JsonPStore自动与{@link Ext.data.JsonReader}和{@link Ext.data.ScriptTagProxy ScriptTagProxy}进行配置。 * Small helper class to make creating {@link Ext.data.Store}s from different domain JSON data easier. * A JsonPStore will be automatically configured with a {@link Ext.data.JsonReader} and a {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p> * <p>配置Store的例子如下:A store configuration would be something like:<pre><code> var store = new Ext.data.JsonPStore({ // store configs autoDestroy: true, storeId: 'myStore', // proxy configs url: 'get-images.php', // reader configs root: 'images', idProperty: 'name', fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}] }); * </code></pre></p> * <p>该Store可以配置为读取下面对象的格式:This store is configured to consume a returned object of the form:<pre><code> stcCallback({ images: [ {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)}, {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)} ] }) * </code></pre> * <p>stcCallback是回调函数的名称,需要在请求中指定。请参阅{@link Ext.data.ScriptTagProxy ScriptTagProxy}了解更多。Where stcCallback is the callback name passed in the request to the remote domain. See {@link Ext.data.ScriptTagProxy ScriptTagProxy} * for details of how this works.</p> * An object literal of this form could also be used as the {@link #data} config option.</p> * <p><b>注意*Note:</b>尽管没有列出,<b>{@link Ext.data.JsonReader JsonReader}</b>及<b>{@link Ext.data.ScriptTagProxy ScriptTagProxy}</b>的配置项对于该类同样也是适用的。<b>*Note:</b> Although not listed here, this class accepts all of the configuration options of * <b>{@link Ext.data.JsonReader JsonReader}</b> and <b>{@link Ext.data.ScriptTagProxy ScriptTagProxy}</b>.</p> * @constructor * @param {Object} config * @xtype jsonpstore */ Ext.data.JsonPStore = Ext.extend(Ext.data.Store, { /** * @cfg {Ext.data.DataReader} reader @hide */ constructor: function(config) { Ext.data.JsonPStore.superclass.constructor.call(this, Ext.apply(config, { reader: new Ext.data.JsonReader(config), proxy : new Ext.data.ScriptTagProxy(config) })); } }); Ext.reg('jsonpstore', Ext.data.JsonPStore);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @todo * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Aaron Conran * @class Ext.data.TreeStore * @extends Ext.data.AbstractStore * <p>表示层次数据的Store。A store class that allows the representation of hierarchical data.</p> * @constructor * @param {Object} config 可选的配置项对象。Optional config object */ Ext.data.TreeStore = Ext.extend(Ext.data.AbstractStore, { /** * @cfg {Boolean} clearOnLoad (optional) Default to true. Remove previously existing * child nodes before loading. */ clearOnLoad : true, /** * @cfg {String} nodeParam The name of the parameter sent to the server which contains * the identifier of the node. Defaults to <tt>'node'</tt>. */ nodeParam: 'node', /** * @cfg {String} defaultRootId * The default root id. Defaults to 'root' */ defaultRootId: 'root', constructor: function(config) { config = config || {}; var rootCfg = config.root || {}; rootCfg.id = rootCfg.id || this.defaultRootId; // create a default rootNode and create internal data struct. var rootNode = new Ext.data.RecordNode(rootCfg); this.tree = new Ext.data.Tree(rootNode); this.tree.treeStore = this; Ext.data.TreeStore.superclass.constructor.call(this, config); //<deprecated since=0.99> if (Ext.isDefined(this.nodeParameter)) { throw "Ext.data.TreeStore: nodeParameter has been renamed to nodeParam for consistency"; } //</deprecated> if (config.root) { this.read({ node: rootNode, doPreload: true }); } }, /** * Returns the root node for this tree. * @return {Ext.data.RecordNode} */ getRootNode: function() { return this.tree.getRootNode(); }, /** * Returns the record node by id * @return {Ext.data.RecordNode} */ getNodeById: function(id) { return this.tree.getNodeById(id); }, // new options are // * node - a node within the tree // * doPreload - private option used to preload existing childNodes load: function(options) { options = options || {}; options.params = options.params || {}; var node = options.node || this.tree.getRootNode(), records, record, reader = this.proxy.reader, root; if (this.clearOnLoad) { while (node.firstChild){ node.removeChild(node.firstChild); } } if (!options.doPreload) { Ext.applyIf(options, { node: node }); record = node.getRecord(); options.params[this.nodeParam] = record ? record.getId() : 'root'; return Ext.data.TreeStore.superclass.load.call(this, options); } else { root = reader.getRoot(node.isRoot ? node.attributes : node.getRecord().raw); records = reader.extractData(root, true); this.fillNode(node, records); return true; } }, // @private // fills an Ext.data.RecordNode with records fillNode: function(node, records) { node.loaded = true; var ln = records.length, recordNode, i = 0, raw, subStore = node.subStore; for (; i < ln; i++) { raw = records[i].raw; records[i].data.leaf = raw.leaf; recordNode = new Ext.data.RecordNode({ id: records[i].getId(), leaf: raw.leaf, record: records[i], expanded: raw.expanded }); node.appendChild(recordNode); if (records[i].doPreload) { this.load({ node: recordNode, doPreload: true }); } } // maintain the subStore if its already been created if (subStore) { if (this.clearOnLoad) { subStore.removeAll(); } subStore.add.apply(subStore, records); } }, onProxyLoad: function(operation) { var records = operation.getRecords(); this.fillNode(operation.node, records); this.fireEvent('read', this, operation.node, records, operation.wasSuccessful()); //this is a callback that would have been passed to the 'read' function and is optional var callback = operation.callback; if (typeof callback == 'function') { callback.call(operation.scope || this, records, operation, operation.wasSuccessful()); } }, /** * Returns a flat Ext.data.Store with the correct type of model. * @param {Ext.data.RecordNode/Ext.data.Record} record * @returns Ext.data.Store */ getSubStore: function(node) { // Remap Record to RecordNode if (node && node.node) { node = node.node; } return node.getSubStore(); }, removeAll: function() { var rootNode = this.getRootNode(); rootNode.destroy(); } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.JsonStore * @extends Ext.data.Store * @ignore * * <p> * 小型的辅助类使得转化JSON为{@link Ext.data.Store}更来得容易。ArrayStore自动与{@link Ext.data.JsonReader}进行配置。 * Small helper class to make creating {@link Ext.data.Store}s from JSON data easier. * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p> * * <p>配置Store的例子如下:A store configuration would be something like:</p> * <pre><code> var store = new Ext.data.JsonStore({ // store configs autoDestroy: true, storeId: 'myStore' proxy: { type: 'ajax', url: 'get-images.php', reader: { type: 'json', root: 'images', idProperty: 'name' } }, // 可选的,也可以指定{@link Ext.data.Model}名称,请参阅{@link Ext.data.Store}的例子。alternatively, a {@link Ext.data.Model} name can be given (see {@link Ext.data.Store} for an example) fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}] }); </code></pre> * * <p>样本数据如下:This store is configured to consume a returned object of the form:<pre><code> { images: [ {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)}, {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)} ] } </code></pre> * * <p>如果传入字面化对象,就要指定{@link #data}是哪一个属性。An object literal of this form could also be used as the {@link #data} config option.</p> * * @constructor * @param {Object} config * @xtype jsonstore */ Ext.data.JsonStore = Ext.extend(Ext.data.Store, { /** * @cfg {Ext.data.DataReader} reader @hide */ constructor: function(config) { config = config || {}; Ext.applyIf(config, { proxy: { type : 'ajax', reader: 'json', writer: 'json' } }); Ext.data.JsonStore.superclass.constructor.call(this, config); } }); Ext.reg('jsonstore', Ext.data.JsonStore);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.AbstractStore * @extends Ext.util.Observable * * <p> * 抽象的Store负责和Proxy和Reader耦合,却没有任何的实体数据的存储representation。也就是说AbstractStore只是各对象之间耦合的一些共性内容, * 如真正的数据区域是根据不同组件而不同的,如一般Store就是Ext.util.MixedCollection,而Tree组件就是Ext.data.Tree。 * AbstractStore which provides interactivity with proxies and readers but * does NOT rely on any internal data storage representation. Subclasses of * Store and TreeStore use the internal representation of Ext.util.MixedCollection * and Ext.data.Tree respectively.</p> * */ Ext.data.AbstractStore = Ext.extend(Ext.util.Observable, { remoteSort : false, remoteFilter: false, /** * @cfg {String/Ext.data.Proxy/Object} proxy Store的Proxy。该项可以是字符串、Proxy实例对象、配置项对象,参见{@link #setProxy}。The Proxy to use for this Store. This can be either a string, a config * object or a Proxy instance - see {@link #setProxy} for details. */ /** * @cfg {Boolean/Object} autoLoad 如果有值传入,那么store的load会自动调用,发生在autoLoaded对象创建之后。 * If data is not specified, and if autoLoad is true or an Object, this store's load method * is automatically called after creation. If the value of autoLoad is an Object, this Object will be passed to the store's * load method. Defaults to false. */ autoLoad: false, /** * @cfg {Boolean} autoSave True表示为在每次编辑记录的时候,都自动同步Store及其Proxy。默认为false。True to automatically sync the Store with its Proxy after every edit to one of its Records. * Defaults to false. */ autoSave: false, /** * 根据批处理的同步方案设置更新行为。默认指定的“operation”表示,每当批处理中的每一个操作完成好了之后;就会更新Store内部的数据内容; * 若指定'complete'则会等待到整个批处理结束了才会更新Store的数据内容。对于local storgae Proxy来说'complete'是好的选择, * 'operation'则适用于远程的Proxy,相对比较高延时。 * Sets the updating behavior based on batch synchronization. 'operation' (the default) will update the Store's * internal representation of the data after each operation of the batch has completed, 'complete' will wait until * the entire batch has been completed before updating the Store's data. 'complete' is a good choice for local * storage proxies, 'operation' is better for remote proxies, where there is a comparatively high latency. * @property batchUpdateMode * @type String */ batchUpdateMode: 'operation', /** * true表示为每当Store加载数据之后就进行数据过滤,在触发datachanged事件之前执行。 * 默认为true,如{@link #remoteFilter}=true则忽略该项。 * If true, any filters attached to this Store will be run after loading data, before the datachanged event is fired. * Defaults to true, ignored if {@link #remoteFilter} is true * @property filterOnLoad * @type Boolean */ filterOnLoad: true, /** * true表示为每当Store加载数据之后就进行数据排序,在触发datachanged事件之前执行。 * 默认为true,如{@link #remoteFilter}=true则忽略该项。 * If true, any sorters attached to this Store will be run after loading data, before the datachanged event is fired. * Defaults to true, igored if {@link #remoteSort} is true * @property sortOnLoad * @type Boolean */ sortOnLoad: true, /** * 默认的排序方法(默认是“ASC”)。The default sort direction to use if one is not specified (defaults to "ASC") * @property defaultSortDirection * @type String */ defaultSortDirection: "ASC", /** * True表示为为Store隐式创建模型。只有Store构建器传入了字段信息才有用而不是模型其构建器或名称。 * True if a model was created implicitly for this Store. This happens if a fields array is passed to the Store's constructor * instead of a model constructor or name. * @property implicitModel * @type Boolean * @private */ implicitModel: false, /** * 默认的Proxy类型。默认为{@link Ext.data.MemoryProxy memory proxy}。 * The string type of the Proxy to create if none is specified. This defaults to creating a {@link Ext.data.MemoryProxy memory proxy}. * @property defaultProxyType * @type String */ defaultProxyType: 'memory', /** * True表示为Store已经透过{@link #destroyStore}摧毁了。如果true,Store的引用应该被删除。 * True if the Store has already been destroyed via {@link #destroyStore}. If this is true, the reference to Store should be deleted * as it will not function correctly any more. * @property isDestroyed * @type Boolean */ isDestroyed: false, isStore: true, /** * @cfg {String} storeId 可选的独一无二的Store标识。如果有的话,将会在{@link Ext.StoreMgr}中登记Store。以便更好的复用。默认是undefined。Optional unique identifier for this store. If present, this Store will be registered with * the {@link Ext.StoreMgr}, making it easy to reuse elsewhere. Defaults to undefined. */ //documented above constructor: function(config) { this.addEvents( /** * @event add * 当有Model添加到Store里面后触发。 * Fired when a Model instance has been added to this Store * @param {Ext.data.Store} this Ext.data.Store * @param {Array} records 加入的Model数组(Ext.data.Model [])。The Model instances that were added * @param {Number} index 添加Record的索引。The index at which the instances were inserted */ 'add', /** * @event remove * 当Store中的Model被移除后触发。 * Fired when a Model instance has been removed from this Store * @param {Ext.data.Model} record 被移除的Model。The record that was removed */ 'remove', /** * @event update * 当有Record更新时触发。 * Fires when a Record has been updated * @param {Store} this * @param {Ext.data.Model} record 被更新的Model。The Model instance that was updated * @param {String} operation更新的Opeation对象。可以是以下的值: The update operation being performed. Value may be one of: * <pre><code> Ext.data.Model.EDIT Ext.data.Model.REJECT Ext.data.Model.COMMIT * </code></pre> */ 'update', /** * @event datachanged * 当有数据发生变动的时候触发该事件,包括添加或删除记录,又或者更新记录。 * Fires whenever the records in the Store have changed in some way - this could include adding or removing records, * or updating the data in existing records * @param {Ext.data.Store} this Store对象。The data store */ 'datachanged', /** * @event beforeload * 当一笔新的Record加载之前触发。 * Event description * @param {Ext.data.Store} store This Store * @param {Ext.data.Operation} operation 会传入到Proxy的Ext.data.Operation对象以加载Store数据。The Ext.data.Operation object that will be passed to the Proxy to load the Store */ 'beforeload', /** * @event load * 当一笔新的Record加载完毕后触发。 * Fires whenever the store reads data from a remote data source. * @param {Ext.data.store} this * @param {Array} records 记录数组。An array of records * @param {Boolean} successful True表示为操作成功。True if the operation was successful. */ 'load', /** * @event beforesync * 在执行{@link #sync}之前触发的事件。返回false就取消任何同步的事件。 * Called before a call to {@link #sync} is executed. Return false from any listener to cancel the synv * @param {Object} options 要同步的全体记录。断裂的create、update和destroy。Hash of all records to be synchronized, broken down into create, update and destroy */ 'beforesync' ); Ext.apply(this, config); /** * 临时的缓存,用于保存Proxy同步之前的那些要被移除的模型实例。 * Temporary cache in which removed model instances are kept until successfully synchronised with a Proxy, * at which point this is cleared. * @private * @property removed * @type Array */ this.removed = []; /** * 为每个字段排序的方向('ASC'或'DESC'),只读的。 * Stores the current sort direction ('ASC' or 'DESC') for each field. Used internally to manage the toggling * of sort direction per field. Read only * @property sortToggle * @type Object */ this.sortToggle = {}; Ext.data.AbstractStore.superclass.constructor.apply(this, arguments); this.model = Ext.ModelMgr.getModel(config.model); /** * @property modelDefaults * @type Object * @private * 透过{@link #insert}或{@link #create}创建每一个模型实例的时候,所读取得默认值。 * 这是内部建立外键和其它字段的关系。参阅Association源代码的例子。用户不需要接触这个属性。 * A set of default values to be applied to every model instance added via {@link #insert} or created via {@link #create}. * This is used internally by associations to set foreign keys and other fields. See the Association classes source code * for examples. This should not need to be used by application developers. */ Ext.applyIf(this, { modelDefaults: {} }); //向后兼容 Supports the 3.x style of simply passing an array of fields to the store, implicitly creating a model if (!this.model && config.fields) { this.model = Ext.regModel('ImplicitModel-' + this.storeId || Ext.id(), { fields: config.fields }); delete this.fields; this.implicitModel = true; } //保证Proxy都被实例化。ensures that the Proxy is instantiated correctly this.setProxy(config.proxy || this.model.proxy); if (this.id && !this.storeId) { this.storeId = this.id; delete this.id; } if (this.storeId) { Ext.StoreMgr.register(this); } /** * 当前应用到该Store的{@link Ext.util.Sorter 排序器}集合。 * The collection of {@link Ext.util.Sorter Sorters} currently applied to this Store. * @property sorters * @type Ext.util.MixedCollection */ this.sorters = new Ext.util.MixedCollection(); this.sorters.addAll(this.decodeSorters(config.sorters)); /** * 当前应用到该Store的{@link Ext.util.Filter 过滤器}集合。 * The collection of {@link Ext.util.Filter Filters} currently applied to this Store * @property filters * @type Ext.util.MixedCollection */ this.filters = new Ext.util.MixedCollection(); this.filters.addAll(this.decodeFilters(config.filters)); }, /** * 设置Store的Proxy,该项可以是字符串、Proxy实例对象、配置项对象。 * Sets the Store's Proxy by string, config object or Proxy instance * @param {String|Object|Ext.data.Proxy} proxy 新型Proxy,该项可以是字符串、Proxy实例对象、配置项对象。The new Proxy, which can be either a type string, a configuration object * or an Ext.data.Proxy instance * @return {Ext.data.Proxy} 加入的Proxy对象。The attached Proxy object */ setProxy: function(proxy) { if (proxy instanceof Ext.data.Proxy) { proxy.setModel(this.model); } else { Ext.applyIf(proxy, { model: this.model }); proxy = Ext.data.ProxyMgr.create(proxy); } this.proxy = proxy; return this.proxy; }, /** * 返回当前绑定到Store的Proxy。 * Returns the proxy currently attached to this proxy instance * @return {Ext.data.Proxy} Proxy实例。The Proxy instance */ getProxy: function() { return this.proxy; }, //保存虚记录。 saves any phantom records create: function(data, options) { var instance = Ext.ModelMgr.create(Ext.applyIf(data, this.modelDefaults), this.model.modelName), operation; options = options || {}; Ext.applyIf(options, { action : 'create', records: [instance] }); operation = new Ext.data.Operation(options); this.proxy.create(operation, this.onProxyWrite, this); return instance; }, read: function() { return this.load.apply(this, arguments); }, onProxyRead: Ext.emptyFn, update: function(options) { options = options || {}; Ext.applyIf(options, { action : 'update', records: this.getUpdatedRecords() }); var operation = new Ext.data.Operation(options); return this.proxy.update(operation, this.onProxyWrite, this); }, onProxyWrite: Ext.emptyFn, //让加入的proxy消耗指定的记录。tells the attached proxy to destroy the given records destroy: function(options) { options = options || {}; Ext.applyIf(options, { action : 'destroy', records: this.getRemovedRecords() }); var operation = new Ext.data.Operation(options); return this.proxy.destroy(operation, this.onProxyWrite, this); }, onBatchOperationComplete: function(batch, operation) { if (operation.action == 'create') { var records = operation.records, length = records.length, i; for (i = 0; i < length; i++) { records[i].needsAdd = false; } } this.fireEvent('datachanged', this); }, /** * @private * 为Proxy的批处理对象登记“complete”事件。遍历批处理的Opeartion对象并更新Store内部的MixedCollection数据集合。 * Attached as the 'complete' event listener to a proxy's Batch object. Iterates over the batch operations * and updates the Store's internal data MixedCollection. */ onBatchComplete: function(batch, operation) { var operations = batch.operations, length = operations.length, i; this.suspendEvents(); for (i = 0; i < length; i++) { this.onProxyWrite(operations[i]); } this.resumeEvents(); this.fireEvent('datachanged', this); }, onBatchException: function(batch, operation) { // //decide what to do... could continue with the next operation // batch.start(); // // //or retry the last operation // batch.retry(); }, /** * @private * 新纪录的过滤器函数。 * Filter function for new records. */ filterNew: function(item) { return item.phantom == true || item.needsAdd == true; }, /** * 返回全部模型实例 * 返回全部虚模型实例(例如没有id的),或者返回有ID但是这个Store尚未保存的模型实例(当从另外一个Store取得一个非虚记录到这个Store的时候发生)。 * Returns all Model instances that are either currently a phantom (e.g. have no id), or have an ID but have not * yet been saved on this Store (this happens when adding a non-phantom record from another Store into this one) * @return {Array} Model实例。The Model instances */ getNewRecords: function() { return []; }, /** *返回全部已经更新但是没有与Proxy同步的模型实例。 * Returns all Model instances that have been updated in the Store but not yet synchronized with the Proxy * @return {Array} 更新的模型实例。The updated Model instances */ getUpdatedRecords: function() { return []; }, /** * @private * 脏纪录的过滤器函数。 * Filter function for dirty records. */ filterDirty: function(item) { return item.dirty == true; }, // 返回在Store已经消失的记录,但在Proxy上尚未被摧毁这些记录。 //returns any records that have been removed from the store but not yet destroyed on the proxy getRemovedRecords: function() { return this.removed; }, sort: function(sorters, direction) { }, /** * @private * 常规化排序器对象,保证它们都是Ext.util.Sorter实例。 * Normalizes an array of sorter objects, ensuring that they are all Ext.util.Sorter instances * @param {Array} sorters 排序器对象。The sorters array * @return {Array} Ext.util.Sorter对象组成的数组。Array of Ext.util.Sorter objects */ decodeSorters: function(sorters) { if (!Ext.isArray(sorters)) { if (sorters == undefined) { sorters = []; } else { sorters = [sorters]; } } var length = sorters.length, Sorter = Ext.util.Sorter, config, i; for (i = 0; i < length; i++) { config = sorters[i]; if (!(config instanceof Sorter)) { if (Ext.isString(config)) { config = { property: config }; } Ext.applyIf(config, { root : 'data', direction: "ASC" }); //支持3.x 向后兼容。support for 3.x style sorters where a function can be defined as 'fn' if (config.fn) { config.sorterFn = config.fn; } //支持函数类型的。support a function to be passed as a sorter definition if (typeof config == 'function') { config = { sorterFn: config }; } sorters[i] = new Sorter(config); } } return sorters; }, filter: function(filters, value) { }, /** * @private * 创建排序函数。 * Creates and returns a function which sorts an array by the given field and direction * @param {String} field 要排序的字段。The field to create the sorter for * @param {String} direction 排序大的方向(默认“ASC”)The direction to sort by (defaults to "ASC") * @return {Function} 排序函数。A function which sorts by the field/direction combination provided */ createSortFunction: function(field, direction) { direction = direction || "ASC"; var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1; var fields = this.model.prototype.fields, sortType = fields.get(field).sortType; //create a comparison function. Takes 2 records, returns 1 if record 1 is greater, //-1 if record 2 is greater or 0 if they are equal return function(r1, r2) { var v1 = sortType(r1.data[field]), v2 = sortType(r2.data[field]); return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0)); }; }, /** * @private * 常规化排序器对象,保证它们都是Ext.util.Filter实例。 * Normalizes an array of filter objects, ensuring that they are all Ext.util.Filter instances * @param {Array} filters 排序器对象。The filters array * @return {Array} Ext.util.Sorter对象组成的数组。Array of Ext.util.Filter objects */ decodeFilters: function(filters) { if (!Ext.isArray(filters)) { if (filters == undefined) { filters = []; } else { filters = [filters]; } } var length = filters.length, Filter = Ext.util.Filter, config, i; for (i = 0; i < length; i++) { config = filters[i]; if (!(config instanceof Filter)) { Ext.apply(config, { root: 'data' }); //向后兼容 support for 3.x style filters where a function can be defined as 'fn' if (config.fn) { config.filterFn = config.fn; } //support a function to be passed as a filter definition if (typeof config == 'function') { config = { filterFn: config }; } filters[i] = new Filter(config); } } return filters; }, clearFilter: function(supressEvent) { }, isFiltered: function() { }, filterBy: function(fn, scope) { }, /** * 使得Store及其Proxy于同步的状态,让Proxy打包任何Store中的new、updated、deleted的记录,更新Store内部的记录内容为每个操作的完成状态。 * Synchronizes the Store with its Proxy. This asks the Proxy to batch together any new, updated * and deleted records in the store, updating the Store's internal representation of the records * as each operation completes. */ sync: function() { var me = this, options = {}, toCreate = me.getNewRecords(), toUpdate = me.getUpdatedRecords(), toDestroy = me.getRemovedRecords(), needsSync = false; if (toCreate.length > 0) { options.create = toCreate; needsSync = true; } if (toUpdate.length > 0) { options.update = toUpdate; needsSync = true; } if (toDestroy.length > 0) { options.destroy = toDestroy; needsSync = true; } if (needsSync && me.fireEvent('beforesync', options) !== false) { me.proxy.batch(options, me.getBatchListeners()); } }, /** * @private * 返回传入到this.sync中的proxy.batch侦听器参数。这里分开了函数是为了可以自定义侦听器。 * Returns an object which is passed in as the listeners argument to proxy.batch inside this.sync. * This is broken out into a separate function to allow for customisation of the listeners * @return {Object} 侦听器对象。The listeners object */ getBatchListeners: function() { var listeners = { scope: this, exception: this.onBatchException }; if (this.batchUpdateMode == 'operation') { listeners['operationcomplete'] = this.onBatchOperationComplete; } else { listeners['complete'] = this.onBatchComplete; } return listeners; }, //deprecated, will be removed in 5.0 save: function() { return this.sync.apply(this, arguments); }, /** * 通过已配置的{@link #proxy}加载Store的数据。 * Loads the Store using its configured {@link #proxy}. * @param {Object} options 可选的配置项对象。该对象会传入到里面要创建的{@link Ext.data.Operation Operation}对象中去。 * 然后送到Proxy的{@link Ext.data.Proxy#read}函数。 * Optional config object. This is passed into the {@link Ext.data.Operation Operation} * object that is created and then sent to the proxy's {@link Ext.data.Proxy#read} function */ load: function(options) { var me = this, operation; options = options || {}; Ext.applyIf(options, { action : 'read', filters: me.filters.items, sorters: me.sorters.items }); operation = new Ext.data.Operation(options); if (me.fireEvent('beforeload', me, operation) !== false) { me.loading = true; me.proxy.read(operation, me.onProxyLoad, me); } return me; }, /** * @private * 当{@link Ext.data.Model#join joined}到Store后,模型实例应该调用这个方法。 * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to. * @param {Ext.data.Model} record 编辑的模型实例。The model instance that was edited */ afterEdit : function(record) { this.fireEvent('update', this, record, Ext.data.Model.EDIT); }, /** * @private * 当{@link Ext.data.Model#join joined}到Store后,模型实例应该调用这个方法。 * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to.. * @param {Ext.data.Model} record 编辑的模型实例。The model instance that was edited */ afterReject : function(record) { this.fireEvent('update', this, record, Ext.data.Model.REJECT); }, /** * @private * 当{@link Ext.data.Model#join joined}到Store后,模型实例应该调用这个方法。 * A model instance should call this method on the Store it has been {@link Ext.data.Model#join joined} to. * @param {Ext.data.Model} record 编辑的模型实例。The model instance that was edited */ afterCommit : function(record) { if (this.autoSave) { this.sync(); } this.fireEvent('update', this, record, Ext.data.Model.COMMIT); }, clearData: Ext.emptFn, destroyStore: function() { if (!this.isDestroyed) { if (this.storeId) { Ext.StoreMgr.unregister(this); } this.clearData(); this.data = null; this.tree = null; // Ext.destroy(this.proxy); this.reader = this.writer = null; this.clearListeners(); this.isDestroyed = true; if (this.implicitModel) { Ext.destroy(this.model); } } }, /** * 返回描述该Store的排列对象信息的对象。 * Returns an object describing the current sort state of this Store. * @return {Object} Store的排序信息。有两个属性:The sort state of the Store. An object with two properties:<ul> * <li><b>field : String<p class="sub-desc">Records的那一个对象被排序。The name of the field by which the Records are sorted.</p></li> * <li><b>direction : String<p class="sub-desc">排序方向:'ASC'或'DESC'(大小写敏感的)The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li> * </ul> * 参阅<tt>{@link #sortInfo}</tt>了解更多。See <tt>{@link #sortInfo}</tt> for additional details. */ getSortState : function() { return this.sortInfo; }, getCount: function() { }, getById: function(id) { }, // individual substores should implement a "fast" remove // and fire a clear event afterwards removeAll: function() { } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ArrayStore * @extends Ext.data.Store * @ignore * * <p> * 小型的辅助类使得数组转化为{@link Ext.data.Store}更来得容易。ArrayStore自动与{@link Ext.data.ArrayReader}进行配置。 * Small helper class to make creating {@link Ext.data.Store}s from Array data easier. * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p> * * <p>配置Store的例子如下:A store configuration would be something like:</p> <pre><code> var store = new Ext.data.ArrayStore({ // store configs autoDestroy: true, storeId: 'myStore', // reader configs idIndex: 0, fields: [ 'company', {name: 'price', type: 'float'}, {name: 'change', type: 'float'}, {name: 'pctChange', type: 'float'}, {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'} ] }); </code></pre> * <p>样本数据如下:This store is configured to consume a returned object of the form: <pre><code> var myData = [ ['3m Co',71.72,0.02,0.03,'9/1 12:00am'], ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'], ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'], ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am'] ]; </code></pre> * * <p>如果传入字面化对象,就要指定{@link #data}是哪一个属性。An object literal of this form could also be used as the {@link #data} config option.</p> * * <p><b>注意*Note:</b>尽管没有列出,{@link Ext.data.ArrayReader ArrayReader}的配置项对于该类同样也是适用的。 Although not listed here, this class accepts all of the configuration options of * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p> * * @constructor * @param {Object} config * @xtype arraystore */ Ext.data.ArrayStore = Ext.extend(Ext.data.Store, { /** * @cfg {Ext.data.DataReader} reader @hide */ constructor: function(config) { config = config || {}; Ext.applyIf(config, { proxy: { type: 'memory', reader: 'array' } }); Ext.data.ArrayStore.superclass.constructor.call(this, config); }, loadData: function(data, append) { if (this.expandData === true) { var r = [], i = 0, ln = data.length; for (; i < ln; i++) { r[r.length] = [data[i]]; } data = r; } Ext.data.ArrayStore.superclass.loadData.call(this, data, append); } }); Ext.reg('arraystore', Ext.data.ArrayStore); // backwards compat Ext.data.SimpleStore = Ext.data.ArrayStore; Ext.reg('simplestore', Ext.data.SimpleStore);
JavaScript
/* * @version Sencha 1.0RC * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.data.Tree * @extends Ext.util.Observable * 该对象抽象了一棵树的结构和树节点的事件上报。树包含的节点拥有大部分的DOM功能。<br /> * Represents a tree data structure and bubbles all the events for its nodes. The nodes * in the tree have most standard DOM functionality. * @constructor * @param {Node} root (可选的)根节点。(optional) The root node */ Ext.data.Tree = Ext.extend(Ext.util.Observable, { constructor: 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", /** * @event remove * 当树中有子节点从一个节点那里移动开来的时候触发。 * Fires when a child node is removed from a node in this tree. * @param {Tree} tree 主树。The owner tree * @param {Node} parent 父节点。The parent node * @param {Node} node 要移除的节点。The child node removed */ "remove", /** * @event move * 当树中有节点被移动到新的地方时触发。 * Fires when a node is moved to a new location in the tree * @param {Tree} tree 主树。The owner tree * @param {Node} node 移动的节点 The node moved * @param {Node} oldParent 该节点的旧父节点。The old parent of this node * @param {Node} newParent 该节点的新父节点。The new parent of this node * @param {Number} index 被移动的原索引。The index it was moved to */ "move", /** * @event insert * 当树中有一个新的节点添加到某个节点上的时候触发。 * Fires when a new child node is inserted in a node in this tree. * @param {Tree} tree 主树。The owner tree * @param {Node} parent 父节点。The parent node * @param {Node} node 插入的子节点。The child node inserted * @param {Node} refNode 节点之前插入的子节点。The child node the node was inserted before */ "insert", /** * @event beforeappend * 当树中有新的子节点添加到某个节点上之前触发,返回false表示取消这个添加行动。 * Fires before a new child is appended to a node in this tree, return false to cancel the append. * @param {Tree} tree 主树。The owner tree * @param {Node} parent 父节点。The parent node * @param {Node} node 要被移除的子节点。The child node to be appended */ "beforeappend", /** * @event beforeremove * 当树中有节点移动到新的地方之前触发,返回false表示取消这个移动行动。 * Fires before a child is removed from a node in this tree, return false to cancel the remove. * @param {Tree} tree 主树。The owner tree * @param {Node} parent 父节点。The parent node * @param {Node} node 要被添加的子节点。The child node to be removed */ "beforeremove", /** * @event beforemove * 当树中有新的子节点移除到某个节点上之前触发,返回false表示取消这个移除行动。 * Fires before a node is moved to a new location in the tree. Return false to cancel the move. * @param {Tree} tree 主树。The owner tree * @param {Node} node 父节点 The node being moved * @param {Node} oldParent 节点的父节点。The parent of the node * @param {Node} newParent 要移动到的新的父节点。The new parent the node is moving to * @param {Number} index 要被移动到的索引。The index it is being moved to */ "beforemove", /** * @event beforeinsert * 当树中有新的子节点插入某个节点之前触发,返回false表示取消这个插入行动。 * Fires before a new child is inserted in a node in this tree, return false to cancel the insert. * @param {Tree} tree 主树。The owner tree * @param {Node} parent 父节点。The parent node * @param {Node} node 要被插入的子节点。The child node to be inserted * @param {Node} refNode 在插入之前节点所在的那个子节点。The child node the node is being inserted before */ "beforeinsert" ); Ext.data.Tree.superclass.constructor.call(this); }, /** * @cfg {String} pathSeparator * 分割节点Id的标识符(默认为"/")。 * The token used to separate paths in node ids (defaults to '/'). */ pathSeparator: "/", // private proxyNodeEvent : function(){ return this.fireEvent.apply(this, arguments); }, /** * 为这棵树返回根节点。 * Returns the root node for this tree. * @return {Node} */ getRootNode : function() { return this.root; }, /** * 设置这棵树的根节点。 * Sets the root node for this tree. * @param {Node} node * @return {Node} */ setRootNode : function(node) { this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); return node; }, /** * 根据ID查找节点。 * Gets a node in this tree by its id. * @param {String} id * @return {Node} */ getNodeById : function(id) { return this.nodeHash[id]; }, // private registerNode : function(node) { this.nodeHash[node.id] = node; }, // private unregisterNode : function(node) { delete this.nodeHash[node.id]; }, toString : function() { return "[Tree"+(this.id?" "+this.id:"")+"]"; } });
JavaScript
/** * @author Ed Spencer * @class Ext.data.ProxyMgr * @extends Ext.AbstractManager * @singleton * @ignore */ Ext.data.ProxyMgr = new Ext.AbstractManager({ create: function(config) { if (config == undefined || typeof config == 'string') { config = { type: config }; } if (!(config instanceof Ext.data.Proxy)) { Ext.applyIf(config, { type : this.defaultProxyType, model: this.model }); var type = config[this.typeName] || config.type, Constructor = this.types[type]; if (Constructor == undefined) { throw new Error(Ext.util.Format.format("The '{0}' type has not been registered with this manager", type)); } return new Constructor(config); } else { return config; } } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.RestProxy * @extends Ext.data.AjaxProxy * * <p> * 如果需要进行RESTful的风格应用,我们可以在{@link Ext.data.AjaxProxy AjaxProxy}的基础上增加四个HTTP动词(CRUD对应POST、GET、PUT、DELETE)。 * Specialization of the {@link Ext.data.AjaxProxy AjaxProxy} which simply maps the four actions (create, read, * update and destroy) to RESTful HTTP verbs</p> */ Ext.data.RestProxy = Ext.extend(Ext.data.AjaxProxy, { /** * 映射动作名称到HTTP请求方法。默认常规就是'create', 'read','update' and 'destroy'分别对应POST、GET、PUT、DELETE。 * 该项应该保持不变除非使用全局{@link Ext.override}的方法,也可以用重写{@link #getMethod}来代替。 * Mapping of action name to HTTP request method. These default to RESTful conventions for the 'create', 'read', * 'update' and 'destroy' actions (which map to 'POST', 'GET', 'PUT' and 'DELETE' respectively). This object should * not be changed except globally via {@link Ext.override} - the {@link #getMethod} function can be overridden instead. * @property actionMethods * @type Object */ actionMethods: { create : 'POST', read : 'GET', update : 'PUT', destroy: 'DELETE' }, api: { create : 'create', read : 'read', update : 'update', destroy: 'destroy' } }); Ext.data.ProxyMgr.registerType('rest', Ext.data.RestProxy);
JavaScript
/** * @author Ed Spencer * @class Ext.data.SessionStorageProxy * @extends Ext.data.WebStorageProxy * * <p>这个Proxy是以HTML5 Session存储为服务对象的,但倘若浏览器不支持HTML5 Session客户端存储方案,构造函数就会立刻抛出一个异常。Proxy which uses HTML5 local storage as its data storage/retrieval mechanism. * 本地存储需要一个独一无二的ID作为存放全部记录对象的KEY。 * Proxy which uses HTML5 session storage as its data storage/retrieval mechanism. * If this proxy is used in a browser where session storage is not supported, the constructor will throw an error. * A session storage proxy requires a unique ID which is used as a key in which all record data are stored in the * session storage object.</p> * * <p> * 切记送入的ID必须是独一无二的,否则调用过程将是不稳定的。如果没有送入ID,则storeId会视为ID。如果什么ID都没有将会抛出一个异常。 * It's important to supply this unique ID as it cannot be reliably determined otherwise. If no id is provided * but the attached store has a storeId, the storeId will be used. If neither option is presented the proxy will * throw an error.</p> * * <p>Proxy总是结合{@link Ext.data.Store store}使用的,如下例:Proxies are almost always used with a {@link Ext.data.Store store}:<p> * <pre><code> new Ext.data.Store({ proxy: { type: 'sessionstorage', id : 'myProxyKey' } }); </code></pre> * * <p>外你也可以直接地创建Proxy:Alternatively you can instantiate the Proxy directly:</p> * <pre><code> new Ext.data.SessionStorageProxy({ id : 'myOtherProxyKey' }); </code></pre> * * <p> * 那么Session存储与本地存储(也就是{@link Ext.data.LocalStorageProxy})有什么区别呢?就是如果浏览器的Session会话结束后(比如您关闭了浏览器), * 将会丢失SessionStorageProxy中所有的数据。但是{@link Ext.data.LocalStorageProxy}中的数据还是存在。 * Note that session storage is different to local storage (see {@link Ext.data.LocalStorageProxy}) - if a browser * session is ended (e.g. by closing the browser) then all data in a SessionStorageProxy are lost. Browser restarts * don't affect the {@link Ext.data.LocalStorageProxy} - the data are preserved.</p> */ Ext.data.SessionStorageProxy = Ext.extend(Ext.data.WebStorageProxy, { //inherit docs getStorageObject: function() { return window.sessionStorage; } }); Ext.data.ProxyMgr.registerType('sessionstorage', Ext.data.SessionStorageProxy);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.MemoryProxy * @extends Ext.data.ClientProxy * * <p>内存中proxy,所以一刷新浏览器的话,就没有了本地数据。通常来说不会直接使用到这个类,什么时候使用呢? * 比如一个User模型和来源不同的数据,它们之间的结构并不是十分吻合,我们就可以灵活使用MemoryProxy和JsonReader作转换,然后加载到{@link Ext.data.Store Store} 中去。 * In-memory proxy. This proxy simply uses a local variable for data storage/retrieval, so its contents are * lost on every page refresh. Usually this Proxy isn't used directly, serving instead as a helper to a * {@link Ext.data.Store Store} where a reader is required to load data. For example, say we have a Store for * a User model and have some inline data we want to load, but this data isn't in quite the right format: we * can use a MemoryProxy with a JsonReader to read it into our Store:</p> * <pre><code> //这时Store中所使用的模型。this is the model we'll be using in the store Ext.regModel('User', { fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'}, {name: 'phone', type: 'string', mapping: 'phoneNumber'} ] }); //此数据并不是与我们上面定义的模型所吻合,就是phone字段必须映射为phoneNumber。this data doesn't line up to our model fields - the phone field is called phoneNumber var data = { users: [ { id: 1, name: 'Ed Spencer', phoneNumber: '555 1234' }, { id: 2, name: 'Abe Elias', phoneNumber: '666 1234' } ] }; //注意如何设置reader中的“root: 'users'”,看看是怎么对应上面的数据结构的。note how we set the 'root' in the reader to match the data structure above var store = new Ext.data.Store({ autoLoad: true, model: 'User', data : data, proxy: { type: 'memory', reader: { type: 'json', root: 'users' } } }); </code></pre> */ Ext.data.MemoryProxy = Ext.extend(Ext.data.ClientProxy, { /** * @cfg {Array} data 可选的,加载到Proxy的Record数组。Optional array of Records to load into the Proxy */ constructor: function(config) { Ext.data.MemoryProxy.superclass.constructor.call(this, config); //保证reader一定要实例化了的才可以。 ensures that the reader has been instantiated properly this.setReader(this.reader); }, /** * 通过Proxy所依赖的{@link #reader}去读本对象身上{@link #data}对象。 * Reads data from the configured {@link #data} object. Uses the Proxy's {@link #reader}, if present * @param {Ext.data.Operation} operation 读操作对象。The read Operation * @param {Function} callback 回调函数。The callback to call when reading has completed * @param {Object} scope 作用域。 The scope to call the callback function in */ read: function(operation, callback, scope) { var reader = this.getReader(), result = reader.read(this.data); // operation.resultSet = result; Ext.apply(operation, { resultSet: result }); operation.setCompleted(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, // 覆盖掉原来的throw函数。 clear: Ext.emptyFn }); Ext.data.ProxyMgr.registerType('memory', Ext.data.MemoryProxy);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ClientProxy * @extends Ext.data.Proxy * * <p> * Ext.data.ClientProxy是为服务端而设的存储基类。它的子类有{@link Ext.data.MemoryProxy Memory}和{@link Ext.data.WebStorageProxy Web Storage}。 * 因为是基类,请不要直接使用。 * Base class for any client-side storage. Used as a superclass for {@link Ext.data.MemoryProxy Memory} and * {@link Ext.data.WebStorageProxy Web Storage} proxies. Do not use directly, use one of the subclasses instead.</p> */ Ext.data.ClientProxy = Ext.extend(Ext.data.Proxy, { /** * 抽象函数,每一个子类都必须实现该方法。这个方法会删除掉客户端的使所有记录数据,包括像IDs的这样的支持数据。 * Abstract function that must be implemented by each ClientProxy subclass. This should purge all record data * from the client side storage, as well as removing any supporting data (such as lists of record IDs) */ clear: function() { throw new Error("The Ext.data.ClientProxy subclass that you are using has not defined a 'clear' function. See src/data/ClientProxy.js for details."); } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.AjaxProxy * @extends Ext.data.ServerProxy * * <p>处理数据请求的{@link Ext.data.Proxy}实现,只针对同源的页面。An implementation of {@link Ext.data.Proxy} that processes data requests within the same * domain of the originating page.</p> * * <p> * 注意这个类不能脱离本页面的范围进行跨域(Cross Domain)获取数据。要进行跨域获取数据,请使用{@link Ext.data.ScriptTagProxy ScriptTagProxy}。 * <b>Note</b>: this class cannot be used to retrieve data from a domain other * than the domain from which the running page was served. For cross-domain requests, use a * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p> * * <p> * 为了浏览器能成功解析返回来的XML document对象,HTTP Response头的Content-Type必须被设成为"<tt>text/xml</tt>"。 * 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 "<tt>text/xml</tt>".</p> * * @constructor * * <p> * 注意如果该AjaxProxy正在使用的是{@link Ext.data.Store Store},那么Store的{@link #load}调用将会覆盖全部指定的<tt>callback</tt>与<tt>params</tt>选项。 * 这样,在Store的{@link Ext.data.Store#events events}那里就可以改变参数,或处理加载事件。 * 在实例化的时候就会使用了Store的{@link Ext.data.Store#baseParams baseParams}。<br /> * Note that if this AjaxProxy is being used by a {@link Ext.data.Store Store}, then the * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt> * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters, * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be * used to pass parameters known at instantiation time.</p> * * <p>如果传入一个选项参数,那么就即会使用{@link Ext.Ajax}这个单例对象进行网络通讯。If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make * the request.</p> */ Ext.data.AjaxProxy = Ext.extend(Ext.data.ServerProxy, { /** * @property actionMethods * 映射动作名称到HTTP请求方法。AjaxProxy只是简单地认为“GET”是读操作,而“POST”就代表了其余的 'create', 'update' and 'destroy'操作。 * 要应用的RESTful方法,可以参考{@link Ext.data.RestProxy}。 * Mapping of action name to HTTP request method. In the basic AjaxProxy these are set to 'GET' for 'read' actions and 'POST' * for 'create', 'update' and 'destroy' actions. The {@link Ext.data.RestProxy} maps these to the correct RESTful methods. */ actionMethods: { create : 'POST', read : 'GET', update : 'POST', destroy: 'POST' }, /** * @cfg {Object} headers 添加到AJAX请求的头部。默认为<tt>undefined</tt>。Any headers to add to the Ajax request. Defaults to <tt>undefined</tt>. */ constructor: function() { this.addEvents( /** * @event exception * 当数据加载的时候如有错误发生触发该事件。 * Fires when the server returns an exception * @param {Ext.data.Proxy} this * @param {Object} response 响应对象。The response from the AJAX request * @param {Ext.data.Operation} operation 操作对象。The operation that triggered request */ 'exception' ); Ext.data.AjaxProxy.superclass.constructor.apply(this, arguments); }, /** * @ignore */ doRequest: function(operation, callback, scope) { var writer = this.getWriter(), request = this.buildRequest(operation, callback, scope); if (operation.allowWrite()) { request = writer.write(request); } Ext.apply(request, { headers : this.headers, timeout : this.timeout, scope : this, callback: this.createRequestCallback(request, operation, callback, scope), method : this.getMethod(request) }); Ext.Ajax.request(request); return request; }, /** * 根据给出请求对象返回其HTTP方法。默认返回{@link #actionMethods}中的一种。 * Returns the HTTP method name for a given request. By default this returns based on a lookup on {@link #actionMethods}. * @param {Ext.data.Request} request 请求对象。The request object * @return {String} HTTP请求方法,应该是以下'GET'、'POST'、'PUT'或'DELETE'中的一种。The HTTP method to use (should be one of 'GET', 'POST', 'PUT' or 'DELETE') */ getMethod: function(request) { return this.actionMethods[request.action]; }, /** * @private * TODO: This is currently identical to the ScriptTagProxy version except for the return function's signature. There is a lot * of code duplication inside the returned function so we need to find a way to DRY this up. * @param {Ext.data.Request} request The Request object * @param {Ext.data.Operation} operation The Operation being executed * @param {Function} callback The callback function to be called when the request completes. This is usually the callback * passed to doRequest * @param {Object} scope The scope in which to execute the callback function * @return {Function} The callback function */ createRequestCallback: function(request, operation, callback, scope) { var me = this; return function(options, success, response) { if (success === true) { var reader = me.getReader(), result = reader.read(response); //see comment in buildRequest for why we include the response object here Ext.apply(operation, { response : response, resultSet: result }); operation.setCompleted(); operation.setSuccessful(); } else { me.fireEvent('exception', this, response, operation); //TODO: extract error message from reader operation.setException(); } //this callback is the one that was passed to the 'read' or 'write' function above if (typeof callback == 'function') { callback.call(scope || me, operation); } me.afterRequest(request, true); }; } }); Ext.data.ProxyMgr.registerType('ajax', Ext.data.AjaxProxy); //backwards compatibility, remove in Ext JS 5.0 Ext.data.HttpProxy = Ext.data.AjaxProxy;
JavaScript
/* * @version Sencha 0.98 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.LocalStorageProxy * @extends Ext.data.WebStorageProxy * * <p>这个Proxy是以HTML5本地存储为服务对象的,但倘若浏览器不支持HTML5客户端存储方案,构造函数就会立刻抛出一个异常。Proxy which uses HTML5 local storage as its data storage/retrieval mechanism. * 本地存储需要一个独一无二的ID作为存放全部记录对象的KEY。 * If this proxy is used in a browser where local storage is not supported, the constructor will throw an error. * A local storage proxy requires a unique ID which is used as a key in which all record data are stored in the * local storage object.</p> * * <p> * 切记送入的ID必须是独一无二的,否则调用过程将是不稳定的。如果没有送入ID,则storeId会视为ID。如果什么ID都没有将会抛出一个异常。 * It's important to supply this unique ID as it cannot be reliably determined otherwise. If no id is provided * but the attached store has a storeId, the storeId will be used. If neither option is presented the proxy will * throw an error.</p> * * <p>Proxy总是结合{@link Ext.data.Store store}使用的,如下例:Proxies are almost always used with a {@link Ext.data.Store store}:<p> * <pre><code> new Ext.data.Store({ proxy: { type: 'localstorage', id : 'myProxyKey' } }); </code></pre> * * <p>另外你也可以直接地创建Proxy:Alternatively you can instantiate the Proxy directly:</p> * <pre><code> new Ext.data.LocalStorageProxy({ id : 'myOtherProxyKey' }); </code></pre> */ Ext.data.LocalStorageProxy = Ext.extend(Ext.data.WebStorageProxy, { //inherit docs getStorageObject: function() { return window.localStorage; } }); Ext.data.ProxyMgr.registerType('localstorage', Ext.data.LocalStorageProxy);
JavaScript
/* * @version Sencha 0.98 * @ignore * @todo * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.WebStorageProxy * @extends Ext.data.ClientProxy * * <p> * WebStorageProxy是{@link Ext.data.LocalStorageProxy localStorage}及{@link Ext.data.SessionStorageProxy sessionStorage} 的基类, * 它使用了HTML5新型的ley/value客户端存储方案来保存{@link Ext.data.Model model instances},达到离线存储之目的。 * WebStorageProxy is simply a superclass for the {@link Ext.data.LocalStorageProxy localStorage} and * {@link Ext.data.SessionStorageProxy sessionStorage} proxies. It uses the new HTML5 key/value client-side storage * objects to save {@link Ext.data.Model model instances} for offline use.</p> * * @constructor * 创建proxy,如果浏览器不支持HTML5客户端存储方案,就立刻抛出一个异常。 * Creates the proxy, throws an error if local storage is not supported in the current browser * @param {Object} config 可选的配置项对象。Optional config object */ Ext.data.WebStorageProxy = Ext.extend(Ext.data.ClientProxy, { /** * @cfg {String} id The unique ID used as the key in which all record data are stored in the local storage object */ id: undefined, /** * @ignore */ constructor: function(config) { Ext.data.WebStorageProxy.superclass.constructor.call(this, config); /** * Cached map of records already retrieved by this Proxy - ensures that the same instance is always retrieved * @property cache * @type Object */ this.cache = {}; if (this.getStorageObject() == undefined) { throw "Local Storage is not supported in this browser, please use another type of data proxy"; } //if an id is not given, try to use the store's id instead this.id = this.id || (this.store ? this.store.storeId : undefined); if (this.id == undefined) { throw "No unique id was provided to the local storage proxy. See Ext.data.LocalStorageProxy documentation for details"; } this.initialize(); }, //inherit docs create: function(operation, callback, scope) { var records = operation.records, length = records.length, ids = this.getIds(), id, record, i; operation.setStarted(); for (i = 0; i < length; i++) { record = records[i]; if (record.phantom) { record.phantom = false; id = this.getNextId(); } else { id = record.getId(); } this.setRecord(record, id); ids.push(id); } this.setIds(ids); operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, //inherit docs read: function(operation, callback, scope) { //TODO: respect sorters, filters, start and limit options on the Operation var records = [], ids = this.getIds(), length = ids.length, i, recordData, record; //read a single record if (operation.id) { record = this.getRecord(operation.id); if (record) { records.push(record); operation.setSuccessful(); } } else { for (i = 0; i < length; i++) { records.push(this.getRecord(ids[i])); } operation.setSuccessful(); } operation.setCompleted(); operation.resultSet = new Ext.data.ResultSet({ records: records, total : records.length, loaded : true }); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, //inherit docs update: function(operation, callback, scope) { var records = operation.records, length = records.length, ids = this.getIds(), record, id, i; operation.setStarted(); for (i = 0; i < length; i++) { record = records[i]; this.setRecord(record); //we need to update the set of ids here because it's possible that a non-phantom record was added //to this proxy - in which case the record's id would never have been added via the normal 'create' call id = record.getId(); if (id !== undefined && ids.indexOf(id) == -1) { ids.push(id); } } this.setIds(ids); operation.setCompleted(); operation.setSuccessful(); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, //inherit destroy: function(operation, callback, scope) { var records = operation.records, length = records.length, ids = this.getIds(), //newIds is a copy of ids, from which we remove the destroyed records newIds = [].concat(ids), i; for (i = 0; i < length; i++) { newIds.remove(records[i].getId()); this.removeRecord(records[i], false); } this.setIds(newIds); if (typeof callback == 'function') { callback.call(scope || this, operation); } }, /** * @private * Fetches a model instance from the Proxy by ID. Runs each field's decode function (if present) to decode the data * @param {String} id The record's unique ID * @return {Ext.data.Model} The model instance */ getRecord: function(id) { if (this.cache[id] == undefined) { var rawData = Ext.decode(this.getStorageObject().getItem(this.getRecordKey(id))), data = {}, Model = this.model, fields = Model.prototype.fields.items, length = fields.length, i, field, name, record; for (i = 0; i < length; i++) { field = fields[i]; name = field.name; if (typeof field.decode == 'function') { data[name] = field.decode(rawData[name]); } else { data[name] = rawData[name]; } } record = new Model(data); record.phantom = false; this.cache[id] = record; } return this.cache[id]; }, /** * Saves the given record in the Proxy. Runs each field's encode function (if present) to encode the data * @param {Ext.data.Model} record The model instance * @param {String} id The id to save the record under (defaults to the value of the record's getId() function) */ setRecord: function(record, id) { if (id) { record.setId(id); } else { id = record.getId(); } var rawData = record.data, data = {}, model = this.model, fields = model.prototype.fields.items, length = fields.length, i, field, name; for (i = 0; i < length; i++) { field = fields[i]; name = field.name; if (typeof field.encode == 'function') { data[name] = field.encode(rawData[name], record); } else { data[name] = rawData[name]; } } var obj = this.getStorageObject(), key = this.getRecordKey(id); //keep the cache up to date this.cache[id] = record; //iPad bug requires that we remove the item before setting it obj.removeItem(key); obj.setItem(key, Ext.encode(data)); }, /** * @private * Physically removes a given record from the local storage. Used internally by {@link #destroy}, which you should * use instead because it updates the list of currently-stored record ids * @param {String|Number|Ext.data.Model} id The id of the record to remove, or an Ext.data.Model instance */ removeRecord: function(id, updateIds) { if (id instanceof Ext.data.Model) { id = id.getId(); } if (updateIds !== false) { var ids = this.getIds(); ids.remove(id); this.setIds(ids); } this.getStorageObject().removeItem(this.getRecordKey(id)); }, /** * @private * Given the id of a record, returns a unique string based on that id and the id of this proxy. This is used when * storing data in the local storage object and should prevent naming collisions. * @param {String|Number|Ext.data.Model} id The record id, or a Model instance * @return {String} The unique key for this record */ getRecordKey: function(id) { if (id instanceof Ext.data.Model) { id = id.getId(); } return Ext.util.Format.format("{0}-{1}", this.id, id); }, /** * @private * Returns the unique key used to store the current record counter for this proxy. This is used internally when * realizing models (creating them when they used to be phantoms), in order to give each model instance a unique id. * @return {String} The counter key */ getRecordCounterKey: function() { return Ext.util.Format.format("{0}-counter", this.id); }, /** * @private * Returns the array of record IDs stored in this Proxy * @return {Array} The record IDs. Each is cast as a Number */ getIds: function() { var ids = (this.getStorageObject().getItem(this.id) || "").split(","), length = ids.length, i; if (length == 1 && ids[0] == "") { ids = []; } else { for (i = 0; i < length; i++) { ids[i] = parseInt(ids[i], 10); } } return ids; }, /** * @private * Saves the array of ids representing the set of all records in the Proxy * @param {Array} ids The ids to set */ setIds: function(ids) { var obj = this.getStorageObject(), str = ids.join(","); obj.removeItem(this.id); if (!Ext.isEmpty(str)) { obj.setItem(this.id, str); } }, /** * @private * Returns the next numerical ID that can be used when realizing a model instance (see getRecordCounterKey). Increments * the counter. * @return {Number} The id */ getNextId: function() { var obj = this.getStorageObject(), key = this.getRecordCounterKey(), last = obj[key], ids, id; if (last == undefined) { ids = this.getIds(); last = ids[ids.length - 1] || 0; } id = parseInt(last, 10) + 1; obj.setItem(key, id); return id; }, /** * @private * Sets up the Proxy by claiming the key in the storage object that corresponds to the unique id of this Proxy. Called * automatically by the constructor, this should not need to be called again unless {@link #clear} has been called. */ initialize: function() { var storageObject = this.getStorageObject(); storageObject.setItem(this.id, storageObject.getItem(this.id) || ""); }, /** * Destroys all records stored in the proxy and removes all keys and values used to support the proxy from the storage object */ clear: function() { var obj = this.getStorageObject(), ids = this.getIds(), len = ids.length, i; //remove all the records for (i = 0; i < len; i++) { this.removeRecord(ids[i]); } //remove the supporting objects obj.removeItem(this.getRecordCounterKey()); obj.removeItem(this.id); }, /** * @private * Abstract function which should return the storage object that data will be saved to. This must be implemented * in each subclass. * @return {Object} The storage object */ getStorageObject: function() { throw new Error("The getStorageObject function has not been defined in your Ext.data.WebStorageProxy subclass"); } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Proxy * @extends Ext.util.Observable * * <p> * 当{@link Ext.data.Store Stores}要为{@link Ext.data.Model Model}加载或者保存数据的时候,就必须通过这个Proxy类。 * 一般情况下开发者不要直接使用这个类。 * Proxies are used by {@link Ext.data.Store Stores} to handle the loading and saving of {@link Ext.data.Model Model} data. * Usually developers will not need to create or interact with proxies directly.</p> * <p><u>Proxy类型:Types of Proxy</u></p> * * <p> * 主要的两种Proxy是{@link Ext.data.ClientProxy Client}和{@link Ext.data.ServerProxy Server}。 * Client Proxy的意思是在客户端保存本地的数据,有下面的子类: * There are two main types of Proxy - {@link Ext.data.ClientProxy Client} and {@link Ext.data.ServerProxy Server}. The Client proxies * save their data locally and include the following subclasses:</p> * * <ul style="list-style-type: disc; padding-left: 25px"> * <li>{@link Ext.data.LocalStorageProxy LocalStorageProxy} -如果浏览器支持,保存localStorage的数据。 saves its data to localStorage if the browser supports it</li> * <li>{@link Ext.data.SessionStorageProxy SessionStorageProxy} -如果浏览器支持,保存sessionStorage的数据。 saves its data to sessionStorage if the browsers supports it</li> * <li>{@link Ext.data.MemoryProxy MemoryProxy} - 内存中的数据,一旦刷新页面数据将不复存在。 holds data in memory only, any data is lost when the page is refreshed</li> * </ul> * * <p>Server Proxy就是通过Request发送数据到远端。有以下子类: The Server proxies save their data by sending requests to some remote server. These proxies include:</p> * * <ul style="list-style-type: disc; padding-left: 25px"> * <li>{@link Ext.data.AjaxProxy AjaxProxy} -同源的数据请求。 sends requests to a server on the same domain</li> * <li>{@link Ext.data.ScriptTagProxy ScriptTagProxy} - 使用JSON-P进行跨域通讯。 uses JSON-P to send requests to a server on a different domain</li> * </ul> * * <p> * Proxy的操作就是将所有全部的操作视作为增、删、改、查四种,即Create、Read、Update或Delete。这四个操作分别映射了{@link #create}, {@link #read}, {@link #update} and {@link #destroy}。 * 不同的Proxy子类就要逐个去具体化这些CRUD是什么了。 * Proxies operate on the principle that all operations performed are either Create, Read, Update or Delete. These four operations * are mapped to the methods {@link #create}, {@link #read}, {@link #update} and {@link #destroy} respectively. Each Proxy subclass * implements these functions. * </p> * * <p> * CRUD方法期待一个{@link Ext.data.Operation operation}对象的独占参数传入。 * Opeartion封装了Stroe将要执行的动作信息、要修改的{@link Ext.data.Model model}实例等等。 * 请参阅{@link Ext.data.Operation Operation}文档了解更多。 * 在完成阶段,每个CRUD方法都支持异步的回调函数。 * The CRUD methods each expect an {@link Ext.data.Operation operation} object as the sole argument. The Operation encapsulates * information about the action the Store wishes to perform, the {@link Ext.data.Model model} instances that are to be modified, etc. * See the {@link Ext.data.Operation Operation} documentation for more details. Each CRUD method also accepts a callback function to be * called asynchronously on completion.</p> * * <p> * Proxy支持多个Opeartions的批处理,也就是{@link Ext.data.Batch batch}对象,参见{@link #batch}方法。 * Proxies also support batching of Operations via a {@link Ext.data.Batch batch} object, invoked by the {@link #batch} method.</p> * * @constructor * Creates the Proxy * @param {Object} config 可选的配置项对象。Optional config object */ Ext.data.Proxy = Ext.extend(Ext.util.Observable, { /** * @cfg {String} batchOrder * 当执行批处理时执行'create'、'update'和'destroy'动作的顺序。要改变个中顺序可以覆盖这个属性。默认就是'create,update,destroy'。 * Comma-separated ordering 'create', 'update' and 'destroy' actions when batching. Override this * to set a different order for the batched CRUD actions to be executed in. Defaults to 'create,update,destroy' */ batchOrder: 'create,update,destroy', /** * @cfg {String} defaultReaderType 默认的reader类型。默认是“json”。The default registered reader type. Defaults to 'json' */ defaultReaderType: 'json', /** * @cfg {String} defaultWriterType 默认的writer类型。默认是“json”。The default registered writer type. Defaults to 'json' */ defaultWriterType: 'json', constructor: function(config) { config = config || {}; if (config.model == undefined) { delete config.model; } Ext.data.Proxy.superclass.constructor.call(this, config); if (this.model != undefined && !(this.model instanceof Ext.data.Model)) { this.setModel(this.model); } }, /** * 设置这个proxy关联的模型。通常由Store来调用。 * Sets the model associated with this proxy. This will only usually be called by a Store * @param {String|Ext.data.Model} model 新模型。既可以是模型名称的字符串,也可以是模型构造器的引用。The new model. Can be either the model name string, * or a reference to the model's constructor * @param {Boolean} setOnStore 如果有的话,设置一个新的模型在关联的Store身上。Sets the new model on the associated Store, if one is present */ setModel: function(model, setOnStore) { this.model = Ext.ModelMgr.getModel(model); var reader = this.reader, writer = this.writer; this.setReader(reader); this.setWriter(writer); if (setOnStore && this.store) { this.store.setModel(this.model); } }, /** * 返回附加在这个Proxy身上的模型。 * Returns the model attached to this Proxy * @return {Ext.data.Model} 模型。The model */ getModel: function() { return this.model; }, /** * 设置Proxy的Reader,可以传入字符串、配置项对象或Reader实例本身。 * Sets the Proxy's Reader by string, config object or Reader instance * @param {String|Object|Ext.data.Reader} reader 可以传入字符串、配置项对象或Reader实例本身。The new Reader, which can be either a type string, a configuration object * or an Ext.data.Reader instance * @return {Ext.data.Reader} 已绑定的Reader对象。The attached Reader object */ setReader: function(reader) { if (reader == undefined || typeof reader == 'string') { reader = { type: reader }; } if (!(reader instanceof Ext.data.Reader)) { Ext.applyIf(reader, { proxy: this, model: this.model, type : this.defaultReaderType }); reader = Ext.data.ReaderMgr.create(reader); } this.reader = reader; return this.reader; }, /** * 返回当前Proxy实例的Reader对象。 * Returns the reader currently attached to this proxy instance * @return {Ext.data.Reader} Reader实例。The Reader instance */ getReader: function() { return this.reader; }, /** * 设置Proxy的Writer,可以传入字符串、配置项对象或Writer实例本身。 * Sets the Proxy's Writer by string, config object or Writer instance * @param {String|Object|Ext.data.Writer} writer 可以传入字符串、配置项对象或Writer实例本身。The new Writer, which can be either a type string, a configuration object * or an Ext.data.Writer instance * @return {Ext.data.Writer} 加入的Writer对象。The attached Writer object */ setWriter: function(writer) { if (writer == undefined || typeof writer == 'string') { writer = { type: writer }; } if (!(writer instanceof Ext.data.Writer)) { Ext.applyIf(writer, { model: this.model, type : this.defaultWriterType }); writer = Ext.data.WriterMgr.create(writer); } this.writer = writer; return this.writer; }, /** * 返回当前Proxy实例的writer对象。 * Returns the writer currently attached to this proxy instance * @return {Ext.data.Writer} writer对象The Writer instance */ getWriter: function() { return this.writer; }, /** * 执行指定的Create操作。 * Performs the given create operation. * @param {Ext.data.Operation} operation 所执行的Operation对象。The Operation to perform * @param {Function} callback 当操作完成后调用的回调函数(不管是否成功都执行的)。Callback function to be called when the Operation has completed (whether successful or not) * @param {Object} scope 回调函数的作用域。Scope to execute the callback function in */ create: Ext.emptyFn, /** * 执行指定的Read操作。 * Performs the given read operation. * @param {Ext.data.Operation} operation 所执行的Operation对象。The Operation to perform * @param {Function} callback 当操作完成后调用的回调函数(不管是否成功都执行的)。Callback function to be called when the Operation has completed (whether successful or not) * @param {Object} scope 回调函数的作用域。Scope to execute the callback function in */ read: Ext.emptyFn, /** * 执行指定的Update操作。 * Performs the given update operation. * @param {Ext.data.Operation} operation 所执行的Operation对象。The Operation to perform * @param {Function} callback 当操作完成后调用的回调函数(不管是否成功都执行的)。Callback function to be called when the Operation has completed (whether successful or not) * @param {Object} scope 回调函数的作用域。Scope to execute the callback function in */ update: Ext.emptyFn, /** * 执行指定的Destroy操作。 * Performs the given destroy operation. * @param {Ext.data.Operation} operation 所执行的Operation对象。The Operation to perform * @param {Function} callback 当操作完成后调用的回调函数(不管是否成功都执行的)。Callback function to be called when the Operation has completed (whether successful or not) * @param {Object} scope 回调函数的作用域。Scope to execute the callback function in */ destroy: Ext.emptyFn, /** * 执行{@link Ext.data.Operation Operations}的批处理命令,其顺序由{@link #batchOrder}决定。 * 它内部会调用{@link Ext.data.Store}的{@link Ext.data.Store#sync sync}方法。例子如下: * Performs a batch of {@link Ext.data.Operation Operations}, in the order specified by {@link #batchOrder}. Used internally by * {@link Ext.data.Store}'s {@link Ext.data.Store#sync sync} method. Example usage: * <pre><code> * myProxy.batch({ * create : [myModel1, myModel2], * update : [myModel3], * destroy: [myModel4, myModel5] * }); * </code></pre> * 上面的myModel*就是{@link Ext.data.Model Model}实例。假设1和2都是新实例还没有保存的,3就是之前保存过的了但是需要更新,4和5就是已经保存的了但是现在要删除。 * Where the myModel* above are {@link Ext.data.Model Model} instances - in this case 1 and 2 are new instances and have not been * saved before, 3 has been saved previously but needs to be updated, and 4 and 5 have already been saved but should now be destroyed. * @param {Object} operations模型实例的所在对象,(??也可以是字符串的key??) Object containing the Model instances to act upon, keyed by action name * @param {Object} listeners 可选的事件侦听器的配置项对象,会被传入的{@link Ext.data.Batch}对象中,请参阅其文档。 Optional listeners object passed straight through to the Batch - see {@link Ext.data.Batch} * @return {Ext.data.Batch} 新创建的Ext.data.Batch对象。 The newly created Ext.data.Batch object */ batch: function(operations, listeners) { var batch = new Ext.data.Batch({ proxy: this, listeners: listeners || {} }); Ext.each(this.batchOrder.split(','), function(action) { if (operations[action]) { batch.add(new Ext.data.Operation({ action : action, records: operations[action] })); } }, this); batch.start(); return batch; } }); //backwards compatibility Ext.data.DataProxy = Ext.data.Proxy; Ext.data.ProxyMgr.registerType('proxy', Ext.data.Proxy);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @todo * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ServerProxy * @extends Ext.data.Proxy * * <p> * ServerProxy是{@link Ext.data.ScriptTagProxy ScriptTagProxy}这{@link Ext.data.AjaxProxy AjaxProxy}这个两个类的超类。一般情况下不直接使用。 * ServerProxy is a superclass of {@link Ext.data.ScriptTagProxy ScriptTagProxy} and {@link Ext.data.AjaxProxy AjaxProxy}, * and would not usually be used directly.</p> * * <p> * 理想情况下,应该称ServerProxy为HttpProxy,因为这是涵盖所有HTTP Proxy的超类——但在Ext4.0中作了调整,HttpProxy只是AjaxProxy的简写。 * 3.x中的HttpProxy则变为这里的ServerProxy。 * ServerProxy should ideally be named HttpProxy as it is a superclass for all HTTP proxies - for Ext JS 4.x it has been * called ServerProxy to enable any 3.x applications that reference the HttpProxy to continue to work (HttpProxy is now an * alias of AjaxProxy).</p> */ Ext.data.ServerProxy = Ext.extend(Ext.data.Proxy, { /** * @cfg {String} url 请求数据对象到哪里的url。The URL from which to request the data object. */ /** * @cfg {Boolean} noCache (可选项)设置为true就会添加一个独一无二的cache-buster参数来获取请求(默认值为true)。(optional) Defaults to true. Disable caching by adding a unique parameter * name to the request. */ noCache : true, /** * @cfg {String} cacheString 防止缓存参数的名称。(默认为_dc)。The name of the cache param added to the url when using noCache (defaults to "_dc") */ cacheString: "_dc", /** * @cfg {Number} timeout (可选项)一次请求超时的毫秒数(默认为30秒钟)。(optional) The number of milliseconds to wait for a response. Defaults to 30 seconds. */ timeout : 30000, /** * @ignore */ constructor: function(config) { Ext.data.ServerProxy.superclass.constructor.call(this, config); /** * @cfg {Object} extraParams 外部参数,一个包含属性的对象(这些属性在该Connection发起的每次请求中作为外部参数)。 * Extra parameters that will be included on every request. Individual requests with params * of the same name will override these params when they are in conflict. */ this.extraParams = config.extraParams || {}; //backwards compatibility, will be deprecated in 5.0 this.nocache = this.noCache; }, //in a ServerProxy all four CRUD operations are executed in the same manner, so we delegate to doRequest in each case create: function() { return this.doRequest.apply(this, arguments); }, read: function() { return this.doRequest.apply(this, arguments); }, update: function() { return this.doRequest.apply(this, arguments); }, destroy: function() { return this.doRequest.apply(this, arguments); }, /** * 通过该Proxy所在的{@link Ext.data.Store Store}对象,依据其参数创建并返回一个Ext.data.Request对象。 * Creates and returns an Ext.data.Request object based on the options passed by the {@link Ext.data.Store Store} * that this Proxy is attached to. * @param {Ext.data.Operation} operation 要执行的{@link Ext.data.Operation Operation}对象。The {@link Ext.data.Operation Operation} object to execute * @return {Ext.data.Request} 请求对象。The request object */ buildRequest: function(operation) { var params = Ext.applyIf(operation.params || {}, this.extraParams || {}); //copy any sorters, filters etc into the params so they can be sent over the wire params = Ext.applyIf(params, this.getParams(params, operation)); var request = new Ext.data.Request({ params : params, action : operation.action, records : operation.records, operation: operation }); request.url = this.buildUrl(request); /* * Save the request on the Operation. Operations don't usually care about Request and Response data, but in the * ServerProxy and any of its subclasses we add both request and response as they may be useful for further processing */ operation.request = request; return request; }, /** * @private * Copy any sorters, filters etc into the params so they can be sent over the wire */ getParams: function(params, operation) { var options = ['page', 'start', 'limit', 'group', 'filters', 'sorters'], o = {}, len = options.length, i, opt; for (i = 0; i < len; ++i) { opt = options[i]; o[opt] = params[opt] || operation[opt] || o[opt]; } return o; }, /** * Generates a url based on a given Ext.data.Request object. By default, ServerProxy's buildUrl will * add the cache-buster param to the end of the url. Subclasses may need to perform additional modifications * to the url. * @param {Ext.data.Request} request The request object * @return {String} The url */ buildUrl: function(request) { var url = request.url || this.url; if (!url) { throw "You are using a ServerProxy but have not supplied it with a url. "; } if (this.noCache) { url = Ext.urlAppend(url, Ext.util.Format.format("{0}={1}", this.cacheString, (new Date().getTime()))); } return url; }, /** * In ServerProxy subclasses, the {@link #create}, {@link #read}, {@link #update} and {@link #destroy} methods all pass * through to doRequest. Each ServerProxy subclass must implement the doRequest method - see {@link Ext.data.ScriptTagProxy} * and {@link Ext.data.AjaxProxy} for examples. This method carries the same signature as each of the methods that delegate to it. * @param {Ext.data.Operation} operation The Ext.data.Operation object * @param {Function} callback The callback function to call when the Operation has completed * @param {Object} scope The scope in which to execute the callback */ doRequest: function(operation, callback, scope) { throw new Error("The doRequest function has not been implemented on your Ext.data.ServerProxy subclass. See src/data/ServerProxy.js for details"); }, /** * Optional callback function which can be used to clean up after a request has been completed. * @param {Ext.data.Request} request The Request object * @param {Boolean} success True if the request was successful */ afterRequest: Ext.emptyFn, onDestroy: function() { Ext.destroy(this.reader, this.writer); Ext.data.ServerProxy.superclass.destroy.apply(this, arguments); } });
JavaScript
Ext.apply(Ext, { /** * Returns the current document body as an {@link Ext.Element}. * @ignore * @memberOf Ext * @return Ext.Element The document body */ getHead : function() { var head; return function() { if (head == undefined) { head = Ext.get(document.getElementsByTagName("head")[0]); } return head; }; }() }); /* * @version Sencha 1.0 RC-1 * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ScriptTagProxy * @extends Ext.data.ServerProxy * * <p> * 一个{@link Ext.data.DataProxy}所实现的子类,能从一个与本页不同的域的URL地址上读取数据对象。<br /> * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain * other than the originating domain of the running page.</p> * * <p><b> * 注意如果你从与一个本页所在域不同的地方获取数据的话,应该使用这个类,而非HttpProxy。 * Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain * of the running page, you must use this class, rather than HttpProxy.</b></p> * * <p> * 透过ScriptTagProxy获取回来的服务端内容必须得是合法可执行的JavaScript代码,因为这都是在&lt;script>中执行的。 * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript * source code because it is used as the source inside a &lt;script> tag.</p> * * <p> * 为了浏览器能够自动处理返回的数据,服务器应该在打包数据对象的同时,指定一个回调函数的函数名称,这个名称从ScriptTagProxy发出的参数送出。 * 下面是一个Java中的Servlet例子,可适应ScriptTagProxy或者HttpProxy的情况,取决于是否有callback的参数送入: * In order for the browser to process the returned data, the server must wrap the data object * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy. * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy * depending on whether the callback name was passed:</p> * <pre><code> boolean scriptTag = false; String cb = request.getParameter("callback"); if (cb != null) { scriptTag = true; response.setContentType("text/javascript"); } else { response.setContentType("application/x-json"); } Writer out = response.getWriter(); if (scriptTag) { out.write(cb + "("); } out.print(dataBlock.toJsonString()); if (scriptTag) { out.write(");"); } </code></pre> * <p>下面的PHP例子同样如是:Below is a PHP example to do the same thing:</p><pre><code> $callback = $_REQUEST['callback']; // 定义输出对象。Create the output object. $output = array('a' => 'Apple', 'b' => 'Banana'); // 开始输出 start output if ($callback) { header('Content-Type: text/javascript'); echo $callback . '(' . json_encode($output) . ');'; } else { header('Content-Type: application/x-json'); echo json_encode($output); } </code></pre> * * <p>下面的ASP.Net同样如是:Below is the ASP.Net code to do the same thing:</p> * <pre><code> String jsonString = "{success: true}"; String cb = Request.Params.Get("callback"); String responseString = ""; if (!String.IsNullOrEmpty(cb)) { responseString = cb + "(" + jsonString + ")"; } else { responseString = jsonString; } Response.Write(responseString); </code></pre> * */ Ext.data.ScriptTagProxy = Ext.extend(Ext.data.ServerProxy, { defaultWriterType: 'base', /** * @cfg {String} callbackParam (Optional) (可选的)这个值会作为参数传到服务端方面。默认是“callback”。The name of the parameter to pass to the server which tells * the server the name of the callback function set up by the load call to process the returned data object. * Defaults to "callback".<p> * 得到返回的数据后,客户端方面会执行callbackParam指定名称的函数,因此这个值必须要让服务端进行处理。这个函数将有一个唯一的参数,就是数据对象本身。 * The server-side processing must read this parameter value, and generate * javascript output which calls this named function passing the data object as its only parameter. */ callbackParam : "callback", /** * @cfg {String} scriptIdPrefix * 为注入的script标签元素创建其独一无二的ID字符串(默认为“stcScript”)。 * The prefix string that is used to create a unique ID for the injected script tag element (defaults to 'stcScript') */ scriptIdPrefix: 'stcScript', /** * @cfg {String} callbackPrefix * 在全局空间中,创建一个独特的回调函数。这是该函数名称的前缀字符串。如果对服务器通话时,需要修改服务器生成的回调函数其名称,可以修改这项。默认为“stcCallback”。 * The prefix string that is used to create a unique callback function name in the global scope. This can optionally * be modified to give control over how the callback string passed to the remote server is generated. Defaults to 'stcCallback' */ callbackPrefix: 'stcCallback', /** * @cfg {String} recordParam * 当传送记录到服务器时所用的参数名称(如“records=someEncodedRecordString”)。默认为“records” * The param name to use when passing records to the server (e.g. 'records=someEncodedRecordString'). * Defaults to 'records' */ recordParam: 'records', /** * 这是记录最近通过Proxy所产生的请求对象。当Proxy被销毁会内部用来清理。 * Reference to the most recent request made through this Proxy. Used internally to clean up when the Proxy is destroyed * @property lastRequest * @type Ext.data.Request */ lastRequest: undefined, /** * @cfg {Boolean} autoAppendParams True表示为自动添加请求的参数到生成的URL。默认为true。True to automatically append the request's params to the generated url. Defaults to true */ autoAppendParams: true, constructor: function(){ this.addEvents( /** * @event exception * 当服务器返回一个异常时触发该事件。 * Fires when the server returns an exception * @param {Ext.data.Proxy} this * @param {Ext.data.Request} request 发出的请求对象。The request that was sent * @param {Ext.data.Operation} operation 请求所触发的操作对象。The operation that triggered the request */ 'exception' ); Ext.data.ScriptTagProxy.superclass.constructor.apply(this, arguments); }, /** * @private * 执行一个通往远程域的读取请求。ScriptTagProxy不会产生AJAX请求,而是依据内置的Ext.data.Request对象动态创建一个<script>标签来进行。 * Performs the read request to the remote domain. ScriptTagProxy does not actually create an Ajax request, * instead we write out a&lt;script> tag based on the configuration of the internal Ext.data.Request object * @param {Ext.data.Operation} operation 要执行的{@link Ext.data.Operation Operation}对象。The {@link Ext.data.Operation Operation} object to execute * @param {Function} callback 当请求对象完成后执行的回调函数。A callback function to execute when the Operation has been completed * @param {Object} scope 回调函数所执行的作用域。The scope to execute the callback in */ doRequest: function(operation, callback, scope) { //generate the unique IDs for this request var format = Ext.util.Format.format, transId = ++Ext.data.ScriptTagProxy.TRANS_ID, scriptId = format("{0}{1}", this.scriptIdPrefix, transId), stCallback = format("{0}{1}", this.callbackPrefix, transId); var writer = this.getWriter(), request = this.buildRequest(operation), //FIXME: ideally this would be in buildUrl, but we don't know the stCallback name at that point url = Ext.urlAppend(request.url, format("{0}={1}", this.callbackParam, stCallback)); if (operation.allowWrite()) { request = writer.write(request); } // 根据ScriptTagProxy的特殊属性应用在请求对象身上。 //apply ScriptTagProxy-specific attributes to the Request Ext.apply(request, { url : url, transId : transId, scriptId : scriptId, stCallback: stCallback }); // 如果请求太久了就会执行这个超时函数取消它。 //if the request takes too long this timeout function will cancel it request.timeoutId = Ext.defer(this.createTimeoutHandler, this.timeout, this, [request, operation]); // 这是请求完成后就会执行的回调函数。 //this is the callback that will be called when the request is completed window[stCallback] = this.createRequestCallback(request, operation, callback, scope); // 创建注入到document的script标签名称。 //create the script tag and inject it into the document var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("async", true); script.setAttribute("type", "text/javascript"); script.setAttribute("id", scriptId); Ext.getHead().appendChild(script); operation.setStarted(); this.lastRequest = request; return request; }, /** * @private * 创建并返回一个用于完成请求之时就要执行的函数。返回的函数应该要接受一个Response对象,该对象应该包含会给配置好Reader来解析的那些响应信息。 * 第三个参数就是完成请求后所执行的回调函数,并由Reader解码Repsonse。典型地,这个回调会被传入到一个Store,如proxy.read(operation, theCallback, scope) * 这儿的代码还会决定回调其参数是什么。 * Creates and returns the function that is called when the request has completed. The returned function * should accept a Response object, which contains the response to be read by the configured Reader. * The third argument is the callback that should be called after the request has been completed and the Reader has decoded * the response. This callback will typically be the callback passed by a store, e.g. in proxy.read(operation, theCallback, scope) * theCallback refers to the callback argument received by this function. * See {@link #doRequest} for details. * @param {Ext.data.Request} request 请求对象。The Request object * @param {Ext.data.Operation} operation 正在执行的Opearion对象。The Operation being executed * @param {Function} callback 当完成请求后执行的回调函数。通常这是传入到doRquest的回调函数。The callback function to be called when the request completes. This is usually the callback * passed to doRequest * @param {Object} scope 回调函数所执行的作用域。The scope in which to execute the callback function * @return {Function} 回调函数。The callback function */ createRequestCallback: function(request, operation, callback, scope) { var me = this; return function(response) { var reader = me.getReader(), result = reader.read(response); //see comment in buildRequest for why we include the response object here Ext.apply(operation, { response : response, resultSet: result }); operation.setCompleted(); operation.setSuccessful(); //this callback is the one that was passed to the 'read' or 'write' function above if (typeof callback == 'function') { callback.call(scope || me, operation); } me.afterRequest(request, true); }; }, /** * 当完成了请求之后,通过移除DOM中无用的script标签,执行的清理动作。 * Cleans up after a completed request by removing the now unnecessary script tag from the DOM. Also removes the * global JSON-P callback function. * @param {Ext.data.Request} request 请求对象。The request object * @param {Boolean} isLoaded True表示为已经成功完成了请求。True if the request completed successfully */ afterRequest: function() { // 清除函数 var cleanup = function(functionName) { return function() { window[functionName] = undefined; try { delete window[functionName]; } catch(e) {} }; }; return function(request, isLoaded) { Ext.get(request.scriptId).remove(); clearTimeout(request.timeoutId); var callbackName = request.stCallback; if (isLoaded) { // 为何需要多个函数?直接cleanup()不可? cleanup(callbackName)(); this.lastRequest.completed = true; } else { // 原来是表示为加载完毕,所以还需要调用函数,不过就覆盖旧函数,变为cleanup的函数。也就是cleanup返回函数的原因。 // if we haven't loaded yet, the callback might still be called in the future so don't unset it immediately window[callbackName] = cleanup(callbackName); } }; }(), /** * 根据给出的Ext.data.Request生成一个url。还会替url加上参数和回调函数其名称。 * Generates a url based on a given Ext.data.Request object. Adds the params and callback function name to the url * @param {Ext.data.Request} request The request object * @return {String} The url */ buildUrl: function(request) { var url = Ext.data.ScriptTagProxy.superclass.buildUrl.call(this, request), params = Ext.apply({}, request.params), filters = params.filters, filter, i; delete params.filters; if (this.autoAppendParams) { url = Ext.urlAppend(url, Ext.urlEncode(params)); } if (filters.length) { for (i = 0; i < filters.length; i++) { filter = filters[i]; if (filter.value) { url = Ext.urlAppend(url, filter.property + "=" + filter.value); } } } // 如果遇到多个记录,每个都要加上url。 //if there are any records present, append them to the url also var records = request.records; if (Ext.isArray(records) && records.length > 0) { url = Ext.urlAppend(url, Ext.util.Format.format("{0}={1}", this.recordParam, this.encodeRecords(records))); } return url; }, //inherit docs destroy: function() { this.abort(); Ext.data.ScriptTagProxy.superclass.destroy.apply(this, arguments); }, /** * @private * @return {Boolean} True表示为当前全球尚未完成。True if there is a current request that hasn't completed yet */ isLoading : function(){ var lastRequest = this.lastRequest; return (lastRequest != undefined && !lastRequest.completed); }, /** * 如果请求中执行该方法会终止请求。 * Aborts the current server request if one is currently running */ abort: function() { if (this.isLoading()) { this.afterRequest(this.lastRequest); } }, /** * 对script标签的src地址添加适合的字符串,这是对Records而言的。这是从原来的函数中分裂出来,这样才能方便地为大家来重写。 * Encodes an array of records into a string suitable to be appended to the script src url. This is broken * out into its own function so that it can be easily overridden. * @param {Array} records 记录数组。The records array * @return {String} 已编码的记录字符串。The encoded records string */ encodeRecords: function(records) { var encoded = ""; for (var i = 0, length = records.length; i < length; i++) { encoded += Ext.urlEncode(records[i].data); } return encoded; }, /** * @private * 按照this.timeout的值开始计时器,到了时候执行到这儿,如果触发了的话,表明请求太久了必须取消。如果请求成功的话,this.afterRequest会取消掉计时器计时。 * Starts a timer with the value of this.timeout - if this fires it means the request took too long so we * cancel the request. If the request was successful this timer is cancelled by this.afterRequest * @param {Ext.data.Request} request 处理的请求对象。The Request to handle */ createTimeoutHandler: function(request, operation) { this.afterRequest(request, false); this.fireEvent('exception', this, request, operation); if (typeof request.callback == 'function') { request.callback.call(request.scope || window, null, request.options, false); } } }); Ext.data.ScriptTagProxy.TRANS_ID = 1000; Ext.data.ProxyMgr.registerType('scripttag', Ext.data.ScriptTagProxy);
JavaScript
/** * @author Ed Spencer * @class Ext.data.PolymorphicAssociation * @extends Ext.data.Association * @ignore */ Ext.data.PolymorphicAssociation = Ext.extend(Ext.data.Association, { constructor: function(config) { Ext.data.PolymorphicAssociation.superclass.constructor.call(this, config); var ownerProto = this.ownerModel.prototype, name = this.name; Ext.applyIf(this, { associationIdField: this.ownerName.toLowerCase() + "_id" }); ownerProto[name] = this.createStore(); }, /** * @private * Creates the association function that will be injected on the ownerModel. Most of what this is doing * is filtering the dataset down to the appropriate model/id combination, and adding modelDefaults to * any model instances that are created/inserted into the generated store. * @return {Function} The store-generating function */ createStore: function() { var association = this, ownerName = this.ownerName, storeName = this.name + "Store", associatedModel = this.associatedModel, primaryKey = this.primaryKey, associationIdField = 'associated_id', associationModelField = 'associated_model'; return function() { var me = this, modelDefaults = {}, config, filters; if (me[storeName] == undefined) { filters = [ { property : associationIdField, value : me.get(primaryKey), exactMatch: true }, { property : associationModelField, value : ownerName, exactMatch: true } ]; modelDefaults[associationIdField] = me.get(primaryKey); modelDefaults[associationModelField] = ownerName; config = Ext.apply({}, association.storeConfig || {}, { model : associatedModel, filters : filters, remoteFilter : false, modelDefaults: modelDefaults }); me[storeName] = new Ext.data.Store(config); } return me[storeName]; }; } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Writer * @extends Object * * <p>Base Writer class used by most subclasses of {@link Ext.data.ServerProxy}. This class is * responsible for taking a set of {@link Ext.data.Operation} objects and a {@link Ext.data.Request} * object and modifying that request based on the Operations. * 通常为{@link Ext.data.ServerProxy}其子类所使用。该类的作用是让{@link Ext.data.Operation}与{@link Ext.data.Request}产生关系, * 具体说,就是根据Operations修改请求对象。 * </p> * * <p> * 例如{@link Ext.data.JsonWriter}会根据配置项参数格式化操作对象及其{@link Ext.data.Model}实例。配置项参数来自哪里? * 就是来自{@link Ext.data.JsonWriter JsonWriter's}的构造器参数。 * For example a {@link Ext.data.JsonWriter} would format the Operations and their {@link Ext.data.Model} * instances based on the config options passed to the {@link Ext.data.JsonWriter JsonWriter's} constructor.</p> * * <p>Writers对于本地储存(local storage)而言没什么意义。 * Writers are not needed for any kind of local storage - whether via a * {@link Ext.data.WebStorageProxy Web Storage proxy} (see {@link Ext.data.LocalStorageProxy localStorage} * and {@link Ext.data.SessionStorageProxy sessionStorage}) or just in memory via a * {@link Ext.data.MemoryProxy MemoryProxy}.</p> * * @constructor * @param {Object} config 可选的配置项对象。Optional config object */ Ext.data.Writer = Ext.extend(Object, { constructor: function(config) { Ext.apply(this, config); }, /** * 准备Proxy的Ext.data.Request请求对象。Prepares a Proxy's Ext.data.Request object * @param {Ext.data.Request} request 请求对象。The request object * @return {Ext.data.Request} 已准备好的请求对象。The modified request object */ write: function(request) { var operation = request.operation, records = operation.records || [], ln = records.length, i = 0, data = []; for (; i < ln; i++) { data.push(this.getRecordData(records[i])); } return this.writeRecords(request, data); }, /** * 在发送数据服务端之前先格式化数据。应该重写这个函数以适应不同格式的需求。 * Formats the data for each record before sending it to the server. This * method should be overridden to format the data in a way that differs from the default. * @param {Object} record 我们对服务端正在写入的记录。The record that we are writing to the server. * @return {Object} 符合服务端要求的JSON。默认该方法返回Record对象的data属性。An object literal of name/value keys to be written to the server. * By default this method returns the data property on the record. */ getRecordData: function(record) { return record.data; } }); Ext.data.WriterMgr.registerType('base', Ext.data.Writer);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.XmlWriter * @extends Ext.data.Writer * * <p>Writer负责将Model的实体数据以XML格式输出。Writer that outputs model data in XML format</p> */ Ext.data.XmlWriter = Ext.extend(Ext.data.Writer, { /** * @cfg {String} documentRoot 文档的各节点的名称是什么。默认是<tt>'xmlData'</tt>。The name of the root element of the document. Defaults to <tt>'xmlData'</tt>. */ documentRoot: 'xmlData', /** * @cfg {String} header XML文档的header是什么,默认是<tt>''</tt>。A header to use in the XML document (such as setting the encoding or version). * Defaults to <tt>''</tt>. */ header: '', /** * @cfg {String} record 每一个记录变为i节点时它的标签名称是什么。默认是“record”。The name of the node to use for each record. Defaults to <tt>'record'</tt>. */ record: 'record', //inherit docs writeRecords: function(request, data) { var tpl = this.buildTpl(request, data); request.xmlData = tpl.apply(data); return request; }, buildTpl: function(request, data) { if (this.tpl) { return this.tpl; } var tpl = [], root = this.documentRoot, record = this.record, first, key; if (this.header) { tpl.push(this.header); } tpl.push('<', root, '>'); if (data.length > 0) { tpl.push('<tpl for="."><', record, '>'); first = data[0]; for (key in first) { if (first.hasOwnProperty(key)) { tpl.push('<', key, '>{', key, '}</', key, '>'); } } tpl.push('</', record, '></tpl>'); } tpl.push('</', root, '>'); this.tpl = new Ext.XTemplate(tpl.join('')); return this.tpl; } }); Ext.data.WriterMgr.registerType('xml', Ext.data.XmlWriter);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.JsonWriter * @extends Ext.data.Writer * * <p>Writer负责将Model的实体数据以JSON格式输出。Writer that outputs model data in JSON format</p> */ Ext.data.JsonWriter = Ext.extend(Ext.data.Writer, { /** * @cfg {String} root 哪一个key将作为数据的key,默认是“records”。The key under which the records in this Writer will be placed. Defaults to 'records'. * Example generated request: <pre><code> {'records': [{name: 'my record'}, {name: 'another record'}]} </code></pre> */ root: 'records', /** * @cfg {Boolean} encode True表示使用Ext.encode()编码JSON,默认是<tt>false</tt>。True to use Ext.encode() on the data before sending. Defaults to <tt>false</tt>. */ encode: false, //inherit docs writeRecords: function(request, data) { if (this.encode === true) { data = Ext.encode(data); } request.jsonData = request.jsonData || {}; request.jsonData[this.root] = data; return request; } }); Ext.data.WriterMgr.registerType('json', Ext.data.JsonWriter);
JavaScript
/* * @version Sencha 1.0RC * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.data.Types * @ignore * <p> * 这是由Ext定义的数据类型静态类,可用于{@link Ext.data.Field Field}的时候指定。 * This is s static class containing the system-supplied data types which may be given to a {@link Ext.data.Field Field}.<p/> * <p> * {@link Ext.data.Field Field}类中的类型标识指的就是这个类的属性,所以如要测试某个字段的类型,拿它与Ext.data.Types['类型名称']比较即可。 * The properties in this class are used as type indicators in the {@link Ext.data.Field Field} class, so to * test whether a Field is of a certain type, compare the {@link Ext.data.Field#type type} property against properties * of this class.</p> * <p>新建的数据类型,一定要以下的三项属性齐备:Developers may add their own application-specific data types to this class. Definition names must be UPPERCASE. * each type definition must contain three properties:</p> * <div class="mdetail-params"><ul> * <li><code>convert</code> : <i>Function</i><div class="sub-desc"> * A function to convert raw data values from a data block into the data * to be stored in the Field. The function is passed the collowing parameters: * 形成自定义数据类型的转换函数。 * 从数据源得到是原始数据,可能性需要经过特定转换,变为符合该数据类型其结构的对象。 * 该函数有两个参数供调用: * <div class="mdetail-params"><ul> * <li><b>v</b> : Mixed<div class="sub-desc"> * Reader读取过的值(一切合法的JavaScript的数据类型), * 如果没有的话便读取<tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>的值(默认值)。 * The data value as read by the Reader, if undefined will use * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li> * <li><b>rec</b> : * Reader读取过的整行数据。如果这是一个{@link Ext.data.ArrayReader ArrayReader},那么这将是一个Array; * 如果这是一个{@link Ext.data.JsonReader JsonReader},那么这将是一个JSON对象;如果这是一个{@link Ext.data.XMLReader XMLReader}, * 那么这是一个XML Element节点或元素的对象。 * Mixed<div class="sub-desc">The data object containing the row as read by the Reader. * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object * ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li> * </ul></div></div></li> * <li><code>sortType</code> : <i>Function</i> <div class="sub-desc">排序函数。根据Ext.data.SortTypes的配置信息来定义。A function to convert the stored data into comparable form, as defined by {@link Ext.data.SortTypes}.</div></li> * <li><code>type</code> : <i>String</i> <div class="sub-desc">自定义类型的名称。A textual data type name.</div></li> * </ul></div> * <p>假设有这么一个例子,创建一个VELatLong字段,微软在线地图专用的数据类型,才可以访问微软Bing地图的API。首先我们从 JsonReader中得到数据块,其中包含了laittude/longitude信息和内容,即lat和long属性,那么,我们可以这样定义 VELatLong数据类型 * For example, to create a VELatLong field (See the Microsoft Bing Mapping API) containing the latitude/longitude value of a datapoint on a map from a JsonReader data block * which contained the properties <code>lat</code> and <code>long</code>, you would define a new data type like this:</p> *<pre><code> // Add a new Field data type which stores a VELatLong object in the Record. Ext.data.Types.VELATLONG = { convert: function(v, data) { return new VELatLong(data.lat, data.long); }, sortType: function(v) { return v.Latitude; // When sorting, order by latitude }, type: 'VELatLong' }; </code></pre> * <p>Then, when declaring a Record, use <pre><code> var types = Ext.data.Types; // allow shorthand type access UnitRecord = Ext.data.Record.create([ { name: 'unitName', mapping: 'UnitName' }, { name: 'curSpeed', mapping: 'CurSpeed', type: types.INT }, { name: 'latitude', mapping: 'lat', type: types.FLOAT }, { name: 'latitude', mapping: 'lat', type: types.FLOAT }, { name: 'position', type: types.VELATLONG } ]); </code></pre> * @singleton */ Ext.data.Types = new function() { var st = Ext.data.SortTypes; Ext.apply(this, { /** * @type Regexp * @property stripRe * 为数字剔除非数字的字符串的正则。默认为 <tt>/[\$,%]/g</tt>,可按照本地化覆盖这个值。 * A regular expression for stripping non-numeric characters from a numeric value. Defaults to <tt>/[\$,%]/g</tt>. * This should be overridden for localization. */ stripRe: /[\$,%]/g, /** * @type Object. * @property AUTO * 该数据类型的意思是不作转换,将原始数据放到Record之中去。 * This data type means that no conversion is applied to the raw data before it is placed into a Record. */ AUTO: { convert: function(v) { return v; }, sortType: st.none, type: 'auto' }, /** * @type Object. * @property STRING * 该数据类型的意思是将原始数据转换为String后再放到Record之中去。 * This data type means that the raw data is converted into a String before it is placed into a Record. */ STRING: { convert: function(v) { return (v === undefined || v === null) ? '' : String(v); }, sortType: st.asUCString, type: 'string' }, /** * @type Object. * @property INT * 该数据类型的意思是将原始数据转换为整数类型后再放到Record之中去。 * This data type means that the raw data is converted into an integer before it is placed into a Record. * <p> * 另外,全称 <code>INTEGER</code>也是等价的。 * The synonym <code>INTEGER</code> is equivalent.</p> */ INT: { convert: function(v) { return v !== undefined && v !== null && v !== '' ? parseInt(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0); }, sortType: st.none, type: 'int' }, /** * @type Object. * @property FLOAT * 该数据类型的意思是将原始数据转换为Nubmer后再放到Record之中去。 * This data type means that the raw data is converted into a number before it is placed into a Record. * <p> * 另外,全称 <code>NUMBER</code>也是等价的。 * The synonym <code>NUMBER</code> is equivalent.</p> */ FLOAT: { convert: function(v) { return v !== undefined && v !== null && v !== '' ? parseFloat(String(v).replace(Ext.data.Types.stripRe, ''), 10) : (this.useNull ? null : 0); }, sortType: st.none, type: 'float' }, /** * @type Object. * @property BOOL * <p> * 该数据类型的意思是将原始数据转换为Boolean后再放到Record之中去。 * 字符串“true”和数字 1 都会被转换为布尔值<code>true</code>。 * This data type means that the raw data is converted into a boolean before it is placed into * a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p> * <p> * 另外,全称 <code>BOOLEAN</code>也是等价的。 * The synonym <code>BOOLEAN</code> is equivalent.</p> */ BOOL: { convert: function(v) { return v === true || v === 'true' || v == 1; }, sortType: st.none, type: 'bool' }, /** * @type Object. * @property DATE * 该数据类型的意思是将原始数据转换为Date后再放到Record之中去。 * 可在{@link Ext.data.Field}构造函数中指定日期的格式化函数。 * This data type means that the raw data is converted into a Date before it is placed into a Record. * The date format is specified in the constructor of the {@link Ext.data.Field} to which this type is * being applied. */ DATE: { convert: function(v) { var df = this.dateFormat; if (!v) { return null; } if (Ext.isDate(v)) { return v; } if (df) { if (df == 'timestamp') { return new Date(v*1000); } if (df == 'time') { return new Date(parseInt(v, 10)); } return Date.parseDate(v, df); } var parsed = Date.parse(v); return parsed ? new Date(parsed) : null; }, sortType: st.asDate, type: 'date' } }); Ext.apply(this, { /** * @type Object. * @property BOOLEAN * 表示数据在放置到Record之前,从原始数据转换为布尔类型的数据。 * 字符串“true”和数字1都被视作布尔类型的<code>true</code>。 * <p>同义词<code>BOOL</code>与它是等价的。</p> * <p>This data type means that the raw data is converted into a boolean before it is placed into * a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p> * <p>The synonym <code>BOOL</code> is equivalent.</p> */ BOOLEAN: this.BOOL, /** * @type Object. * @property INTEGER * 表示数据在放置到Record之前,从原始数据转换为整数类型的数据。 * <p>同义词<code>INT</code>与它是等价的。</p> * This data type means that the raw data is converted into an integer before it is placed into a Record. * <p>The synonym <code>INT</code> is equivalent.</p> */ INTEGER: this.INT, /** * @type Object. * @property NUMBER * 表示数据在放置到Record之前,从原始数据转换为数字类型的数据。 * <p>同义词<code>FLOAT</code>与它是等价的。</p> * This data type means that the raw data is converted into a number before it is placed into a Record. * <p>The synonym <code>FLOAT</code> is equivalent.</p> */ NUMBER: this.FLOAT }); };
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Errors * @extends Ext.util.MixedCollection * * <p> * 为某个字段提供访问的函数和封装验证时错误信息的对象集合。 * Wraps a collection of validation error responses and provides convenient functions for * accessing and errors for specific fields.</p> * * <p> * 一般来说不用直接实例化该类,当调用模型实例的{@link Ext.data.Model#validate validate}方法就自动创建该类的实例。 * Usually this class does not need to be instantiated directly - instances are instead created * automatically when {@link Ext.data.Model#validate validate} on a model instance:</p> * <pre><code> // 对当前的模型实例进行验证,本例中返回两个错误信息。validate some existing model instance - in this case it returned 2 failures messages var errors = myModel.validate(); errors.isValid(); //false errors.length; //2 errors.getByField('name'); // [{field: 'name', error: 'must be present'}] errors.getByField('title'); // [{field: 'title', error: 'is too short'}] </code></pre> */ Ext.data.Errors = Ext.extend(Ext.util.MixedCollection, { /** * 如果集合中没有错误返回true。 * Returns true if there are no errors in the collection * @return {Boolean} */ isValid: function() { return this.length == 0; }, /** * 返回指定字段的所有错误信息。 * Returns all of the errors for the given field * @param {String} fieldName 字段名称。The field to get errors for * @return {Array} 错误信息组成的数组。All errors for the given field */ getByField: function(fieldName) { var errors = [], error, field, i; for (i = 0; i < this.length; i++) { error = this.items[i]; if (error.field == fieldName) { errors.push(error); } } return errors; } });
JavaScript
/* * @version Sencha 0.98 * @ignore * @todo * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Field * @extends Object * * <p> * 该类封装了字段信息,用于{@link Ext.regModel}方法中的字段定义对象所用。 * <br /> * This class encapsulates the field definition information specified in the field definition objects * passed to {@link Ext.regModel}.</p> * * <p> * 开发者一般不需要实例化这该类。{@link Ext.regModel}一般会创建实例,并且在Model构建器的原型中定义设置Field,进而达到缓存之目的。 * <br /> * Developers do not need to instantiate this class. Instances are created by {@link Ext.regModel} * and cached in the {@link Ext.data.Model#fields fields} property of the created Model constructor's <b>prototype.</b></p> */ Ext.data.Field = Ext.extend(Object, { constructor : function(config) { if (Ext.isString(config)) { config = {name: config}; } Ext.apply(this, config); var types = Ext.data.Types, st = this.sortType, t; if (this.type) { if (Ext.isString(this.type)) { this.type = types[this.type.toUpperCase()] || types.AUTO; } } else { this.type = types.AUTO; } // named sortTypes are supported, here we look them up if (Ext.isString(st)) { this.sortType = Ext.data.SortTypes[st]; } else if(Ext.isEmpty(st)) { this.sortType = this.type.sortType; } if (!this.convert) { this.convert = this.type.convert; } }, /** * @cfg {String} name * Record对象所引用的字段名称。通常是一标识作它者引用, * 例如,在列定义中,该值会作为{@link Ext.grid.ColumnModel}的<em>dataIndex</em>属性。 * <p>注意,字段定义中,其他不需要其他字段,但最起码得有name项。</p> * The name by which the field is referenced within the Record. This is referenced by, for example, * the <code>dataIndex</code> property in column definition objects passed to {@link Ext.grid.ColumnModel}. * <p>Note: In the simplest case, if no properties other than <code>name</code> are required, a field * definition may consist of just a String for the field name.</p> */ /** * @cfg {Mixed} type * (可选的) 指明数据类型,转化为可显示的值。有效值是: * (Optional) The data type for automatic conversion from received data to the <i>stored</i> value if <code>{@link Ext.data.Field#convert convert}</code> * has not been specified. This may be specified as a string value. Possible values are * <div class="mdetail-params"><ul> * <li>auto (auto是默认的,不声明就用auto。不作转换Default, implies no conversion)</li> * <li>string</li> * <li>int</li> * <li>float</li> * <li>boolean</li> * <li>date</li></ul></div> * <p>This may also be specified by referencing a member of the {@link Ext.data.Types} class.</p> * <p>Developers may create their own application-specific data types by defining new members of the * {@link Ext.data.Types} class.</p> */ /** * @cfg {Function} convert * (可选的) 由Reader提供的用于转换值的函数,将值变为Record下面的对象。它会送入以下的参数: * (Optional) A function which converts the value provided by the Reader into an object that will be stored * in the Record. It is passed the following parameters:<div class="mdetail-params"><ul> * <li><b>v</b> : Mixed<div class="sub-desc">数据值,和Reader读取的一样。The data value as read by the Reader, if undefined will use * the configured <code>{@link Ext.data.Field#defaultValue defaultValue}</code>.</div></li> * <li><b>rec</b> : Mixed<div class="sub-desc">包含行的数据对象,和Reader读取的一样。 * 这可以是数组,对象,XML元素对象,这取决于{@link Ext.data.XMLReader XMLReader}对象的类型。 * The data object containing the row as read by the Reader. * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object * ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li> * </ul></div> * <pre><code> // example of convert function function fullName(v, record){ return record.name.last + ', ' + record.name.first; } function location(v, record){ return !record.city ? '' : (record.city + ', ' + record.state); } var Dude = Ext.data.Record.create([ {name: 'fullname', convert: fullName}, {name: 'firstname', mapping: 'name.first'}, {name: 'lastname', mapping: 'name.last'}, {name: 'city', defaultValue: 'homeless'}, 'state', {name: 'location', convert: location} ]); // create the data store var store = new Ext.data.Store({ reader: new Ext.data.JsonReader( { idProperty: 'key', root: 'daRoot', totalProperty: 'total' }, Dude // recordType ) }); var myData = [ { key: 1, name: { first: 'Fat', last: 'Albert' } // notice no city, state provided in data object }, { key: 2, name: { first: 'Barney', last: 'Rubble' }, city: 'Bedrock', state: 'Stoneridge' }, { key: 3, name: { first: 'Cliff', last: 'Claven' }, city: 'Boston', state: 'MA' } ]; * </code></pre> */ /** * @cfg {String} dateFormat * <p>(可选的) 字符串格式的{@link Date#parseDate Date.parseDate}函数,或“timestamp”表示Reader读取UNIX格式的timestamp,或“time”是Reader读取的是javascript毫秒的timestamp。 * (Optional) Used when converting received data into a Date when the {@link #type} is specified as <code>"date"</code>.</p> * <p>A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a * javascript millisecond timestamp. See {@link Date}</p> */ dateFormat: null, /** * @cfg {Boolean} useNull * <p>(Optional) Use when converting received data into a Number type (either int or float). If the value cannot be parsed, * null will be used if useNull is true, otherwise the value will be 0. Defaults to <tt>false</tt> */ useNull: false, /** * @cfg {Mixed} defaultValue * 当经过{@link Ext.data.Reader Reader}创建Record时会使用该值;</b> 当<b><tt>mapping</tt></b>的引用项不存在的时候,典型的情况为undefined时候会使用该值(默认为'')。 * (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b> * when the item referenced by the <code>{@link Ext.data.Field#mapping mapping}</code> does not exist in the data * object (i.e. undefined). (defaults to "") */ defaultValue: "", /** * @cfg {String/Number} mapping * <p> * (可选的) 如果使用的是{@link Ext.data.DataReader},这是一个Reader能够获取数据对象的数组值创建到{@link Ext.data.Record Record}对象下面的对应的映射项; * (Optional) A path expression for use by the {@link Ext.data.DataReader} implementation * that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object. * If the path expression is the same as the field name, the mapping may be omitted.</p> * * <p>The form of the mapping expression depends on the Reader being used.</p> * <div class="mdetail-params"><ul> * <li> * 如果使用的是{@link Ext.data.JsonReader},那么这是一个javascript表达式的字符串,能够获取数据的引用到Record对象的下面; * {@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript * expression to reference the data from an element of the data item's {@link Ext.data.JsonReader#root root} Array. Defaults to the field name.</div></li> * * <li>如果使用的是{@link Ext.data.XmlReader},这是一个{@link Ext.DomQuery}路径,能够获取数据元素的引用到{@link Ext.data.XmlReader#record record}对象的下面;默认是字段名称。 * {@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data * item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li> * <li> * 如果映射名与字段名都是相同的,那么映射名可以省略。 * {@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index * of the field's value. Defaults to the field specification's Array position.</div></li> * </ul></div> * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert} * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to * return the desired data.</p> */ mapping: null, /** * @cfg {Function} sortType * 按照既定的排序而设的函数。在这个函数中,将Field的值转换为可比较的数值。 * 预定义的函数储存在{@link Ext.data.SortTypes}。自定义的例子如下: * (Optional) A function which converts a Field's value to a comparable value in order to ensure * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom * sort example:<pre><code> // current sort after sort we want // +-+------+ +-+------+ // |1|First | |1|First | // |2|Last | |3|Second| // |3|Second| |2|Last | // +-+------+ +-+------+ sortType: function(value) { switch (value.toLowerCase()) // native toLowerCase(): { case 'first': return 1; case 'second': return 2; default: return 3; } } * </code></pre> */ sortType : null, /** * @cfg {String} sortDir * (可选的) 初始化的排序方向,“ASC”或“DESC”。默认为code>"ASC"</code>。 * (Optional) Initial direction to sort (<code>"ASC"</code> or <code>"DESC"</code>). Defaults to * <code>"ASC"</code>. */ sortDir : "ASC", /** * @cfg {Boolean} allowBlank * (可选的)用于验证{@link Ext.data.Record record},默认为<code>true</code>。若空值的话会引起{@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}视其为<code>false</code>。 * (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <code>true</code>. * An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid} * to evaluate to <code>false</code>. */ allowBlank : true });
JavaScript
/* * @version Sencha 0.98 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Association * @extends Object * * <p> * 定义关联的基类。一般情况不会直接使用到这个类,而是使用其子类{@link Ext.data.HasManyAssociation}和{@link Ext.data.BelongsToAssociation}。 * <br /> * Base Association class. Not to be used directly as it simply supports its subclasses * {@link Ext.data.HasManyAssociation} and {@link Ext.data.BelongsToAssociation}.</p> * * @constructor * @param {Object} config 配置项对象。Optional config object */ Ext.data.Association = Ext.extend(Object, { /** * @cfg {String} ownerModel 拥有关联的模型其名称,字符串,必须的。The string name of the model that owns the association. Required */ /** * @cfg {String} associatedModel 被关联的模型名称,字符串,必须的。The string name of the model that is being associated with. Required */ /** * @cfg {String} primaryKey 关联模型的外键名称。默认为'id'。The name of the primary key on the associated model. Defaults to 'id' */ primaryKey: 'id', constructor: function(config) { Ext.apply(this, config); var types = Ext.ModelMgr.types, ownerName = config.ownerModel, associatedName = config.associatedModel, ownerModel = types[ownerName], associatedModel = types[associatedName], ownerProto; if (ownerModel == undefined) { throw("The configured ownerModel was not valid (you tried " + ownerName + ")"); } if (associatedModel == undefined) { throw("The configured associatedModel was not valid (you tried " + associatedName + ")"); } this.ownerModel = ownerModel; this.associatedModel = associatedModel; Ext.applyIf(this, { ownerName : ownerName, associatedName: associatedName }); } });
JavaScript
/* * @version Sencha 1.0RC * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.WriterMgr * @extends Ext.AbstractManager * @ignore * * <p>保存了所有已登记的{@link Ext.data.Writer Writers}类型。Keeps track of all of the registered {@link Ext.data.Writer Writers}</p> */ Ext.data.WriterMgr = new Ext.AbstractManager({ });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Request * @extends Object * * <p> * 用于表示Request对象的这么一个简单的类,它是由{@link Ext.data.ServerProxy}其子类所产生。该类就是表示统一请求的表示(representation),可在任意ServerProxy子类中使用。 * 它并不包含任何业务逻辑也不会进行自身的请求。 * Simple class that represents a Request that will be made by any {@link Ext.data.ServerProxy} subclass. * All this class does is standardize the representation of a Request as used by any ServerProxy subclass, * it does not contain any actual logic or perform the request itself.</p> * * @constructor * @param {Object} config 可选的配置项对象。Optional config object */ Ext.data.Request = Ext.extend(Object, { /** * @cfg {String} action 该请求所代表的动作名称,可以是“create”、“read”、“update”或“destory”。The name of the action this Request represents. Usually one of 'create', 'read', 'update' or 'destroy' */ action: undefined, /** * @cfg {Object} params HTTP请求的参数。可以允许Proxu及其Writer访问并且允许修改。HTTP request params. The Proxy and its Writer have access to and can modify this object. */ params: undefined, /** * @cfg {String} method 请求的方法(默认为“GET”)。该值应该为“GET”、“POST”、“PUT”、“DELETE”之中的一个值。The HTTP method to use on this Request (defaults to 'GET'). Should be one of 'GET', 'POST', 'PUT' or 'DELETE' */ method: 'GET', /** * @cfg {String} url 发起请求的url。The url to access on this Request */ url: undefined, constructor: function(config) { Ext.apply(this, config); } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Batch * @extends Ext.util.Observable * * <p> * 提供一个运行一个或多个的手段,可指定既定的顺序。当完成了一个操作对象就触发“operationcomplete”事件;当完成好所有的操作就触发“complete”事件;当操作抛出任何异常就会触发“exception”事件。 * Provides a mechanism to run one or more {@link Ext.data.Operation operations} in a given order. Fires the 'operationcomplete' event * after the completion of each Operation, and the 'complete' event when all Operations have been successfully executed. Fires an 'exception' * event if any of the Operations encounter an exception.</p> * * <p>一般情况下,由{@link Ext.data.Proxy}类调用该类。Usually these are only used internally by {@link Ext.data.Proxy} classes</p> * * @constructor * @param {Object} config 可选定的,配置项对象。Optional config object */ Ext.data.Batch = Ext.extend(Ext.util.Observable, { /** * 当实例化该类的时候就是立刻进行批处理(默认为false)。True to immediately start processing the batch as soon as it is constructed (defaults to false) * @property autoStart * @type Boolean */ autoStart: false, /** * 当前执行第几个的Opeartion。The index of the current operation being executed * @property current * @type Number */ current: -1, /** * 该批处理中所有Operation的总数。只读的。 * The total number of operations in this batch. Read only * @property total * @type Number */ total: 0, /** * True表示为批处理正在运行着。 * True if the batch is currently running * @property isRunning * @type Boolean */ isRunning: false, /** * True表示为批处理已经执行完毕。True if this batch has been executed completely * @property isComplete * @type Boolean */ isComplete: false, /** * True表示为该批处理遇到异常。轮到下一个操作执行时就会清除该值。True if this batch has encountered an exception. This is cleared at the start of each operation * @property hasException * @type Boolean */ hasException: false, /** * True表示为,如果操作抛出一个异常,就自动暂停批处理的执行(默认为true)。 * True to automatically pause the execution of the batch if any operation encounters an exception (defaults to true) * @property pauseOnException * @type Boolean */ pauseOnException: true, constructor: function(config) { this.addEvents( /** * @event complete * 当全部的操作都执行完毕后触发该事件。Fired when all operations of this batch have been completed * @param {Ext.data.Batch} batch 批处理对象。The batch object * @param {Object} operation 最后一个执行的操作对象。The last operation that was executed */ 'complete', /** * @event exception * 当抛出异常时触发该事件。Fired when a operation encountered an exception * @param {Ext.data.Batch} batch The batch object * @param {Object} operation 遭遇异常的那个操作对象。The operation that encountered the exception */ 'exception', /** * @event operationcomplete * 当批处理中每一个处理对象执行完成后触发。 * Fired when each operation of the batch completes * @param {Ext.data.Batch} batch 批处理对象。The batch object * @param {Object} operation 上一个已完成的操作对象。The operation that just completed */ 'operationcomplete', //TODO: Remove this once we deprecate this function in 1.0. See below for further details 'operation-complete' ); Ext.data.Batch.superclass.constructor.call(this, config); /** * 已排序的操作对象。 * Ordered array of operations that will be executed by this batch * @property operations * @type Array */ this.operations = []; }, /** * 加入一个新的操作对象到批处理。Adds a new operation to this batch * @param {Object} operation The {@link Ext.data.Operation Operation} object */ add: function(operation) { this.total++; operation.setBatch(this); this.operations.push(operation); }, /** * 开始执行批处理。如果前一个操作抛出异常继续执行下一个操作,除非异常要求暂停。 * Kicks off the execution of the batch, continuing from the next operation if the previous * operation encountered an exception, or if execution was paused */ start: function() { this.hasException = false; this.isRunning = true; this.runNextOperation(); }, /** * @private * 运行下个操作,关联到this.current。 * Runs the next operation, relative to this.current. */ runNextOperation: function() { this.runOperation(this.current + 1); }, /** * 暂停批处理的执行,但不取消当前的操作。 * Pauses execution of the batch, but does not cancel the current operation */ pause: function() { this.isRunning = false; }, /** * 指定一个索引,执行索引的操作。 * Executes a operation by its numeric index * @param {Number} index 哪个索引? The operation index to run */ runOperation: function(index) { var operations = this.operations, operation = operations[index]; if (operation == undefined) { this.isRunning = false; this.isComplete = true; this.fireEvent('complete', this, operations[operations.length - 1]); } else { this.current = index; var onProxyReturn = function(operation) { var hasException = operation.hasException(); if (hasException) { this.hasException = true; this.fireEvent('exception', this, operation); } else { //TODO: deprecate the dashed version of this event name 'operation-complete' as it breaks convention //to be removed in 1.0 this.fireEvent('operation-complete', this, operation); this.fireEvent('operationcomplete', this, operation); } if (hasException && this.pauseOnException) { this.pause(); } else { operation.setCompleted(); this.runNextOperation(); } }; operation.setStarted(); this.proxy[operation.action](operation, onProxyReturn, this); } } });
JavaScript
/* * @version Sencha 0.98 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.ModelMgr * @extends Ext.AbstractManager * @singleton * * <p> * 创建和管理模型。 * Creates and manages the current set of models</p> */ Ext.ModelMgr = new Ext.AbstractManager({ typeName: 'mtype', /** * 指定Model的代理Proxy是什么,用字符串表示。默认为“ajax”。 * The string type of the default Model Proxy. Defaults to 'ajax' * @property defaultProxyType * @type String */ defaultProxyType: 'ajax', /** * @property associationStack * @type Array * 当定义关系之后,保存在哪里呢?就放在这个数组里面。 * Private stack of associations that must be created once their associated model has been defined */ associationStack: [], /** * 登记一个模型的定义。所有模型的插件会被立即启动,插件的参数就来自于model的配置项。 * Registers a model definition. All model plugins marked with isDefault: true are bootstrapped * immediately, as are any addition plugins defined in the model config. */ registerType: function(name, config) { /* * This function does a lot. In order, it normalizes the configured associations (see the belongsTo/hasMany if blocks) * then looks to see if we are extending another model, in which case it copies all of the fields, validations and * associations from the superclass model. Once we have collected all of these configurations, the actual creation * is delegated to createFields and createAssociations. Finally we just link up a few convenience functions on the new model. */ var PluginMgr = Ext.PluginMgr, plugins = PluginMgr.findByType('model', true), fields = config.fields || [], associations = config.associations || [], belongsTo = config.belongsTo, hasMany = config.hasMany, extendName = config.extend, modelPlugins = config.plugins || [], association, model, length, i, extendModel, extendModelProto, extendValidations, proxy; //associations can be specified in the more convenient format (e.g. not inside an 'associations' array). //we support that here if (belongsTo) { if (!Ext.isArray(belongsTo)) { belongsTo = [belongsTo]; } for (i = 0; i < belongsTo.length; i++) { association = belongsTo[i]; if (!Ext.isObject(association)) { association = {model: association}; } Ext.apply(association, {type: 'belongsTo'}); associations.push(association); } delete config.belongsTo; } if (hasMany) { if (!Ext.isArray(hasMany)) { hasMany = [hasMany]; } for (i = 0; i < hasMany.length; i++) { association = hasMany[i]; if (!Ext.isObject(association)) { association = {model: association}; } Ext.apply(association, {type: 'hasMany'}); associations.push(association); } delete config.hasMany; } //if we're extending another model, inject its fields, associations and validations if (extendName) { // 现有的业务类,继承之 extendModel = this.types[extendName]; extendModelProto = extendModel.prototype; extendValidations = extendModelProto.validations; proxy = extendModel.proxy; fields = extendModelProto.fields.items.concat(fields); associations = extendModelProto.associations.items.concat(associations); config.validations = extendValidations ? extendValidations.concat(config.validations) : config.validations; } else { // 从Ext.data.Model继承,诞生全新的业务类。 extendModel = Ext.data.Model; proxy = config.proxy; } // 创建新的业务类/ model = Ext.extend(extendModel, config); // 初始化插件 for (i = 0, length = modelPlugins.length; i < length; i++) { plugins.push(PluginMgr.create(modelPlugins[i])); } // 保存model到ModelMgr this.types[name] = model; // override方法修改prototype Ext.override(model, { plugins : plugins, fields : this.createFields(fields), associations: this.createAssociations(associations, name) }); model.modelName = name; // 注意call()用得巧妙! Ext.data.Model.setProxy.call(model, proxy || this.defaultProxyType); model.getProxy = model.prototype.getProxy; // 静态方法 model.load = function() { Ext.data.Model.load.apply(this, arguments); }; // 启动插件 for (i = 0, length = plugins.length; i < length; i++) { plugins[i].bootstrap(model, config); } model.defined = true; this.onModelDefined(model); return model; }, /** * @private * Private callback called whenever a model has just been defined. This sets up any associations * that were waiting for the given model to be defined * @param {Function} model The model that was just created */ onModelDefined: function(model) { var stack = this.associationStack, length = stack.length, create = [], association, i; for (i = 0; i < length; i++) { association = stack[i]; if (association.associatedModel == model.modelName) { create.push(association); } } length = create.length; for (i = 0; i < length; i++) { this.addAssociation(create[i], this.types[create[i].ownerModel].prototype.associations); stack.remove(create[i]); } }, /** * @private * Creates and returns a MixedCollection representing the associations on a model * @param {Array} associations The array of Association configs * @param {String} name The string name of the owner model * @return {Ext.util.MixedCollection} The Mixed Collection */ createAssociations: function(associations, name) { var length = associations.length, i, associationsMC, association; associationsMC = new Ext.util.MixedCollection(false, function(association) { return association.name; }); for (i = 0; i < length; i++) { association = associations[i]; Ext.apply(association, { ownerModel: name, associatedModel: association.model }); if (this.types[association.model] == undefined) { this.associationStack.push(association); } else { this.addAssociation(association, associationsMC); } } return associationsMC; }, /** * @private * Creates an Association based on config and the supplied MixedCollection. TODO: this will * probably need to be refactored into a more elegant solution - it was initially pulled out * to support deferred Association creation when the associated model has not been defined yet. */ addAssociation: function(association, associationsMC) { var type = association.type; if (type == 'belongsTo') { associationsMC.add(new Ext.data.BelongsToAssociation(association)); } if (type == 'hasMany') { associationsMC.add(new Ext.data.HasManyAssociation(association)); } if (type == 'polymorphic') { associationsMC.add(new Ext.data.PolymorphicAssociation(association)); } }, /** * @private * Creates and returns a MixedCollection representing the fields in a model * @param {Array} fields The array of field configurations * @return {Ext.util.MixedCollection} The Mixed Collection */ createFields: function(fields) { var length = fields.length, i, fieldsMC; fieldsMC = new Ext.util.MixedCollection(false, function(field) { return field.name; }); for (i = 0; i < length; i++) { fieldsMC.add(new Ext.data.Field(fields[i])); } return fieldsMC; }, /** * 根据id返回{@link Ext.data.Model} * Returns the {@link Ext.data.Model} for a given model name * @param {String/Object} id The id of the model or the model instance. */ getModel: function(id) { var model = id; if (typeof model == 'string') { model = this.types[model]; } return model; }, create: function(config, name) { var con = typeof name == 'function' ? name : this.types[name || config.name]; return new con(config); } }); /** * Shorthand for {@link Ext.ModelMgr#registerType} * Creates a new Model class from the specified config object. See {@link Ext.data.Model} for full examples. * * @param {Object} config A configuration object for the Model you wish to create. * @return {Ext.data.Model} The newly registered Model * @member Ext * @method regModel */ Ext.regModel = function() { return Ext.ModelMgr.registerType.apply(Ext.ModelMgr, arguments); };
JavaScript
/* * @version Sencha 0.98 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.HasManyAssociation * @extends Ext.data.Association * * <p>表示一对多的关系模型。一般使用model声明来指定:Represents a one-to-many relationship between two models. Usually created indirectly via a model definition:</p> * <pre><code> Ext.regModel('Product', { fields: [ {name: 'id', type: 'int'}, {name: 'user_id', type: 'int'}, {name: 'name', type: 'string'} ] }); Ext.regModel('User', { fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'} ], associations: [ {type: 'hasMany', model: 'Product', name: 'products'} ] }); </pre></code> * * <p>以上我们创建了Products和model模型,我们可以说用户有许多商品。 * 每一个User实例都有一个新的函数,此时此刻具体这个函数就是“product”,这正是我们在name配置项中所指定的名字。 * Above we created Product and User models, and linked them by saying that a User hasMany Products. This gives * us a new function on every User instance, in this case the function is called 'products' because that is the name * we specified in the association configuration above.</p> * * <p> * 新的函数返回一个特殊的Ext.data.Store,自动根据模型实例建立产品。 * This new function returns a specialized {@link Ext.data.Store Store} which is automatically filtered to load * only Products for the given model instance:</p> * <pre><code> // 首先,为user创建一笔新的纪录1。first, we load up a User with id of 1 var user = Ext.ModelMgr.create({id: 1, name: 'Ed'}, 'User'); // 根据既定的关系,创建user.products方法,该方法返回Store对象。the user.products function was created automatically by the association and returns a {@link Ext.data.Store Store} // 创建的Store的作用域自动定义为User的id等于1的产品。the created store is automatically scoped to the set of Products for the User with id of 1 var products = user.products(); // products是一个普通的Store,可以加入轻松地通过add()纪录we still have all of the usual Store functions, for example it's easy to add a Product for this User products.add({ name: 'Another Product' }); // 执行Store的保存命令。保存之前都自动哦你将产品的user_id为1。saves the changes to the store - this automatically sets the new Product's user_id to 1 before saving products.sync(); </code></pre> * * <p>所述的Store只在头一次执行product()时实例化,持久化在内存中不会反复创建。The new Store is only instantiated the first time you call products() to conserve memory and processing time, * though calling products() a second time returns the same store instance.</p> * * <p><u>Custom filtering</u></p> * * <p>由于Store的API中自带filter过滤器的功能,所以默认下过滤器告诉Store只返回关联模型其外键所匹配主模型其主键。例如,用户User是ID=100拥有的产品Products,那么过滤器只会返回那些符合user_id=100的产品。The Store is automatically furnished with a filter - by default this filter tells the store to only return * records where the associated model's foreign key matches the owner model's primary key. For example, if a User * with ID = 100 hasMany Products, the filter loads only Products with user_id == 100.</p> * * <p> * 但是有些时间必须指定任意字段来过滤,例如Twitter搜索的应用程序,我们就需要Search和Tweet模型: * Sometimes we want to filter by another field - for example in the case of a Twitter search application we may * have models for Search and Tweet:</p> * <pre><code> var Search = Ext.regModel('Search', { fields: [ 'id', 'query' ], hasMany: { model: 'Tweet', name : 'tweets', filterProperty: 'query' } }); Ext.regModel('Tweet', { fields: [ 'id', 'text', 'from_user' ] }); // 返回filterProperty指定的过程字段。returns a Store filtered by the filterProperty var store = new Search({query: 'Sencha Touch'}).tweets(); </code></pre> * * <p>例子中的tweets关系等价于下面,也就是通过Ext.data.HasManyAssociation.filterProperty定义过滤器。The tweets association above is filtered by the query property by setting the {@link #filterProperty}, and is * equivalent to this:</p> * <pre><code> var store = new Ext.data.Store({ model: 'Tweet', filters: [ { property: 'query', value : 'Sencha Touch' } ] }); </code></pre> */ Ext.data.HasManyAssociation = Ext.extend(Ext.data.Association, { /** * @cfg {String} foreignKey The name of the foreign key on the associated model that links it to the owner * model. Defaults to the lowercased name of the owner model plus "_id", e.g. an association with a where a * model called Group hasMany Users would create 'group_id' as the foreign key. */ /** * @cfg {String} name 创建主模型函数的名称,必须的。The name of the function to create on the owner model. Required */ /** * @cfg {Object} storeConfig (可选的)传入到生成那个Store的配置项对象。默认是undefined.Optional configuration object that will be passed to the generated Store. Defaults to * undefined. */ /** * @cfg {String} filterProperty Optionally overrides the default filter that is set up on the associated Store. If * this is not set, a filter is automatically created which filters the association based on the configured * {@link #foreignKey}. See intro docs for more details. Defaults to undefined */ constructor: function(config) { Ext.data.HasManyAssociation.superclass.constructor.apply(this, arguments); var ownerProto = this.ownerModel.prototype, name = this.name; Ext.applyIf(this, { storeName : name + "Store", foreignKey: this.ownerName.toLowerCase() + "_id" }); ownerProto[name] = this.createStore(); }, /** * @private * Creates a function that returns an Ext.data.Store which is configured to load a set of data filtered * by the owner model's primary key - e.g. in a hasMany association where Group hasMany Users, this function * returns a Store configured to return the filtered set of a single Group's Users. * @return {Function} The store-generating function */ createStore: function() { var associatedModel = this.associatedModel, storeName = this.storeName, foreignKey = this.foreignKey, primaryKey = this.primaryKey, filterProperty = this.filterProperty, storeConfig = this.storeConfig || {}; return function() { var me = this, config, filter, modelDefaults = {}; if (me[storeName] == undefined) { if (filterProperty) { filter = { property : filterProperty, value : me.get(filterProperty), exactMatch: true }; } else { filter = { property : foreignKey, value : me.get(primaryKey), exactMatch: true }; } modelDefaults[foreignKey] = me.get(primaryKey); config = Ext.apply({}, storeConfig, { model : associatedModel, filters : [filter], remoteFilter : false, modelDefaults: modelDefaults }); me[storeName] = new Ext.data.Store(config); } return me[storeName]; }; } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ReaderMgr * @extends Ext.AbstractManager * @singleton * @ignore * * <p>保存了所有已登记的{@link Ext.data.Reader Reader}类型。Maintains the set of all registered {@link Ext.data.Reader Reader} types.</p> */ Ext.data.ReaderMgr = new Ext.AbstractManager({ typeName: 'rtype' });
JavaScript
/* * @version Sencha 1.0RC-1 * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.StoreMgr * @extends Ext.util.MixedCollection * store组管理器。这是全局的、并且是缺省的。<br /> * The default global group of stores. * @singleton * TODO: Make this an AbstractMgr */ Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), { /** * @cfg {Object} listeners @hide */ /** * 登记更多的Store对象到StoreMgr。一般情况下你不需要手动加入。任何透过{@link Ext.data.Store#storeId}初始化的Store都会自动登记。 * Registers one or more Stores with the StoreMgr. You do not normally need to register stores * manually. Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered. * @param {Ext.data.Store} store1 A Store instance * @param {Ext.data.Store} store2 (optional) * @param {Ext.data.Store} etc... (optional) */ register : function() { for (var i = 0, s; (s = arguments[i]); i++) { this.add(s); } }, /** * 注销一个或多个Stores。 * Unregisters one or more Stores with the StoreMgr * @param {String/Object} id1 Store的id或是Store对象The id of the Store, or a Store instance * @param {String/Object} id2 (可选的)Store实例2。(optional) * @param {String/Object} etc... (可选的)Store实例x……。(optional) */ unregister : function() { for (var i = 0, s; (s = arguments[i]); i++) { this.remove(this.lookup(s)); } }, /** * 由id返回一个已登记的Store。 * Gets a registered Store by id * @param {String/Object} id Store的id或是Store对象。The id of the Store, or a Store instance * @return {Ext.data.Store} */ lookup : function(id) { if (Ext.isArray(id)) { var fields = ['field1'], expand = !Ext.isArray(id[0]); if(!expand){ for(var i = 2, len = id[0].length; i <= len; ++i){ fields.push('field' + i); } } return new Ext.data.ArrayStore({ data : id, fields: fields, expandData : expand, autoDestroy: true, autoCreated: true }); } return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id); }, // getKey implementation for MixedCollection getKey : function(o) { return o.storeId; } }); /** * <p> * 指定id和配置项创建新的Store,并将其登记到{@link Ext.StoreMgr Store Mananger}。 * Creates a new store for the given id and config, then registers it with the {@link Ext.StoreMgr Store Mananger}. * 简单用法:Sample usage:</p> <pre><code> Ext.regStore('AllUsers', { model: 'User' }); // 这样Store很容易与UI作整合。the store can now easily be used throughout the application new Ext.List({ store: 'AllUsers', ... other config }); </code></pre> * @param {String} id 新Store它的id。The id to set on the new store * @param {Object} config Store的配置项。The store config * @param {Constructor} cls 新组件??The new Component class. * @member Ext * @method regStore */ Ext.regStore = function(name, config) { var store; if (Ext.isObject(name)) { config = name; } else { config.storeId = name; } if (config instanceof Ext.data.Store) { store = config; } else { store = new Ext.data.Store(config); } return Ext.StoreMgr.register(store); }; /** * 返回已注册的Store(简写方式为{@link #lookup}) * Gets a registered Store by id (shortcut to {@link #lookup}) * @param {String/Object} id Stroe的Id,Store实例亦可。The id of the Store, or a Store instance * @return {Ext.data.Store} * @member Ext * @method getStore */ Ext.getStore = function(name) { return Ext.StoreMgr.lookup(name); };
JavaScript
/* * @version Sencha 1.0RC-1 * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.data.SortTypes * @singleton * @ignore * 定义一些缺省的比较函数,供排序时使用。<br /> * Defines the default sorting (casting?) comparison functions used when sorting data. */ Ext.data.SortTypes = { /** * Default sort that does nothing * @param {Mixed} s The value being converted * @return {Mixed} The comparison value */ none : function(s) { return s; }, /** * 用来去掉标签的规则表达式。 * The regular expression used to strip tags * @type {RegExp} * @property stripTagsRE */ stripTagsRE : /<\/?[^>]+>/gi, /** * 去掉所有html标签来基于纯文本排序。 * Strips all HTML tags to sort on text only * @param {Mixed} s 将被转换的值将被转换的值。The value being converted * @return {String} 用来比较的值所比较的值。The comparison value */ asText : function(s) { return String(s).replace(this.stripTagsRE, ""); }, /** * 去掉所有html标签来基于无大小写区别的文本的排序。 * Strips all HTML tags to sort on text only - Case insensitive * @param {Mixed} s 将被转换的值。The value being converted * @return {String} 所比较的值所比较的值。The comparison value */ asUCText : function(s) { return String(s).toUpperCase().replace(this.stripTagsRE, ""); }, /** * 无分大小写的字符串。 * Case insensitive string * @param {Mixed} s 将被转换的值。The value being converted * @return {String} 所比较的值。The comparison value */ asUCString : function(s) { return String(s).toUpperCase(); }, /** * 对日期排序。 * Date sorting * @param {Mixed} s 将被转换的值。The value being converted * @return {Number} 所比较的值。The comparison value */ asDate : function(s) { if(!s){ return 0; } if(Ext.isDate(s)){ return s.getTime(); } return Date.parse(String(s)); }, /** * 浮点数的排序。 * Float sorting * @param {Mixed} s 将被转换的值。The value being converted * @return {Float} 所比较的值。The comparison value */ asFloat : function(s) { var val = parseFloat(String(s).replace(/,/g, "")); return isNaN(val) ? 0 : val; }, /** * 整数的排序。 * Integer sorting * @param {Mixed} s 将被转换的值。The value being converted * @return {Number} 所比较的值。The comparison value */ asInt : function(s) { var val = parseInt(String(s).replace(/,/g, ""), 10); return isNaN(val) ? 0 : val; } };
JavaScript
/** * @author Ed Spencer * @class Ext.data.Store * @extends Ext.data.AbstractStore * * <p>The Store class encapsulates a client side cache of {@link Ext.data.Model Model} objects. Stores load * data via a {@link Ext.data.Proxy Proxy}, and also provide functions for {@link #sort sorting}, * {@link #filter filtering} and querying the {@link Ext.data.Model model} instances contained within it.</p> * * <p>Creating a Store is easy - we just tell it the Model and the Proxy to use to load and save its data:</p> * <pre><code> // Set up a {@link Ext.data.Model model} to use in our Store Ext.regModel('User', { fields: [ {name: 'firstName', type: 'string'}, {name: 'lastName', type: 'string'}, {name: 'age', type: 'int'}, {name: 'eyeColor', type: 'string'} ] }); var myStore = new Ext.data.Store({ model: 'User', proxy: { type: 'ajax', url : '/users.json', reader: { type: 'json', root: 'users' } }, autoLoad: true }); </code></pre> * <p>In the example above we configured an AJAX proxy to load data from the url '/users.json'. We told our Proxy * to use a {@link Ext.data.JsonReader JsonReader} to parse the response from the server into Model object - * {@link Ext.data.JsonReader see the docs on JsonReader} for details.</p> * <p><u>Inline data</u></p> * * <p>Stores can also load data inline. Internally, Store converts each of the objects we pass in as {@link #data} * into Model instances:</p> * <pre><code> new Ext.data.Store({ model: 'User', data : [ {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Aaron', lastName: 'Conran'}, {firstName: 'Jamie', lastName: 'Avins'} ] }); </code></pre> * * <p>Loading inline data using the method above is great if the data is in the correct format already (e.g. it doesn't need * to be processed by a {@link Ext.data.Reader reader}). If your inline data requires processing to decode the data structure, * use a {@link Ext.data.MemoryProxy MemoryProxy} instead (see the {@link Ext.data.MemoryProxy MemoryProxy} docs for an example).</p> * * <p>Additional data can also be loaded locally using {@link #add}.</p> * * <p><u>Loading Nested Data</u></p> * * <p>Applications often need to load sets of associated data - for example a CRM system might load a User and her Orders. * Instead of issuing an AJAX request for the User and a series of additional AJAX requests for each Order, we can load a nested dataset * and allow the Reader to automatically populate the associated models. Below is a brief example, see the {@link Ext.data.Reader} intro * docs for a full explanation:</p> * <pre><code> var store = new Ext.data.Store({ autoLoad: true, model: "User", proxy: { type: 'ajax', url : 'users.json', reader: { type: 'json', root: 'users' } } }); </code></pre> * * <p>Which would consume a response like this:</p> * <pre><code> { "users": [ { "id": 1, "name": "Ed", "orders": [ { "id": 10, "total": 10.76, "status": "invoiced" }, { "id": 11, "total": 13.45, "status": "shipped" } ] } ] } </code></pre> * * <p>See the {@link Ext.data.Reader} intro docs for a full explanation.</p> * * <p><u>Filtering and Sorting</u></p> * * <p>Stores can be sorted and filtered - in both cases either remotely or locally. The {@link #sorters} and {@link #filters} are * held inside {@link Ext.util.MixedCollection MixedCollection} instances to make them easy to manage. Usually it is sufficient to * either just specify sorters and filters in the Store configuration or call {@link #sort} or {@link #filter}: * <pre><code> var store = new Ext.data.Store({ model: 'User', sorters: [ { property : 'age', direction: 'DESC' }, { property : 'firstName', direction: 'ASC' } ], filters: [ { property: 'firstName', value : /Ed/ } ] }); </code></pre> * * <p>The new Store will keep the configured sorters and filters in the MixedCollection instances mentioned above. By default, sorting * and filtering are both performed locally by the Store - see {@link #remoteSort} and {@link #remoteFilter} to allow the server to * perform these operations instead.</p> * * <p>Filtering and sorting after the Store has been instantiated is also easy. Calling {@link #filter} adds another filter to the Store * and automatically filters the dataset (calling {@link #filter} with no arguments simply re-applies all existing filters). Note that by * default {@link #sortOnFilter} is set to true, which means that your sorters are automatically reapplied if using local sorting.</p> * <pre><code> store.filter('eyeColor', 'Brown'); </code></pre> * * <p>Change the sorting at any time by calling {@link #sort}:</p> * <pre><code> store.sort('height', 'ASC'); </code></pre> * * <p>Note that all existing sorters will be removed in favor of the new sorter data (if {@link #sort} is called with no arguments, * the existing sorters are just reapplied instead of being removed). To keep existing filters and add new ones, just add sorters * to the MixedCollection:</p> * <pre><code> store.sorters.add(new Ext.util.Sorter({ property : 'shoeSize', direction: 'ASC' })); store.sort(); </code></pre> * * <p><u>Registering with StoreMgr</u></p> * * <p>Any Store that is instantiated with a {@link #storeId} will automatically be registed with the {@link Ext.StoreMgr StoreMgr}. * This makes it easy to reuse the same store in multiple views:</p> * <pre><code> //this store can be used several times new Ext.data.Store({ model: 'User', storeId: 'usersStore' }); new Ext.List({ store: 'usersStore', //other config goes here }); new Ext.DataView({ store: 'usersStore', //other config goes here }); </code></pre> * * <p><u>Further Reading</u></p> * * <p>Stores are backed up by an ecosystem of classes that enables their operation. To gain a full understanding of these * pieces and how they fit together, see:</p> * * <ul style="list-style-type: disc; padding-left: 25px"> * <li>{@link Ext.data.Proxy Proxy} - overview of what Proxies are and how they are used</li> * <li>{@link Ext.data.Model Model} - the core class in the data package</li> * <li>{@link Ext.data.Reader Reader} - used by any subclass of {@link Ext.data.ServerProxy ServerProxy} to read a response</li> * </ul> * * @constructor * @param {Object} config Optional config object */ Ext.data.Store = Ext.extend(Ext.data.AbstractStore, { /** * @cfg {Boolean} remoteSort * True to defer any sorting operation to the server. If false, sorting is done locally on the client. Defaults to <tt>false</tt>. */ remoteSort: false, /** * @cfg {Boolean} remoteFilter * True to defer any filtering operation to the server. If false, filtering is done locally on the client. Defaults to <tt>false</tt>. */ remoteFilter: false, /** * @cfg {String/Ext.data.Proxy/Object} proxy The Proxy to use for this Store. This can be either a string, a config * object or a Proxy instance - see {@link #setProxy} for details. */ /** * @cfg {Array} data Optional array of Model instances or data objects to load locally. See "Inline data" above for details. */ /** * The (optional) field by which to group data in the store. Internally, grouping is very similar to sorting - the * groupField and {@link #groupDir} are injected as the first sorter (see {@link #sort}). Stores support a single * level of grouping, and groups can be fetched via the {@link #getGroups} method. * @property groupField * @type String */ groupField: undefined, /** * The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DESC" * @property groupDir * @type String */ groupDir: "ASC", /** * The number of records considered to form a 'page'. This is used to power the built-in * paging using the nextPage and previousPage functions. Defaults to 25. * @property pageSize * @type Number */ pageSize: 25, /** * The page that the Store has most recently loaded (see {@link #loadPage}) * @property currentPage * @type Number */ currentPage: 1, /** * @cfg {Boolean} clearOnPageLoad True to empty the store when loading another page via {@link #loadPage}, * {@link #nextPage} or {@link #previousPage} (defaults to true). Setting to false keeps existing records, allowing * large data sets to be loaded one page at a time but rendered all together. */ clearOnPageLoad: true, /** * True if a model was created implicitly for this Store. This happens if a fields array is passed to the Store's constructor * instead of a model constructor or name. * @property implicitModel * @type Boolean * @private */ implicitModel: false, /** * True if the Store is currently loading via its Proxy * @property loading * @type Boolean * @private */ loading: false, /** * @cfg {Boolean} sortOnFilter For local filtering only, causes {@link #sort} to be called whenever {@link #filter} is called, * causing the sorters to be reapplied after filtering. Defaults to true */ sortOnFilter: true, isStore: true, //documented above constructor: function(config) { config = config || {}; /** * The MixedCollection that holds this store's local cache of records * @property data * @type Ext.util.MixedCollection */ this.data = new Ext.util.MixedCollection(false, function(record) { return record.internalId; }); if (config.data) { this.inlineData = config.data; delete config.data; } Ext.data.Store.superclass.constructor.call(this, config); var proxy = this.proxy, data = this.inlineData; if (data) { if (proxy instanceof Ext.data.MemoryProxy) { proxy.data = data; this.read(); } else { this.add.apply(this, data); } this.sort(); delete this.inlineData; } else if (this.autoLoad) { Ext.defer(this.load, 10, this, [typeof this.autoLoad == 'object' ? this.autoLoad : undefined]); // Remove the defer call, we may need reinstate this at some point, but currently it's not obvious why it's here. // this.load(typeof this.autoLoad == 'object' ? this.autoLoad : undefined); } }, /** * Returns an object containing the result of applying grouping to the records in this store. See {@link #groupField}, * {@link #groupDir} and {@link #getGroupString}. Example for a store containing records with a color field: <pre><code> var myStore = new Ext.data.Store({ groupField: 'color', groupDir : 'DESC' }); myStore.getGroups(); //returns: [ { name: 'yellow', children: [ //all records where the color field is 'yellow' ] }, { name: 'red', children: [ //all records where the color field is 'red' ] } ] </code></pre> * @return {Array} The grouped data */ getGroups: function() { var records = this.data.items, length = records.length, groups = [], pointers = {}, record, groupStr, group, i; for (i = 0; i < length; i++) { record = records[i]; groupStr = this.getGroupString(record); group = pointers[groupStr]; if (group == undefined) { group = { name: groupStr, children: [] }; groups.push(group); pointers[groupStr] = group; } group.children.push(record); } return groups; }, /** * Returns the string to group on for a given model instance. The default implementation of this method returns the model's * {@link #groupField}, but this can be overridden to group by an arbitrary string. For example, to group by the first letter * of a model's 'name' field, use the following code: <pre><code> new Ext.data.Store({ groupDir: 'ASC', getGroupString: function(instance) { return instance.get('name')[0]; } }); </code></pre> * @param {Ext.data.Model} instance The model instance * @return {String} The string to compare when forming groups */ getGroupString: function(instance) { return instance.get(this.groupField); }, /** * Convenience function for getting the first model instance in the store * @return {Ext.data.Model/undefined} The first model instance in the store, or undefined */ first: function() { return this.data.first(); }, /** * Convenience function for getting the last model instance in the store * @return {Ext.data.Model/undefined} The last model instance in the store, or undefined */ last: function() { return this.data.last(); }, /** * Inserts Model instances into the Store at the given index and fires the {@link #add} event. * See also <code>{@link #add}</code>. * @param {Number} index The start index at which to insert the passed Records. * @param {Ext.data.Model[]} records An Array of Ext.data.Model objects to add to the cache. */ insert : function(index, records) { var i, record, len; records = [].concat(records); for (i = 0, len = records.length; i < len; i++) { record = this.createModel(records[i]); record.set(this.modelDefaults); this.data.insert(index + i, record); record.join(this); } if (this.snapshot) { this.snapshot.addAll(records); } this.fireEvent('add', this, records, index); this.fireEvent('datachanged', this); }, /** * Adds Model instances to the Store by instantiating them based on a JavaScript object. When adding already- * instantiated Models, use {@link #insert} instead. The instances will be added at the end of the existing collection. * This method accepts either a single argument array of Model instances or any number of model instance arguments. * Sample usage: * <pre><code> myStore.add({some: 'data'}, {some: 'other data'}); </code></pre> * * @param {Object} data The data for each model * @return {Array} The array of newly created model instances */ add: function(records) { //accept both a single-argument array of records, or any number of record arguments if (!Ext.isArray(records)) { records = Array.prototype.slice.apply(arguments); } var length = records.length, record, i; for (i = 0; i < length; i++) { record = this.createModel(records[i]); if (record.phantom == false) { record.needsAdd = true; } records[i] = record; } this.insert(this.data.length, records); return records; }, /** * Converts a literal to a model, if it's not a model already * @private * @{param} record {Ext.data.Model/Object} The record to create * @return {Ext.data.Model} */ createModel: function(record){ if (!(record instanceof Ext.data.Model)) { record = Ext.ModelMgr.create(record, this.model); } return record; }, /** * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache. * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter. * Returning <tt>false</tt> aborts and exits the iteration. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. * Defaults to the current {@link Ext.data.Record Record} in the iteration. */ each : function(fn, scope) { this.data.each(fn, scope); }, /** * Removes the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single * 'datachanged' event after removal. * @param {Ext.data.Model/Array} records The Ext.data.Model instance or array of instances to remove */ remove: function(records) { if (!Ext.isArray(records)) { records = [records]; } var length = records.length, i, index, record; for (i = 0; i < length; i++) { record = records[i]; index = this.data.indexOf(record); if (index > -1) { this.removed.push(record); if (this.snapshot) { this.snapshot.remove(record); } record.unjoin(this); this.data.remove(record); this.fireEvent('remove', this, record, index); } } this.fireEvent('datachanged', this); }, /** * Removes the model instance at the given index * @param {Number} index The record index */ removeAt: function(index) { var record = this.getAt(index); if (record) { this.remove(record); } }, /** * <p>Loads data into the Store via the configured {@link #proxy}. This uses the Proxy to make an * asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved * instances into the Store and calling an optional callback if required. Example usage:</p> * <pre><code> store.load({ scope : this, callback: function(records, operation, success) { //the {@link Ext.data.Operation operation} object contains all of the details of the load operation console.log(records); } }); </code></pre> * * <p>If the callback scope does not need to be set, a function can simply be passed:</p> * <pre><code> store.load(function(records, operation, success) { console.log('loaded records'); }); </code></pre> * * @param {Object/Function} options Optional config object, passed into the Ext.data.Operation object before loading. */ load: function(options) { options = options || {}; if (Ext.isFunction(options)) { options = { callback: options }; } Ext.applyIf(options, { group : {field: this.groupField, direction: this.groupDir}, start : 0, limit : this.pageSize, addRecords: false }); return Ext.data.Store.superclass.load.call(this, options); }, /** * Returns true if the Store is currently performing a load operation * @return {Boolean} True if the Store is currently loading */ isLoading: function() { return this.loading; }, /** * @private * Called internally when a Proxy has completed a load request */ onProxyLoad: function(operation) { var records = operation.getRecords(); this.loadRecords(records, operation.addRecords); this.loading = false; this.fireEvent('load', this, records, operation.wasSuccessful()); //TODO: deprecate this event, it should always have been 'load' instead. 'load' is now documented, 'read' is not //People are definitely using this so can't deprecate safely until 2.x this.fireEvent('read', this, records, operation.wasSuccessful()); //this is a callback that would have been passed to the 'read' function and is optional var callback = operation.callback; if (typeof callback == 'function') { callback.call(operation.scope || this, records, operation, operation.wasSuccessful()); } }, /** * @private * Callback for any write Operation over the Proxy. Updates the Store's MixedCollection to reflect * the updates provided by the Proxy */ onProxyWrite: function(operation) { var data = this.data, action = operation.action, records = operation.getRecords(), length = records.length, callback = operation.callback, record, i; if (operation.wasSuccessful()) { if (action == 'create' || action == 'update') { for (i = 0; i < length; i++) { record = records[i]; record.phantom = false; record.join(this); data.replace(record); } } else if (action == 'destroy') { for (i = 0; i < length; i++) { record = records[i]; record.unjoin(this); data.remove(record); } this.removed = []; } this.fireEvent('datachanged'); } //this is a callback that would have been passed to the 'create', 'update' or 'destroy' function and is optional if (typeof callback == 'function') { callback.call(operation.scope || this, records, operation, operation.wasSuccessful()); } }, //inherit docs getNewRecords: function() { return this.data.filterBy(this.filterNew).items; }, //inherit docs getUpdatedRecords: function() { return this.data.filterBy(this.filterDirty).items; }, /** * <p>Sorts the data in the Store by one or more of its properties. Example usage:</p> <pre><code> //sort by a single field myStore.sort('myField', 'DESC'); //sorting by multiple fields myStore.sort([ { field : 'age', direction: 'ASC' }, { field : 'name', direction: 'DESC' } ]); </code></pre> * <p>Internally, Store converts the passed arguments into an array of {@link Ext.util.Sorter} instances, and delegates the actual * sorting to its internal {@link Ext.util.MixedCollection}.</p> * <p>When passing a single string argument to sort, Store maintains a ASC/DESC toggler per field, so this code:</p> <pre><code> store.sort('myField'); store.sort('myField'); </code></pre> * <p>Is equivalent to this code, because Store handles the toggling automatically:</p> <pre><code> store.sort('myField', 'ASC'); store.sort('myField', 'DESC'); </code></pre> * @param {String|Array} sorters Either a string name of one of the fields in this Store's configured {@link Ext.data.Model Model}, * or an Array of sorter configurations. * @param {String} direction The overall direction to sort the data by. Defaults to "ASC". */ sort: function(sorters, direction) { if (Ext.isString(sorters)) { var property = sorters, sortToggle = this.sortToggle, toggle = Ext.util.Format.toggle; if (direction == undefined) { sortToggle[property] = toggle(sortToggle[property] || "", "ASC", "DESC"); direction = sortToggle[property]; } sorters = { property : property, direction: direction }; } if (arguments.length != 0) { this.sorters.clear(); } this.sorters.addAll(this.decodeSorters(sorters)); if (this.remoteSort) { //the load function will pick up the new sorters and request the sorted data from the proxy this.load(); } else { this.data.sort(this.sorters.items); this.fireEvent('datachanged', this); } }, /** * Filters the loaded set of records by a given set of filters. * @param {Mixed} filters The set of filters to apply to the data. These are stored internally on the store, * but the filtering itself is done on the Store's {@link Ext.util.MixedCollection MixedCollection}. See * MixedCollection's {@link Ext.util.MixedCollection#filter filter} method for filter syntax. Alternatively, * pass in a property string * @param {String} value Optional value to filter by (only if using a property string as the first argument) */ filter: function(filters, value) { if (Ext.isString(filters)) { filters = { property: filters, value : value }; } this.filters.addAll(this.decodeFilters(filters)); if (this.remoteFilter) { //the load function will pick up the new filters and request the filtered data from the proxy this.load(); } else { /** * A pristine (unfiltered) collection of the records in this store. This is used to reinstate * records when a filter is removed or changed * @property snapshot * @type Ext.util.MixedCollection */ this.snapshot = this.snapshot || this.data.clone(); this.data = this.data.filter(this.filters.items); if (this.sortOnFilter && !this.remoteSort) { this.sort(); } else { this.fireEvent('datachanged', this); } } }, /** * Revert to a view of the Record cache with no filtering applied. * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the * {@link #datachanged} event. */ clearFilter : function(suppressEvent) { this.filters.clear(); if (this.isFiltered()) { this.data = this.snapshot.clone(); delete this.snapshot; if (suppressEvent !== true) { this.fireEvent('datachanged', this); } } }, /** * Returns true if this store is currently filtered * @return {Boolean} */ isFiltered : function() { return !!this.snapshot && this.snapshot != this.data; }, /** * Filter by a function. The specified function will be called for each * Record in this Store. If the function returns <tt>true</tt> the Record is included, * otherwise it is filtered out. * @param {Function} fn The function to be called. It will be passed the following parameters:<ul> * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record} * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li> * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li> * </ul> * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store. */ filterBy : function(fn, scope) { this.snapshot = this.snapshot || this.data.clone(); this.data = this.queryBy(fn, scope || this); this.fireEvent('datachanged', this); }, /** * Query the cached records in this Store using a filtering function. The specified function * will be called with each record in this Store. If the function returns <tt>true</tt> the record is * included in the results. * @param {Function} fn The function to be called. It will be passed the following parameters:<ul> * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record} * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li> * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li> * </ul> * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store. * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records **/ queryBy : function(fn, scope) { var data = this.snapshot || this.data; return data.filterBy(fn, scope||this); }, /** * Loads an array of data straight into the Store * @param {Array} data Array of data to load. Any non-model instances will be cast into model instances first * @param {Boolean} append True to add the records to the existing records in the store, false to remove the old ones first */ loadData: function(data, append) { var model = this.model, length = data.length, i, record; //make sure each data element is an Ext.data.Model instance for (i = 0; i < length; i++) { record = data[i]; if (!(record instanceof Ext.data.Model)) { data[i] = Ext.ModelMgr.create(record, model); } } this.loadRecords(data, append); }, /** * Loads an array of {@Ext.data.Model model} instances into the store, fires the datachanged event. This should only usually * be called internally when loading from the {@link Ext.data.Proxy Proxy}, when adding records manually use {@link #add} instead * @param {Array} records The array of records to load * @param {Boolean} add True to add these records to the existing records, false to remove the Store's existing records first */ loadRecords: function(records, add) { if (!add) { this.data.clear(); } this.data.addAll(records); //FIXME: this is not a good solution. Ed Spencer is totally responsible for this and should be forced to fix it immediately. for (var i = 0, length = records.length; i < length; i++) { records[i].needsAdd = false; records[i].join(this); } /* * this rather inelegant suspension and resumption of events is required because both the filter and sort functions * fire an additional datachanged event, which is not wanted. Ideally we would do this a different way. The first * datachanged event is fired by the call to this.add, above. */ this.suspendEvents(); if (this.filterOnLoad && !this.remoteFilter) { this.filter(); } if (this.sortOnLoad && !this.remoteSort) { this.sort(); } this.resumeEvents(); this.fireEvent('datachanged', this, records); }, // PAGING METHODS /** * Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal * load operation, passing in calculated 'start' and 'limit' params * @param {Number} page The number of the page to load */ loadPage: function(page) { this.currentPage = page; this.read({ page : page, start: (page - 1) * this.pageSize, limit: this.pageSize, addRecords: !this.clearOnPageLoad }); }, /** * Loads the next 'page' in the current data set */ nextPage: function() { this.loadPage(this.currentPage + 1); }, /** * Loads the previous 'page' in the current data set */ previousPage: function() { this.loadPage(this.currentPage - 1); }, // private clearData: function(){ this.data.each(function(record) { record.unjoin(); }); this.data.clear(); }, /** * Finds the index of the first matching Record in this store by a specific field value. * @param {String} fieldName The name of the Record field to test. * @param {String/RegExp} value Either a string that the field value * should begin with, or a RegExp to test against the field. * @param {Number} startIndex (optional) The index to start searching at * @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 * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. * @return {Number} The matched index or -1 */ find : function(property, value, start, anyMatch, caseSensitive, exactMatch) { var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch); return fn ? this.data.findIndexBy(fn, null, start) : -1; }, /** * Finds the first matching Record in this store by a specific field value. * @param {String} fieldName The name of the Record field to test. * @param {String/RegExp} value Either a string that the field value * should begin with, or a RegExp to test against the field. * @param {Number} startIndex (optional) The index to start searching at * @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 * @return {Ext.data.Record} The matched record or null */ findRecord : function() { var index = this.find.apply(this, arguments); return index != -1 ? this.getAt(index) : null; }, /** * @private * Returns a filter function used to test a the given property's value. Defers most of the work to * Ext.util.MixedCollection's createValueMatcher function * @param {String} property The property to create the filter function for * @param {String/RegExp} value The string/regex to compare the property value to * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false) * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false) * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. * Ignored if anyMatch is true. */ createFilterFn : function(property, value, anyMatch, caseSensitive, exactMatch) { if(Ext.isEmpty(value)){ return false; } value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch); return function(r) { return value.test(r.data[property]); }; }, /** * Finds the index of the first matching Record in this store by a specific field value. * @param {String} fieldName The name of the Record field to test. * @param {Mixed} value The value to match the field against. * @param {Number} startIndex (optional) The index to start searching at * @return {Number} The matched index or -1 */ findExact: function(property, value, start) { return this.data.findIndexBy(function(rec){ return rec.get(property) === value; }, this, start); }, /** * Find the index of the first matching Record in this Store by a function. * If the function returns <tt>true</tt> it is considered a match. * @param {Function} fn The function to be called. It will be passed the following parameters:<ul> * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record} * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li> * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li> * </ul> * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store. * @param {Number} startIndex (optional) The index to start searching at * @return {Number} The matched index or -1 */ findBy : function(fn, scope, start) { return this.data.findIndexBy(fn, scope, start); }, /** * 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 **/ collect : function(dataIndex, allowNull, bypassFilter) { var values = [], uniques = {}, length, value, strValue, data, i; if (bypassFilter === true && this.snapshot) { data = this.snapshot.items; } else { data = this.data.items; } length = data.length; for (i = 0; i < length; i++) { value = data[i].data[dataIndex]; strValue = String(value); if ((allowNull || !Ext.isEmpty(value)) && !uniques[strValue]) { uniques[strValue] = true; values[values.length] = value; } } return values; }, /** * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt> * and <tt>end</tt> and returns the result. * @param {String} property A field in each record * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>) * @param {Number} end (optional) The last record index to include (defaults to length - 1) * @return {Number} The sum */ sum : function(property, start, end) { var records = this.data.items, value = 0, i; start = start || 0; end = (end || end === 0) ? end : records.length - 1; for (i = start; i <= end; i++) { value += (records[i].data[property] || 0); } return value; }, /** * Gets the number of cached records. * <p>If using paging, this may not be the total size of the dataset. If the data object * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p> * @return {Number} The number of Records in the Store's cache. */ getCount : function() { return this.data.length || 0; }, /** * Get the Record at the specified index. * @param {Number} index The index of the Record to find. * @return {Ext.data.Model} The Record at the passed index. Returns undefined if not found. */ getAt : function(index) { return this.data.getAt(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.Model[]} An array of Records */ getRange : function(start, end) { return this.data.getRange(start, end); }, /** * 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. */ getById : function(id) { return (this.snapshot || this.data).findBy(function(record) { return record.getId() === id; }); }, /** * Get the index within the cache of the passed Record. * @param {Ext.data.Model} record The Ext.data.Model object to find. * @return {Number} The index of the passed Record. Returns -1 if not found. */ 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. */ indexOfId : function(id) { return this.data.indexOfKey(id); }, removeAll: function(silent) { var items = []; this.each(function(rec){ items.push(rec); }); this.clearData(); if(this.snapshot){ this.snapshot.clear(); } //if(this.pruneModifiedRecords){ // this.modified = []; //} if (silent !== true) { this.fireEvent('clear', this, items); } } });
JavaScript
/* * @version Sencha 0.98 * @ignore * @todo * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.validations * @extends Object * * <p> * 这是一个单例,其下面的一系列方法和属性用于验证数据所必须的数据类型。但是多数情况是{@link Ext.data.Model Models}来自动调用。 * This singleton contains a set of validation functions that can be used to validate any type * of data. They are most often used in {@link Ext.data.Model Models}, where they are automatically * set up and executed.</p> */ Ext.data.validations = { /** * 当验证是否存在不符合要求时,所提示的错误消息。 * The default error message used when a presence validation fails * @property presenceMessage * @type String */ presenceMessage: 'must be present', /** * 当验证长度(length)不符合要求时,所提示的错误消息。The default error message used when a length validation fails * @property lengthMessage * @type String */ lengthMessage: 'is the wrong length', /** * 当验证格式(format)不符合要求时,所提示的错误消息。The default error message used when a format validation fails * @property formatMessage * @type Boolean */ formatMessage: 'is the wrong format', /** * 当验证可接纳内容不符合要求时,所提示的错误消息。 * The default error message used when an inclusion validation fails * @property inclusionMessage * @type String */ inclusionMessage: 'is not included in the list of acceptable values', /** * 当验证不可接纳内容不符合要求时,所提示的错误消息。 * The default error message used when an exclusion validation fails * @property exclusionMessage * @type String */ exclusionMessage: 'is not an acceptable value', /** * 验证输入的是否存在。 * Validates that the given value is present * @param {Object} config Optional config object * @param {Mixed} value The value to validate * @return {Boolean} True if validation passed */ presence: function(config, value) { if (value == undefined) { value = config; } return !!value; }, /** * Returns true if the given value is between the configured min and max values * @param {Object} config Optional config object * @param {String} value The value to validate * @return {Boolean} True if the value passes validation */ length: function(config, value) { if (value == undefined) { return false; } var length = value.length, min = config.min, max = config.max; if ((min && length < min) || (max && length > max)) { return false; } else { return true; } }, /** * Returns true if the given value passes validation against the configured {@link #matcher} regex * @param {Object} config Optional config object * @param {String} value The value to validate * @return {Boolean} True if the value passes the format validation */ format: function(config, value) { return !!(config.matcher && config.matcher.test(value)); }, /** * Validates that the given value is present in the configured {@link #list} * @param {String} value The value to validate * @return {Boolean} True if the value is present in the list */ inclusion: function(config, value) { return config.list && config.list.indexOf(value) != -1; }, /** * Validates that the given value is present in the configured {@link #list} * @param {Object} config Optional config object * @param {String} value The value to validate * @return {Boolean} True if the value is not present in the list */ exclusion: function(config, value) { return config.list && config.list.indexOf(value) == -1; } };
JavaScript
/* * @version Sencha 1.0 RC-1 * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.data.Node * @extends Ext.util.Observable * @cfg {Boolean} leaf true表示该节点是树叶节点没有子节点。 * true if this node is a leaf and does not have children * @cfg {String} id 该节点的Id。如不指定一个,会生成一个。 * The id for this node. If one is not specified, one is generated. * @constructor * @param {Object} attributes 节点的属性/配置项。The attributes/config for the node */ Ext.data.Node = Ext.extend(Ext.util.Observable, { constructor: function(attributes) { /** * 节点属性。你可以在此添加任意的自定义的属性。 * The attributes supplied for the node. You can use this property to access any custom attributes you supplied. * @type Object * @property attributes */ this.attributes = attributes || {}; this.leaf = !!this.attributes.leaf; /** * 节点ID。The node id. * @type String * @property id */ this.id = this.attributes.id; if (!this.id) { this.id = Ext.id(null, "xnode-"); this.attributes.id = this.id; } /** * 此节点的所有子节点。 * All child nodes of this node. * @type Array * @property childNodes */ this.childNodes = []; /** * 此节点的父节点。 * The parent node for this node. * @type Node * @property parentNode */ this.parentNode = null; /** * 该节点下面最前一个子节点(直属的),null的话就表示这是没有子节点的。 * The first direct child node of this node, or null if this node has no child nodes. * @type Node * @property firstChild */ this.firstChild = null; /** * 该节点下面最后一个子节点(直属的),null的话就表示这是没有子节点的。 * The last direct child node of this node, or null if this node has no child nodes. * @type Node * @property lastChild */ this.lastChild = null; /** * 该节点前面一个节点,同级的,null的话就表示这没有侧边节点。 * The node immediately preceding this node in the tree, or null if there is no sibling node. * @type Node * @property previousSibling */ this.previousSibling = null; /** * 该节点后面一个节点,同级的,null的话就表示这没有侧边节点。 * The node immediately following this node in the tree, or null if there is no sibling node. * @type Node * @property nextSibling */ this.nextSibling = null; this.addEvents({ /** * @event append * 当有新的子节点添加时触发。 * Fires when a new child node is appended * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} node 新加入的节点。The newly appended node * @param {Number} index 新加入节点的索引值。The index of the newly appended node */ "append" : true, /** * @event remove * 当有子节点被移出的时候触发。 * Fires when a child node is removed * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} node 被移出的节点。The removed node */ "remove" : true, /** * @event move * 当该节点移动到树中的新位置触发。 * Fires when this node is moved to a new location in the tree * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} oldParent 原来的父节点。The old parent of this node * @param {Node} newParent 新的父节点。The new parent of this node * @param {Number} index 移入的新索引。The index it was moved to */ "move" : true, /** * @event insert * 当有子节点被插入的触发。 * Fires when a new child node is inserted. * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} node 插入的新子节点。The child node inserted * @param {Node} refNode 被插入节点的前面一个字节点。The child node the node was inserted before */ "insert" : true, /** * @event beforeappend * 当有新的子节点被添加时触发,返回false就取消添加。 * Fires before a new child is appended, return false to cancel the append. * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} node 新加入的子节点。The child node to be appended */ "beforeappend" : true, /** * @event beforeremove * 当有子节点被移出的时候触发,返回false就取消移出。 * Fires before a child is removed, return false to cancel the remove. * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} node 被移出的子节点。The child node to be removed */ "beforeremove" : true, /** * @event beforemove * 当该节点移动到树下面的另外一个新位置的时候触发。返回false就取消移动。 * Fires before this node is moved to a new location in the tree. Return false to cancel the move. * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} oldParent 该节点的父节点。The parent of this node * @param {Node} newParent 将要移入新位置的父节点。The new parent this node is moving to * @param {Number} index 将要移入的新索引。The index it is being moved to */ "beforemove" : true, /** * @event beforeinsert * 当有新的节点插入时触发,返回false就取消插入。 * Fires before a new child is inserted, return false to cancel the insert. * @param {Tree} tree 主树。The owner tree * @param {Node} this 此节点。This node * @param {Node} node 被插入的子节点。The child node to be inserted * @param {Node} refNode 被插入节点的前面一个字节点。The child node the node is being inserted before */ "beforeinsert" : true }); this.listeners = this.attributes.listeners; Ext.data.Node.superclass.constructor.call(this); }, // private fireEvent : function(evtName) { // first do standard event for this node if (Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false) { return false; } // then bubble it up to the tree if the event wasn't cancelled var ot = this.getOwnerTree(); if (ot) { if (ot.proxyNodeEvent.apply(ot, arguments) === false) { return false; } } return true; }, /** * 若节点是叶子节点的话返回true。 * Returns true if this node is a leaf * @return {Boolean} */ isLeaf : function() { return this.leaf === true; }, // private setFirstChild : function(node) { this.firstChild = node; }, //private setLastChild : function(node) { this.lastChild = node; }, /** * 如果这个节点是其父节点下面的最后一个节点的话返回true。 * Returns true if this node is the last child of its parent * @return {Boolean} */ isLast : function() { return (!this.parentNode ? true : this.parentNode.lastChild == this); }, /** * 如果这个节点是其父节点下面的第一个节点的话返回true。 * Returns true if this node is the first child of its parent * @return {Boolean} */ isFirst : function() { return (!this.parentNode ? true : this.parentNode.firstChild == this); }, /** * 如果有子节点返回true。 * Returns true if this node has one or more child nodes, else false. * @return {Boolean} */ hasChildNodes : function() { return !this.isLeaf() && this.childNodes.length > 0; }, /** * 如果该节点有一个或多个的子节点,或其节点<tt>可展开的</tt>属性是明确制定为true的话返回true。 * Returns true if this node has one or more child nodes, or if the <tt>expandable</tt> * node attribute is explicitly specified as true (see {@link #attributes}), otherwise returns false. * @return {Boolean} */ isExpandable : function() { return this.attributes.expandable || this.hasChildNodes(); }, /** * 在该节点里面最后的位置上插入节点,可以多个。 * Insert node(s) as the last child node of this node. * @param {Node/Array} node 要加入的节点或节点数组。The node or Array of nodes to append * @return {Node} 如果是单个节点,加入后返回true,如果是数组返回null。The appended node if single append, or null if an array was passed */ appendChild : function(node) { var multi = false, i, len; if (Ext.isArray(node)) { multi = node; } else if (arguments.length > 1) { multi = arguments; } // if passed an array or multiple args do them one by one if (multi) { len = multi.length; for (i = 0; i < len; i++) { this.appendChild(multi[i]); } } else { if (this.fireEvent("beforeappend", this.ownerTree, this, node) === false) { return false; } var index = this.childNodes.length; var oldParent = node.parentNode; // it's a move, make sure we move it cleanly if (oldParent) { if (node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false) { return false; } oldParent.removeChild(node); } index = this.childNodes.length; if (index === 0) { this.setFirstChild(node); } this.childNodes.push(node); node.parentNode = this; var ps = this.childNodes[index-1]; if (ps) { node.previousSibling = ps; ps.nextSibling = node; } else { node.previousSibling = null; } node.nextSibling = null; this.setLastChild(node); node.setOwnerTree(this.getOwnerTree()); this.fireEvent("append", this.ownerTree, this, node, index); if (oldParent) { node.fireEvent("move", this.ownerTree, node, oldParent, this, index); } return node; } }, /** * * Removes a child node from this node. * @param {Node} node 要移除的节点。The node to remove * @return {Node} 移除后的节点。The removed node */ /** * 从该节点中移除一个子节点。Removes a child node from this node. * @param {Node} node 要移除的节点。The node to remove * @param {Boolean} destroy <tt>true</tt>表示为,移除之后要销毁这个节点。默认为<tt>false</tt>。<tt>true</tt> to destroy the node upon removal. Defaults to <tt>false</tt>. * @return {Node}移除后的节点。 The removed node */ removeChild : function(node, destroy) { var index = this.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); } this.fireEvent("remove", this.ownerTree, this, node); if (destroy) { node.destroy(true); } else { node.clear(); } return node; }, // private clear : function(destroy) { // clear any references from the node this.setOwnerTree(null, destroy); this.parentNode = this.previousSibling = this.nextSibling = null; if (destroy) { this.firstChild = this.lastChild = null; } }, /** * 销毁节点 * Destroys the node. */ destroy : function(silent) { /* * Silent is to be used in a number of cases * 1) When setRootNode is called. * 2) When destroy on the tree is called * 3) For destroying child nodes on a node */ if (silent === true) { this.clearListeners(); this.clear(true); Ext.each(this.childNodes, function(n) { n.destroy(true); }); this.childNodes = null; } else { this.remove(true); } }, /** * 在当前节点的子节点的集合中,位于第二个节点之前插入节点(第一个参数)。 * Inserts the first node before the second node in this nodes childNodes collection. * @param {Node} node 要插入的节点。he node to insert * @param {Node} refNode 前面插入的节点(如果为null表示节点是追加的)。The node to insert before (if null the node is appended) * @return {Node} 插入的节点。The inserted node */ insertBefore : function(node, refNode) { if (!refNode) { // like standard Dom, refNode can be null for append return this.appendChild(node); } // nothing to do if (node == refNode) { return false; } if (this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false) { return false; } var index = this.indexOf(refNode), oldParent = node.parentNode, refIndex = index; // when moving internally, indexes will change after remove if (oldParent == this && this.indexOf(node) < index) { refIndex--; } // it's a move, make sure we move it cleanly if (oldParent) { if (node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false) { return false; } oldParent.removeChild(node); } if (refIndex === 0) { this.setFirstChild(node); } this.childNodes.splice(refIndex, 0, node); node.parentNode = this; var ps = this.childNodes[refIndex-1]; if (ps) { node.previousSibling = ps; ps.nextSibling = node; } else { node.previousSibling = null; } node.nextSibling = refNode; refNode.previousSibling = node; node.setOwnerTree(this.getOwnerTree()); this.fireEvent("insert", this.ownerTree, this, node, refNode); if (oldParent) { node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode); } return node; }, /** * 从父节点上移除子节点。Removes this node from its parent * @param {Boolean} destroy <tt>true</tt>表示为,移除之后要销毁这个节点。默认为<tt>false</tt>。<tt>true</tt> to destroy the node upon removal. Defaults to <tt>false</tt>. * @return {Node} this */ remove : function(destroy) { var parentNode = this.parentNode; if (parentNode) { parentNode.removeChild(this, destroy); } return this; }, /** * 从这个节点上移除所有的子节点。 * Removes all child nodes from this node. * @param {Boolean} destroy <tt>true</tt>表示为,移除之后要销毁这个节点。默认为<tt>false</tt>。<tt>true</tt> to destroy the node upon removal. Defaults to <tt>false</tt>. * @return {Node} this */ removeAll : function(destroy) { var cn = this.childNodes, n; while ((n = cn[0])) { this.removeChild(n, destroy); } return this; }, /** * 指定索引,在自节点中查找匹配索引的节点。 * Returns the child node at the specified index. * @param {Number} index * @return {Node} */ getChildAt : function(index) { return this.childNodes[index]; }, /** * 把下面的某个子节点替换为其他节点。 * Replaces one child node in this node with another. * @param {Node} newChild 进来的节点。The replacement node * @param {Node} oldChild 去掉的节点。The node to replace * @return {Node} 去掉的节点。The replaced node */ replaceChild : function(newChild, oldChild) { var s = oldChild ? oldChild.nextSibling : null; this.removeChild(oldChild); this.insertBefore(newChild, s); return oldChild; }, /** * 返回某个子节点的索引。 * Returns the index of a child node * @param {Node} node 节点 * @return {Number} 节点的索引或是-1表示找不到。The index of the node or -1 if it was not found */ indexOf : function(child) { return this.childNodes.indexOf(child); }, /** * 返回节点所在的树对象。 * Returns the tree this node is in. * @return {Tree} */ getOwnerTree : function() { // if it doesn't have one, look for one if (!this.ownerTree) { var p = this; while (p) { if (p.ownerTree) { this.ownerTree = p.ownerTree; break; } p = p.parentNode; } } return this.ownerTree; }, /** * 返回该节点的深度(根节点的深度是0)。 * Returns depth of this node (the root node has a depth of 0) * @return {Number} */ getDepth : function() { var depth = 0, p = this; while (p.parentNode) { ++depth; p = p.parentNode; } return depth; }, // private setOwnerTree : function(tree, destroy) { // if it is a move, we need to update everyone if (tree != this.ownerTree) { if (this.ownerTree) { this.ownerTree.unregisterNode(this); } this.ownerTree = tree; // If we're destroying, we don't need to recurse since it will be called on each child node if (destroy !== true) { Ext.each(this.childNodes, function(n) { n.setOwnerTree(tree); }); } if (tree) { tree.registerNode(this); } } }, /** * 改变该节点的id * Changes the id of this node. * @param {String} id 节点的新id。The new id for the node. */ setId: function(id) { if (id !== this.id) { var t = this.ownerTree; if (t) { t.unregisterNode(this); } this.id = this.attributes.id = id; if (t) { t.registerNode(this); } this.onIdChange(id); } }, // private onIdChange: Ext.emptyFn, /** * 返回该节点的路径,以方便控制这个节点展开或选择。 * Returns the path for this node. The path can be used to expand or select this node programmatically. * @param {String} attr(可选的)路径采用的属性(默认为节点的id)。 (optional) The attr to use for the path (defaults to the node's id) * @return {String} 路径。The path */ getPath : function(attr) { attr = attr || "id"; var p = this.parentNode, b = [this.attributes[attr]]; while (p) { b.unshift(p.attributes[attr]); p = p.parentNode; } var sep = this.getOwnerTree().pathSeparator; return sep + b.join(sep); }, /** * 从该节点开始逐层上报(Bubbles up)节点,上报过程中对每个节点执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。 * 函数的参数可经由args指定或当前节点,如果函数在某一个层次上返回false,上升将会停止。Bubbles up the tree from this node, calling the specified function with each node. The scope (<i>this</i>) of * function call will be the scope provided or the current node. The arguments to the function * will be the args provided or the current node. If the function returns false at any point, * the bubble is stopped. * @param {Function} fn 要调用的函数。The function to call * @param {Object} scope(可选的)函数的作用域(默认为当前节点)。(optional)The scope of the function (defaults to current node) * @param {Array} args (可选的)调用的函数要送入的参数(不指定就默认为遍历过程中当前的节点)。(optional)The args to call the function with (default to passing the current node) */ bubble : function(fn, scope, args) { var p = this; while (p) { if (fn.apply(scope || p, args || [p]) === false) { break; } p = p.parentNode; } }, //<deprecated since=0.99> cascade: function() { throw "Ext.data.Node: cascade method renamed to cascadeBy."; }, //</deprecated> /** * 从该节点开始逐层下报(Bubbles up)节点,上报过程中对每个节点执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。 * 函数的参数可经由args指定或当前节点,如果函数在某一个层次上返回false,下升到那个分支的位置将会停止。 * Cascades down the tree from this node, calling the specified function with each 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 (<code>this</code> reference) in which the function is executed. Defaults to the current Node. * @param {Array} args (可选的) 调用的函数要送入的参数(不指定就默认为遍历过程中当前的节点)。(optional) The args to call the function with (default to passing the current Node) */ cascadeBy : function(fn, scope, args) { if (fn.apply(scope || this, args || [this]) !== false) { var childNodes = this.childNodes, length = childNodes.length, i; for (i = 0; i < length; i++) { childNodes[i].cascadeBy(fn, scope, args); } } }, /** * 遍历该节点下的子节点,枚举过程中对每个节点执行指定的函数。函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。 * 函数的参数可经由args指定或当前节点,如果函数走到某处地方返回false,遍历将会停止。 * Interates the child nodes of this node, calling the specified function with each 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 (<code>this</code> reference) in which the function is executed. Defaults to the current Node in the iteration. * @param {Array} args (可选的) 调用的函数要送入的参数(不指定就默认为遍历过程中当前的节点)。(optional) The args to call the function with (default to passing the current Node) */ eachChild : function(fn, scope, args) { var childNodes = this.childNodes, length = childNodes.length, i; for (i = 0; i < length; i++) { if (fn.apply(scope || this, args || [childNodes[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 * @param {Boolean} deep (Optional) True to search through nodes deeper than the immediate children * @return {Node} 已找到的子节点或null表示找不到。The found child or null if none was found */ findChild : function(attribute, value, deep) { return this.findChildBy(function(){ return this.attributes[attribute] == value; }, null, deep); }, /** * 通过传入的一个函数执行后查找子元素。如果函数返回<code>true</code>表面这个子元素符合要求,而且停止查找。 * Finds the first child by a custom function. The child matches if the function passed returns <code>true</code>. * @param {Function} fn 要调用的函数。A function which must return <code>true</code> if the passed Node is the required Node. * @param {Object} scope (可选的) 函数的作用域(默认为当前节点)。(optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Node being tested. * @param {Boolean} deep (Optional) True to search through nodes deeper than the immediate children * @return {Node} 已找到的子节点或null表示找不到。The found child or null if none was found */ findChildBy : function(fn, scope, deep) { var cs = this.childNodes, len = cs.length, i = 0, n, res; for(; i < len; i++){ n = cs[i]; if(fn.call(scope || n, n) === true){ return n; }else if (deep){ res = n.findChildBy(fn, scope, deep); if(res != null){ return res; } } } return null; }, /** * 用自定义的排序函数对节点的子函数进行排序。Sorts this nodes children using the supplied sort function. * @param {Function} fn 函数。A function which, when passed two Nodes, returns -1, 0 or 1 depending upon required sort order. * @param {Object} scope 函数(可选的)。(optional)The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window. */ sort : function(fn, scope) { var cs = this.childNodes, len = cs.length, i, n; if (len > 0) { var sortFn = scope ? function(){return fn.apply(scope, arguments);} : fn; cs.sort(sortFn); for (i = 0; i < len; i++) { n = cs[i]; n.previousSibling = cs[i-1]; n.nextSibling = cs[i+1]; if (i === 0){ this.setFirstChild(n); } if (i == len - 1) { this.setLastChild(n); } } } }, /** * 返回true表示为该节点是送入节点的祖先节点(无论在哪那一级的)。 * Returns true if this node is an ancestor (at any point) of the passed node. * @param {Node} node 节点 * @return {Boolean} */ contains : function(node) { return node.isAncestor(this); }, /** * 返回true表示为送入的节点是该的祖先节点(无论在哪那一级的)。 * Returns true if the passed node is an ancestor (at any point) of this node. * @param {Node} node 节点 * @return {Boolean} */ isAncestor : function(node) { var p = this.parentNode; while (p) { if (p == node) { return true; } p = p.parentNode; } return false; }, toString : function() { return "[Node" + (this.id ? " " + this.id : "") + "]"; } }); Ext.data.RecordNode = Ext.extend(Ext.data.Node, { constructor: function(config) { config = config || {}; if (config.record) { // provide back reference config.record.node = this; } Ext.data.RecordNode.superclass.constructor.call(this, config); }, getChildRecords: function() { var cn = this.childNodes, ln = cn.length, i = 0, rs = [], r; for (; i < ln; i++) { r = cn[i].attributes.record; // Hack to inject leaf attribute into the // data portion of a record, this will be // removed once Record and Ext.data.Node have // been combined rather than aggregated. r.data.leaf = cn[i].leaf; rs.push(r); } return rs; }, getRecord: function() { return this.attributes.record; }, getSubStore: function() { // <debug> if (this.isLeaf()) { throw "Attempted to get a substore of a leaf node."; } // </debug> var treeStore = this.getOwnerTree().treeStore; if (!this.subStore) { this.subStore = new Ext.data.Store({ model: treeStore.model }); // if records have already been preLoaded, apply them // to the subStore, if not they will be loaded by the // read within the TreeStore itself. var children = this.getChildRecords(); this.subStore.add.apply(this.subStore, children); } if (!this.loaded) { treeStore.load({ node: this }); } return this.subStore; }, destroy : function(silent) { if (this.subStore) { this.subStore.destroyStore(); } var attr = this.attributes; if (attr.record) { delete attr.record.node; delete attr.record; } return Ext.data.RecordNode.superclass.destroy.call(this, silent); } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ResultSet * @extends Object * * <p>简单的包装类,用于表示由Proxy返回过来的记录集合。Simple wrapper class that represents a set of records returned by a Proxy.</p> * * @constructor * 创建一个ResultSet。 * Creates the new ResultSet */ Ext.data.ResultSet = Ext.extend(Object, { /** * @cfg {Boolean} loaded * True表示为已经加载记录完毕。这是在处理SQL后端Proxy时才有意义。 * True if the records have already been loaded. This is only meaningful when dealing with * SQL-backed proxies */ loaded: true, /** * @cfg {Number} count * 记录集合的记录总数。请注意total与该值的不同 * The number of records in this ResultSet. Note that total may differ from this number */ count: 0, /** * @cfg {Number} total * 由数据源报告的记录总数。该记录集合可能会形成一个子记录的集合(参见count)。 * The total number of records reported by the data source. This ResultSet may form a subset of * those records (see count) */ total: 0, /** * @cfg {Boolean} success * True表示为加载记录集合成功。false表示遇到了错误。 * True if the ResultSet loaded successfully, false if any errors were encountered */ success: false, /** * @cfg {Array} records record实例的数组。必须得。The array of record instances. Required */ constructor: function(config) { Ext.apply(this, config); /** * DEPRECATED - 在5.0中将会被移除。will be removed in Ext JS 5.0. This is just a copy of this.total - use that instead * @property totalRecords * @type Mixed */ this.totalRecords = this.total; if (config.count == undefined) { this.count = this.records.length; } } });
JavaScript
/* * @version Sencha 0.98 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.BelongsToAssociation * @extends Ext.data.Association * * <p>Ext.data.Association表示一对一的关系模型。主模型(owner model)应该有一个外键(a foreign key)的设置,也就是与之关联模型的主键(the primary key)。 * <br /> * Represents a one to one association with another model. The owner model is expected to have * a foreign key which references the primary key of the associated model:</p> * <pre><code> var Category = Ext.regModel('Category', { fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'} ] }); var Product = Ext.regModel('Product', { fields: [ {name: 'id', type: 'int'}, {name: 'category_id', type: 'int'}, {name: 'name', type: 'string'} ], associations: [ {type: 'belongsTo', model: 'Category'} ] }); </code></pre> * <p>上面例子中我们分别创建了Products和Cattegory模型,然后将它们关联起来,此过程我们可以说产品Product是“属于”种类Category的。 * 默认情况下,Product有一个category_id的字段,通过该字段,每个Product实体可以与Category关联在一起,并在Product模型身上产生新的函数: * <br /> * In the example above we have created models for Products and Categories, and linked them together * by saying that each Product belongs to a Category. This automatically links each Product to a Category * based on the Product's category_id, and provides new functions on the Product model:</p> * * <p><u>通过反射得出getter函数Generated getter function</u></p> * * <p>第一个加入到主模型的函数是Getter函数。The first function that is added to the owner model is a getter function:</p> * <pre><code> var product = new Product({ id: 100, category_id: 20, name: 'Sneakers' }); product.getCategory(function(category, operation) { //这里可以根据cateory对象来完成一些任务。do something with the category object alert(category.get('id')); //alerts 20 }, this); </code></pre> * * <p> * 在定义关联关系的时候,就为Product模型创建了getCategory函数。 * 另外一种getCategory函数的用法是送入一个包含success、failure和callback的对象,都是函数类型。 * 其中,必然一定会调用callback,而success就是成功加载所关联的模型后,才会调用的success的函数;反之没有加载关联模型,就执行failure函数。 * <br /> * The getCategory function was created on the Product model when we defined the association. This uses the * Category's configured {@link Ext.data.Proxy proxy} to load the Category asynchronously, calling the provided * callback when it has loaded. The new getCategory function will also accept an object containing success, * failure and callback properties - callback will always be called, success will only be called if the associated * model was loaded successfully and failure will only be called if the associatied model could not be loaded:</p> * <pre><code> product.getCategory({ callback: function(category, operation), //一定会调用的函数。a function that will always be called success : function(category, operation), //成功时调用的函数。a function that will only be called if the load succeeded failure : function(category, operation), //失败时调用的函数。a function that will only be called if the load did not succeed scope : this // 作用域对象是一个可选的参数,其决定了回调函数中的作用域。optionally pass in a scope object to execute the callbacks in }); </code></pre> * * <p>以上的回调函数执行时带有两个参数:1、所关联的模型之实例;2、负责加载模型实例的{@link Ext.data.Operation operation}对象。当加载实例有问题时,Operation对象就非常有用。 * <br /> * In each case above the callbacks are called with two arguments - the associated model instance and the * {@link Ext.data.Operation operation} object that was executed to load that instance. The Operation object is * useful when the instance could not be loaded.</p> * * <p><u>Generated setter function</u></p> * * <p> * 第二个生成的函数设置了关联的模型实例。如果只传入一个参数到setter那么下面的两个调用是一致的: * The second generated function sets the associated model instance - if only a single argument is passed to * the setter then the following two calls are identical:</p> * <pre><code> // this call product.setCategory(10); //is equivalent to this call: product.set('category_id', 10); </code></pre> * <p>如果传入第二个参数,那么模型会自动保存并且将第二个参数传入到主模型的{@link Ext.data.Model#save save}方法:If we pass in a second argument, the model will be automatically saved and the second argument passed to * the owner model's {@link Ext.data.Model#save save} method:</p> <pre><code> product.setCategory(10, function(product, operation) { //商品已经保持了。the product has been saved alert(product.get('category_id')); //now alerts 10 }); //另外一种语法: alternative syntax: product.setCategory(10, { callback: function(product, operation), //一定会调用的函数。a function that will always be called success : function(product, operation), //成功时调用的函数。a function that will only be called if the load succeeded failure : function(product, operation), //失败时调用的函数。a function that will only be called if the load did not succeed scope : this //作用域对象是一个可选的参数,其决定了回调函数中的作用域。optionally pass in a scope object to execute the callbacks in }) </code></pre> * * <p><u>自定义 Customisation</u></p> * * <p>若不设置,关联模型的时候会自动根据{@link #primaryKey}和{@link #foreignKey}属性设置。可制定的值有:Associations reflect on the models they are linking to automatically set up properties such as the * {@link #primaryKey} and {@link #foreignKey}. These can alternatively be specified:</p> * <pre><code> var Product = Ext.regModel('Product', { fields: [...], associations: [ {type: 'belongsTo', model: 'Category', primaryKey: 'unique_id', foreignKey: 'cat_id'} ] }); </code></pre> * * <p>这里我们替换掉了默认的主键(默认为'id')和外键(默认为'category_id')。一般情况却是不需要的。和Here we replaced the default primary key (defaults to 'id') and foreign key (calculated as 'category_id') * with our own settings. Usually this will not be needed.</p> */ Ext.data.BelongsToAssociation = Ext.extend(Ext.data.Association, { /** * @cfg {String} foreignKey The name of the foreign key on the owner model that links it to the associated * model. Defaults to the lowercased name of the associated model plus "_id", e.g. an association with a * model called Product would set up a product_id foreign key. */ /** * @cfg {String} getterName The name of the getter function that will be added to the local model's prototype. * Defaults to 'get' + the name of the foreign model, e.g. getCategory */ /** * @cfg {String} setterName The name of the setter function that will be added to the local model's prototype. * Defaults to 'set' + the name of the foreign model, e.g. setCategory */ constructor: function(config) { Ext.data.BelongsToAssociation.superclass.constructor.apply(this, arguments); var me = this, ownerProto = me.ownerModel.prototype, associatedName = me.associatedName, getterName = me.getterName || 'get' + associatedName, setterName = me.setterName || 'set' + associatedName; Ext.applyIf(me, { name : associatedName, foreignKey: associatedName.toLowerCase() + "_id" }); ownerProto[getterName] = me.createGetter(); ownerProto[setterName] = me.createSetter(); }, /** * @private * Returns a setter function to be placed on the owner model's prototype * @return {Function} The setter function */ createSetter: function() { var me = this, ownerModel = me.ownerModel, associatedModel = me.associatedModel, foreignKey = me.foreignKey, primaryKey = me.primaryKey; //'this' refers to the Model instance inside this function return function(value, options, scope) { this.set(foreignKey, value); if (typeof options == 'function') { options = { callback: options, scope: scope || this }; } if (Ext.isObject(options)) { return this.save(options); } }; }, /** * @private * Returns a getter function to be placed on the owner model's prototype. We cache the loaded instance * the first time it is loaded so that subsequent calls to the getter always receive the same reference. * @return {Function} The getter function */ createGetter: function() { var me = this, ownerModel = me.ownerModel, associatedName = me.associatedName, associatedModel = me.associatedModel, foreignKey = me.foreignKey, primaryKey = me.primaryKey, instanceName = me.name + 'BelongsToInstance'; //'this' refers to the Model instance inside this function return function(options, scope) { options = options || {}; var foreignKeyId = this.get(foreignKey), instance, callbackFn; if (this[instanceName] == undefined) { instance = Ext.ModelMgr.create({}, associatedName); instance.set(primaryKey, foreignKeyId); if (typeof options == 'function') { options = { callback: options, scope: scope || this }; } associatedModel.load(foreignKeyId, options); } else { instance = this[instanceName]; //TODO: We're duplicating the callback invokation code that the instance.load() call above //makes here - ought to be able to normalize this - perhaps by caching at the Model.load layer //instead of the association layer. if (typeof options == 'function') { options.call(scope || this, instance); } if (options.success) { options.success.call(scope || this, instance); } if (options.callback) { options.callback.call(scope || this, instance); } return instance; } }; } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @todo * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.XmlReader * @extends Ext.data.Reader * * <p>Xml Reader</p> */ Ext.data.XmlReader = Ext.extend(Ext.data.Reader, { /** * @cfg {String} record 指明一个DomQuery查询路径,指定包含所有行对象的信息。这是一个{@link #root}配置项对象的简写方式。The DomQuery path to the repeated element which contains record information. * <b>This is an alias for the {@link #root} config option.</b> */ /** * @private * 返回获取访问器的函数。 * Creates a function to return some particular key of data from a response. The totalProperty and * successProperty are treated as special cases for type casting, everything else is just a simple selector. * @param {String} key * @return {Function} */ createAccessor: function() { var selectValue = function(key, root, defaultValue){ var node = Ext.DomQuery.selectNode(key, root), val; if(node && node.firstChild){ val = node.firstChild.nodeValue; } return Ext.isEmpty(val) ? defaultValue : val; }; return function(key) { var fn; if (key == this.totalProperty) { fn = function(root, defaultValue) { var value = selectValue(key, root, defaultValue); return parseFloat(value); }; } else if (key == this.successProperty) { fn = function(root, defaultValue) { var value = selectValue(key, root, true); return (value !== false && value !== 'false'); }; } else { fn = function(root, defaultValue) { return selectValue(key, root, defaultValue); }; } return fn; }; }(), //inherit docs getResponseData: function(response) { var xml = response.responseXML; if (!xml) { throw {message: 'Ext.data.XmlReader.read: XML data not found'}; } return xml; }, /** * 获取数据。 * Normalizes the data object * @param {Object} data 原始数据。The raw data object * @return {Object} Returns the documentElement property of the data object if present, or the same object if not */ getData: function(data) { return data.documentElement || data; }, /** * @private * Given an XML object, returns the Element that represents the root as configured by the Reader's meta data * @param {Object} data The XML data object * @return {Element} The root node element */ getRoot: function(data) { return Ext.DomQuery.select(this.root, data); }, //EVERYTHING BELOW THIS LINE WILL BE DEPRECATED IN EXT JS 5.0 /** * @cfg {String} idPath DEPRECATED - this will be removed in Ext JS 5.0. Please use idProperty instead */ /** * @cfg {String} id DEPRECATED - this will be removed in Ext JS 5.0. Please use idProperty instead */ /** * @cfg {String} success DEPRECATED - this will be removed in Ext JS 5.0. Please use successProperty instead */ /** * @constructor * @ignore * TODO: This can be removed in 5.0 as all it does is support some deprecated config */ constructor: function(config) { config = config || {}; // backwards compat, convert idPath or id / success // DEPRECATED - remove this in 5.0 /* * Want to leave record in here. Makes sense to have it, since "root" doesn't really match * When describing the XmlReader. Internally we can apply it as root, however for the public * API it makes more sense for it to be called record. Especially since in the writer, we will * need both root AND record. */ Ext.applyIf(config, { idProperty : config.idPath || config.id, successProperty: config.success, root : config.record }); Ext.data.XmlReader.superclass.constructor.call(this, config); }, /** * 由一个XML文档产生一个包含实例模型的ResultSet对象。 * Parses an XML document and returns a ResultSet containing the model instances * @param {Object} doc 一个可被解析的XML文档。Parsed XML document * @return {Ext.data.ResultSet} 已解析的记录集合。The parsed result set */ readRecords: function(doc) { /** * DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead * @property xmlData * @type Object */ this.xmlData = doc; return Ext.data.XmlReader.superclass.readRecords.call(this, doc); } }); Ext.data.ReaderMgr.registerType('xml', Ext.data.XmlReader);
JavaScript
/* * @version Sencha 1.0.1 * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Reader * @extends Object * <p>Readers are used to interpret data to be loaded into a {@link Ext.data.Model Model} instance or a {@link Ext.data.Store Store} * - usually in response to an AJAX request. This is normally handled transparently by passing some configuration to either the * {@link Ext.data.Model Model} or the {@link Ext.data.Store Store} in question - see their documentation for further details.</p> <p>Reader负责解析加载到Model或Store的数据,通常值的是AJAX请求完毕后的那些数据。要告诉Reader类怎么工作,实际就是在配置Model或Sotre的时候说明清楚Reader该怎么做。参阅它们的文档或者更好。 </p> * * <p><u>加载内嵌数据Loading Nested Data</u></p> * * <p>Reader可以按照 Ext.data.Association 为每个model所设定的规则读取复杂多层的数据。如下一个例子充分说明了怎么在一个财务CRM中灵活地透析模型与数据之间操作。首先时定义一些模型: Readers have the ability to automatically load deeply-nested data objects based on the {@link Ext.data.Association associations} * configured on each Model. Below is an example demonstrating the flexibility of these associations in a fictional CRM system which * manages a User, their Orders, OrderItems and Products. First we'll define the models: * <pre><code> Ext.regModel("User", { fields: [ 'id', 'name' ], hasMany: {model: 'Order', name: 'orders'}, proxy: { type: 'rest', url : 'users.json', reader: { type: 'json', root: 'users' } } }); Ext.regModel("Order", { fields: [ 'id', 'total' ], hasMany : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'}, belongsTo: 'User' }); Ext.regModel("OrderItem", { fields: [ 'id', 'price', 'quantity', 'order_id', 'product_id' ], belongsTo: ['Order', {model: 'Product', associationKey: 'product'}] }); Ext.regModel("Product", { fields: [ 'id', 'name' ], hasMany: 'OrderItem' }); </code></pre> * * <p>看上去工作量不少,我们只需要知道,用户有许多张订单,其中每张订单有不同的货物组成。它们的实体数据演示如下:This may be a lot to take in - basically a User has many Orders, each of which is composed of several OrderItems. Finally, * each OrderItem has a single Product. This allows us to consume data like this:</p> * <pre><code> { "users": [ { "id": 123, "name": "Ed", "orders": [ { "id": 50, "total": 100, "order_items": [ { "id" : 20, "price" : 40, "quantity": 2, "product" : { "id": 1000, "name": "MacBook Pro" } }, { "id" : 21, "price" : 20, "quantity": 3, "product" : { "id": 1001, "name": "iPhone" } } ] } ] } ] } </code></pre> * * <p>返回的JSON层数很多,包括有全部用户(出于演示目的暂且一个)以及用户下面的全部订单(演示一个)以及每张订单里面具体有什么货品(演示两个),最后就是Product关联与OrderItem。于是,我们可以这样地读取和使用数据: The JSON response is deeply nested - it returns all Users (in this case just 1 for simplicity's sake), all of the Orders * for each User (again just 1 in this case), all of the OrderItems for each Order (2 order items in this case), and finally * the Product associated with each OrderItem. Now we can read the data and use it as follows: * <pre><code> var store = new Ext.data.Store({ model: "User" }); store.load({ callback: function() { //得到的用户 the user that was loaded var user = store.first(); console.log("Orders for " + user.get('name') + ":") //列出用户的订单 iterate over the Orders for each User user.orders().each(function(order) { console.log("Order ID: " + order.getId() + ", which contains items:"); //列出每张订单的货物 iterate over the OrderItems for each Order order.orderItems().each(function(orderItem) { // 货品数据已经有了,因此我们可以getProduct同步数据。一般而言我们用异步的版本(请参阅{@link Ext.data.BelongsToAssociation}) // we know that the Product data is already loaded, so we can use the synchronous getProduct //usually, we would use the asynchronous version (see {@link Ext.data.BelongsToAssociation}) var product = orderItem.getProduct(); console.log(orderItem.get('quantity') + ' orders of ' + product.get('name')); }); }); } }); </code></pre> * * <p>运行上述代码的结果会如下: Running the code above results in the following:</p> * <pre><code> Orders for Ed: Order ID: 50, which contains items: 2 orders of MacBook Pro 3 orders of iPhone </code></pre> * * @constructor * @param {Object} config Optional config object */ Ext.data.Reader = Ext.extend(Object, { /** * @cfg {String} idProperty 在行对象中说明记录独一无二值的名称。默认是<tt>id</tt>。Name of the property within a row object * that contains a record identifier value. Defaults to <tt>id</tt> */ idProperty: 'id', /** * @cfg {String} totalProperty 决定数据集合中哪一个属性是可以获取记录总算的名称。 * 如果一次性地获取所有数据到这里的话,不需要这个值;但在分页远程服务器数据的时候,就需要明确总数是几多。 * 默认是<tt>total</tt>。 * Name of the property from which to * retrieve the total number of records in the dataset. This is only needed * if the whole dataset is not passed in one go, but is being paged from * the remote server. Defaults to <tt>total</tt>. */ totalProperty: 'total', /** * @cfg {String} successProperty 决定哪一个属性是获取“成功”的属性。 * 默认是<tt>success</tt>。请参阅{@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}了解更多。 * Name of the property from which to * retrieve the success attribute. Defaults to <tt>success</tt>. See * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception} * for additional information. */ successProperty: 'success', /** * @cfg {String} root <b>必须指定的属性。</b> * 包含行对象的那个属性。默认是<tt>undefined</tt>。这是必须指定的属性,若为undefined,就会抛出一个异常。 * 这是属性所对应的数据包应该是一个空的数组,用来清除数据或者显示数据。 * <b>Required</b>. The name of the property * which contains the Array of row objects. Defaults to <tt>undefined</tt>. * An exception will be thrown if the root property is undefined. The data * packet value for this property should be an empty array to clear the data * or show no data. */ root: '', /** * @cfg {Boolean} implicitIncludes True表示为遇到响应中的模型如果有内嵌其他模型的话,也一同解析。参阅Ext.data.Reader的完整解释。默认为true。True to automatically parse models nested within other models in a response * object. See the Ext.data.Reader intro docs for full explanation. Defaults to true. */ implicitIncludes: true, constructor: function(config) { Ext.apply(this, config || {}); this.model = Ext.ModelMgr.getModel(config.model); if (this.model) { this.buildExtractors(); } }, /** * 为Reader设置一个新的模型。 * Sets a new model for the reader. * @private * @param {Object} model 新模型。The model to set. * @param {Boolean} setOnProxy True表示为也为Proxy设置新的模型。True to also set on the Proxy, if one is configured */ setModel: function(model, setOnProxy) { this.model = Ext.ModelMgr.getModel(model); this.buildExtractors(true); if (setOnProxy && this.proxy) { this.proxy.setModel(this.model, true); } }, /** * 读取指定的响应对象。这个方法会常规化可以传入到响应对象其不同的类型,在{@link readRecords}函数读取解析记录之前。 * Reads the given response object. This method normalizes the different types of response object that may be passed * to it, before handing off the reading of records to the {@link readRecords} function. * @param {Object} response 响应对象。既可以是XMLHttpRequest对象,也可以是一个普通的JS对象。The response object. This may be either an XMLHttpRequest object or a plain JS object * @return {Ext.data.ResultSet} 以解析的ResultSet对象。The parsed ResultSet object */ read: function(response) { var data = response; if (response.responseText) { data = this.getResponseData(response); } return this.readRecords(data); }, /** * 由Reader的所有子类来使用的抽象功能函数。每个子类的方法应该先执行这个父类的方法然后才执行自己的逻辑,最后返回Ext.data.ResultSet实例。对于大多数子类而言,不需要添加额外的处理过程。 * Abstracts common functionality used by all Reader subclasses. Each subclass is expected to call * this function before running its own logic and returning the Ext.data.ResultSet instance. For most * Readers additional processing should not be needed. * @param {Mixed} data 原始数据对象。The raw data object * @return {Ext.data.ResultSet} 一个ResultSet对象。A ResultSet object */ readRecords: function(data) { /** * 最后送入到readRecords的原始数据对象。如果打后仍需要的话,可以先存储。 * The raw data object that was last passed to readRecords. Stored for further processing if needed * @property rawData * @type Mixed */ this.rawData = data; data = this.getData(data); var root = this.getRoot(data), total = root.length, success = true, value, records, recordCount; if (this.totalProperty) { value = parseInt(this.getTotal(data), 10); if (!isNaN(value)) { total = value; } } if (this.successProperty) { value = this.getSuccess(data); if (value === false || value === 'false') { success = false; } } records = this.extractData(root, true); recordCount = records.length; return new Ext.data.ResultSet({ total : total || recordCount, count : recordCount, records: records, success: success }); }, /** * 返回已展开,类型转换的行数据。 * Returns extracted, type-cast rows of data. Iterates to call #extractValues for each row * @param {Object[]/Object} data-root from server response * @param {Boolean} returnRecords [false] Set true to return instances of Ext.data.Record * @private */ extractData : function(root, returnRecords) { var values = [], records = [], Model = this.model, length = root.length, idProp = this.idProperty, node, id, record, i; for (i = 0; i < length; i++) { node = root[i]; values = this.extractValues(node); id = this.getId(node); if (returnRecords === true) { record = new Model(values, id); record.raw = node; records.push(record); if (this.implicitIncludes) { this.readAssociated(record, node); } } else { values[idProp] = id; records.push(values); } } return records; }, /** * @private * 加载数据对象的记录关联。这会预取hasMany和belongTo关系。 * Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations * on the record provided. * @param {Ext.data.Model} record The record to load associations for * @param {Mixed} data 数据对象。The data object * @return {String} 返回值得描述。Return value description */ readAssociated: function(record, data) { var associations = record.associations.items, length = associations.length, association, associationName, associatedModel, associationData, inverseAssociation, proxy, reader, store, i; for (i = 0; i < length; i++) { association = associations[i]; associationName = association.name; associationData = this.getAssociatedDataRoot(data, association.associationKey || associationName); associatedModel = association.associatedModel; if (associationData) { proxy = associatedModel.proxy; // if the associated model has a Reader already, use that, otherwise attempt to create a sensible one if (proxy) { reader = proxy.getReader(); } else { reader = new this.constructor({ model: association.associatedName }); } if (association.type == 'hasMany') { store = record[associationName](); store.add.apply(store, reader.read(associationData).records); //now that we've added the related records to the hasMany association, set the inverse belongsTo //association on each of them if it exists inverseAssociation = associatedModel.prototype.associations.findBy(function(assoc) { return assoc.type == 'belongsTo' && assoc.associatedName == record.constructor.modelName; }); //if the inverse association was found, set it now on each record we've just created if (inverseAssociation) { store.data.each(function(associatedRecord) { associatedRecord[inverseAssociation.instanceName] = record; }); } } else if (association.type == 'belongsTo') { record[association.instanceName] = reader.read([associationData]).records[0]; } } } }, /** * @private * 只对XML Reader适用。 * Used internally by {@link #readAssociated}. Given a data object (which could be json, xml etc) for a specific * record, this should return the relevant part of that data for the given association name. This is only really * needed to support the XML Reader, which has to do a query to get the associated data object * @param {Mixed} data 原始数据对象。The raw data object * @param {String} associationName 关联名称。The name of the association to get data for (uses associationKey if present) * @return {Mixed} 根。The root */ getAssociatedDataRoot: function(data, associationName) { return data[associationName]; }, /** * @private * 根据模型实例的数据,迭代模型的字段和构建每个字段的值。 * Given an object representing a single model instance's data, iterates over the model's fields and * builds an object with the value for each field. * @param {Object} data 要转换的数据对象。The data object to convert * @return {Object} 适合模型构造器所用的模型。Data object suitable for use with a model constructor */ extractValues: function(data) { var fields = this.model.prototype.fields.items, length = fields.length, output = {}, field, value, i; for (i = 0; i < length; i++) { field = fields[i]; value = this.extractorFunctions[i](data) || field.defaultValue; output[field.name] = value; } return output; }, /** * @private * 默认下这个函数送入什么就返回什么,这需要由一个子类来实现的方法。参阅XmlReader就是一个例子。 * By default this function just returns what is passed to it. It can be overridden in a subclass * to return something else. See XmlReader for an example. * @param {Object} data 数据对象。The data object * @return {Object} 常规化数据对象。The normalized data object */ getData: function(data) { return data; }, /** * @private * 这需要由一个子类来实现的方法。该方法返回的对象就是供Reader的“root”元数据配置项。参阅XmlReader的getRoot实现就是一个例子。默认下这个函数送入什么就返回什么。 * This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type * of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config. * See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned. * @param {Mixed} data The data object * @return {Mixed} The same data object */ getRoot: function(data) { return data; }, /** * 把原始数据对象(即送入到this.read的)并返回有用的数据判断。必须由每个子类来实现这个方法。 * Takes a raw response object (as passed to this.read) and returns the useful data segment of it. This must be implemented by each subclass * @param {Object} response 响应对象。 The responce object * @return {Object} 来自响应有用的数据。 The useful data from the response */ getResponseData: function(response) { throw new Error("getResponseData must be implemented in the Ext.data.Reader subclass"); }, /** * @private * 对绑定到该Reader的元数据重新配置。 * Reconfigures the meta data tied to this Reader */ onMetaChange : function(meta) { var fields = meta.fields, newModel; Ext.apply(this, meta); if (fields) { newModel = Ext.regModel("JsonReader-Model" + Ext.id(), {fields: fields}); this.setModel(newModel, true); } else { this.buildExtractors(true); } }, /** * @private * 为获取记录数据和元数据构建优化的函数。子类的话可以不用实现其自身的getRoot函数。 * This builds optimized functions for retrieving record data and meta data from an object. * Subclasses may need to implement their own getRoot function. * @param {Boolean} force True表示为先自动移除现有的extractor函数(默认为false)。True to automatically remove existing extractor functions first (defaults to false) */ buildExtractors: function(force) { if (force === true) { delete this.extractorFunctions; } if (this.extractorFunctions) { return; } var idProp = this.id || this.idProperty, totalProp = this.totalProperty, successProp = this.successProperty, messageProp = this.messageProperty; //build the extractors for all the meta data if (totalProp) { this.getTotal = this.createAccessor(totalProp); } if (successProp) { this.getSuccess = this.createAccessor(successProp); } if (messageProp) { this.getMessage = this.createAccessor(messageProp); } if (idProp) { var accessor = this.createAccessor(idProp); this.getId = function(record) { var id = accessor(record); return (id == undefined || id == '') ? null : id; }; } else { this.getId = function() { return null; }; } this.buildFieldExtractors(); }, /** * @private */ buildFieldExtractors: function() { //now build the extractors for all the fields var fields = this.model.prototype.fields.items, ln = fields.length, i = 0, extractorFunctions = [], field, map; for (; i < ln; i++) { field = fields[i]; map = (field.mapping !== undefined && field.mapping !== null) ? field.mapping : field.name; extractorFunctions.push(this.createAccessor(map)); } this.extractorFunctions = extractorFunctions; } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.JsonReader * @extends Ext.data.Reader * * <p> * 数据阅读器,定位在从JSON数据包以创建{@link Ext.data.Model}对象的数组,其中的映射关系来自于{@link Ext.data.Model}的构造器。 * Data reader class to create an Array of {@link Ext.data.Model} objects from a * JSON packet based on mappings in a provided Ext.data.Model constructor.</p> * * <p>例子:Example code:</p> * <pre><code> var myReader = new Ext.data.Store({ proxy: { type: 'ajax', reader: { type: 'json', // 元数据 metadata configuration options: idProperty: 'id' root: 'rows', totalProperty: 'results' } }, // 这些字段的配置参数将会用于内部创建Ext.data.Model的构建器。 // the fields config option will internally create an Ext.data.Model // constructor that provides mapping for reading the record data objects fields: [ // map Record's 'firstname' field to data object's key of same name {name: 'name'}, // map Record's 'job' field to data object's 'occupation' key {name: 'job', mapping: 'occupation'} ], }); </code></pre> * * <p>被分析的JSON数据对象假设如下:This would consume a JSON data object of the form:</p> * <pre><code> { results: 2000, // Reader指定的总数。 Reader's configured totalProperty rows: [ // Reader指定的根节点。Reader's configured root // 记录对象如下:record data objects: { id: 1, firstname: 'Bill', occupation: 'Gardener' }, { id: 2, firstname: 'Ben' , occupation: 'Horticulturalist' }, ... ] } </code></pre> */ Ext.data.JsonReader = Ext.extend(Ext.data.Reader, { /** * 读取JSON对象,返回ResultSet。使用内部的getTotal和getSuccess方法读取来自响应的元数据,并将这些JSON数据输出到模型实例。 * Reads a JSON object and returns a ResultSet. Uses the internal getTotal and getSuccess extractors to * retrieve meta data from the response, and extractData to turn the JSON data into model instances. * @param {Object} data 原始的JSON数据。The raw JSON data * @return {Ext.data.ResultSet} 携带实体数据的ResultSet。A ResultSet containing model instances and meta data about the results */ readRecords: function(data) { //this has to be before the call to super because we use the meta data in the superclass readRecords if (data.metaData) { this.onMetaChange(data.metaData); } /** * 这只是this.rawData的拷贝,会被弃置。 * DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead * @property jsonData * @type Mixed */ this.jsonData = data; return Ext.data.JsonReader.superclass.readRecords.call(this, data); }, //inherit docs getResponseData: function(response) { try { var data = Ext.decode(response.responseText); } catch (ex) { throw 'Ext.data.JsonReader.getResponseData: Unable to parse JSON returned by Server.'; } if (!data) { throw 'Ext.data.JsonReader.getResponseData: JSON object not found'; } return data; }, //inherit docs buildExtractors : function() { Ext.data.JsonReader.superclass.buildExtractors.apply(this, arguments); if (this.root) { this.getRoot = this.createAccessor(this.root); } else { this.getRoot = function(root) { return root; }; } }, /** * @private * 返回accessor函数。 * Returns an accessor function for the given property string. Gives support for properties such as the following: * 'someProperty' * 'some.property' * 'some["property"]' * This is used by buildExtractors to create optimized extractor functions when casting raw data into model instances. */ createAccessor: function() { var re = /[\[\.]/; return function(expr) { if (Ext.isEmpty(expr)) { return Ext.emptyFn; } if (Ext.isFunction(expr)) { return expr; } var i = String(expr).search(re); if (i >= 0) { return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr); } return function(obj) { return obj[expr]; }; }; }() }); Ext.data.ReaderMgr.registerType('json', Ext.data.JsonReader);
JavaScript
Ext.data.TreeReader = Ext.extend(Ext.data.JsonReader, { extractData : function(root, returnRecords) { var records = Ext.data.TreeReader.superclass.extractData.call(this, root, returnRecords), ln = records.length, i = 0, record; if (returnRecords) { for (; i < ln; i++) { record = records[i]; record.doPreload = !!this.getRoot(record.raw); } } return records; } }); Ext.data.ReaderMgr.registerType('tree', Ext.data.TreeReader);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.ArrayReader * @extends Ext.data.JsonReader * * <p> * Data reader透过一个数组而转化成为{@link Ext.data.Record}对象所组成的数组,数组内的每个元素就代表一行数据。 * 字段定义中,通过使用下标来把字段抽取到Record对象,属性<em>mapping</em>用于指定下标,如果不指定就按照定义的先后顺序。<br /> * Data reader class to create an Array of {@link Ext.data.Record} objects from an Array. * Each element of that Array represents a row of data fields. The * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property * of the field definition if it exists, or the field's ordinal position in the definition.</p> * * <p><u>示例代码:Example code:</u></p> * <pre><code> var Employee = Ext.data.Record.create([ {name: 'name', mapping: 1}, // 属性<em>mapping</em>用于指定下标"mapping" only needed if an "id" field is present which {name: 'occupation', mapping: 2} // 如果不指定就按照定义的先后顺序precludes using the ordinal position as the index. ]); var myReader = new Ext.data.ArrayReader({ {@link #idIndex}: 0 }, Employee); </code></pre> * * <p>形成这种形式的数组:This would consume an Array like this:</p> * <pre><code> [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ] </code></pre> * * @constructor * 创建一个ArrayReader对象。Create a new ArrayReader * @param {Object} meta 元数据配置参数。Metadata configuration options. * @param {Array/Object} recordType * <p> 既可以是{@link Ext.data.Field Field}的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由 * {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。 * Either an Array of {@link Ext.data.Field Field} definition objects (which * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record} * constructor created from {@link Ext.data.Record#create}.</p> */ Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, { /** * @private * 由一个数组产生一个包含Ext.data.Records的对象块。 * Most of the work is done for us by JsonReader, but we need to overwrite the field accessors to just * reference the correct position in the array. */ buildExtractors: function() { Ext.data.ArrayReader.superclass.buildExtractors.apply(this, arguments); var fields = this.model.prototype.fields.items, length = fields.length, extractorFunctions = [], i; for (i = 0; i < length; i++) { extractorFunctions.push(function(index) { return function(data) { return data[index]; }; }(fields[i].mapping || i)); } this.extractorFunctions = extractorFunctions; } }); Ext.data.ReaderMgr.registerType('array', Ext.data.ArrayReader);
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Operation * @extends Object * * <p>Operation类表征了{@link Ext.data.Proxy Proxy}进行单个读或者写的时候的具体操作。 * Operation对象用于激活Stores和Proxy之间操作。开发人员通常不会直接与Operation对象打交道。 * Represents a single read or write operation performed by a {@link Ext.data.Proxy Proxy}. * Operation objects are used to enable communication between Stores and Proxies. Application * developers should rarely need to interact with Operation objects directly.</p> * * <p>多个Operation可以批处理为一个{@link Ext.data.Batch batch}。Several Operations can be batched together in a {@link Ext.data.Batch batch}.</p> * * @constructor * @param {Object} config 可选的配置项对象。Optional config object */ Ext.data.Operation = Ext.extend(Object, { /** * @cfg {Boolean} synchronous True表示为执行操作的时候是同步的(默认为True)。该属性为{@link Ext.data.Batch Batch}而设,看是否可以并行处理多个Operation。True if this Operation is to be executed synchronously (defaults to true). This * property is inspected by a {@link Ext.data.Batch Batch} to see if a series of Operations can be executed in * parallel or not. */ synchronous: true, /** * @cfg {String} action Operation执行的动作。可以是“create”、“read”、“update”或“destory”。The action being performed by this Operation. Should be one of 'create', 'read', 'update' or 'destroy' */ action: undefined, /** * @cfg {Array} filters 可选的。过滤器对象数组。只当‘read读’操作时有效。Optional array of filter objects. Only applies to 'read' actions. */ filters: undefined, /** * @cfg {Array} sorters 可选的。排序对象数组。只当‘read读’操作时有效。Optional array of sorter objects. Only applies to 'read' actions. */ sorters: undefined, /** * @cfg {Object} group 可选的。分组信息。只当在‘read读’操作时候期望分组有效。Optional grouping configuration. Only applies to 'read' actions where grouping is desired. */ group: undefined, /** * @cfg {Number} start start(offset)'read读'操作时的分页有用。The start index (offset), used in paging when running a 'read' action. */ start: undefined, /** * @cfg {Number} limit 指定要加载的记录数量。'read读'操作时的分页有用。 The number of records to load. Used on 'read' actions when paging is being used. */ limit: undefined, /** * @cfg {Ext.data.Batch} batch 可选的。该操作所在的batch对象。The batch that this Operation is a part of (optional) */ batch: undefined, /** * 只读的属性,用于跟踪该操作的异常状态。该属性私有的请使用{@link #isStarted}。 * Read-only property tracking the start status of this Operation. Use {@link #isStarted}. * @property started * @type Boolean * @private */ started: false, /** * 只读的属性,用于跟踪该操作的运行状态。该属性私有的请使用{@link #isRunning}。 * Read-only property tracking the run status of this Operation. Use {@link #isRunning}. * @property running * @type Boolean * @private */ running: false, /** * 只读的属性,用于跟踪该操作的完成状态。该属性私有的请使用{@link #isComplete}。 * Read-only property tracking the completion status of this Operation. Use {@link #isComplete}. * @property complete * @type Boolean * @private */ complete: false, /** * 只读的属性,用于跟踪该操作是否成功的状态。该值开始时是undefined,而当透过Proxy执行Operation后,该值会设置为true或false。{@link #setException}也会设置该值。请使用{@link #wasSuccessful}查询是否成功的状态。 * Read-only property tracking whether the Operation was successful or not. This starts as undefined and is set to true * or false by the Proxy that is executing the Operation. It is also set to false by {@link #setException}. Use * {@link #wasSuccessful} to query success status. * @property success * @type Boolean * @private */ success: undefined, /** * 只读的属性,用于跟踪该操作的异常状态。该属性私有的请使用{@link #hasException}并参阅{@link #getError}。 * Read-only property tracking the exception status of this Operation. Use {@link #hasException} and see {@link #getError}. * @property exception * @type Boolean * @private */ exception: false, /** *传入到{@link #setException}的错误对象。该对象应该是私有的。 The error object passed when {@link #setException} was called. This could be any object or primitive. * @property error * @type Mixed * @private */ error: undefined, constructor: function(config) { Ext.apply(this, config || {}); }, /** * 标记Opeationn为开始的。 * Marks the Operation as started */ setStarted: function() { this.started = true; this.running = true; }, /** * 标记Opeationn为完成的。 * Marks the Operation as completed */ setCompleted: function() { this.complete = true; this.running = false; }, /** * 标记Opeationn为成功的。 * Marks the Operation as successful */ setSuccessful: function() { this.success = true; }, /** * 标记Opeationn已经遭遇过一次异常。可以送入一个错误消息或对象的。 * Marks the Operation as having experienced an exception. Can be supplied with an option error message/object. * @param {Mixed} error 可选的错误字符串或对象。Optional error string/object */ setException: function(error) { this.exception = true; this.success = false; this.running = false; this.error = error; }, /** * @private */ markStarted: function() { console.warn("Operation: markStarted has been deprecated. Please use setStarted"); return this.setStarted(); }, /** * @private */ markCompleted: function() { console.warn("Operation: markCompleted has been deprecated. Please use setCompleted"); return this.setCompleted(); }, /** * @private */ markSuccessful: function() { console.warn("Operation: markSuccessful has been deprecated. Please use setSuccessful"); return this.setSuccessful(); }, /** * @private */ markException: function() { console.warn("Operation: markException has been deprecated. Please use setException"); return this.setException(); }, /** * 返回true表示Opeaetion遭遇到一次异常(请参阅{@link #getError}) * Returns true if this Operation encountered an exception (see also {@link #getError}) * @return {Boolean} True表示为有异常。True if there was an exception */ hasException: function() { return this.exception === true; }, /** * 返回通过{@link #setException}设置的错误字符串或对象。 * Returns the error string or object that was set using {@link #setException} * @return {Mixed} 错误对象。The error object */ getError: function() { return this.error; }, /** * 返回通过Proxy设置的Ext.data.Model实例数组。 * Returns an array of Ext.data.Model instances as set by the Proxy. * @return {Array} Any loaded Records */ getRecords: function() { var resultSet = this.getResultSet(); return (resultSet == undefined ? this.records : resultSet.records); }, /** * 返回记录集合对象(如有通过Proxy设置的话)。该对象会包含{@link Ext.data.Model model}还有建立实例、可用数等的元数据。 * Returns the ResultSet object (if set by the Proxy). This object will contain the {@link Ext.data.Model model} instances * as well as meta data such as number of instances fetched, number available etc * @return {Ext.data.ResultSet} 记录集合对象。The ResultSet object */ getResultSet: function() { return this.resultSet; }, /** * 返回True表示Operation已经开始了。注意Operation或者已经开始并且完成了的了,参阅{@link #isRunning}以了解如何测试Operation当前是否在运行着的。Returns true if the Operation has been started. Note that the Operation may have started AND completed, * see {@link #isRunning} to test if the Operation is currently running. * @return {Boolean} True表示为Operation已经开始。True if the Operation has started */ isStarted: function() { return this.started === true; }, /** * 返回True表示Operation已经开始却并没有完成。 * Returns true if the Operation has been started but has not yet completed. * @return {Boolean} True表示Operation正在运行。True if the Operation is currently running */ isRunning: function() { return this.running === true; }, /** * 返回True表示Operation已结束。 * eturns true if the Operation has been completed * @return {Boolean} True表示Operation已结束。。True if the Operation is complete */ isComplete: function() { return this.complete === true; }, /** * 返回True表示Operation已经完成并且是成功的。 * Returns true if the Operation has completed and was successful * @return {Boolean} True表示为成功。True if successful */ wasSuccessful: function() { return this.isComplete() && this.success === true; }, /** * @private * 关联一个Batch到Operation。 * Associates this Operation with a Batch * @param {Ext.data.Batch} batch The batch */ setBatch: function(batch) { this.batch = batch; }, /** * 是否允许这个Operation可以写操作。 * Checks whether this operation should cause writing to occur. * @return {Boolean} 是否可以进行写的操作。Whether the operation should cause a write to occur. */ allowWrite: function() { return this.action != 'read'; } });
JavaScript
/* * @version Sencha 0.98 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.data.Model * @extends Ext.util.Stateful * * <p> * Model模型就是一些归你程序所管理的对象。例如,为用户、产品、汽车……等等其他现实世界中的食物,只要您认为可以加入到系统的,都可被认为模型。 * 你可以向{@link Ext.ModelMgr model manager}登记一个模型对象。 * 模型是抽象的,其实体数据就是{@link Ext.data.Store stores}所携带的数据,用于Ext组件的通用数据绑定。 * <br /> * A Model represents some object that your application manages. * For example, one might define a Model for Users, Products, * Cars, or any other real-world object that we want to model in the system. * Models are registered via the {@link Ext.ModelMgr model manager}, * and are used by {@link Ext.data.Store stores}, * which are in turn used by many of the data-bound components in Ext.</p> * * <p> * 虽然说模型是抽象的,但是模型中总得包含一些内容吧?模型中有什么呢?API规定,模型由一系列的字段、相关的方法/属性组成。例如: * <br /> * Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:</p> * <pre><code> Ext.regModel('User', { fields: [ {name: 'name', type: 'string'}, {name: 'age', type: 'int'}, {name: 'phone', type: 'string'}, {name: 'alive', type: 'boolean', defaultValue: true} ], changeName: function() { var oldName = this.get('name'), newName = oldName + " The Barbarian"; this.set('name', newName); } }); </code></pre> * * <p> * 字段所构成的数组会经过{@link Ext.ModelMgr ModelMgr}自动转化为{@link Ext.util.MixedCollection MixedCollection}的结构,而所有的函数和属性就会被指向Model的原型prototype。 * <br /> * The fields array is turned into a {@link Ext.util.MixedCollection MixedCollection} automatically * by the {@link Ext.ModelMgr ModelMgr}, and all * other functions and properties are copied to the new Model's prototype.</p> * * <p> * 现在我们测试一下,创建用户的模型,调用其方法: * <br /> * Now we can create instances of our User model and call any model logic we defined:</p> * <pre><code> var user = Ext.ModelMgr.create({ name : 'Conan', age : 24, phone: '555-555-5555' }, 'User'); user.changeName(); user.get('name'); //returns "Conan The Barbarian" </code></pre> * * <p><u>数据验证 Validations</u></p> * * <p> * 通过{@link Ext.data.validations}验证器,Model内部可实现数据验证功能(请参阅{@link Ext.data.validations 了解更多地验证器函数}),而且在模型身上加入验证器是非常简单的。 * <br /> * Models have built-in support for validations, which are executed against the validator functions in * {@link Ext.data.validations} ({@link Ext.data.validations see all validation functions}). Validations are easy to add to models:</p> * <pre><code> Ext.regModel('User', { fields: [ {name: 'name', type: 'string'}, {name: 'age', type: 'int'}, {name: 'phone', type: 'string'}, {name: 'gender', type: 'string'}, {name: 'username', type: 'string'}, {name: 'alive', type: 'boolean', defaultValue: true} ], validations: [ {type: 'presence', field: 'age'}, {type: 'length', field: 'name', min: 2}, {type: 'inclusion', field: 'gender', list: ['Male', 'Female']}, {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']}, {type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/} ] }); </code></pre> * * <p> * 只需要调用{@link #validate}函数就可进入验证的程序,该程序返回一个{@link Ext.data.Errors}对象。 * The validations can be run by simply calling the {@link #validate} function, which returns a {@link Ext.data.Errors} * object:</p> * <pre><code> var instance = Ext.ModelMgr.create({ name: 'Ed', gender: 'Male', username: 'edspencer' }, 'User'); var errors = instance.validate(); </code></pre> * * <p><u>关联 Associations</u></p> * * <p> * 除了加入业务的方法外,还可以通过{@link Ext.data.BelongsToAssociation belongsTo}方法和{@link Ext.data.HasManyAssociation hasMany}方法建立模型之间的关系。 * 例如,假设一个博客的管理程序,有用户Users、贴子Posts和评论Comments业务对象。我们可以用以下语法表达它们之间的关系: * <br /> * Models can have associations with other Models via {@link Ext.data.BelongsToAssociation belongsTo} and * {@link Ext.data.HasManyAssociation hasMany} associations. For example, let's say we're writing a blog administration * application which deals with Users, Posts and Comments. We can express the relationships between these models like this:</p> * <pre><code> Ext.regModel('Post', { fields: ['id', 'user_id'], belongsTo: 'User', hasMany : {model: 'Comment', name: 'comments'} }); Ext.regModel('Comment', { fields: ['id', 'user_id', 'post_id'], belongsTo: 'Post' }); Ext.regModel('User', { fields: ['id'], hasMany: [ 'Post', {model: 'Comment', name: 'comments'} ] }); </code></pre> * * <p> * 参阅{@link Ext.data.BelongsToAssociation}和{@link Ext.data.HasManyAssociation}了解更多关联的用法和配置。请注意也可以这样关联: * See the docs for {@link Ext.data.BelongsToAssociation} and {@link Ext.data.HasManyAssociation} for details on the usage * and configuration of associations. Note that associations can also be specified like this:</p> * <pre><code> Ext.regModel('User', { fields: ['id'], associations: [ {type: 'hasMany', model: 'Post', name: 'posts'}, {type: 'hasMany', model: 'Comment', name: 'comments'} ] }); </code></pre> * * @constructor * @param {Object} data 模型字段所涉及的相关信息,和字段Value。An object containing keys corresponding to this model's fields, and their associated values * @param {Number} id 可选的,分配到模型实例的ID。Optional unique ID to assign to this model instance */ Ext.data.Model = Ext.extend(Ext.util.Stateful, { evented: false, isModel: true, /** * <tt>true</tt> when the record does not yet exist in a server-side database (see * {@link #markDirty}). Any record which has a real database pk set as its id property * is NOT a phantom -- it's real. * @property phantom * @type {Boolean} */ phantom : false, /** * 说明那一个字段才是模型的id。(默认为“id”)。The name of the field treated as this Model's unique id (defaults to 'id'). * @property idProperty * @type String */ idProperty: 'id', /** * 默认模型的通讯代理,默认为“ajax”。 * The string type of the default Model Proxy. Defaults to 'ajax' * @property defaultProxyType * @type String */ defaultProxyType: 'ajax', constructor: function(data, id) { data = data || {}; if (this.evented) { this.addEvents( ); } /** * 内部用的模型实例id,用于在没有提供id情况下的识别。 * An internal unique ID for each Model instance, used to identify Models that don't have an ID yet * @property internalId * @type String * @private */ this.internalId = (id || id === 0) ? id : Ext.data.Model.id(this); Ext.data.Model.superclass.constructor.apply(this); //如果有默认内容,加入。add default field values if present var fields = this.fields.items, length = fields.length, field, name, i; for (i = 0; i < length; i++) { field = fields[i]; name = field.name; if (data[name] == undefined) { data[name] = field.defaultValue; } } this.set(data); if (this.getId()) { this.phantom = false; } if (typeof this.init == 'function') { this.init(); } }, /** * 根据所配置的{@link #validations}进行当前数据验证,并返回一个{@link Ext.data.Errors Errors}对象。 * Validates the current data against all of its configured {@link #validations} and returns an * {@link Ext.data.Errors Errors} object * @return {Ext.data.Errors} The errors object */ validate: function() { var errors = new Ext.data.Errors(), validations = this.validations, validators = Ext.data.validations, length, validation, field, valid, type, i; if (validations) { length = validations.length; for (i = 0; i < length; i++) { validation = validations[i]; field = validation.field; type = validation.type; valid = validators[type](validation, this.get(field)); if (!valid) { errors.add({ field : field, message: validation.message || validators[type + 'Message'] }); } } } return errors; }, /** * 返回该模型的Proxy。 * Returns the configured Proxy for this Model * @return {Ext.data.Proxy} The proxy */ getProxy: function() { return this.constructor.proxy; }, /** * 根据已配置的proxy保存一个模型实例。 * Saves the model instance using the configured proxy * @param {Object} options 传入到proxy的配置项。Options to pass to the proxy * @return {Ext.data.Model} 模型实例。The Model instance */ save: function(options) { var action = this.phantom ? 'create' : 'update'; options = options || {}; Ext.apply(options, { records: [this], action : action }); var operation = new Ext.data.Operation(options), successCb = options.success, failureCb = options.failure, callbackFn = options.callback, scope = options.scope, record; var callback = function(operation) { record = operation.getRecords()[0]; if (operation.wasSuccessful()) { record.dirty = false; if (typeof successCb == 'function') { successCb.call(scope, record, operation); } } else { if (typeof failureCb == 'function') { failureCb.call(scope, record, operation); } } if (typeof callbackFn == 'function') { callbackFn.call(scope, record, operation); } }; this.getProxy()[action](operation, callback, this); return this; }, /** * * Returns the unique ID allocated to this model instance as defined by {@link #idProperty} * @return {Number} The id */ getId: function() { return this.get(this.idProperty); }, /** * Sets the model instance's id field to the given id * @param {Number} id The new id */ setId: function(id) { this.set(this.idProperty, id); }, /** * Tells this model instance that it has been added to a store * @param {Ext.data.Store} store The store that the model has been added to */ join : function(store) { /** * The {@link Ext.data.Store} to which this Record belongs. * @property store * @type {Ext.data.Store} */ this.store = store; }, /** * Tells this model instance that it has been removed from the store * @param {Ext.data.Store} store The store to unjoin */ unjoin: function(store) { delete this.store; }, /** * @private * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's * afterEdit method is called */ afterEdit : function() { this.callStore('afterEdit'); }, /** * @private * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's * afterReject method is called */ afterReject : function() { this.callStore("afterReject"); }, /** * @private * If this Model instance has been {@link #join joined} to a {@link Ext.data.Store store}, the store's * afterCommit method is called */ afterCommit: function() { this.callStore('afterCommit'); }, /** * @private * Helper function used by afterEdit, afterReject and afterCommit. Calls the given method on the * {@link Ext.data.Store store} that this instance has {@link #join joined}, if any. The store function * will always be called with the model instance as its single argument. * @param {String} fn The function to call on the store */ callStore: function(fn) { var store = this.store; if (store != undefined && typeof store[fn] == "function") { store[fn](this); } } }); Ext.apply(Ext.data.Model, { /** * 设置该模型所用的Proxy对象。输入的对象必须符合{@link Ext.data.ProxyMgr#create}的参数要求。 * Sets the Proxy to use for this model. Accepts any options that can be accepted by {@link Ext.data.ProxyMgr#create} * @param {String/Object/Ext.data.Proxy} proxy The proxy */ setProxy: function(proxy) { //make sure we have an Ext.data.Proxy object proxy = Ext.data.ProxyMgr.create(proxy); proxy.setModel(this); this.proxy = proxy; return proxy; }, /** * 通过id指定一个model,进行异步加载。用法如下: * Asynchronously loads a model instance by id. Sample usage: <pre><code> MyApp.User = Ext.regModel('User', { fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'} ] }); MyApp.User.load(10, { scope: this, failure: function(record, operation) { //do something if the load failed }, success: function(record, operation) { //do something if the load succeeded }, callback: function(record, operation) { //do something whether the load succeeded or failed } }); </code></pre> * @param {Number} id 加载模型的id。The id of the model to load * @param {Object} config 包含success、failure、callback和作用域的配置项对象。Optional config object containing success, failure and callback functions, plus optional scope */ load: function(id, config) { config = Ext.applyIf(config || {}, { action: 'read', id : id }); var operation = new Ext.data.Operation(config), callbackFn = config.callback, successCb = config.success, failureCb = config.failure, scope = config.scope, record, callback; callback = function(operation) { record = operation.getRecords()[0]; if (operation.wasSuccessful()) { if (typeof successCb == 'function') { successCb.call(scope, record, operation); } } else { if (typeof failureCb == 'function') { failureCb.call(scope, record, operation); } } if (typeof callbackFn == 'function') { callbackFn.call(scope, record, operation); } }; this.proxy.read(operation, callback, this); } }); /** * Generates a sequential id. This method is typically called when a record is {@link #create}d * and {@link #Record no id has been specified}. The returned id takes the form: * <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul> * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.PREFIX</tt> * (defaults to <tt>'ext-record'</tt>)</p></li> * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Model.AUTO_ID</tt> * (defaults to <tt>1</tt> initially)</p></li> * </ul></div> * @param {Record} rec The record being created. The record does not exist, it's a {@link #phantom}. * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>; */ Ext.data.Model.id = function(rec) { rec.phantom = true; return [Ext.data.Model.PREFIX, '-', Ext.data.Model.AUTO_ID++].join(''); }; //[deprecated 5.0] Ext.ns('Ext.data.Record'); //Backwards compat Ext.data.Record.id = Ext.data.Model.id; //[end] Ext.data.Model.PREFIX = 'ext-record'; Ext.data.Model.AUTO_ID = 1; Ext.data.Model.EDIT = 'edit'; Ext.data.Model.REJECT = 'reject'; Ext.data.Model.COMMIT = 'commit';
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.util.Dispatcher * @extends Ext.util.Observable * @ignore * * @constructor */ Ext.util.Dispatcher = Ext.extend(Ext.util.Observable, { constructor: function(config) { this.addEvents( /** * @event before-dispatch * 当调度交互之前触发该事件。返回false表示取消调度。 * Fires before an interaction is dispatched. Return false from any listen to cancel the dispatch * @param {Ext.Interaction} interaction 要被调度的交互对象。The Interaction about to be dispatched */ 'before-dispatch', /** * @event dispatch * 当已经调度交互后触发该事件。 * Fired once an Interaction has been dispatched * @param {Ext.Interaction} interaction 刚才被调度的交互对象。The Interaction that was just dispatched */ 'dispatch' ); Ext.util.Dispatcher.superclass.constructor.call(this, config); }, /** * 调度一个独立的交互对象到控制器、 动作结对。 * Dispatches a single interaction to a controller/action pair * @param {Object} options 至少包含一個控制器、动作结对的配置项对象。Options representing at least the controller and action to dispatch to */ dispatch: function(options) { var interaction = new Ext.Interaction(options), controller = interaction.controller, action = interaction.action, History = Ext.History; if (this.fireEvent('before-dispatch', interaction) !== false) { if (History && options.historyUrl) { History.suspendEvents(false); History.add(options.historyUrl); Ext.defer(History.resumeEvents, 100, History); } if (controller && action) { controller[action].call(controller, interaction); interaction.dispatched = true; } this.fireEvent('dispatch', interaction); } }, /** * 调度到控制器、 动作结对,加入新的url到历史记录。 * Dispatches to a controller/action pair, adding a new url to the History stack */ redirect: function(options) { if (options instanceof Ext.data.Model) { //compose a route for the model } else if (typeof options == 'string') { //use router var route = Ext.Router.recognize(options); if (route) { return this.dispatch(route); } } return null; }, /** * 快捷方法,返回一个调用Ext.Dirspatcher.redirect的函数。当设置几个转移的侦听器时有用。例如: * Convenience method which returns a function that calls Ext.Dispatcher.redirect. Useful when setting * up several listeners that should redirect, e.g.: <pre><code> myComponent.on({ homeTap : Ext.Dispatcher.createRedirect('home'), inboxTap: Ext.Dispatcher.createRedirect('inbox'), }); </code></pre> * @param {String/Object} url 创建跳转函数的url。The url to create the redirect function for * @return {Function} 跳转函数。The redirect function */ createRedirect: function(url) { return function() { Ext.Dispatcher.redirect(url); }; } }); Ext.Dispatcher = new Ext.util.Dispatcher(); //译注:此处是不是很绕啊?呵呵——不過話說囘來這裡真是必須的。 Ext.dispatch = function() { return Ext.Dispatcher.dispatch.apply(Ext.Dispatcher, arguments); }; Ext.redirect = function() { return Ext.Dispatcher.redirect.apply(Ext.Dispatcher, arguments); }; Ext.createRedirect = Ext.Dispatcher.createRedirect;
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.Controller * @extends Ext.util.Observable * * @constructor */ Ext.Controller = Ext.extend(Ext.util.Observable, { constructor: function(config) { this.addEvents( /** * @event instance-created * 当控制器成功创建了模型实例的时候触发该事件。 * Fired when a new model instance has been successfully created by this controller * @param {Ext.data.Model} instance 新创建的模型。The newly-created model instance */ 'instance-created', /** * @event instance-creation-failed * 当控制器创建失败模型实例的时候触发该事件。 * Fired when an attempt at saving a new instance failed * @param {Ext.data.Model} instance 不能保存的实例。The instance that could not be saved * @param {Object} errors 导致失败的错误原因(如果有任何)。The set of errors (if any) that caused the failure */ 'instance-creation-failed', /** * @event instance-updated * 当模型实例被这个控制器更新后触发该事件。 * Fired when an existing model instance has been successfully updated by this controller * @param {Ext.data.Model} instance 更新的实例。The instance that was updated */ 'instance-updated', /** * @event instance-update-failed * 当模型实例不能被这个控制器更新之后就触发该事件。 * Fired when an update to existing model instance could not be successfully completed * @param {Ext.data.Model} instance 不能更新的实例。The instance that could not be updated * @param {Object} errors 导致失败的错误原因(如果有任何)。The set of errors (if any) that caused the failure */ 'instance-update-failed', /** * @event instance-destroyed * 当控制器销毁一个现有的模型实例的时候触发该事件。 * Fired when an existing instance has been successfully destroyed by this controller * @param {Ext.data.Model} instance 被销毁的实例。The instance that was destroyed */ 'instance-destroyed', /** * @event instance-destruction-failed * 当控制器不能销毁一个现有的模型实例的时候触发该事件。 * Fired when an existing instance could not be destroyed * @param {Ext.data.Model} instance 未被销毁的实例。The instance that could not be destroyed * @param {Object} errors 导致失败的错误原因(如果有任何)。The set of errors (if any) that caused the failure */ 'instance-destruction-failed' ); Ext.Controller.superclass.constructor.call(this, config); Ext.apply(this, config || {}); if (typeof this.model == 'string') { this.model = Ext.ModelMgr.getModel(this.model); } }, index: function() { this.render('index', { listeners: { scope : this, edit : this.edit, build : this.build, create : this.onCreateInstance, destroy: this.onDestroyInstance } }); }, /** * 根据指定的模型实例渲染编辑形式。 * Renders the edit form for a given model instance * @param {Ext.data.Model} instance 编辑的实例。The instance to edit */ edit: function(instance) { var view = this.render('edit', { listeners: this.getEditListeners() }); view.loadModel(instance); }, /** * 绑定到索引的“build”事件。默认下只是渲染登记好的“build”试图。 * Callback automatically tied to the index view's 'build' event. By default this just renders the registered 'build' view */ build: function() { this.render('build', { listeners: this.getBuildListeners() }); }, /** * 通过其配置好的Proxy保存一个影子模型实例。如成功触发'instance-created'时,如果不成功触发'instance-creation-failed'事件。 * Saves a phantom Model instance via its configured Proxy. Fires the 'instance-created' event if successful, * the 'instance-creation-failed' event if not. * @param {Object} data 从哪个实例得到的数据要创建? The data to create the instance from * @param {Object} options 可选的,包含成功和失败外加可选的作用域回调的对象。 Optional options object containing callbacks for success and failure plus optional scope */ create: function(data, options) { options = options || {}; var model = this.getModel(), instance = new model(data), successCb = options.success, failureCb = options.failure, scope = options.scope || this; instance.save({ scope : this, success: function(instance) { if (typeof successCb == 'function') { successCb.call(scope, instance); } this.fireEvent('instance-created', instance); }, failure: function(instance, errors) { if (typeof failureCb == 'function') { failureCb.call(scope, instance, errors); } this.fireEvent('instance-creation-failed', instance, errors); } }); }, /** * 通过应用可选的更新和尝试保存更新一个现有的模型实例。 * Updates an existing model instance by applying optional updates to it and attempting to save * @param {Ext.data.Model} instance 现有的实例。The existing instance * @param {Object} updates 可选的,在保存之前应用到实例的额外更新。Optional additional updates to apply to the instance before saving * @param {Object} options 成功与失败的回调。success and failure callback functions */ update: function(instance, updates, options) { options = options || {}; var successCb = options.success, failureCb = options.failure, scope = options.scope || this; if (Ext.isObject(updates)) { instance.set(updates); } instance.save({ scope : this, success: function(instance) { if (typeof successCb == 'function') { successCb.call(scope, instance); } this.fireEvent('instance-updated', instance); }, failure: function(instance, errors) { if (typeof failureCb == 'function') { failureCb.call(scope, instance, errors); } this.fireEvent('instance-update-failed', instance, errors); } }); }, /** * 销毁一个或多个、之前保存的模型实例。 * Destroys one or more existing, previously saved model instances * @param {Ext.data.Model} instance 要销毁的实例模型。The model instance to destroy * @param {Object} options 成功与失败的回调。success and failure callbacks */ destroy: function(instance, options) { options = options || {}; var successCb = options.success, failureCb = options.failure, scope = options.scope || this; instance.destroy({ scope : this, success: function(instance) { if (typeof successCb == 'function') { successCb.call(scope, instance); } this.fireEvent('instance-destroyed', instance); }, failure: function(instance, errors) { if (typeof failureCb == 'function') { failureCb.call(scope, instance, errors); } this.fireEvent('instance-destruction-failed', instance, errors); } }); }, /** * 返回通过{@link #build}动作渲染的视图它所附加的事件侦听器。默认下该方法返回 保存 和 取消 的事件,但也重写该方法。 * Returns the listeners to attach to the view rendered by the {@link #build} action. By default this returns listeners * for save and cancel, but this can be overridden * @return {Object} listeners */ getBuildListeners: function() { return { scope : this, save : this.onCreateInstance, cancel: this.onCancelBuild }; }, /** * 返回通过{@link #edit}动作渲染的视图它所附加的事件侦听器。默认下该方法返回 保存 和 取消 的事件,但也重写该方法。 * Returns the listeners to attach to the view rendered by the {@link #edit} action. By default this returns listeners * for save and cancel, but this can be overridden * @return {Object} listeners */ getEditListeners: function() { return { scope : this, save : this.onUpdateInstance, cancel: this.onCancelEdit }; }, /** * {@link #edit}视图触发的'cancel'事件其处理器。默认这只是关闭视图。 * Handler for the 'cancel' event fired by an {@link #edit} view. By default this just closes the view * @param {Ext.Component} view 编辑形式。The edit form */ onCancelEdit: function(view) { return this.closeView(view); }, /** * {@link #build}视图触发的'cancel'事件其处理器。默认这只是关闭视图。 * Handler for the 'cancel' event fired by an {@link #build} view. By default this just closes the view * @param {Ext.Component} view 构建形式。The build form */ onCancelBuild: function(view) { return this.closeView(view); }, /** * 绑定到索引视图的“create”事件。默认只是调用控制器的create函数,参数有数据和一个基本的回调,如处理错误或显示成功的回调。可以重写该函数来自定义动作。 * Callback automatically tied to the index view's 'create' event. By default this just calls the controller's * create function with the data and some basic callbacks to handle errors or show success. Can be overridden * to provide custom behavior * @param {Ext.View} view 触发事件的那个视图实例。The view instance that fired the event */ onCreateInstance: function(view) { this.create(view.getValues(), { scope : this, success: function(instance) { this.closeView(view); }, failure: function(instance, errors) { console.log('fail'); } }); }, /** * 绑定到索引视图的“update”事件。默认只是调用控制器的update函数,参数有数据和一个基本的回调,如处理错误或显示成功的回调。可以重写该函数来自定义动作。 * Callback automatically tied to the index view's 'update' event. By default this just calls the controller's * update function with the data and some basic callbacks to handle errors or show success. Can be overridden * to provide custom behavior * @param {Ext.Component} view 触发事件的那个视图实例。The view instance that fired the event */ onUpdateInstance: function(view) { this.update(view.getRecord(), view.getValues(), { scope : this, success: function(instance) { this.closeView(view); }, failure: function(instance, errors) { } }); }, /** * 绑定到索引视图的“destroy”事件。默认只是调用控制器的destroy函数,参数有数据和一个基本的回调,如处理错误或显示成功的回调。可以重写该函数来自定义动作。 * Callback automatically tied to the index view's 'destroy' event. By default that just calls the controller's * destroy function with the model instance and some basic callbacks to handle errors or show success. Can be * overridden to provide custom behavior. * @param {Ext.data.Model} instance 要销毁的实例。The instance to destroy * @param {Ext.View} view 触发事件的那个视图实例。The view instance that fired the event */ onDestroyInstance: function(instance, view) { this.destroy(instance, { scope : this, success: function(instance) { }, failure: function(instance, errors) { } }); }, /** * 设置组件通过{@link #render}渲染所在默认的容器。 * 许多程序中有固定的导航面板和内容面板,在该类型的设置中内容面板通常就是渲染目标。 * Sets the default container that components rendered using {@link #render} will be added to. * In many applications there is a fixed navigation panel and a content panel - the content * panel would usually form the render target in this type of setup. * @param {Ext.Container} target 对已渲染好组件其所在的容器。The container to add rendered components to */ setRenderTarget: function(target) { /** * @property renderTarget * @type Ext.Container * 当前{@link #setRenderTarget 渲染目标}。只读的。 * The current {@link #setRenderTarget render target}. Read only */ Ext.Controller.renderTarget = target; }, /** * 根据已登记名称渲染给定的视图。 * Renders a given view based on a registered name * @param {String} viewName 要渲染视图的名称。The name of the view to render * @param {Object} config 可选的配置项对象。Optional config object * @return {Ext.View} 视图实例。The view instance */ render: function(config, target) { var Controller = Ext.Controller, application = this.application, profile = application ? application.currentProfile : undefined, profileTarget, view; Ext.applyIf(config, { profile: profile }); view = Ext.ComponentMgr.create(config); if (target !== false) { //give the current Ext.Profile a chance to set the target profileTarget = profile ? profile.getRenderTarget(config, application) : target; if (target == undefined) { target = profileTarget || (application ? application.defaultTarget : undefined); } if (typeof target == 'string') { target = Ext.getCmp(target); } if (target != undefined && target.add) { if (profile) { profile.beforeLayout(view, target, application); } target.add(view); if (target.layout && target.layout.setActiveItem) { target.layout.setActiveItem(view); } target.doComponentLayout(); if (profile) { profile.afterLayout(view, target, application); } } } return view; }, /** * 你个函数允许你以方便的方法为视图加入侦听器。 * This function allows you to add listeners to a view * in a convenient way */ control : function(view, actions, itemName) { if (!view || !view.isView) { throw 'Trying to control a view that doesnt exist'; } var item = itemName ? view.refs[itemName] : view, key, value, name, child, listener; if (!item) { throw "No item called " + itemName + " found inside the " + view.name + " view."; } for (key in actions) { value = actions[key]; // If it is an object, it can either be a listener with a handler defined // in which case the key is the event name, or it can be an object containing // listener(s), in which case key will be the items name if (Ext.isObject(value) && !value.fn) { this.control(view, value, key); } else { // Now hopefully we can be sure that key is an event name. We will loop over all // child items and enable bubbling for this event if (item.refs) { for (name in item.refs) { child = item.refs[name]; if (child.isObservable && child.events[key]) { child.enableBubble(key); } } } if (!value.fn) { listener = {}; listener[key] = value; listener.scope = this; } else { listener = value; if (listener.scope === undefined) { listener.scope = this; } } // Finally we bind the listener on this item item.addListener(listener); } } return view; }, /** * 返回关联到该控制器的模型类型其控制器。 * Returns the constructor for the model type linked to this controller * @return {Ext.data.Model} 模型构造器。The model constructor */ getModel: function() { return Ext.ModelMgr.getModel(this.model); }, /** * @private * 从父容器中移除组件的时候使用。参阅onCancelEdit和onCancelBuild。 * Used internally whenever we want to remove a component from its parent container. See onCancelEdit and onCancelBuild * @param {Ext.Component} view 要关闭的组件。The component to close */ closeView: function(view) { var ownerCt = view.ownerCt; if (ownerCt) { ownerCt.remove(view); ownerCt.doLayout(); ownerCt.setActiveItem(ownerCt.items.last()); } } });
JavaScript
/* * @version Sencha 1.0RC-1 * @ignore * @author Frank Cheung <frank@ajaxjs.com> * ---------------------请保留该段信息。------------------------- * 项目主页:http://code.google.com/p/chineseext/ * 欢迎参与我们翻译的工作!详见《Sencha Touch中文化相关事宜》: * http://bbs.ajaxjs.com/viewthread.php?tid=2951 * JS堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @author Ed Spencer * @class Ext.util.Route * @extends Object * @ignore * <p>该类表征了一个url与控制器、控制器/动作结对之间的结合体。它也可以加入其它的参数。Represents a mapping between a url and a controller/action pair. May also contain additional params</p> */ Ext.util.Route = Ext.extend(Object, { /** * @cfg {String} url 要匹配的url字符串。必须的。The url string to match. Required. */ constructor: function(config) { Ext.apply(this, config, { conditions: {} }); /* * The regular expression we use to match a segment of a route mapping * this will recognise segments starting with a colon, * e.g. on 'namespace/:controller/:action', :controller and :action will be recognised */ this.paramMatchingRegex = new RegExp(/:([0-9A-Za-z\_]*)/g); /* * Converts a route string into an array of symbols starting with a colon. e.g. * ":controller/:action/:id" => [':controller', ':action', ':id'] */ this.paramsInMatchString = this.url.match(this.paramMatchingRegex) || []; this.matcherRegex = this.createMatcherRegex(this.url); }, /** * 尝试识辨一个url字符串并与控制器、动作相结合。 * Attempts to recognize a given url string and return controller/action pair for it * @param {String} url 要识辨的urlThe url to recognize * @return {Object} 匹配的数据,如果返回false表示没有命中匹配。The matched data, or false if no match */ recognize: function(url) { if (this.recognizes(url)) { var matches = this.matchesFor(url); return Ext.applyIf(matches, { controller: this.controller, action : this.action, historyUrl: url }); } }, /** * 返回ture表示该路由对象匹配了一个指定的url字符串。 * Returns true if this Route matches the given url string * @param {String} url 要测试的url。。The url to test * @return {Boolean} True表示为路由对象争取识辨了这个url。True if this Route recognizes the url */ recognizes: function(url) { return this.matcherRegex.test(url); }, /** * @private * 指定一个url,返回其匹配的url参数hash。 * Returns a hash of matching url segments for the given url. * @param {String} url 要抽取的url。The url to extract matches for * @return {Object} 匹配的url。matching url segments */ matchesFor: function(url) { var params = {}, keys = this.paramsInMatchString, values = url.match(this.matcherRegex), length = keys.length, i; //第一个元素是判断条件,不需要。(注:shift()很爽)first value is the entire match so reject values.shift(); for (i = 0; i < length; i++) { params[keys[i].replace(":", "")] = values[i]; } return params; }, /** * 根据一个配置对象构造一个url,支持通贝符。(貌似该函数未搞掂) * Constructs a url for the given config object by replacing wildcard placeholders in the Route's url * @param {Object} config 配置对象。The config object * @return {String} 构建好的url。The constructed url */ urlFor: function(config) { }, /** * @private * 送入一个带通贝符的已配置url,返回可以用于匹配url的正则。 * Takes the configured url string including wildcards and returns a regex that can be used to match * against a url * @param {String} url url字符串。The url string * @return {RegExp} 匹配的正则。The matcher regex */ createMatcherRegex: function(url) { /** * Converts a route string into an array of symbols starting with a colon. e.g. * ":controller/:action/:id" => [':controller', ':action', ':id'] */ var paramsInMatchString = this.paramsInMatchString, length = paramsInMatchString.length, i, cond, matcher; for (i = 0; i < length; i++) { cond = this.conditions[paramsInMatchString[i]]; matcher = Ext.util.Format.format("({0})", cond || "[%a-zA-Z0-9\\_\\s,]+"); url = url.replace(new RegExp(paramsInMatchString[i]), matcher); } //we want to match the whole string, so include the anchors return new RegExp("^" + url + "$"); } });
JavaScript