code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * @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.Router * @extends Ext.util.Observable * @ignore */ Ext.util.Router = Ext.extend(Ext.util.Observable, { constructor: function(config) { config = config || {}; Ext.apply(this, config, { defaults: { action: 'index' } }); this.routes = []; Ext.util.Router.superclass.constructor.call(this, config); }, /** * 连接基于url的路由到一个加上额外参数的控制器、动作结对。 * Connects a url-based route to a controller/action pair plus additional params * @param {String} url 要识辨的url。The url to recognize */ connect: function(url, params) { params = Ext.apply({url: url}, params || {}, this.defaults); var route = new Ext.util.Route(params); this.routes.push(route); return route; }, /** * 识辨到路由器的url字符串,返回控制器、动作结对。 * Recognizes a url string connected to the Router, return the controller/action pair plus any additional * config associated with it * @param {String} url 要识辨的url。The url to recognize * @return {Object/undefined} 如果能够识别url,那么调用控制器和动作。否则就是undefined。If the url was recognized, the controller and action to call, else undefined */ recognize: function(url) { var routes = this.routes, length = routes.length, i, result; for (i = 0; i < length; i++) { result = routes[i].recognize(url); if (result != undefined) { return result; } } return undefined; }, /** * 快捷方法, 调用送入的函数,该函数包含了路由器实例。例如: * Convenience method which just calls the supplied function with the Router instance. Example usage: <pre><code> Ext.Router.draw(function(map) { map.connect('activate/:token', {controller: 'users', action: 'activate'}); map.connect('home', {controller: 'index', action: 'home'}); }); </code></pre> * @param {Function} fn 要调用的函数。The fn to call */ draw: function(fn) { fn.call(this, this); } }); Ext.Router = new Ext.util.Router();
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.Interaction * @extends Ext.util.Observable * @ignore * * <p>该类表征了控制器与特定动作的结合体。Represents a single interaction performed by a controller/action pair</p> * @constructor * @param {Object} config 至少包含一個控制器、动作结对的配置项对象。Options object containing at least a controller/action pair */ Ext.Interaction = Ext.extend(Ext.util.Observable, { /** * @cfg {String} controller 要调度的控制器。The controller to dispatch to */ controller: '', /** * @cfg {String} action 控制器相关的动作。The controller action to invoke */ action: '', /** * @cfg {Array} args 送入动作当中的参数列表。Any arguments to pass to the action */ /** * @cfg {Object} scope 可选的,控制器执行的动作。Optional scope to execute the controller action in */ /** * True表示为这次交互已经被调遣。True if this Interaction has already been dispatched * @property dispatched * @type Boolean */ dispatched: false, constructor: function(config) { Ext.Interaction.superclass.constructor.apply(this, arguments); config = config || {}; Ext.applyIf(config, { scope: this }); Ext.apply(this, config); if (typeof this.controller == 'string') { this.controller = Ext.ControllerManager.get(this.controller); } } });
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.ApplicationManager * @extends Ext.AbstractManager * @singleton * @ignore */ Ext.ApplicationManager = new Ext.AbstractManager({ register: function(name, options) { if (Ext.isObject(name)) { options = name; } else { options.name = name; } var application = new Ext.Application(options); this.all.add(application); return application; } }); /** * Shorthand for {@link Ext.ApplicationManager#register} * 根据指定的配置项对象创建一个Application实例。请参阅{@link Ext.Application}了解完整的例子。 * Creates a new Application class from the specified config object. See {@link Ext.Application} for full examples. * * @param {Object} config 一个你打算为你的程序所定义的配置项对象。A configuration object for the Model you wish to create. * @return {Ext.Application} 刚创建的Application对象。The newly created Application * @member Ext * @method regApplication */ Ext.regApplication = function() { return Ext.ApplicationManager.register.apply(Ext.ApplicationManager, 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.ControllerManager * @extends Ext.AbstractManager * @singleton * * <p> * 对全体已登记的控制作跟踪。开发者应该很少用到这个类。 * 其原理是{@link Ext.AbstractManager AbstractManager}加上一个自定义的{@link #register}函数, * 用于设置控制器及其关联的{@link Ext.Application application}。 * Keeps track of all of the registered controllers. This should very rarely need to be used by developers. This * is simply an {@link Ext.AbstractManager AbstractManager} with a custom {@link #register} function which sets up * the controller and its linked {@link Ext.Application application}.</p> */ Ext.ControllerManager = new Ext.AbstractManager({ register: function(id, options) { options.id = id; var controller = new Ext.Controller(options); var application = Ext.ApplicationManager.all.items[0]; if (application) { controller.application = application; } if (controller.init) { controller.init(); } this.all.add(controller); return controller; } }); /** * {@link Ext.ControllerMgr#register}的快捷方式。以特定的配置项对象创建一个新的控制器类。参阅{@link Ext.Controller}的完整例子。 * Shorthand for {@link Ext.ControllerMgr#register} * Creates a new Controller class from the specified config object. See {@link Ext.Controller} for full examples. * * @param {Object} config 你想创建控制器其配置项对象。A configuration object for the Controller you wish to create. * @return {Ext.Controller} 新登记的控制器。The newly registered Controller * @member Ext * @method regController */ Ext.regController = function() { return Ext.ControllerManager.register.apply(Ext.ControllerManager, 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.Application * @extends Ext.util.Observable * *<p> * 表示整个Sencha的应用程序。对于大多数程序而言,它至少包括有应用程序的名称和一个启动函数: * Represents a Sencha Application. Most Applications consist of at least the application's name and a launch * function:</p> * <pre><code> new Ext.Application({ name: 'MyApp', launch: function() { this.viewport = new Ext.Panel({ fullscreen: true, id : 'mainPanel', layout: 'card', items : [ { html: '欢迎来到我们的程序!Welcome to My App!' } ] }); } }); </code></pre> * * <p> 实例化新的程序的时候,会自动依据配置项{@link #name}定义一个全局变量,设置程序的命名空间,包括有视图的命名空间、store的命名空间和控制器的命名空间。Instantiating a new application automatically creates a global variable using the configured {@link #name} * property and sets up namespaces for views, stores, models and controllers within the app:</p> * <pre> <code> // 当创建程序就是定义下面的代码 this code is run internally automatically when creating the app {@link Ext.ns}('MyApp', 'MyApp.views', 'MyApp.stores', 'MyApp.models', 'MyApp.controllers'); </code></pre> * * <p> 启动函数其职责一般是创建应用程序的Viewport视图和任何程序需要启动的步骤。启动函数应该只会运行一次。The launch function usually creates the Application's Viewport and runs any actions the Application needs to * perform when it boots up. The launch function is only expected to be run once.</p> * * <p><u>路由与历史的支持 Routes and history support</u></p> * * <p> Ext应用程序提供紧密的关联与历史的支持,允许你的用户在应用程序中,既可以使用“后退”按钮,也可以“刷新”页面,哪怕关闭回来后相同的屏幕。紧密的历史回溯依靠路由引擎(Routing Engine)的支持,将url映射到controller/action。这里是一个定义路由的例子:Sencha Applications provide in-app deep linking and history support, allowing your users both to use the back * button inside your application and to refresh the page and come back to the same screen even after navigating. * In-app history support relies on the Routing engine, which maps urls to controller/action pairs. Here's an example * route definition:</p> * <pre><code> //Note the # in the url examples below Ext.Router.draw(function(map) { //maps the url http://mydomain.com/#dashboard to the home controller's index action map.connect('dashboard', {controller: 'home', action: 'index'}); //fallback route - would match routes like http://mydomain.com/#users/list to the 'users' controller's //'list' action map.connect(':controller/:action'); }); </code></pre> * * <p> 如果你透过Sencha Command工具生成脚本来导出Sencha程序,那么将会看到这个文件已经位于程序目录的app/routes.js。历史驱动可以指定{@link #defaultUrl} 配置项,在当前没有设置url的情况下派遣到默认的url。If you generated your Sencha app using the Sencha Command application generator script, you'll see this file is * already present in your application's app/routes.js file. History-driven apps can specify the {@link #defaultUrl} * configuration option, which will dispatch to that url if no url is currently set:</p> * <pre><code> new Ext.Application({ name: 'MyApp', defaultUrl: 'dashboard' }); </code></pre> * * <p><u>Application profiles</u></p> * * <p> Applications支持为程序提供多个profiles并且可以依据此自配置。这里我们设置了Application的三个profile,一个是手机上的,另外两个是table PC的landscape和portrait方向。Applications support multiple app profiles and reconfigure itself accordingly. Here we set up an Application * with 3 profiles - one if the device is a phone, one for tablets in landscape orientation and one for tablets in * portrait orientation:</p> * <pre><code> new Ext.Application({ name: 'MyApp', profiles: { phone: function() { return Ext.is.Phone; }, tabletPortrait: function() { return Ext.is.Tablet && Ext.orientation == 'portrait'; }, tabletLandscape: function() { return Ext.is.Tablet && Ext.orientation == 'landscape'; } } }); </code></pre> * * <p> 当Application 检查其prfile的列表时候,第一个返回true的那个函数表示就是当前的函数。当profile发生变化时,Application会自动检测哪一个profile使用(比如,在tablet方向从portrait变为landscape模式的时候),并触发{@link #profilechange}事件。同时也会通知页面上所有的{@link Ext.Component Components} 已经改变了当前的profile,进而调用组件的{@link Ext.Component#setProfile setProfile}函数。setProfile函数一个空函数,你可以为你的组件在交互不同设备写入新的实现。When the Application checks its list of profiles, the first function that returns true becomes the current profile. * The Application will normally automatically detect when a profile change has occurred (e.g. if a tablet is rotated * from portrait to landscape mode) and fire the {@link #profilechange} event. It will also by default inform all * {@link Ext.Component Components} on the page that the current profile has changed by calling their * {@link Ext.Component#setProfile setProfile} functions. The setProfile function is left as an empty function for you * to implement if your component needs to react to different device/application profiles.</p> * * <p> 可用通过{@link #getProfile}获取当前的profile。如果Application没有成功检测profile发生改变可以手动执行{@link #determineProfile} 。The current profile can be found using {@link #getProfile}. If the Application does not correctly detect device * profile changes, calling the {@link #determineProfile} function will force it to re-check.</p */ Ext.Application = Ext.extend(Ext.util.Observable, { /** * @cfg {String} name * Application的名称。起名最好与这个程序所使用的单个全局变量的那个名称一致,最好不要有空格。 * The name of the Application. This should be the same as the single global variable that the * application uses, and should not contain spaces */ /** * @cfg {Object} scope {@link #launch}函数的作用域。默认为Application实例。 * The scope to execute the {@link #launch} function in. Defaults to the Application * instance. */ scope: undefined, /** * @cfg {Boolean} useHistory True表示为自动初始化Ext.History的支持(默认为true)。True to automatically set up Ext.History support (defaults to true) */ useHistory: true, /** * @cfg {String} defaultUrl 当应用程序第一次加载,转向的url。默认是undefined。 When the app is first loaded, this url will be redirected to. Defaults to undefined */ /** * @cfg {Boolean} autoUpdateComponentProfiles * 若为true便在每个组件上自动调用{@link Ext.Component#setProfile},无论application/device的profile有否变动(默认为true)。 * If true, automatically calls {@link Ext.Component#setProfile} on * all components whenever a application/device profile change is detected (defaults to true) */ autoUpdateComponentProfiles: true, /** * @cfg {Boolean} setProfilesOnLaunch * 若为true,则在调用启动函数便检测当前程序的profile。默认为true。 * If true, determines the current application profile on launch and calls * {@link #updateComponentProfiles}. Defaults to true */ setProfilesOnLaunch: true, /** * @cfg {Object} profiles * 程序可支持的profile的集合。请参阅介绍的列子。 * A set of named profile specifications that this application supports. See the intro * docs for an example */ constructor: function(config) { this.addEvents( /** * @event launch * 当程序启动时触发该函数。 * Fires when the application is launched * @param {Ext.Application} app Application实例。The Application instance */ 'launch', /** * @event beforeprofilechange * 当程序的profile检测到改变的时候之后并且在通知应用程序的组件之前触发该事件。任何事件侦听器返回false的是取消程序自动更新(参阅{@link #autoUpdateComponentProfiles})。 * Fires when a change in Application profile has been detected, but before any action is taken to * update the application's components about the change. Return false from any listener to cancel the * automatic updating of application components (see {@link #autoUpdateComponentProfiles}) * @param {String} profile 新profile的名称。The name of the new profile * @param {String} oldProfile 旧profile的名称(可能是undefined)。The name of the old profile (may be undefined) */ 'beforeprofilechange', /** * @event profilechange * 当程序的profile检测到改变的时候并且已通知应用程序的组件之后触发该事件。如果需要可以在这里执行事件侦听器。 * Fires when a change in Applicatino profile has been detected and the application's components have * already been informed. Listeners can perform additional processing here if required * @param {String} profile 新profile的名称。The name of the new profile * @param {String} oldProfile 旧profile的名称(可能是undefined)。The name of the old profile (may be undefined) */ 'profilechange' ); Ext.Application.superclass.constructor.call(this, config); this.bindReady(); var name = this.name; if (name) { window[name] = this; Ext.ns( name, name + ".views", name + ".stores", name + ".models", name + ".controllers" ); } if (Ext.addMetaTags) { Ext.addMetaTags(config); } }, /** * @private * 我们不再构造器中写而是在这里写为了可以我们可以取消测试环境。 * We bind this outside the constructor so that we can cancel it in the test environment */ bindReady : function() { Ext.onReady(this.onReady, this); }, /** *当页面完成加载后自动调用该函数。这是一个空的函数表示可以由每一个程序自己来制定情况。 * Called automatically when the page has completely loaded. This is an empty function that should be * overridden by each application that needs to take action on page load * @property launch * @type Function * @param {String} profile 检测的{@link #profiles application profile}。The detected {@link #profiles application profile} * @return {Boolean} 默认下,在运行完毕了启动函数后,Application会立刻派遣已配置好的启动控制器和动作。返回false阻止该行为发生。By default, the Application will dispatch to the configured startup controller and * action immediately after running the launch function. Return false to prevent this behavior. */ launch: Ext.emptyFn, /** * @cfg {Boolean/String} useLoadMask True表示当DOM可用时自动移除程序的。true的话也表示需要一个id为"loading-mask"的div元素。如果需要自定义loading mask元素的话,可以传入一个DOM元素的id。默认为false。loading mask。True to automatically remove an application loading mask when the * DOM is ready. If set to true, this expects a div called "loading-mask" to be present in the body. * Pass the id of some other DOM node if using a custom loading mask element. Defaults to false. */ useLoadMask: false, /** * @cfg {Number} loadMaskFadeDuration * load mask减退的毫秒数。默认为1000。 * The number of milliseconds the load mask takes to fade out. Defaults to 1000 */ loadMaskFadeDuration: 1000, /** * @cfg {Number} loadMaskRemoveDuration * 当开始了{@link #loadMaskFadeDuration fadeout}之后,进行多久就移除mask的毫秒数。默认为1050. * The number of milliseconds until the load mask is removed after starting the * {@link #loadMaskFadeDuration fadeout}. Defaults to 1050. */ loadMaskRemoveDuration: 1050, /** * 派遣一个给定的 controller/action 组合,带有可选的参数。 * Dispatches to a given controller/action combo with optional arguments. * @param {Object} options 对象。包含指向要派遣控制器与动作的字符串,还可以有可选的参数数组。Object containing strings referencing the controller and action to dispatch * to, plus optional args array * @return {Boolean} True表示为找到控制器和动作,false则没有。True if the controller and action were found and dispatched to, false otherwise */ dispatch: function(options) { return Ext.dispatch(options); }, /** * @private * 初始化loading阴影,如果通过onReady设置了{@link #useLoadMask}会自动调用。 * Initializes the loading mask, called automatically by onReady if {@link #useLoadMask} is configured */ initLoadMask: function() { var useLoadMask = this.useLoadMask, defaultId = 'loading-mask', loadMaskId = typeof useLoadMask == 'string' ? useLoadMask : defaultId; if (useLoadMask) { if (loadMaskId == defaultId) { Ext.getBody().createChild({id: defaultId}); } var loadingMask = Ext.get('loading-mask'), fadeDuration = this.loadMaskFadeDuration, hideDuration = this.loadMaskRemoveDuration; Ext.defer(function() { loadingMask.addCls('fadeout'); Ext.defer(function() { loadingMask.remove(); }, hideDuration); }, fadeDuration); } }, /** * @private * 当DOM可用是调用的函数。调用程序指定的启动函数和派遣第一个 控制器/动作 的组合。 * Called when the DOM is ready. Calls the application-specific launch function and dispatches to the * first controller/action combo */ onReady: function() { var History = Ext.History, useHistory = History && this.useHistory, profile = this.determineProfile(true); if (this.useLoadMask) { this.initLoadMask(); } Ext.EventManager.onOrientationChange(this.determineProfile, this); if (useHistory) { this.historyForm = Ext.getBody().createChild({ id : 'history-form', cls : 'x-hide-display', style : 'display: none;', tag : 'form', action: '#', children: [ { tag: 'div', children: [ { tag : 'input', id : History.fieldId, type: 'hidden' }, { tag: 'iframe', id : History.iframeId } ] } ] }); History.init(); History.on('change', this.onHistoryChange, this); var token = History.getToken(); if (this.launch.call(this.scope || this, profile) !== false) { Ext.redirect(token || this.defaultUrl || {controller: 'application', action: 'index'}); } } else { this.launch.call(this.scope || this, profile); } this.launched = true; this.fireEvent('launch', this); if (this.setProfilesOnLaunch) { this.updateComponentProfiles(profile); } return this; }, /** * 调用每个配置好的{@link #profile}函数,标记第一个返回的为当前应用程序的profile。如果profile有变化则触发“beforeprofilechange”和“profilechange”事件。 * Calls each configured {@link #profile} function, marking the first one that returns true as the current * application profile. Fires the 'beforeprofilechange' and 'profilechange' events if the profile has changed * @param {Boolean} silent true表示为不触发profilechange事件。 * If true, the events profilechange event is not fired */ determineProfile: function(silent) { var currentProfile = this.currentProfile, profiles = this.profiles, name; for (name in profiles) { if (profiles[name]() === true) { if (name != currentProfile && this.fireEvent('beforeprofilechange', name, currentProfile) !== false) { if (this.autoUpdateComponentProfiles) { this.updateComponentProfiles(name); } if (silent !== true) { this.fireEvent('profilechange', name, currentProfile); } } this.currentProfile = name; break; } } return this.currentProfile; }, /** * @private * 为每个组件设置页面上的profile。 * Sets the profile on every component on the page. Will probably refactor this to something * less hacky. * @param {String} profile 新的profile名称。The new profile name */ updateComponentProfiles: function(profile) { var components = Ext.ComponentMgr.all.items, length = components.length, i; for (i = 0; i < length; i++) { if (components[i].setProfile) { components[i].setProfile(profile); } } }, /** * 获取当前检测到的profile名称。 * Gets the name of the currently-detected application profile * @return {String} Profile名称。The profile name */ getProfile: function() { return this.currentProfile; }, /** * @private */ onHistoryChange: function(token) { return Ext.redirect(token); } });
JavaScript
/** * @class Ext.PluginMgr * <p>Provides a registry of available Plugin <i>classes</i> indexed by a mnemonic code known as the Plugin's ptype. * 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>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>For a list of all available <code>{@link Ext.Component#xtype xtypes}</code>, see {@link Ext.Component}.</p> * @singleton */ Ext.PluginMgr = new Ext.AbstractManager({ typeName: 'ptype', /** * Creates a new Plugin from the specified config object using the * config object's {@link Ext.component#ptype ptype} to determine the class to instantiate. * @param {Object} config A configuration object for the Plugin you wish to create. * @param {Constructor} defaultType The constructor to provide the default Plugin type if * the config object does not contain a <code>ptype</code>. (Optional if the config contains a <code>ptype</code>). * @return {Ext.Component} The newly instantiated Plugin. */ create : function(config, defaultType){ var PluginCls = this.types[config.ptype || defaultType]; if (PluginCls.init) { return PluginCls; } else { return new PluginCls(config); } }, /** * Returns all plugins registered with the given type. Here, 'type' refers to the type of plugin, not its ptype. * @param {String} type The type to search for * @param {Boolean} defaultsOnly True to only return plugins of this type where the plugin's isDefault property is truthy * @return {Array} All matching plugins */ findByType: function(type, defaultsOnly) { var matches = [], types = this.types; for (var name in types) { if (!types.hasOwnProperty(name)) { continue; } var item = types[name]; if (item.type == type && (!defaultsOnly || (defaultsOnly === true && item.isDefault))) { matches.push(item); } } return matches; } }); /** * Shorthand for {@link Ext.PluginMgr#registerType} * @param {String} ptype The {@link Ext.component#ptype mnemonic string} by which the Plugin class * may be looked up. * @param {Constructor} cls The new Plugin class. * @member Ext * @method preg */ Ext.preg = function() { return Ext.PluginMgr.registerType.apply(Ext.PluginMgr, arguments); };
JavaScript
Ext.applyIf(Ext.Element, { unitRe: /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i, camelRe: /(-[a-z])/gi, opacityRe: /alpha\(opacity=(.*)\)/i, propertyCache: {}, defaultUnit : "px", borders: {l: 'border-left-width', r: 'border-right-width', t: 'border-top-width', b: 'border-bottom-width'}, paddings: {l: 'padding-left', r: 'padding-right', t: 'padding-top', b: 'padding-bottom'}, margins: {l: 'margin-left', r: 'margin-right', t: 'margin-top', b: 'margin-bottom'}, addUnits : function(size) { if (size === "" || size == "auto" || size === null || size === undefined) { size = size || ''; } else if (!isNaN(size) || !this.unitRe.test(size)) { size = size + (this.defaultUnit || 'px'); } return size; }, /** * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) * @param {Number|String} box The encoded margins * @return {Object} An object with margin sizes for top, right, bottom and left */ parseBox : function(box) { if (typeof box != 'string') { box = box.toString(); } var parts = box.split(' '), ln = parts.length; if (ln == 1) { parts[1] = parts[2] = parts[3] = parts[0]; } else if (ln == 2) { parts[2] = parts[0]; parts[3] = parts[1]; } else if (ln == 3) { parts[3] = parts[1]; } return { top :parseFloat(parts[0]) || 0, right :parseFloat(parts[1]) || 0, bottom:parseFloat(parts[2]) || 0, left :parseFloat(parts[3]) || 0 }; }, /** * Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations * (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result) * @param {Number|String} box The encoded margins * @return {String} An string with unitized (px) metrics for top, right, bottom and left */ unitizeBox : function(box){ var A = this.addUnits, B = this.parseBox(box); return A( B.top ) + ' ' + A( B.right ) + ' ' + A( B.bottom ) + ' ' + A( B.left ); }, // private camelReplaceFn : function(m, a) { return a.charAt(1).toUpperCase(); }, /** * Normalizes CSS property keys from dash delimited to camel case JavaScript Syntax. * For example: * <ul> * <li>border-width -> borderWidth</li> * <li>padding-top -> paddingTop</li> * </ul> */ normalize : function(prop) { return this.propertyCache[prop] || (this.propertyCache[prop] = prop == 'float' ? 'cssFloat' : prop.replace(this.camelRe, this.camelReplaceFn)); }, /** * Retrieves the document height * @returns {Number} documentHeight */ getDocumentHeight: function() { return Math.max(!Ext.isStrict ? document.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight()); }, /** * Retrieves the document width * @returns {Number} documentWidth */ getDocumentWidth: function() { return Math.max(!Ext.isStrict ? document.body.scrollWidth : document.documentElement.scrollWidth, this.getViewportWidth()); }, /** * Retrieves the viewport height of the window. * @returns {Number} viewportHeight */ getViewportHeight: function(){ return window.innerHeight; }, /** * Retrieves the viewport width of the window. * @returns {Number} viewportWidth */ getViewportWidth : function() { return window.innerWidth; }, /** * Retrieves the viewport size of the window. * @returns {Object} object containing width and height properties */ getViewSize : function() { return { width: window.innerWidth, height: window.innerHeight }; }, /** * Retrieves the current orientation of the window. This is calculated by * determing if the height is greater than the width. * @returns {String} Orientation of window: 'portrait' or 'landscape' */ getOrientation : function() { if (Ext.supports.OrientationChange) { return (window.orientation == 0) ? 'portrait' : 'landscape'; } return (window.innerHeight > window.innerWidth) ? 'portrait' : 'landscape'; }, /** Returns the top Element that is located at the passed coordinates * Function description * @param {Number} x The x coordinate * @param {Number} x The y coordinate * @return {String} The found Element */ fromPoint: function(x, y) { return Ext.get(document.elementFromPoint(x, y)); } });
JavaScript
/** * @class Ext.Element */ Ext.Element.addMethods({ /** * Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child) * @param {String} selector The simple selector to test * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 50 || document.body) * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node * @return {HTMLElement} The matching DOM node (or null if no match was found) */ findParent : function(simpleSelector, maxDepth, returnEl) { var p = this.dom, b = document.body, depth = 0, stopEl; maxDepth = maxDepth || 50; if (isNaN(maxDepth)) { stopEl = Ext.getDom(maxDepth); maxDepth = Number.MAX_VALUE; } while (p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl) { if (Ext.DomQuery.is(p, simpleSelector)) { return returnEl ? Ext.get(p) : p; } depth++; p = p.parentNode; } return null; }, /** * Looks at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child) * @param {String} selector The simple selector to test * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body) * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node * @return {HTMLElement} The matching DOM node (or null if no match was found) */ findParentNode : function(simpleSelector, maxDepth, returnEl) { var p = Ext.fly(this.dom.parentNode, '_internal'); return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; }, /** * Walks up the dom looking for a parent node that matches the passed simple selector (e.g. div.some-class or span:first-child). * This is a shortcut for findParentNode() that always returns an Ext.Element. * @param {String} selector The simple selector to test * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body) * @return {Ext.Element} The matching DOM node (or null if no match was found) */ up : function(simpleSelector, maxDepth) { return this.findParentNode(simpleSelector, maxDepth, true); }, /** * Creates a {@link Ext.CompositeElement} for child nodes based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @return {CompositeElement/CompositeElement} The composite element */ select : function(selector, composite) { return Ext.Element.select(selector, this.dom, composite); }, /** * Selects child nodes based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @return {Array} An array of the matched nodes */ query : function(selector) { return Ext.DomQuery.select(selector, this.dom); }, /** * Selects a single child at any depth below this element based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false) * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true) */ down : function(selector, returnDom) { var n = Ext.DomQuery.selectNode(selector, this.dom); return returnDom ? n : Ext.get(n); }, /** * Selects a single *direct* child based on the passed CSS selector (the selector should not contain an id). * @param {String} selector The CSS selector * @param {Boolean} returnDom (optional) True to return the DOM node instead of Ext.Element (defaults to false) * @return {HTMLElement/Ext.Element} The child Ext.Element (or DOM node if returnDom = true) */ child : function(selector, returnDom) { var node, me = this, id; id = Ext.get(me).id; // Escape . or : id = id.replace(/[\.:]/g, "\\$0"); node = Ext.DomQuery.selectNode('#' + id + " > " + selector, me.dom); return returnDom ? node : Ext.get(node); }, /** * Gets the parent node for this element, optionally chaining up trying to match a selector * @param {String} selector (optional) Find a parent node that matches the passed simple selector * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element * @return {Ext.Element/HTMLElement} The parent node or null */ parent : function(selector, returnDom) { return this.matchNode('parentNode', 'parentNode', selector, returnDom); }, /** * Gets the next sibling, skipping text nodes * @param {String} selector (optional) Find the next sibling that matches the passed simple selector * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element * @return {Ext.Element/HTMLElement} The next sibling or null */ next : function(selector, returnDom) { return this.matchNode('nextSibling', 'nextSibling', selector, returnDom); }, /** * Gets the previous sibling, skipping text nodes * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element * @return {Ext.Element/HTMLElement} The previous sibling or null */ prev : function(selector, returnDom) { return this.matchNode('previousSibling', 'previousSibling', selector, returnDom); }, /** * Gets the first child, skipping text nodes * @param {String} selector (optional) Find the next sibling that matches the passed simple selector * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element * @return {Ext.Element/HTMLElement} The first child or null */ first : function(selector, returnDom) { return this.matchNode('nextSibling', 'firstChild', selector, returnDom); }, /** * Gets the last child, skipping text nodes * @param {String} selector (optional) Find the previous sibling that matches the passed simple selector * @param {Boolean} returnDom (optional) True to return a raw dom node instead of an Ext.Element * @return {Ext.Element/HTMLElement} The last child or null */ last : function(selector, returnDom) { return this.matchNode('previousSibling', 'lastChild', selector, returnDom); }, matchNode : function(dir, start, selector, returnDom) { if (!this.dom) return null; var n = this.dom[start]; while (n) { if (n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))) { return !returnDom ? Ext.get(n) : n; } n = n[dir]; } return null; } });
JavaScript
/** * @class Ext.Element */ Ext.Element.addMethods({ /** * Appends the passed element(s) to this element * @param {String/HTMLElement/Array/Element/CompositeElement} el * @return {Ext.Element} this */ appendChild : function(el) { return Ext.get(el).appendTo(this); }, /** * Appends this element to the passed element * @param {Mixed} el The new parent element * @return {Ext.Element} this */ appendTo : function(el) { Ext.getDom(el).appendChild(this.dom); return this; }, /** * Inserts this element before the passed element in the DOM * @param {Mixed} el The element before which this element will be inserted * @return {Ext.Element} this */ insertBefore : function(el) { el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el); return this; }, /** * Inserts this element after the passed element in the DOM * @param {Mixed} el The element to insert after * @return {Ext.Element} this */ insertAfter : function(el) { el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el.nextSibling); return this; }, /** * Inserts (or creates) an element (or DomHelper config) as the first child of this element * @param {Mixed/Object} el The id or element to insert or a DomHelper config to create and insert * @return {Ext.Element} The new child */ insertFirst : function(el, returnDom) { el = el || {}; if (el.nodeType || el.dom || typeof el == 'string') { // element el = Ext.getDom(el); this.dom.insertBefore(el, this.dom.firstChild); return !returnDom ? Ext.get(el) : el; } else { // dh config return this.createChild(el, this.dom.firstChild, returnDom); } }, /** * Inserts (or creates) the passed element (or DomHelper config) as a sibling of this element * @param {Mixed/Object/Array} el The id, element to insert or a DomHelper config to create and insert *or* an array of any of those. * @param {String} where (optional) 'before' or 'after' defaults to before * @param {Boolean} returnDom (optional) True to return the .;ll;l,raw DOM element instead of Ext.Element * @return {Ext.Element} The inserted Element. If an array is passed, the last inserted element is returned. */ insertSibling: function(el, where, returnDom){ var me = this, rt, isAfter = (where || 'before').toLowerCase() == 'after', insertEl; if(Ext.isArray(el)){ insertEl = me; Ext.each(el, function(e) { rt = Ext.fly(insertEl, '_internal').insertSibling(e, where, returnDom); if(isAfter){ insertEl = rt; } }); return rt; } el = el || {}; if(el.nodeType || el.dom){ rt = me.dom.parentNode.insertBefore(Ext.getDom(el), isAfter ? me.dom.nextSibling : me.dom); if (!returnDom) { rt = Ext.get(rt); } }else{ if (isAfter && !me.dom.nextSibling) { rt = Ext.DomHelper.append(me.dom.parentNode, el, !returnDom); } else { rt = Ext.DomHelper[isAfter ? 'insertAfter' : 'insertBefore'](me.dom, el, !returnDom); } } return rt; }, /** * Replaces the passed element with this element * @param {Mixed} el The element to replace * @return {Ext.Element} this */ replace : function(el) { el = Ext.get(el); this.insertBefore(el); el.remove(); return this; }, /** * Replaces this element with the passed element * @param {Mixed/Object} el The new element or a DomHelper config of an element to create * @return {Ext.Element} this */ replaceWith: function(el){ var me = this; if(el.nodeType || el.dom || typeof el == 'string'){ el = Ext.get(el); me.dom.parentNode.insertBefore(el, me.dom); }else{ el = Ext.DomHelper.insertBefore(me.dom, el); } delete Ext.cache[me.id]; Ext.removeNode(me.dom); me.id = Ext.id(me.dom = el); Ext.Element.addToCache(me.isFlyweight ? new Ext.Element(me.dom) : me); return me; }, /** * Creates the passed DomHelper config and appends it to this element or optionally inserts it before the passed child element. * @param {Object} config DomHelper element config object. If no tag is specified (e.g., {tag:'input'}) then a div will be * automatically generated with the specified attributes. * @param {HTMLElement} insertBefore (optional) a child element of this element * @param {Boolean} returnDom (optional) true to return the dom node instead of creating an Element * @return {Ext.Element} The new child element */ createChild : function(config, insertBefore, returnDom) { config = config || {tag:'div'}; if (insertBefore) { return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true); } else { return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); } }, /** * Creates and wraps this element with another element * @param {Object} config (optional) DomHelper element config object for the wrapper element or null for an empty div * @param {Boolean} returnDom (optional) True to return the raw DOM element instead of Ext.Element * @return {HTMLElement/Element} The newly created wrapper element */ wrap : function(config, returnDom) { var newEl = Ext.DomHelper.insertBefore(this.dom, config || {tag: "div"}, !returnDom); newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); return newEl; }, /** * Inserts an html fragment into this element * @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd. * @param {String} html The HTML fragment * @param {Boolean} returnEl (optional) True to return an Ext.Element (defaults to false) * @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted) */ insertHtml : function(where, html, returnEl) { var el = Ext.DomHelper.insertHtml(where, this.dom, html); return returnEl ? Ext.get(el) : el; } });
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 Array */ Ext.applyIf(Array.prototype, { /** * 检查对象是否存在于当前数组中。 * Checks whether or not the specified object exists in the array. * @param {Object} o 要检查的对象。The object to check for * @param {Number} from (可选的)开始搜索的位置。(Optional) The index at which to begin the search * @return {Number} 返回该对象在数组中的位置(不存在则返回-1)。The index of o in the array (or -1 if it is not found) */ indexOf: function(o, from) { var len = this.length; from = from || 0; from += (from < 0) ? len: 0; for (; from < len; ++from) { if (this[from] === o) { return from; } } return - 1; }, /** * 删除数组中指定对象。如果该对象不在数组中,则不进行操作。 * Removes the specified object from the array. If the object is not found nothing happens. * @param {Object} o 要移除的对象。The object to remove * @return {Array} 该数组。this array */ remove: function(o) { var index = this.indexOf(o); if (index != -1) { this.splice(index, 1); } return this; }, contains: function(o) { return this.indexOf(o) !== -1; } });
JavaScript
/** * @class Ext.EventManager * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides * several useful events directly. * See {@link Ext.EventObject} for more details on normalized event objects. * @singleton */ Ext.EventManager = { optionsRe: /^(?:capture|scope|delay|buffer|single|stopEvent|disableLocking|preventDefault|stopPropagation|normalized|args|delegate|horizontal|vertical|dragThreshold|holdThreshold|doubleTapThreshold|cancelThreshold|singleTapThreshold|fireClickEvent)$/, touchRe: /^(?:pinch|pinchstart|pinchend|tap|singletap|doubletap|swipe|swipeleft|swiperight|drag|dragstart|dragend|touchdown|touchstart|touchmove|touchend|taphold|tapstart|tapcancel)$/i, /** * Appends an event handler to an element. The shorthand version {@link #on} is equivalent. Typically you will * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version. * @param {String/HTMLElement} el The html element or id to assign the event handler to. * @param {String} eventName The name of the event to listen for. * @param {Function} handler The handler function the event invokes. This function is passed * the following parameters:<ul> * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li> * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event. * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li> * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li> * </ul> * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>. * @param {Object} options (optional) An object containing handler configuration properties. * This may contain any of the following properties:<ul> * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li> * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li> * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li> * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li> * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li> * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li> * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li> * <li>single : 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>buffer : 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> * <li>target : 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> * </ul><br> * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p> */ addListener : function(element, eventName, fn, scope, o){ // handle our listener config object syntax if (Ext.isObject(eventName)) { this.handleListenerConfig(element, eventName); return; } var dom = Ext.getDom(element); // if the element doesnt exist throw an error if (!dom){ throw "Error listening for \"" + eventName + '\". Element "' + element + '" doesn\'t exist.'; } if (!fn) { throw 'Error listening for "' + eventName + '". No handler function specified'; } var touch = this.touchRe.test(eventName); // create the wrapper function var wrap = this.createListenerWrap(dom, eventName, fn, scope, o, touch); // add all required data into the event cache this.getEventListenerCache(dom, eventName).push({ fn: fn, wrap: wrap, scope: scope }); if (touch) { Ext.gesture.Manager.addEventListener(dom, eventName, wrap, o); } else { // now add the event listener to the actual element! o = o || {}; dom.addEventListener(eventName, wrap, o.capture || false); } }, /** * Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version. * @param {String/HTMLElement} el The id or html element from which to remove the listener. * @param {String} eventName The name of the event. * @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. */ removeListener : function(element, eventName, fn, scope) { // handle our listener config object syntax if (Ext.isObject(eventName)) { this.handleListenerConfig(element, eventName, true); return; } var dom = Ext.getDom(element), cache = this.getEventListenerCache(dom, eventName), i = cache.length, j, listener, wrap, tasks; while (i--) { listener = cache[i]; if (listener && (!fn || listener.fn == fn) && (!scope || listener.scope === scope)) { wrap = listener.wrap; // clear buffered calls if (wrap.task) { clearTimeout(wrap.task); delete wrap.task; } // clear delayed calls j = wrap.tasks && wrap.tasks.length; if (j) { while (j--) { clearTimeout(wrap.tasks[j]); } delete wrap.tasks; } if (this.touchRe.test(eventName)) { Ext.gesture.Manager.removeEventListener(dom, eventName, wrap); } else { // now add the event listener to the actual element! dom.removeEventListener(eventName, wrap, false); } // remove listener from cache cache.splice(i, 1); } } }, /** * Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners} * directly on an Element in favor of calling this version. * @param {String/HTMLElement} el The id or html element from which to remove all event handlers. */ removeAll : function(element){ var dom = Ext.getDom(element), cache = this.getElementEventCache(dom), ev; for (ev in cache) { if (!cache.hasOwnProperty(ev)) { continue; } this.removeListener(dom, ev); } Ext.cache[dom.id].events = {}; }, purgeElement : function(element, recurse, eventName) { var dom = Ext.getDom(element), i = 0, len; if(eventName) { this.removeListener(dom, eventName); } else { this.removeAll(dom); } if(recurse && dom && dom.childNodes) { for(len = element.childNodes.length; i < len; i++) { this.purgeElement(element.childNodes[i], recurse, eventName); } } }, handleListenerConfig : function(element, config, remove) { var key, value; // loop over all the keys in the object for (key in config) { if (!config.hasOwnProperty(key)) { continue; } // if the key is something else then an event option if (!this.optionsRe.test(key)) { value = config[key]; // if the value is a function it must be something like click: function(){}, scope: this // which means that there might be multiple event listeners with shared options if (Ext.isFunction(value)) { // shared options this[(remove ? 'remove' : 'add') + 'Listener'](element, key, value, config.scope, config); } // if its not a function, it must be an object like click: {fn: function(){}, scope: this} else { // individual options this[(remove ? 'remove' : 'add') + 'Listener'](element, key, config.fn, config.scope, config); } } } }, getId : function(element) { // if we bind listeners to either the document or the window // we have to put them in their own id cache since they both // can't get id's on the actual element var skip = false, id; element = Ext.getDom(element); if (element === document || element === window) { skip = true; } id = Ext.id(element); if (!Ext.cache[id]){ Ext.Element.addToCache(new Ext.Element(element), id); if(skip){ Ext.cache[id].skipGarbageCollection = true; } } return id; }, // private createListenerWrap : function(dom, ename, fn, scope, o, touch) { o = !Ext.isObject(o) ? {} : o; var f = ["if(!window.Ext) {return;}"]; if (touch) { f.push('e = new Ext.TouchEventObjectImpl(e, args);'); } else { if(o.buffer || o.delay) { f.push('e = new Ext.EventObjectImpl(e);'); } else { f.push('e = Ext.EventObject.setEvent(e);'); } } if (o.delegate) { f.push('var t = e.getTarget("' + o.delegate + '", this);'); f.push('if(!t) {return;}'); } else { f.push('var t = e.target;'); } if (o.target) { f.push('if(e.target !== o.target) {return;}'); } if(o.stopEvent) { f.push('e.stopEvent();'); } else { if(o.preventDefault) { f.push('e.preventDefault();'); } if(o.stopPropagation) { f.push('e.stopPropagation();'); } } if(o.normalized === false) { f.push('e = e.browserEvent;'); } if(o.buffer) { f.push('(wrap.task && clearTimeout(wrap.task));'); f.push('wrap.task = setTimeout(function(){'); } if(o.delay) { f.push('wrap.tasks = wrap.tasks || [];'); f.push('wrap.tasks.push(setTimeout(function(){'); } // finally call the actual handler fn f.push('fn.call(scope || dom, e, t, o);'); if(o.single) { f.push('Ext.EventManager.removeListener(dom, ename, fn, scope);'); } if(o.delay) { f.push('}, ' + o.delay + '));'); } if(o.buffer) { f.push('}, ' + o.buffer + ');'); } var gen = new Function('e', 'o', 'fn', 'scope', 'ename', 'dom', 'wrap', 'args', f.join("\n")); return function(e, args) { gen.call(dom, e, o, fn, scope, ename, dom, arguments.callee, args); }; }, getEventListenerCache : function(element, eventName) { var eventCache = this.getElementEventCache(element); return eventCache[eventName] || (eventCache[eventName] = []); }, getElementEventCache : function(element) { var elementCache = Ext.cache[this.getId(element)]; return elementCache.events || (elementCache.events = {}); }, /** * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be * accessed shorthanded as Ext.onReady(). * @param {Function} fn The method the event invokes. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window. * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options * <code>{single: true}</code> be used so that the handler is removed on first invocation. */ onDocumentReady : function(fn, scope, options){ var me = this, readyEvent = me.readyEvent, intervalId; if(Ext.isReady){ // if it already fired readyEvent || (readyEvent = new Ext.util.Event()); readyEvent.addListener(fn, scope, options); readyEvent.fire(); readyEvent.listeners = []; // clearListeners no longer compatible. Force single: true? } else { if(!readyEvent) { readyEvent = me.readyEvent = new Ext.util.Event(); // the method that will actually fire the event and clean up any listeners and intervals var fireReady = function() { Ext.isReady = true; //document.removeEventListener('DOMContentLoaded', arguments.callee, false); window.removeEventListener('load', arguments.callee, false); // remove interval if there is one if (intervalId) { clearInterval(intervalId); } // Put this in a timeout to give the browser a chance to hide address // bars or do other things that would screw up viewport measurements setTimeout(function() { Ext.supports.init(); //Ext.TouchEventManager.init(); Ext.gesture.Manager.init(); Ext.orientation = Ext.Element.getOrientation(); // fire the ready event!! readyEvent.fire({ orientation: Ext.orientation, width: Ext.Element.getViewportWidth(), height: Ext.Element.getViewportHeight() }); readyEvent.listeners = []; }, 50); }; // for browsers that support DOMContentLoaded //document.addEventListener('DOMContentLoaded', fireReady, false); // // even though newer versions support DOMContentLoaded, we have to be sure intervalId = setInterval(function(){ if(/loaded|complete/.test(document.readyState)) { clearInterval(intervalId); intervalId = null; fireReady(); } }, 10); // final fallback method window.addEventListener('load', fireReady, false); } options = options || {}; options.delay = options.delay || 1; readyEvent.addListener(fn, scope, options); } }, /** * Adds a listener to be notified when the browser window is resized and provides resize event buffering (50 milliseconds), * passes new viewport width and height to handlers. * @param {Function} fn The handler function the window resize event invokes. * @param {Object} scope The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window. * @param {boolean} options Options object as passed to {@link Ext.Element#addListener} */ onWindowResize : function(fn, scope, options) { var me = this, resizeEvent = me.resizeEvent; if(!resizeEvent){ me.resizeEvent = resizeEvent = new Ext.util.Event(); var onResize = function() { resizeEvent.fire(Ext.Element.getViewportWidth(), Ext.Element.getViewportHeight()); }; this.addListener(window, 'resize', onResize, this); } resizeEvent.addListener(fn, scope, options); }, onOrientationChange : function(fn, scope, options) { var me = this, orientationEvent = me.orientationEvent; if (!orientationEvent) { me.orientationEvent = orientationEvent = new Ext.util.Event(); var onOrientationChange = function(viewport, size) { Ext.orientation = Ext.Viewport.getOrientation(); orientationEvent.fire(Ext.orientation, size.width, size.height); }; Ext.Viewport.on('resize', onOrientationChange, this); } orientationEvent.addListener(fn, scope, options); }, unOrientationChange : function(fn, scope, options) { var me = this, orientationEvent = me.orientationEvent; if (orientationEvent) { orientationEvent.removeListener(fn, scope, options); } } }; /** * Appends an event handler to an element. Shorthand for {@link #addListener}. * @param {String/HTMLElement} el The html element or id to assign the event handler to * @param {String} eventName The name of the event to listen for. * @param {Function} handler The handler function the event invokes. * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>. * @param {Object} options (optional) An object containing standard {@link #addListener} options * @member Ext.EventManager * @method on */ Ext.EventManager.on = Ext.EventManager.addListener; /** * Removes an event handler from an element. Shorthand for {@link #removeListener}. * @param {String/HTMLElement} el The id or html element from which to remove the listener. * @param {String} eventName The name of the event. * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} 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. * @member Ext.EventManager * @method un */ Ext.EventManager.un = Ext.EventManager.removeListener; /** * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}. * @param {Function} fn The method the event invokes. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window. * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options * <code>{single: true}</code> be used so that the handler is removed on first invocation. * @member Ext * @method onReady */ Ext.onReady = Ext.EventManager.onDocumentReady; Ext.EventObjectImpl = Ext.extend(Object, { constructor : function(e) { if (e) { this.setEvent(e.browserEvent || e); } }, /** @private */ setEvent : function(e){ var me = this; if (e == me || (e && e.browserEvent)){ // already wrapped return e; } me.browserEvent = e; if(e) { me.type = e.type; // cache the target for the delayed and or buffered events var node = e.target; me.target = node && node.nodeType == 3 ? node.parentNode : node; // same for XY me.xy = [e.pageX, e.pageY]; me.timestamp = e.timeStamp; } else { me.target = null; me.xy = [0, 0]; } return me; }, /** * Stop the event (preventDefault and stopPropagation) */ stopEvent : function(){ this.stopPropagation(); this.preventDefault(); }, /** * Prevents the browsers default handling of the event. */ preventDefault : function(){ if(this.browserEvent) { this.browserEvent.preventDefault(); } }, /** * Cancels bubbling of the event. */ stopPropagation : function() { if(this.browserEvent) { this.browserEvent.stopPropagation(); } }, /** * 获取事件X坐标。 * Gets the x coordinate of the event. * @return {Number} */ getPageX : function(){ return this.xy[0]; }, /** * 获取事件Y坐标。 * Gets the y coordinate of the event. * @return {Number} */ getPageY : function(){ return this.xy[1]; }, /** * 获取事件的页面坐标。 * Gets the page coordinates of the event. * @return {Array} xy值,格式[x, y]。The xy values like [x, y] */ getXY : function(){ return this.xy; }, /** * 获取事件的目标对象。 * Gets the target for the event. * @param {String} selector (可选的) 一个简易的选择符,用于筛选目标或查找目标的父级元素。(optional) A simple selector to filter the target or look for an ancestor of the target * @param {Number/Mixed} maxDepth (可选的)搜索的最大深度(数字或是元素,默认为10||document.body)。(optional) The max depth to search as a number or element (defaults to 10 || document.body) * @param {Boolean} returnEl (可选的) True表示为返回Ext.Element的对象而非DOM节点。(optional) True to return a Ext.Element object instead of DOM node * @return {HTMLelement} */ /** * Gets the target for the event. * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target * @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 10 || document.body) * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node * @return {HTMLelement} */ getTarget : function(selector, maxDepth, returnEl) { return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target); }, getTime : function() { return this.timestamp; } }); /** * @class Ext.EventObject * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject * wraps the browser's native event-object normalizing cross-browser differences, * such as which mouse button is clicked, keys pressed, mechanisms to stop * event-propagation along with a method to prevent default actions from taking place. * <p>For example:</p> * <pre><code> function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject e.preventDefault(); var target = e.getTarget(); // same as t (the target HTMLElement) ... } var myDiv = {@link Ext#get Ext.get}("myDiv"); // get reference to an {@link Ext.Element} myDiv.on( // 'on' is shorthand for addListener "click", // perform an action on click of myDiv handleClick // reference to the action handler ); // other methods to do the same: Ext.EventManager.on("myDiv", 'click', handleClick); Ext.EventManager.addListener("myDiv", 'click', handleClick); </code></pre> * @singleton */ Ext.EventObject = new Ext.EventObjectImpl();
JavaScript
/** * @class Ext * Ext核心工具与函数 * @singleton */ /** * @class Ext * Ext core utilities and functions. * @singleton */ if (typeof Ext === "undefined") { Ext = {}; } /** * 复制config对象的所有属性到obj(第一个参数为obj,第二个参数为config)。 * Copies all the properties of config to obj. * @param {Object} object 属性接受方对象。The receiver of the properties * @param {Object} config 属性源对象。The source of the properties * @param {Object} defaults 默认对象,如果该参数存在,obj将会得到那些defaults有而config没有的属性。A different object that will also be applied for default values * @return {Object} returns obj * @member Ext apply */ Ext.apply = (function() { // IE doesn't recognize that toString (and valueOf) method as explicit one but it "thinks" that's a native one. for(var key in {valueOf:1}) { return function(object, config, defaults) { // no "this" reference for friendly out of scope calls if (defaults) { Ext.apply(object, defaults); } if (object && config && typeof config === 'object') { for (var key in config) { object[key] = config[key]; } } return object; }; } return function(object, config, defaults) { // no "this" reference for friendly out of scope calls if (defaults) { Ext.apply(object, defaults); } if (object && config && typeof config === 'object') { for (var key in config) { object[key] = config[key]; } if (config.toString !== Object.prototype.toString) { object.toString = config.toString; } if (config.valueOf !== Object.prototype.valueOf) { object.valueOf = config.valueOf; } } return object; }; })(); Ext.apply(Ext, { platformVersion: '0.2', platformVersionDetail: { major: 0, minor: 2, patch: 0 }, userAgent: navigator.userAgent.toLowerCase(), cache: {}, idSeed: 1000, BLANK_IMAGE_URL : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', isStrict: document.compatMode == "CSS1Compat", windowId: 'ext-window', documentId: 'ext-document', /** * 反复使用的空函数。 * A reusable empty function * @property * @type Function */ emptyFn : function() {}, /** * 判断页面是否运行在SSL状态。 * True if the page is running over SSL * @type Boolean */ isSecure : /^https/i.test(window.location.protocol), /** * 页面是否完全被初始化,并可供使用。 * True when the document is fully initialized and ready for action * @type Boolean */ isReady : false, /** * 是否自动定时清除孤立的Ext.Elements缓存(默认为是)。 * True to automatically uncache orphaned Ext.Elements periodically (defaults to true) * @type Boolean */ enableGarbageCollector : true, /** * 是否在垃圾回收期间自动清除事件监听器(默认为true)。 * True to automatically purge event listeners during garbageCollection (defaults to true). * @type Boolean */ enableListenerCollection : true, /** * 复制所有config的属性至obj,如果obj已有该属性,则不复制(第一个参数为obj,第二个参数为config)。 * Copies all the properties of config to obj if they don't already exist. * @param {Object} obj 接受方对象。The receiver of the properties * @param {Object} config 源对象。The source of the properties * @return {Object} returns obj */ applyIf : function(object, config) { var property, undefined; if (object) { for (property in config) { if (object[property] === undefined) { object[property] = config[property]; } } } return object; }, /** * 重绘张页面。该方法解决了移动Safari的绘图问题。 * Repaints the whole page. This fixes frequently encountered painting issues in mobile Safari. */ repaint : function() { var mask = Ext.getBody().createChild({ cls: 'x-mask x-mask-transparent' }); setTimeout(function() { mask.remove(); }, 0); }, /** * 对页面元素生成唯一id,如果该元素已存在id,则不会再生成。 * Generates unique ids. If the element already has an id, it is unchanged * @param {Mixed} el (可选的) 将要生成id的元素。(optional)The element to generate an id for * @param {String} prefix (可选的) 该id的前缀(默认为 "ext-gen")。(optional) Id prefix (defaults "ext-gen") * @return {String} 生成的Id。The generated Id. */ id : function(el, prefix) { el = Ext.getDom(el) || {}; if (el === document) { el.id = this.documentId; } else if (el === window) { el.id = this.windowId; } el.id = el.id || ((prefix || 'ext-gen') + (++Ext.idSeed)); return el.id; }, /** * <p>Extends one class to create a subclass and optionally overrides members with the passed literal. This method * also adds the function "override()" to the subclass that can be used to override members of the class.</p> * For example, to create a subclass of Ext GridPanel: * <pre><code> MyGridPanel = Ext.extend(Ext.grid.GridPanel, { constructor: function(config) { // Create configuration for this Grid. var store = new Ext.data.Store({...}); var colModel = new Ext.grid.ColumnModel({...}); // Create a new config object containing our computed properties // *plus* whatever was in the config parameter. config = Ext.apply({ store: store, colModel: colModel }, config); MyGridPanel.superclass.constructor.call(this, config); // Your postprocessing here }, yourMethod: function() { // etc. } }); </code></pre> * * <p>This function also supports a 3-argument call in which the subclass's constructor is * passed as an argument. In this form, the parameters are as follows:</p> * <div class="mdetail-params"><ul> * <li><code>subclass</code> : Function <div class="sub-desc">The subclass constructor.</div></li> * <li><code>superclass</code> : Function <div class="sub-desc">The constructor of class being extended</div></li> * <li><code>overrides</code> : Object <div class="sub-desc">A literal with members which are copied into the subclass's * prototype, and are therefore shared among all instances of the new class.</div></li> * </ul></div> * * @param {Function} superclass The constructor of class being extended. * @param {Object} overrides <p>A literal with members which are copied into the subclass's * prototype, and are therefore shared between all instances of the new class.</p> * <p>This may contain a special member named <tt><b>constructor</b></tt>. This is used * to define the constructor of the new class, and is returned. If this property is * <i>not</i> specified, a constructor is generated and returned which just calls the * superclass's constructor passing on its parameters.</p> * <p><b>It is essential that you call the superclass constructor in any provided constructor. See example code.</b></p> * @return {Function} The subclass constructor from the <code>overrides</code> parameter, or a generated one if not provided. */ extend : function() { // inline overrides var inlineOverrides = function(o){ for (var m in o) { if (!o.hasOwnProperty(m)) { continue; } this[m] = o[m]; } }; var objectConstructor = Object.prototype.constructor; return function(subclass, superclass, overrides){ // First we check if the user passed in just the superClass with overrides if (Ext.isObject(superclass)) { overrides = superclass; superclass = subclass; subclass = overrides.constructor != objectConstructor ? overrides.constructor : function(){ superclass.apply(this, arguments); }; } if (!superclass) { throw "Attempting to extend from a class which has not been loaded on the page."; } // We create a new temporary class var F = function(){}, subclassProto, superclassProto = superclass.prototype; F.prototype = superclassProto; subclassProto = subclass.prototype = new F(); subclassProto.constructor = subclass; subclass.superclass = superclassProto; if(superclassProto.constructor == objectConstructor){ superclassProto.constructor = superclass; } subclass.override = function(overrides){ Ext.override(subclass, overrides); }; subclassProto.superclass = subclassProto.supr = (function(){ return superclassProto; }); subclassProto.override = inlineOverrides; subclassProto.proto = subclassProto; subclass.override(overrides); subclass.extend = function(o) { return Ext.extend(subclass, o); }; return subclass; }; }(), /** * 在类上添加overrides指定的方法(多个方法),同名则覆盖,例如: * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name. * Usage:<pre><code> Ext.override(MyClass, { newMethod1: function(){ // etc. }, newMethod2: function(foo){ // etc. } }); </code></pre> * @param {Object} origclass 要override的类。The class to override * @param {Object} overrides 加入到origClass的函数列表。这应该是一个包含一个或多个方法的对象。The list of functions to add to origClass. This should be specified as an object literal * containing one or more methods. * @method override */ override : function(origclass, overrides) { Ext.apply(origclass.prototype, overrides); }, /** * 为变量创建其命名空间,这样类就有了“安身之所”,不是飘荡四处的“全局变量”。例如: * Creates namespaces to be used for scoping variables and classes so that they are not global. Usage: * <pre><code> Ext.namespace('Company', 'Company.data'); Ext.namespace('Company.data'); // 与上面的语法相等价,推荐上面的写法。equivalent and preferable to above syntax Company.Widget = function() { ... } Company.data.CustomStore = function(config) { ... } </code></pre> * @param {String} namespace1 命名空间一 * @param {String} namespace2 命名空间二 * @param {String} etc * @return {Object} 命名空间对象(如果传入多个对象,就返回最后一个命名空间对象)。The namespace object. (If multiple arguments are passed, this will be the last namespace created) * @method namespace */ namespace : function() { var ln = arguments.length, i, value, split, x, xln, parts, object; for (i = 0; i < ln; i++) { value = arguments[i]; parts = value.split("."); if (window.Ext) { object = window[parts[0]] = Object(window[parts[0]]); } else { object = arguments.callee.caller.arguments[0]; } for (x = 1, xln = parts.length; x < xln; x++) { object = object[parts[x]] = Object(object[parts[x]]); } } return object; }, /** * 把一个对象转换为一串以编码的URL字符。例如Ext.urlEncode({foo: 1, bar: 2});变为"foo=1&bar=2"。 * 可选地,如果遇到属性的类型是数组的话,那么该属性对应的key就是每个数组元素的key,逐一进行“结对的”编码。 * Takes an object and converts it to an encoded URL. e.g. Ext.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, * property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value. * @param {Object} o 要编码的对象。The object to encode * @param {String} pre (可选的)添加的url编码字符串的那个前缀。(optional) A prefix to add to the url encoded string * @return {String} */ urlEncode : function(o, pre) { var empty, buf = [], e = encodeURIComponent; Ext.iterate(o, function(key, item){ empty = Ext.isEmpty(item); Ext.each(empty ? key : item, function(val){ buf.push('&', e(key), '=', (!Ext.isEmpty(val) && (val != key || !empty)) ? (Ext.isDate(val) ? Ext.encode(val).replace(/"/g, '') : e(val)) : ''); }); }); if(!pre){ buf.shift(); pre = ''; } return pre + buf.join(''); }, /** * 把一个已经encoded的URL字符串转换为对象。如Ext.urlDecode("foo=1&bar=2"); 就是{foo: "1", bar: "2"}; * Takes an encoded URL and and converts it to an object. Example: * <pre><code> Ext.urlDecode("foo=1&bar=2"); // returns {foo: "1", bar: "2"} Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false); // returns {foo: "1", bar: ["2", "3", "4"]} </code></pre> * @param {String} string URL编码后的字符串 * @param {Boolean} overwrite (可选的)重复名称的就当作为数组,如果该项为true就禁止该功能(默认为false)。(optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false). * @return {Object} 成员实体。A literal with members */ urlDecode : function(string, overwrite) { if (Ext.isEmpty(string)) { return {}; } var obj = {}, pairs = string.split('&'), d = decodeURIComponent, name, value; Ext.each(pairs, function(pair) { pair = pair.split('='); name = d(pair[0]); value = d(pair[1]); obj[name] = overwrite || !obj[name] ? value : [].concat(obj[name]).concat(value); }); return obj; }, /** * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages. * @param {String} value The string to encode * @return {String} The encoded text */ htmlEncode : function(value) { return Ext.util.Format.htmlEncode(value); }, /** * Convert certain characters (&, <, >, and ') from their HTML character equivalents. * @param {String} value The string to decode * @return {String} The decoded text */ htmlDecode : function(value) { return Ext.util.Format.htmlDecode(value); }, /** * Appends content to the query string of a URL, handling logic for whether to place * a question mark or ampersand. * @param {String} url The URL to append to. * @param {String} s The content to append to the URL. * @return (String) The resulting URL */ urlAppend : function(url, s) { if (!Ext.isEmpty(s)) { return url + (url.indexOf('?') === -1 ? '?' : '&') + s; } return url; }, /** * Converts any iterable (numeric indices and a length property) into a true array * Don't use this on strings. IE doesn't support "abc"[0] which this implementation depends on. * For strings, use this instead: "abc".match(/./g) => [a,b,c]; * @param {Iterable} array the iterable object to be turned into a true Array. * @param {Number} start a number that specifies where to start the selection. * @param {Number} end a number that specifies where to end the selection. * @return (Array) array */ toArray : function(array, start, end) { return Array.prototype.slice.call(array, start || 0, end || array.length); }, /** * Iterates an array calling the supplied function. * @param {Array/NodeList/Mixed} array The array to be iterated. If this * argument is not really an array, the supplied function is called once. * @param {Function} fn The function to be called with each item. If the * supplied function returns false, iteration stops and this method returns * the current <code>index</code>. This function is called with * the following arguments: * <div class="mdetail-params"><ul> * <li><code>item</code> : <i>Mixed</i> * <div class="sub-desc">The item at the current <code>index</code> * in the passed <code>array</code></div></li> * <li><code>index</code> : <i>Number</i> * <div class="sub-desc">The current index within the array</div></li> * <li><code>allItems</code> : <i>Array</i> * <div class="sub-desc">The <code>array</code> passed as the first * argument to <code>Ext.each</code>.</div></li> * </ul></div> * @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed. * Defaults to the <code>item</code> at the current <code>index</code>util * within the passed <code>array</code>. * @return See description for the fn parameter. */ each : function(array, fn, scope) { if (Ext.isEmpty(array, true)) { return 0; } if (!Ext.isIterable(array) || Ext.isPrimitive(array)) { array = [array]; } for (var i = 0, len = array.length; i < len; i++) { if (fn.call(scope || array[i], array[i], i, array) === false) { return i; } } return true; }, /** * Iterates either the elements in an array, or each of the properties in an object. * <b>Note</b>: If you are only iterating arrays, it is better to call {@link #each}. * @param {Object/Array} object The object or array to be iterated * @param {Function} fn The function to be called for each iteration. * The iteration will stop if the supplied function returns false, or * all array elements / object properties have been covered. The signature * varies depending on the type of object being interated: * <div class="mdetail-params"><ul> * <li>Arrays : <tt>(Object item, Number index, Array allItems)</tt> * <div class="sub-desc"> * When iterating an array, the supplied function is called with each item.</div></li> * <li>Objects : <tt>(String key, Object value, Object)</tt> * <div class="sub-desc"> * When iterating an object, the supplied function is called with each key-value pair in * the object, and the iterated object</div></li> * </ul></divutil> * @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed. Defaults to * the <code>object</code> being iterated. */ iterate : function(obj, fn, scope) { if (Ext.isEmpty(obj)) { return; } if (Ext.isIterable(obj)) { Ext.each(obj, fn, scope); return; } else if (Ext.isObject(obj)) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { if (fn.call(scope || obj, prop, obj[prop], obj) === false) { return; } } } } }, /** * Plucks the value of a property from each item in the Array * // Example: Ext.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className] * * @param {Array|NodeList} arr The Array of items to pluck the value from. * @param {String} prop The property name to pluck from each element. * @return {Array} The value from each item in the Array. */ pluck : function(arr, prop) { var ret = []; Ext.each(arr, function(v) { ret.push(v[prop]); }); return ret; }, /** * Returns the current document body as an {@link Ext.Element}. * @return Ext.Element The document body */ getBody : function() { return Ext.get(document.body || false); }, /** * Returns the current document head as an {@link Ext.Element}. * @return Ext.Element The document head */ getHead : function() { var head; return function() { if (head == undefined) { head = Ext.get(DOC.getElementsByTagName("head")[0]); } return head; }; }(), /** * Returns the current HTML document object as an {@link Ext.Element}. * @return Ext.Element The document */ getDoc : function() { return Ext.get(document); }, /** * This is shorthand reference to {@link Ext.ComponentMgr#get}. * Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id} * @param {String} id The component {@link Ext.Component#id id} * @return Ext.Component The Component, <tt>undefined</tt> if not found, or <tt>null</tt> if a * Class was found. */ getCmp : function(id) { return Ext.ComponentMgr.get(id); }, /** * Returns the current orientation of the mobile device * @return {String} Either 'portrait' or 'landscape' */ getOrientation: function() { return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape'; }, isIterable : function(v) { if (!v) { return false; } //check for array or arguments if (Ext.isArray(v) || v.callee) { return true; } //check for node list type if (/NodeList|HTMLCollection/.test(Object.prototype.toString.call(v))) { return true; } //NodeList has an item and length property //IXMLDOMNodeList has nextNode method, needs to be checked first. return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length)) || false; }, /** * Utility method for validating that a value is numeric, returning the specified default value if it is not. * @param {Mixed} value Should be a number, but any type will be handled appropriately * @param {Number} defaultValue The value to return if the original value is non-numeric * @return {Number} Value, if numeric, else defaultValue */ num : function(v, defaultValue) { v = Number(Ext.isEmpty(v) || Ext.isArray(v) || typeof v == 'boolean' || (typeof v == 'string' && Ext.util.Format.trim(v).length == 0) ? NaN : v); return isNaN(v) ? defaultValue : v; }, /** * <p>Returns true if the passed value is empty.</p> * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul> * <li>null</li> * <li>undefined</li> * <li>an empty array</li> * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li> * </ul></div> * @param {Mixed} value The value to test * @param {Boolean} allowBlank (optional) true to allow empty strings (defaults to false) * @return {Boolean} */ isEmpty : function(value, allowBlank) { var isNull = value == null, emptyArray = (Ext.isArray(value) && !value.length), blankAllowed = !allowBlank ? value === '' : false; return isNull || emptyArray || blankAllowed; }, /** * Returns true if the passed value is a JavaScript array, otherwise false. * @param {Mixed} value The value to test * @return {Boolean} */ isArray : function(v) { return Object.prototype.toString.apply(v) === '[object Array]'; }, /** * Returns true if the passed object is a JavaScript date object, otherwise false. * @param {Object} object The object to test * @return {Boolean} */ isDate : function(v) { return Object.prototype.toString.apply(v) === '[object Date]'; }, /** * Returns true if the passed value is a JavaScript Object, otherwise false. * @param {Mixed} value The value to test * @return {Boolean} */ isObject : function(v) { return !!v && !v.tagName && Object.prototype.toString.call(v) === '[object Object]'; }, /** * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean. * @param {Mixed} value The value to test * @return {Boolean} */ isPrimitive : function(v) { return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v); }, /** * Returns true if the passed value is a JavaScript Function, otherwise false. * @param {Mixed} value The value to test * @return {Boolean} */ isFunction : function(v) { return Object.prototype.toString.apply(v) === '[object Function]'; }, /** * Returns true if the passed value is a number. Returns false for non-finite numbers. * @param {Mixed} value The value to test * @return {Boolean} */ isNumber : function(v) { return Object.prototype.toString.apply(v) === '[object Number]' && isFinite(v); }, /** * Returns true if the passed value is a string. * @param {Mixed} value The value to test * @return {Boolean} */ isString : function(v) { return typeof v === 'string'; }, /**util * Returns true if the passed value is a boolean. * @param {Mixed} value The value to test * @return {Boolean} */ isBoolean : function(v) { return Object.prototype.toString.apply(v) === '[object Boolean]'; }, /** * Returns true if the passed value is an HTMLElement * @param {Mixed} value The value to test * @return {Boolean} */ isElement : function(v) { return v ? !!v.tagName : false; }, /** * Returns true if the passed value is not undefined. * @param {Mixed} value The value to test * @return {Boolean} */ isDefined : function(v){ return typeof v !== 'undefined'; }, /** * 尝试去移除每个传入的对象,包括DOM,事件侦听者,并呼叫他们的destroy方法(如果存在)。 * 该方法主要接纳{@link Ext.Element}与{@link Ext.Component}类型的参数。 * 但理论上任何继承自Ext.util.Observable的子类都可以做为参数传入(支持传入多参)。 * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the * DOM (if applicable) and calling their destroy functions (if available). * This method is primarily intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of * {@link Ext.util.Observable} can be passed in. * Any number of elements and/or components can be passed into this function in a single call as separate arguments. * @param {Mixed} arg1 任意要销毁的{@link Ext.Element}或{@link Ext.Component}。An {@link Ext.Element} or {@link Ext.Component} to destroy * @param {Mixed} arg2 (可选的) * @param {Mixed} etc... (可选的) */ /** * Attempts to destroy any objects passed to it by removing all event listeners, removing them from the * DOM (if applicable) and calling their destroy functions (if available). This method is primarily * intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of * {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be * passed into this function in a single call as separate arguments. * @param {Mixed} arg1 An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy * @param {Mixed} arg2 (optional) * @param {Mixed} etc... (optional) */ destroy : function() { var ln = arguments.length, i, arg; for (i = 0; i < ln; i++) { arg = arguments[i]; if (arg) { if (Ext.isArray(arg)) { this.destroy.apply(this, arg); } else if (Ext.isFunction(arg.destroy)) { arg.destroy(); } else if (arg.dom) { arg.remove(); } } } } }); /** * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent * the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>). * @type String */ Ext.SSL_SECURE_URL = Ext.isSecure && 'about:blank'; Ext.ns = Ext.namespace; Ext.ns( 'Ext.util', 'Ext.data', 'Ext.list', 'Ext.form', 'Ext.menu', 'Ext.state', 'Ext.layout', 'Ext.app', 'Ext.ux', 'Ext.plugins', 'Ext.direct', 'Ext.lib', 'Ext.gesture' );
JavaScript
/** * @class Ext.lib.Panel * @extends Ext.Container * Shared Panel class */ Ext.lib.Panel = Ext.extend(Ext.Container, { /** * @cfg {String} baseCls * The base CSS class to apply to this panel's element (defaults to <code>'x-panel'</code>). */ baseCls : 'x-panel', /** * @cfg {Number/Boolean} bodyPadding * A shortcut for setting a padding style on the body element. The value can either be * a number to be applied to all sides, or a normal css string describing padding. * Defaults to <tt>undefined</tt>. */ /** * @cfg {Number/Boolean} bodyMargin * A shortcut for setting a margin style on the body element. The value can either be * a number to be applied to all sides, or a normal css string describing margins. * Defaults to <tt>undefined</tt>. */ /** * @cfg {Number/Boolean} bodyBorder * A shortcut for setting a border style on the body element. The value can either be * a number to be applied to all sides, or a normal css string describing borders. * Defaults to <tt>undefined</tt>. */ isPanel: true, componentLayout: 'dock', renderTpl: ['<div class="{baseCls}-body<tpl if="bodyCls"> {bodyCls}</tpl>"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>></div>'], /** * @cfg {Object/Array} dockedItems * A component or series of components to be added as docked items to this panel. * The docked items can be docked to either the top, right, left or bottom of a panel. * This is typically used for things like toolbars or tab bars: * <pre><code> var panel = new Ext.Panel({ fullscreen: true, dockedItems: [{ xtype: 'toolbar', dock: 'top', items: [{ text: 'Docked to the bottom' }] }] });</pre></code> */ initComponent : function() { this.addEvents( /** * @event bodyresize * Fires after the Panel has been resized. * @param {Ext.Panel} p the Panel which has been resized. * @param {Number} width The Panel body's new width. * @param {Number} height The Panel body's new height. */ 'bodyresize' // // inherited // 'activate', // // inherited // 'deactivate' ); Ext.applyIf(this.renderSelectors, { body: '.' + this.baseCls + '-body' }); Ext.lib.Panel.superclass.initComponent.call(this); }, // @private initItems : function() { Ext.lib.Panel.superclass.initItems.call(this); var items = this.dockedItems; this.dockedItems = new Ext.util.MixedCollection(false, this.getComponentId); if (items) { this.addDocked(items); } }, /** * Finds a docked component by id, itemId or position * @param {String/Number} comp The id, itemId or position of the child component (see {@link #getComponent} for details) * @return {Ext.Component} The component (if found) */ getDockedComponent: function(comp) { if (Ext.isObject(comp)) { comp = comp.getItemId(); } return this.dockedItems.get(comp); }, /** * Attempts a default component lookup (see {@link Ext.Container#getComponent}). If the component is not found in the normal * items, the dockedItems are searched and the matched component (if any) returned (see {@loink #getDockedComponent}). * @param {String/Number} comp The docked component id or itemId to find * @return {Ext.Component} The docked component, if found */ getComponent: function(comp) { var component = Ext.lib.Panel.superclass.getComponent.call(this, comp); if (component == undefined) { component = this.getDockedComponent(comp); } return component; }, /** * Function description * @return {String} A CSS style string with style, padding, margin and border. * @private */ initBodyStyles: function() { var bodyStyle = Ext.isString(this.bodyStyle) ? this.bodyStyle.split(';') : [], Element = Ext.Element; if (this.bodyPadding != undefined) { bodyStyle.push('padding: ' + Element.unitizeBox((this.bodyPadding === true) ? 5 : this.bodyPadding)); } if (this.bodyMargin != undefined) { bodyStyle.push('margin: ' + Element.unitizeBox((this.bodyMargin === true) ? 5 : this.bodyMargin)); } if (this.bodyBorder != undefined) { bodyStyle.push('border-width: ' + Element.unitizeBox((this.bodyBorder === true) ? 1 : this.bodyBorder)); } delete this.bodyStyle; return bodyStyle.length ? bodyStyle.join(';') : undefined; }, /** * Initialized the renderData to be used when rendering the renderTpl. * @return {Object} Object with keys and values that are going to be applied to the renderTpl * @private */ initRenderData: function() { return Ext.applyIf(Ext.lib.Panel.superclass.initRenderData.call(this), { bodyStyle: this.initBodyStyles(), bodyCls: this.bodyCls }); }, /** * Adds docked item(s) to the panel. * @param {Object/Array} component. The Component or array of components to add. The components * must include a 'dock' paramater on each component to indicate where it should be docked ('top', 'right', * 'bottom', 'left'). * @param {Number} pos (optional) The index at which the Component will be added */ addDocked : function(items, pos) { items = this.prepareItems(items); var item, i, ln; for (i = 0, ln = items.length; i < ln; i++) { item = items[i]; item.dock = item.dock || 'top'; if (pos !== undefined) { this.dockedItems.insert(pos+i, item); } else { this.dockedItems.add(item); } item.onAdded(this, i); this.onDockedAdd(item); } if (this.rendered) { this.doComponentLayout(); } }, // Placeholder empty functions onDockedAdd : Ext.emptyFn, onDockedRemove : Ext.emptyFn, /** * Inserts docked item(s) to the panel at the indicated position. * @param {Number} pos The index at which the Component will be inserted * @param {Object/Array} component. The Component or array of components to add. The components * must include a 'dock' paramater on each component to indicate where it should be docked ('top', 'right', * 'bottom', 'left'). */ insertDocked : function(pos, items) { this.addDocked(items, pos); }, /** * Removes the docked item from the panel. * @param {Ext.Component} item. The Component to remove. * @param {Boolean} autoDestroy (optional) Destroy the component after removal. */ removeDocked : function(item, autoDestroy) { if (!this.dockedItems.contains(item)) { return item; } var layout = this.componentLayout, hasLayout = layout && this.rendered; if (hasLayout) { layout.onRemove(item); } this.dockedItems.remove(item); item.onRemoved(); this.onDockedRemove(item); if (autoDestroy === true || (autoDestroy !== false && this.autoDestroy)) { item.destroy(); } if (hasLayout && !autoDestroy) { layout.afterRemove(item); } this.doComponentLayout(); return item; }, /** * Retrieve an array of all currently docked components. * @return {Array} An array of components. */ getDockedItems : function() { if (this.dockedItems && this.dockedItems.items.length) { return this.dockedItems.items.slice(); } return []; }, // @private getTargetEl : function() { return this.body; }, getRefItems: function(deep) { var refItems = Ext.lib.Panel.superclass.getRefItems.call(this, deep), // deep does not account for dockedItems within dockedItems. dockedItems = this.getDockedItems(), ln = dockedItems.length, i = 0, item; refItems = refItems.concat(dockedItems); if (deep) { for (; i < ln; i++) { item = dockedItems[i]; if (item.getRefItems) { refItems = refItems.concat(item.getRefItems(true)); } } } return refItems; }, beforeDestroy: function(){ var docked = this.dockedItems, c; if (docked) { while ((c = docked.first())) { this.removeDocked(c, true); } } Ext.lib.Panel.superclass.beforeDestroy.call(this); } });
JavaScript
/** * @class Ext.lib.Component * @extends Ext.util.Observable * Shared Component class */ Ext.lib.Component = Ext.extend(Ext.util.Observable, { isComponent: true, /** * @cfg {Mixed} renderTpl * <p>An {@link Ext.XTemplate XTemplate} used to create the {@link #getEl Element} which will * encapsulate this Component.</p> * <p>You do not normally need to specify this. For the base classes {@link Ext.Component}, {@link Ext.Component}, * and {@link Ext.Container}, this defaults to <b><tt>'div'</tt></b>. The more complex Ext classes use a more complex * DOM structure.</p> * <p>This is intended to allow the developer to create application-specific utility Components encapsulated by * different DOM elements. */ renderTpl: null, /** * @cfg {Mixed} renderTo * <p>Specify the id of the element, a DOM element or an existing Element that this component * will be rendered into.</p><div><ul> * <li><b>Notes</b> : <ul> * <div class="sub-desc">Do <u>not</u> use this option if the Component is to be a child item of * a {@link Ext.Container Container}. It is the responsibility of the * {@link Ext.Container Container}'s {@link Ext.Container#layout layout manager} * to render and manage its child items.</div> * <div class="sub-desc">When using this config, a call to render() is not required.</div> * </ul></li> * </ul></div> * <p>See <tt>{@link #render}</tt> also.</p> */ /** * @cfg {String/Object} componentLayout * <br><p>The sizing and positioning of the component Elements is the responsibility of * the Component's layout manager which creates and manages the type of layout specific to the component. * <p>If the {@link #layout} configuration is not explicitly specified for * a general purpose compopnent the * {@link Ext.layout.AutoComponentLayout default layout manager} will be used. */ /** * @cfg {Mixed} tpl * An <bold>{@link Ext.Template}</bold>, <bold>{@link Ext.XTemplate}</bold> * or an array of strings to form an Ext.XTemplate. * Used in conjunction with the <code>{@link #data}</code> and * <code>{@link #tplWriteMode}</code> configurations. */ /** * @cfg {Mixed} data * The initial set of data to apply to the <code>{@link #tpl}</code> to * update the content area of the Component. */ /** * @cfg {String} tplWriteMode The Ext.(X)Template method to use when * updating the content area of the Component. Defaults to <tt>'overwrite'</tt> * (see <code>{@link Ext.XTemplate#overwrite}</code>). */ tplWriteMode: 'overwrite', /** * @cfg {String} baseCls * The base CSS class to apply to this components's element. This will also be prepended to * elements within this component like Panel's body will get a class x-panel-body. This means * that if you create a subclass of Panel, and you want it to get all the Panels styling for the * element and the body, you leave the baseCls x-panel and use componentCls to add specific styling for this * component. */ baseCls: 'x-component', /** * @cfg {String} componentCls * CSS Class to be added to a components root level element to give distinction to it * via styling. */ /** * @cfg {String} cls * An optional extra CSS class that will be added to this component's Element (defaults to ''). This can be * useful for adding customized styles to the component or any of its children using standard CSS rules. */ /** * @cfg {String} disabledCls * CSS class to add when the Component is disabled. Defaults to 'x-item-disabled'. */ disabledCls: 'x-item-disabled', /** * @cfg {String} ui * A set of predefined ui styles for individual components. * * Most components support 'light' and 'dark'. * * Extra string added to the baseCls with an extra '-'. * <pre><code> new Ext.Panel({ title: 'Some Title', baseCls: 'x-component' ui: 'green' }); </code></pre> * <p>The ui configuration in this example would add 'x-component-green' as an additional class.</p> */ /** * @cfg {String} style * A custom style specification to be applied to this component's Element. Should be a valid argument to * {@link Ext.Element#applyStyles}. * <pre><code> new Ext.Panel({ title: 'Some Title', renderTo: Ext.getBody(), width: 400, height: 300, layout: 'form', items: [{ xtype: 'textareafield', style: { width: '95%', marginBottom: '10px' } }, new Ext.Button({ text: 'Send', minWidth: '100', style: { marginBottom: '10px' } }) ] }); </code></pre> */ /** * @cfg {Number} width * The width of this component in pixels. */ /** * @cfg {Number} height * The height of this component in pixels. */ /** * @cfg {Number/String} border * Specifies the border for this component. The border can be a single numeric value to apply to all sides or * it can be a CSS style specification for each style, for example: '10 5 3 10'. */ /** * @cfg {Number/String} padding * Specifies the padding for this component. The padding can be a single numeric value to apply to all sides or * it can be a CSS style specification for each style, for example: '10 5 3 10'. */ /** * @cfg {Number/String} margin * Specifies the margin for this component. The margin can be a single numeric value to apply to all sides or * it can be a CSS style specification for each style, for example: '10 5 3 10'. */ /** * @cfg {Boolean} hidden * Defaults to false. */ hidden: false, /** * @cfg {Boolean} disabled * Defaults to false. */ disabled: false, /** * @cfg {Boolean} draggable * Allows the component to be dragged via the touch event. */ /** * Read-only property indicating whether or not the component can be dragged * @property draggable * @type {Boolean} */ draggable: false, /** * @cfg {Boolean} floating * Create the Component as a floating and use absolute positioning. * Defaults to false. */ floating: false, /** * @cfg {String} contentEl * <p>Optional. Specify an existing HTML element, or the <code>id</code> of an existing HTML element to use as the content * for this component.</p> * <ul> * <li><b>Description</b> : * <div class="sub-desc">This config option is used to take an existing HTML element and place it in the layout element * of a new component (it simply moves the specified DOM element <i>after the Component is rendered</i> to use as the content.</div></li> * <li><b>Notes</b> : * <div class="sub-desc">The specified HTML element is appended to the layout element of the component <i>after any configured * {@link #html HTML} has been inserted</i>, and so the document will not contain this element at the time the {@link #render} event is fired.</div> * <div class="sub-desc">The specified HTML element used will not participate in any <code><b>{@link Ext.Container#layout layout}</b></code> * scheme that the Component may use. It is just HTML. Layouts operate on child <code><b>{@link Ext.Container#items items}</b></code>.</div> * <div class="sub-desc">Add either the <code>x-hidden</code> or the <code>x-hide-display</code> CSS class to * prevent a brief flicker of the content before it is rendered to the panel.</div></li> * </ul> */ /** * @cfg {String/Object} html * An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use as the layout element * content (defaults to ''). The HTML content is added after the component is rendered, * so the document will not contain this HTML at the time the {@link #render} event is fired. * This content is inserted into the body <i>before</i> any configured {@link #contentEl} is appended. */ /** * @cfg {String} styleHtmlContent * True to automatically style the html inside the content target of this component (body for panels). * Defaults to false. */ styleHtmlContent: false, /** * @cfg {String} styleHtmlCls * The class that is added to the content target when you set styleHtmlContent to true. * Defaults to 'x-html' */ styleHtmlCls: 'x-html', /** * @cfg {Number} minHeight * <p>The minimum value in pixels which this Component will set its height to.</p> * <p><b>Warning:</b> This will override any size management applied by layout managers.</p> */ /** * @cfg {Number} minWidth * <p>The minimum value in pixels which this Component will set its width to.</p> * <p><b>Warning:</b> This will override any size management applied by layout managers.</p> */ /** * @cfg {Number} maxHeight * <p>The maximum value in pixels which this Component will set its height to.</p> * <p><b>Warning:</b> This will override any size management applied by layout managers.</p> */ /** * @cfg {Number} maxWidth * <p>The maximum value in pixels which this Component will set its width to.</p> * <p><b>Warning:</b> This will override any size management applied by layout managers.</p> */ // @private allowDomMove: true, autoShow: false, autoRender: false, needsLayout: false, /** * @cfg {Object/Array} plugins * An object or array of objects that will provide custom functionality for this component. The only * requirement for a valid plugin is that it contain an init method that accepts a reference of type Ext.Component. * When a component is created, if any plugins are available, the component will call the init method on each * plugin, passing a reference to itself. Each plugin can then call methods or respond to events on the * component as needed to provide its functionality. */ /** * Read-only property indicating whether or not the component has been rendered. * @property rendered * @type {Boolean} */ rendered: false, constructor : function(config) { config = config || {}; this.initialConfig = config; Ext.apply(this, config); this.addEvents( /** * @event beforeactivate * Fires before a Component has been visually activated. * Returning false from an event listener can prevent the activate * from occurring. * @param {Ext.Component} this */ 'beforeactivate', /** * @event activate * Fires after a Component has been visually activated. * @param {Ext.Component} this */ 'activate', /** * @event beforedeactivate * Fires before a Component has been visually deactivated. * Returning false from an event listener can prevent the deactivate * from occurring. * @param {Ext.Component} this */ 'beforedeactivate', /** * @event deactivate * Fires after a Component has been visually deactivated. * @param {Ext.Component} this */ 'deactivate', /** * @event added * Fires after a Component had been added to a Container. * @param {Ext.Component} this * @param {Ext.Container} container Parent Container * @param {Number} pos position of Component */ 'added', /** * @event disable * Fires after the component is disabled. * @param {Ext.Component} this */ 'disable', /** * @event enable * Fires after the component is enabled. * @param {Ext.Component} this */ 'enable', /** * @event beforeshow * Fires before the component is shown when calling the {@link #show} method. * Return false from an event handler to stop the show. * @param {Ext.Component} this */ 'beforeshow', /** * @event show * Fires after the component is shown when calling the {@link #show} method. * @param {Ext.Component} this */ 'show', /** * @event beforehide * Fires before the component is hidden when calling the {@link #hide} method. * Return false from an event handler to stop the hide. * @param {Ext.Component} this */ 'beforehide', /** * @event hide * Fires after the component is hidden. * Fires after the component is hidden when calling the {@link #hide} method. * @param {Ext.Component} this */ 'hide', /** * @event removed * Fires when a component is removed from an Ext.Container * @param {Ext.Component} this * @param {Ext.Container} ownerCt Container which holds the component */ 'removed', /** * @event beforerender * Fires before the component is {@link #rendered}. Return false from an * event handler to stop the {@link #render}. * @param {Ext.Component} this */ 'beforerender', /** * @event render * Fires after the component markup is {@link #rendered}. * @param {Ext.Component} this */ 'render', /** * @event afterrender * <p>Fires after the component rendering is finished.</p> * <p>The afterrender event is fired after this Component has been {@link #rendered}, been postprocesed * by any afterRender method defined for the Component, and, if {@link #stateful}, after state * has been restored.</p> * @param {Ext.Component} this */ 'afterrender', /** * @event beforedestroy * Fires before the component is {@link #destroy}ed. Return false from an event handler to stop the {@link #destroy}. * @param {Ext.Component} this */ 'beforedestroy', /** * @event destroy * Fires after the component is {@link #destroy}ed. * @param {Ext.Component} this */ 'destroy', /** * @event resize * Fires after the component is resized. * @param {Ext.Component} this * @param {Number} adjWidth The box-adjusted width that was set * @param {Number} adjHeight The box-adjusted height that was set * @param {Number} rawWidth The width that was originally specified * @param {Number} rawHeight The height that was originally specified */ 'resize', /** * @event move * Fires after the component is moved. * @param {Ext.Component} this * @param {Number} x The new x position * @param {Number} y The new y position */ 'move', 'beforestaterestore', 'staterestore', 'beforestatesave', 'statesave' ); this.getId(); this.mons = []; this.additionalCls = []; this.renderData = this.renderData || {}; this.renderSelectors = this.renderSelectors || {}; this.initComponent(); // ititComponent gets a chance to change the id property before registering Ext.ComponentMgr.register(this); // Dont pass the config so that it is not applied to 'this' again Ext.lib.Component.superclass.constructor.call(this); // Move this into Observable? if (this.plugins) { this.plugins = [].concat(this.plugins); for (var i = 0, len = this.plugins.length; i < len; i++) { this.plugins[i] = this.initPlugin(this.plugins[i]); } } // This won't work in Touch if (this.applyTo) { this.applyToMarkup(this.applyTo); delete this.applyTo; } else if (this.renderTo) { this.render(this.renderTo); delete this.renderTo; } //<debug> if (Ext.isDefined(this.disabledClass)) { throw "Component: disabledClass has been deprecated. Please use disabledCls."; } //</debug> }, initComponent: Ext.emptyFn, applyToMarkup: Ext.emptyFn, show: Ext.emptyFn, onShow : function() { // Layout if needed var needsLayout = this.needsLayout; if (Ext.isObject(needsLayout)) { this.doComponentLayout(needsLayout.width, needsLayout.height, needsLayout.isSetSize); } }, // @private initPlugin : function(plugin) { if (plugin.ptype && typeof plugin.init != 'function') { plugin = Ext.PluginMgr.create(plugin); } else if (typeof plugin == 'string') { plugin = Ext.PluginMgr.create({ ptype: plugin }); } plugin.init(this); return plugin; }, // @private render : function(container, position) { if (!this.rendered && this.fireEvent('beforerender', this) !== false) { // If this.el is defined, we want to make sure we are dealing with // an Ext Element. if (this.el) { this.el = Ext.get(this.el); } container = this.initContainer(container); this.onRender(container, position); this.fireEvent('render', this); this.initContent(); this.afterRender(container); this.fireEvent('afterrender', this); this.initEvents(); if (this.autoShow) { this.show(); } if (this.hidden) { // call this so we don't fire initial hide events. this.onHide(false); // no animation after render } if (this.disabled) { // pass silent so the event doesn't fire the first time. this.disable(true); } } return this; }, // @private onRender : function(container, position) { var el = this.el, cls = [], renderTpl, renderData; position = this.getInsertPosition(position); if (!el) { if (position) { el = Ext.DomHelper.insertBefore(position, this.getElConfig(), true); } else { el = Ext.DomHelper.append(container, this.getElConfig(), true); } } else if (this.allowDomMove !== false) { container.dom.insertBefore(el.dom, position); } cls.push(this.baseCls); //<deprecated since=0.99> if (Ext.isDefined(this.cmpCls)) { throw "Ext.Component: cmpCls renamed to componentCls"; } //</deprecated> if (this.componentCls) { cls.push(this.componentCls); } else { this.componentCls = this.baseCls; } if (this.cls) { cls.push(this.cls); delete this.cls; } if (this.ui) { cls.push(this.componentCls + '-' + this.ui); } el.addCls(cls); el.addCls(this.additionalCls); el.setStyle(this.initStyles()); // Here we check if the component has a height set through style or css. // If it does then we set the this.height to that value and it won't be // considered an auto height component // if (this.height === undefined) { // var height = el.getHeight(); // // This hopefully means that the panel has an explicit height set in style or css // if (height - el.getPadding('tb') - el.getBorderWidth('tb') > 0) { // this.height = height; // } // } renderTpl = this.initRenderTpl(); if (renderTpl) { renderData = this.initRenderData(); renderTpl.append(el, renderData); } this.el = el; this.applyRenderSelectors(); this.rendered = true; }, // @private afterRender : function() { this.getComponentLayout(); if (this.x || this.y) { this.setPosition(this.x, this.y); } if (this.styleHtmlContent) { this.getTargetEl().addCls(this.styleHtmlCls); } // If there is a width or height set on this component we will call // which will trigger the component layout if (!this.ownerCt) { this.setSize(this.width, this.height); } }, getElConfig : function() { return {tag: 'div', id: this.id}; }, /** * This function takes the position argument passed to onRender and returns a * DOM element that you can use in the insertBefore. * @param {String/Number/Element/HTMLElement} position Index, element id or element you want * to put this component before. * @return {HTMLElement} DOM element that you can use in the insertBefore */ getInsertPosition: function(position) { // Convert the position to an element to insert before if (position !== undefined) { if (Ext.isNumber(position)) { position = this.container.dom.childNodes[position]; } else { position = Ext.getDom(position); } } return position; }, /** * Adds ctCls to container. * @return {Ext.Element} The initialized container * @private */ initContainer: function(container) { // If you render a component specifying the el, we get the container // of the el, and make sure we dont move the el around in the dom // during the render if (!container && this.el) { container = this.el.dom.parentNode; this.allowDomMove = false; } this.container = Ext.get(container); if (this.ctCls) { this.container.addCls(this.ctCls); } return this.container; }, /** * Initialized the renderData to be used when rendering the renderTpl. * @return {Object} Object with keys and values that are going to be applied to the renderTpl * @private */ initRenderData: function() { return Ext.applyIf(this.renderData, { baseCls: this.baseCls, componentCls: this.componentCls }); }, /** * Initializes the renderTpl. * @return {Ext.XTemplate} The renderTpl XTemplate instance. * @private */ initRenderTpl: function() { var renderTpl = this.renderTpl; if (renderTpl) { if (this.proto.renderTpl !== renderTpl) { if (Ext.isArray(renderTpl) || typeof renderTpl === "string") { renderTpl = new Ext.XTemplate(renderTpl); } } else if (Ext.isArray(this.proto.renderTpl)){ renderTpl = this.proto.renderTpl = new Ext.XTemplate(renderTpl); } } return renderTpl; }, /** * Function description * @return {String} A CSS style string with style, padding, margin and border. * @private */ initStyles: function() { var style = {}, Element = Ext.Element, i, ln, split, prop; if (Ext.isString(this.style)) { split = this.style.split(';'); for (i = 0, ln = split.length; i < ln; i++) { if (!Ext.isEmpty(split[i])) { prop = split[i].split(':'); style[Ext.util.Format.trim(prop[0])] = Ext.util.Format.trim(prop[1]); } } } else { style = Ext.apply({}, this.style); } // Convert the padding, margin and border properties from a space seperated string // into a proper style string if (this.padding != undefined) { style.padding = Element.unitizeBox((this.padding === true) ? 5 : this.padding); } if (this.margin != undefined) { style.margin = Element.unitizeBox((this.margin === true) ? 5 : this.margin); } if (this.border != undefined) { style.borderWidth = Element.unitizeBox((this.border === true) ? 1 : this.border); } delete this.style; return style; }, /** * Initializes this components contents. It checks for the properties * html, contentEl and tpl/data. * @private */ initContent: function() { var target = this.getTargetEl(); if (this.html) { target.update(Ext.DomHelper.markup(this.html)); delete this.html; } if (this.contentEl) { var contentEl = Ext.get(this.contentEl); contentEl.show(); target.appendChild(contentEl.dom); } if (this.tpl) { // Make sure this.tpl is an instantiated XTemplate if (!this.tpl.isTemplate) { this.tpl = new Ext.XTemplate(this.tpl); } if (this.data) { this.tpl[this.tplWriteMode](target, this.data); delete this.data; } } }, // @private initEvents : function() { var afterRenderEvents = this.afterRenderEvents, property, listeners; if (afterRenderEvents) { for (property in afterRenderEvents) { if (!afterRenderEvents.hasOwnProperty(property)) { continue; } listeners = afterRenderEvents[property]; if (this[property] && this[property].on) { this.mon(this[property], listeners); } } } }, /** * Sets references to elements inside the component. E.g body -> x-panel-body * @private */ applyRenderSelectors: function() { var selectors = this.renderSelectors || {}, el = this.el.dom, selector; for (selector in selectors) { if (!selectors.hasOwnProperty(selector)) { continue; } this[selector] = Ext.get(Ext.DomQuery.selectNode(selectors[selector], el)); } }, /** * Retrieves the id of this component. * Will autogenerate an id if one has not already been set. */ getId : function() { return this.id || (this.id = 'ext-comp-' + (++Ext.lib.Component.AUTO_ID)); }, getItemId : function() { return this.itemId || this.id; }, /** * Retrieves the top level element representing this component. */ getEl : function() { return this.el; }, /** * This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component. * @private */ getTargetEl: function() { return this.el; }, /** * <p>Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended * from the xtype (default) or whether it is directly of the xtype specified (shallow = true).</p> * <p><b>If using your own subclasses, be aware that a Component must register its own xtype * to participate in determination of inherited xtypes.</b></p> * <p>For a list of all available xtypes, see the {@link Ext.Component} header.</p> * <p>Example usage:</p> * <pre><code> var t = new Ext.form.Text(); var isText = t.isXType('textfield'); // true var isBoxSubclass = t.isXType('field'); // true, descended from Ext.form.Field var isBoxInstance = t.isXType('field', true); // false, not a direct Ext.form.Field instance </code></pre> * @param {String} xtype The xtype to check for this Component * @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is * the default), or true to check whether this Component is directly of the specified xtype. * @return {Boolean} True if this component descends from the specified xtype, false otherwise. */ isXType: function(xtype, shallow) { //assume a string by default if (Ext.isFunction(xtype)) { xtype = xtype.xtype; //handle being passed the class, e.g. Ext.Component } else if (Ext.isObject(xtype)) { xtype = xtype.constructor.xtype; //handle being passed an instance } return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1: this.constructor.xtype == xtype; }, /** * <p>Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all * available xtypes, see the {@link Ext.Component} header.</p> * <p><b>If using your own subclasses, be aware that a Component must register its own xtype * to participate in determination of inherited xtypes.</b></p> * <p>Example usage:</p> * <pre><code> var t = new Ext.form.Text(); alert(t.getXTypes()); // alerts 'component/field/textfield' </code></pre> * @return {String} The xtype hierarchy string */ getXTypes: function() { var constructor = this.constructor, xtypes = [], superclass = this, xtype; if (!constructor.xtypes) { while (superclass) { xtype = superclass.constructor.xtype; if (xtype != undefined) { xtypes.unshift(xtype); } superclass = superclass.constructor.superclass; } constructor.xtypeChain = xtypes; constructor.xtypes = xtypes.join('/'); } return constructor.xtypes; }, /** * Update the content area of a component. * @param {Mixed} htmlOrData * If this component has been configured with a template via the tpl config * then it will use this argument as data to populate the template. * If this component was not configured with a template, the components * content area will be updated via Ext.Element update * @param {Boolean} loadScripts * (optional) Only legitimate when using the html configuration. Defaults to false * @param {Function} callback * (optional) Only legitimate when using the html configuration. Callback to execute when scripts have finished loading */ update : function(htmlOrData, loadScripts, cb) { if (this.tpl && !Ext.isString(htmlOrData)) { this.data = htmlOrData; if (this.rendered) { this.tpl[this.tplWriteMode](this.getTargetEl(), htmlOrData || {}); } } else { this.html = Ext.isObject(htmlOrData) ? Ext.DomHelper.markup(htmlOrData) : htmlOrData; if (this.rendered) { this.getTargetEl().update(this.html, loadScripts, cb); } } if (this.rendered) { this.doComponentLayout(); } }, /** * Convenience function to hide or show this component by boolean. * @param {Boolean} visible True to show, false to hide * @return {Ext.Component} this */ setVisible : function(visible) { return this[visible ? 'show': 'hide'](); }, /** * Returns true if this component is visible. * @return {Boolean} True if this component is visible, false otherwise. */ isVisible: function() { var visible = !this.hidden, cmp = this.ownerCt; // Clear hiddenOwnerCt property this.hiddenOwnerCt = false; if (this.destroyed) { return false; }; if (visible && this.rendered && cmp) { while (cmp) { if (cmp.hidden || cmp.collapsed) { // Store hiddenOwnerCt property if needed this.hiddenOwnerCt = cmp; visible = false; break; } cmp = cmp.ownerCt; } } return visible; }, /** * Enable the component * @param {Boolean} silent * Passing false will supress the 'enable' event from being fired. */ enable : function(silent) { if (this.rendered) { this.el.removeCls(this.disabledCls); this.el.dom.disabled = false; this.onEnable(); } this.disabled = false; if (silent !== true) { this.fireEvent('enable', this); } return this; }, /** * Disable the component. * @param {Boolean} silent * Passing true, will supress the 'disable' event from being fired. */ disable : function(silent) { if (this.rendered) { this.el.addCls(this.disabledCls); this.el.dom.disabled = true; this.onDisable(); } this.disabled = true; if (silent !== true) { this.fireEvent('disable', this); } return this; }, /** * Method to determine whether this Component is currently disabled. * @return {Boolean} the disabled state of this Component. */ isDisabled : function() { return this.disabled; }, /** * Enable or disable the component. * @param {Boolean} disabled */ setDisabled : function(disabled) { return this[disabled ? 'disable': 'enable'](); }, /** * Method to determine whether this Component is currently set to hidden. * @return {Boolean} the hidden state of this Component. */ isHidden : function() { return this.hidden; }, /** * Adds a CSS class to the top level element representing this component. * @returns {Ext.Component} Returns the Component to allow method chaining. */ addCls : function() { var me = this, args = Ext.toArray(arguments); if (me.rendered) { me.el.addCls(args); } else { me.additionalCls = me.additionalCls.concat(args); } return me; }, //<debug> addClass : function() { throw "Component: addClass has been deprecated. Please use addCls."; }, //</debug> /** * Removes a CSS class from the top level element representing this component. * @returns {Ext.Component} Returns the Component to allow method chaining. */ removeCls : function() { var me = this, args = Ext.toArray(arguments); if (me.rendered) { me.el.removeCls(args); } else if (me.additionalCls.length) { Ext.each(args, function(cls) { me.additionalCls.remove(cls); }); } return me; }, //<debug> removeClass : function() { throw "Component: removeClass has been deprecated. Please use removeCls."; }, //</debug> addListener : function(element, listeners, scope, options) { if (Ext.isString(element) && (Ext.isObject(listeners) || options && options.element)) { if (options.element) { var fn = listeners, option; listeners = {}; listeners[element] = fn; element = options.element; if (scope) { listeners.scope = scope; } for (option in options) { if (!options.hasOwnProperty(option)) { continue; } if (this.eventOptionsRe.test(option)) { listeners[option] = options[option]; } } } // At this point we have a variable called element, // and a listeners object that can be passed to on if (this[element] && this[element].on) { this.mon(this[element], listeners); } else { this.afterRenderEvents = this.afterRenderEvents || {}; this.afterRenderEvents[element] = listeners; } } return Ext.lib.Component.superclass.addListener.apply(this, arguments); }, // @TODO: implement removelistener to support the dom event stuff /** * Provides the link for Observable's fireEvent method to bubble up the ownership hierarchy. * @return {Ext.Container} the Container which owns this Component. */ getBubbleTarget : function() { return this.ownerCt; }, /** * Method to determine whether this Component is floating. * @return {Boolean} the floating state of this component. */ isFloating : function() { return this.floating; }, /** * Method to determine whether this Component is draggable. * @return {Boolean} the draggable state of this component. */ isDraggable : function() { return !!this.draggable; }, /** * Method to determine whether this Component is droppable. * @return {Boolean} the droppable state of this component. */ isDroppable : function() { return !!this.droppable; }, /** * @private * Method to manage awareness of when components are added to their * respective Container, firing an added event. * References are established at add time rather than at render time. * @param {Ext.Container} container Container which holds the component * @param {number} pos Position at which the component was added */ onAdded : function(container, pos) { this.ownerCt = container; this.fireEvent('added', this, container, pos); }, /** * @private * Method to manage awareness of when components are removed from their * respective Container, firing an removed event. References are properly * cleaned up after removing a component from its owning container. */ onRemoved : function() { this.fireEvent('removed', this, this.ownerCt); delete this.ownerCt; }, // @private onEnable : Ext.emptyFn, // @private onDisable : Ext.emptyFn, // @private beforeDestroy : Ext.emptyFn, // @private // @private onResize : Ext.emptyFn, /** * Sets the width and height of this Component. This method fires the {@link #resize} event. This method can accept * either width and height as separate arguments, or you can pass a size object like <code>{width:10, height:20}</code>. * @param {Mixed} width The new width to set. This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS width style.</li> * <li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li> * <li><code>undefined</code> to leave the width unchanged.</li> * </ul></div> * @param {Mixed} height The new height to set (not required if a size object is passed as the first arg). * This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS height style. Animation may <b>not</b> be used.</li> * <li><code>undefined</code> to leave the height unchanged.</li> * </ul></div> * @return {Ext.Component} this */ setSize : function(width, height) { // support for standard size objects if (Ext.isObject(width)) { height = width.height; width = width.width; } if (!this.rendered || !this.isVisible()) { // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag. if (this.hiddenOwnerCt) { var layoutCollection = this.hiddenOwnerCt.layoutOnShow; layoutCollection.remove(this); layoutCollection.add(this); } this.needsLayout = { width: width, height: height, isSetSize: true }; if (!this.rendered) { this.width = (width !== undefined) ? width : this.width; this.height = (height !== undefined) ? height : this.height; } return this; } this.doComponentLayout(width, height, true); return this; }, setCalculatedSize : function(width, height) { // support for standard size objects if (Ext.isObject(width)) { height = width.height; width = width.width; } if (!this.rendered || !this.isVisible()) { // If an ownerCt is hidden, add my reference onto the layoutOnShow stack. Set the needsLayout flag. if (this.hiddenOwnerCt) { var layoutCollection = this.hiddenOwnerCt.layoutOnShow; layoutCollection.remove(this); layoutCollection.add(this); } this.needsLayout = { width: width, height: height, isSetSize: false }; return this; } this.doComponentLayout(width, height); return this; }, /** * This method needs to be called whenever you change something on this component that requires the components * layout to be recalculated. An example is adding, showing or hiding a docked item to a Panel, or changing the * label of a form field. After a component layout, the container layout will automatically be run. So you could * be on the safe side and always call doComponentLayout instead of doLayout. * @return {Ext.Container} this */ doComponentLayout : function(width, height, isSetSize) { var componentLayout = this.getComponentLayout(); if (this.rendered && componentLayout) { width = (width !== undefined || this.collapsed === true) ? width : this.width; height = (height !== undefined || this.collapsed === true) ? height : this.height; if (isSetSize) { this.width = width; this.height = height; } componentLayout.layout(width, height); } return this; }, // @private setComponentLayout : function(layout) { var currentLayout = this.componentLayout; if (currentLayout && currentLayout.isLayout && currentLayout != layout) { currentLayout.setOwner(null); } this.componentLayout = layout; layout.setOwner(this); }, getComponentLayout : function() { if (!this.componentLayout || !this.componentLayout.isLayout) { this.setComponentLayout(Ext.layout.LayoutManager.create(this.componentLayout, 'autocomponent')); } return this.componentLayout; }, afterComponentLayout: Ext.emptyFn, /** * Sets the left and top of the component. To set the page XY position instead, use {@link #setPagePosition}. * This method fires the {@link #move} event. * @param {Number} left The new left * @param {Number} top The new top * @return {Ext.Component} this */ setPosition : function(x, y) { if (Ext.isObject(x)) { y = x.y; x = x.x; } if (!this.rendered) { return this; } if (x !== undefined || y !== undefined) { this.el.setBox(x, y); this.onPosition(x, y); this.fireEvent('move', this, x, y); } return this; }, /* @private * Called after the component is moved, this method is empty by default but can be implemented by any * subclass that needs to perform custom logic after a move occurs. * @param {Number} x The new x position * @param {Number} y The new y position */ onPosition: Ext.emptyFn, /** * Sets the width of the component. This method fires the {@link #resize} event. * @param {Number} width The new width to setThis may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS width style.</li> * </ul></div> * @return {Ext.Component} this */ setWidth : function(width) { return this.setSize(width); }, /** * Sets the height of the component. This method fires the {@link #resize} event. * @param {Number} height The new height to set. This may be one of:<div class="mdetail-params"><ul> * <li>A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels).</li> * <li>A String used to set the CSS height style.</li> * <li><i>undefined</i> to leave the height unchanged.</li> * </ul></div> * @return {Ext.Component} this */ setHeight : function(height) { return this.setSize(undefined, height); }, /** * Gets the current size of the component's underlying element. * @return {Object} An object containing the element's size {width: (element width), height: (element height)} */ getSize : function() { return this.el.getSize(); }, /** * Gets the current width of the component's underlying element. * @return {Number} */ getWidth : function() { return this.el.getWidth(); }, /** * Gets the current height of the component's underlying element. * @return {Number} */ getHeight : function() { return this.el.getHeight(); }, /** * This method allows you to show or hide a LoadMask on top of this component. * @param {Boolean/Object} load True to show the default LoadMask or a config object * that will be passed to the LoadMask constructor. False to hide the current LoadMask. * @param {Boolean} targetEl True to mask the targetEl of this Component instead of the this.el. * For example, setting this to true on a Panel will cause only the body to be masked. (defaults to false) * @return {Ext.LoadMask} The LoadMask instance that has just been shown. */ setLoading : function(load, targetEl) { if (this.rendered) { if (load) { this.loadMask = this.loadMask || new Ext.LoadMask(targetEl ? this.getTargetEl() : this.el, Ext.applyIf(Ext.isObject(load) ? load : {})); this.loadMask.show(); } else { this.loadMask.destroy(); this.loadMask = null; } } return this.loadMask; }, /** * Sets the dock position of this component in its parent panel. Note that * this only has effect if this item is part of the dockedItems collection * of a parent that has a DockLayout (note that any Panel has a DockLayout * by default) * @return {Component} this */ setDocked : function(dock, layoutParent) { this.dock = dock; if (layoutParent && this.ownerCt && this.rendered) { this.ownerCt.doComponentLayout(); } return this; }, onDestroy : function() { if (this.monitorResize && Ext.EventManager.resizeEvent) { Ext.EventManager.resizeEvent.removeListener(this.setSize, this); } Ext.destroy(this.componentLayout); }, /** * Destroys the Component. */ destroy : function() { if (!this.isDestroyed) { if (this.fireEvent('beforedestroy', this) !== false) { this.destroying = true; this.beforeDestroy(); if (this.ownerCt && this.ownerCt.remove) { this.ownerCt.remove(this, false); } if (this.rendered) { this.el.remove(); } this.onDestroy(); Ext.ComponentMgr.unregister(this); this.fireEvent('destroy', this); this.clearListeners(); this.destroying = false; this.isDestroyed = true; } } } }); Ext.lib.Component.prototype.on = Ext.lib.Component.prototype.addListener; // @private Ext.lib.Component.AUTO_ID = 1000;
JavaScript
/** * @class Ext.util.GeoLocation * @extends Ext.util.Observable * * Provides a cross browser class for retrieving location information.<br/> * <br/> * Based on the <a href="http://dev.w3.org/geo/api/spec-source.html">Geolocation API Specification</a>.<br/> * If the browser does not implement that specification (Internet Explorer 6-8), it can fallback on Google Gears * as long as the browser has it installed, and the following javascript file from google is included on the page: * <pre><code>&lt;script type="text/javascript" src="http://code.google.com/apis/gears/gears_init.js"&gt;&lt;/script&gt;</code></pre> * <br/> * Note: Location implementations are only required to return timestamp, longitude, latitude, and accuracy.<br/> * Other properties (altitude, altitudeAccuracy, heading, speed) can be null or sporadically returned.<br/> * <br/> * When instantiated, by default this class immediately begins tracking location information, * firing a {@link #locationupdate} event when new location information is available. To disable this * location tracking (which may be battery intensive on mobile devices), set {@link #autoUpdate} to false.<br/> * When this is done, only calls to {@link #updateLocation} will trigger a location retrieval.<br/> * <br/> * A {@link #locationerror} event is raised when an error occurs retrieving the location, either due to a user * denying the application access to it, or the browser not supporting it.<br/> * <br/> * The below code shows a GeoLocation making a single retrieval of location information. * <pre><code> var geo = new Ext.util.GeoLocation({ autoUpdate: false, listeners: { locationupdate: function (geo) { alert('New latitude: ' + geo.latitude); }, locationerror: function ( geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) { if(bTimeout){ alert('Timeout occurred.'); } else{ alert('Error occurred.'); } } } }); geo.updateLocation();</code></pre> */ Ext.util.GeoLocation = Ext.extend(Ext.util.Observable, { /** * @cfg {Boolean} autoUpdate * Defaults to true.<br/> * When set to true, continually monitor the location of the device * (beginning immediately) and fire {@link #locationupdate}/{@link #locationerror} events.<br/> * <br/> * When using google gears, if the user denies access or another error occurs, this will be reset to false. */ autoUpdate: true, //Position interface /** * Read-only property representing the last retrieved * geographical coordinate specified in degrees. * @type Number */ latitude: null, /** * Read-only property representing the last retrieved * geographical coordinate specified in degrees. * @type Number */ longitude: null, /** * Read-only property representing the last retrieved * accuracy level of the latitude and longitude coordinates, * specified in meters.<br/> * This will always be a non-negative number.<br/> * This corresponds to a 95% confidence level. * @type Number */ accuracy: null, /** * Read-only property representing the last retrieved * height of the position, specified in meters above the ellipsoid * <a href="http://dev.w3.org/geo/api/spec-source.html#ref-wgs">[WGS84]</a>. * @type Number/null */ altitude: null, /** * Read-only property representing the last retrieved * accuracy level of the altitude coordinate, specified in meters.<br/> * If altitude is not null then this will be a non-negative number. * Otherwise this returns null.<br/> * This corresponds to a 95% confidence level. * @type Number/null */ altitudeAccuracy: null, /** * Read-only property representing the last retrieved * direction of travel of the hosting device, * specified in non-negative degrees between 0 and 359, * counting clockwise relative to the true north.<br/> * If speed is 0 (device is stationary), then this returns NaN * @type Number/null */ heading: null, /** * Read-only property representing the last retrieved * current ground speed of the device, specified in meters per second.<br/> * If this feature is unsupported by the device, this returns null.<br/> * If the device is stationary, this returns 0, * otherwise it returns a non-negative number. * @type Number/null */ speed: null, /** * Read-only property representing when the last retrieved * positioning information was acquired by the device. * @type Date */ timestamp: null, //PositionOptions interface /** * @cfg {Boolean} allowHighAccuracy * Defaults to false.<br/> * When set to true, provide a hint that the application would like to receive * the best possible results. This may result in slower response times or increased power consumption. * The user might also deny this capability, or the device might not be able to provide more accurate * results than if this option was set to false. */ allowHighAccuracy: false, /** * @cfg {Number} timeout * Defaults to Infinity.<br/> * The maximum number of milliseconds allowed to elapse between a location update operation * and the corresponding {@link #locationupdate} event being raised. If a location was not successfully * acquired before the given timeout elapses (and no other internal errors have occurred in this interval), * then a {@link #locationerror} event will be raised indicating a timeout as the cause.<br/> * Note that the time that is spent obtaining the user permission is <b>not</b> included in the period * covered by the timeout. The timeout attribute only applies to the location acquisition operation.<br/> * In the case of calling updateLocation, the {@link #locationerror} event will be raised only once.<br/> * If {@link #autoUpdate} is set to true, the {@link #locationerror} event could be raised repeatedly. * The first timeout is relative to the moment {@link #autoUpdate} was set to true * (or this {@link Ext.util.GeoLocation} was initialized with the {@link #autoUpdate} config option set to true). * Subsequent timeouts are relative to the moment when the device determines that it's position has changed. */ timeout: Infinity, /** * @cfg {Number} maximumAge * Defaults to 0.<br/> * This option indicates that the application is willing to accept cached location information whose age * is no greater than the specified time in milliseconds. If maximumAge is set to 0, an attempt to retrieve * new location information is made immediately.<br/> * Setting the maximumAge to Infinity returns a cached position regardless of its age.<br/> * If the device does not have cached location information available whose age is no * greater than the specified maximumAge, then it must acquire new location information.<br/> * For example, if location information no older than 10 minutes is required, set this property to 600000. */ maximumAge: 0, /** * Changes the {@link #maximumAge} option and restarts any active * location monitoring with the updated setting. * @param {Number} maximumAge The value to set the maximumAge option to. */ setMaximumAge: function(maximumAge) { this.maximumAge = maximumAge; this.setAutoUpdate(this.autoUpdate); }, /** * Changes the {@link #timeout} option and restarts any active * location monitoring with the updated setting. * @param {Number} timeout The value to set the timeout option to. */ setTimeout: function(timeout) { this.timeout = timeout; this.setAutoUpdate(this.autoUpdate); }, /** * Changes the {@link #allowHighAccuracy} option and restarts any active * location monitoring with the updated setting. * @param {Number} allowHighAccuracy The value to set the allowHighAccuracy option to. */ setAllowHighAccuracy: function(allowHighAccuracy) { this.allowHighAccuracy = allowHighAccuracy; this.setAutoUpdate(this.autoUpdate); }, //<deprecated since=0.99> setEnableHighAccuracy : function() { console.warn("GeoLocation: setEnableHighAccuracy has been deprecated. Please use setAllowHighAccuracy."); return this.setAllowHighAccuracy.apply(this, arguments); }, //</deprecated> // private Object geolocation provider provider : null, // private Number tracking current watchPosition watchOperation : null, constructor : function(config) { Ext.apply(this, config); //<deprecated since=0.99> if (Ext.isDefined(this.enableHighAccuracy)) { console.warn("GeoLocation: enableHighAccuracy has been removed. Please use allowHighAccuracy."); this.allowHighAccuracy = this.enableHighAccuracy; } //</deprecated> this.coords = this; //@deprecated if (Ext.supports.GeoLocation) { this.provider = this.provider || (navigator.geolocation ? navigator.geolocation : (window.google || {}).gears ? google.gears.factory.create('beta.geolocation') : null); } this.addEvents( /** * @private * @event update * @param {Ext.util.GeoLocation/False} coords * Will return false if geolocation fails (disabled, denied access, timed out). * @param {Ext.util.GeoLocation} this * @deprecated */ 'update', /** * @event locationerror * Raised when a location retrieval operation failed.<br/> * In the case of calling updateLocation, this event will be raised only once.<br/> * If {@link #autoUpdate} is set to true, this event could be raised repeatedly. * The first error is relative to the moment {@link #autoUpdate} was set to true * (or this {@link Ext.util.GeoLocation} was initialized with the {@link #autoUpdate} config option set to true). * Subsequent errors are relative to the moment when the device determines that it's position has changed. * @param {Ext.util.GeoLocation} this * @param {Boolean} timeout * Boolean indicating a timeout occurred * @param {Boolean} permissionDenied * Boolean indicating the user denied the location request * @param {Boolean} locationUnavailable * Boolean indicating that the location of the device could not be determined.<br/> * For instance, one or more of the location providers used in the location acquisition * process reported an internal error that caused the process to fail entirely. * @param {String} message * An error message describing the details of the error encountered.<br/> * This attribute is primarily intended for debugging and should not be used * directly in an application user interface. */ 'locationerror', /** * @event locationupdate * Raised when a location retrieval operation has been completed successfully. * @param {Ext.util.GeoLocation} this * Retrieve the current location information from the GeoLocation object by using the read-only * properties latitude, longitude, accuracy, altitude, altitudeAccuracy, heading, and speed. */ 'locationupdate' ); Ext.util.GeoLocation.superclass.constructor.call(this); if(this.autoUpdate){ var me = this; setTimeout(function(){ me.setAutoUpdate(me.autoUpdate); }, 0); } }, /** * Enabled/disables the auto-retrieval of the location information.<br/> * If called with autoUpdate=true, it will execute an immediate location update * and continue monitoring for location updates.<br/> * If autoUpdate=false, any current location change monitoring will be disabled. * @param {Boolean} autoUpdate Whether to start/stop location monitoring. * @return {Boolean} If enabling autoUpdate, returns false if the location tracking * cannot begin due to an error supporting geolocation. * A locationerror event is also fired. */ setAutoUpdate : function(autoUpdate) { if (this.watchOperation !== null) { this.provider.clearWatch(this.watchOperation); this.watchOperation = null; } if (!autoUpdate) { return true; } if (!Ext.supports.GeoLocation) { this.fireEvent('locationerror', this, false, false, true, null); return false; } try{ this.watchOperation = this.provider.watchPosition( Ext.createDelegate(this.fireUpdate, this), Ext.createDelegate(this.fireError, this), this.parseOptions()); } catch(e){ this.autoUpdate = false; this.fireEvent('locationerror', this, false, false, true, e.message); return false; } return true; }, /** * Executes a onetime location update operation, * raising either a {@link #locationupdate} or {@link #locationerror} event.<br/> * Does not interfere with or restart ongoing location monitoring. * @param {Function} callback * A callback method to be called when the location retrieval has been completed.<br/> * Will be called on both success and failure.<br/> * The method will be passed one parameter, {@link Ext.GeoLocation} (<b>this</b> reference), * set to null on failure. * <pre><code> geo.updateLocation(function (geo) { alert('Latitude: ' + (geo != null ? geo.latitude : 'failed')); }); </code></pre> * @param {Object} scope (optional) * (optional) The scope (<b>this</b> reference) in which the handler function is executed. * <b>If omitted, defaults to the object which fired the event.</b> * <!--positonOptions undocumented param, see W3C spec--> */ updateLocation : function(callback, scope, positionOptions) { var me = this; var failFunction = function(message, error){ if(error){ me.fireError(error); } else{ me.fireEvent('locationerror', me, false, false, true, message); } if(callback){ callback.call(scope || me, null, me); //last parameter for legacy purposes } me.fireEvent('update', false, me); //legacy, deprecated }; if (!Ext.supports.GeoLocation) { setTimeout(function() { failFunction(null); }, 0); return; } try{ this.provider.getCurrentPosition( //success callback function(position){ me.fireUpdate(position); if(callback){ callback.call(scope || me, me, me); //last parameter for legacy purposes } me.fireEvent('update', me, me); //legacy, deprecated }, //error callback function(error){ failFunction(null, error); }, positionOptions ? positionOptions : this.parseOptions()); } catch(e){ setTimeout(function(){ failFunction(e.message); }, 0); } }, // private fireUpdate: function(position){ this.timestamp = position.timestamp; this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; this.accuracy = position.coords.accuracy; this.altitude = position.coords.altitude; this.altitudeAccuracy = position.coords.altitudeAccuracy; //google doesn't provide these two this.heading = typeof position.coords.heading == 'undefined' ? null : position.coords.heading; this.speed = typeof position.coords.speed == 'undefined' ? null : position.coords.speed; this.fireEvent('locationupdate', this); }, fireError: function(error){ this.fireEvent('locationerror', this, error.code == error.TIMEOUT, error.code == error.PERMISSION_DENIED, error.code == error.POSITION_UNAVAILABLE, error.message == undefined ? null : error.message); }, parseOptions: function(){ var ret = { maximumAge: this.maximumAge, allowHighAccuracy: this.allowHighAccuracy }; //Google doesn't like Infinity if(this.timeout !== Infinity){ ret.timeout = this.timeout; } return ret; }, /** * @private * Returns cached coordinates, and updates if there are no cached coords yet. * @deprecated */ getLocation : function(callback, scope) { var me = this; if(this.latitude !== null){ callback.call(scope || me, me, me); } else { me.updateLocation(callback, scope); } } });
JavaScript
/** * @class Ext.util.Observable * 一个抽象基类(Abstract base class),为事件机制的管理提供一个公共接口。子类应有一个"events"属性来定义所有的事件。 * Abstract base class that provides a common interface for publishing events. Subclasses are expected to * to have a property "events" with all the events defined.<br> * 例如:For example: * <pre><code> Employee = function(name){ this.name = name; this.addEvents({ "fired" : true, "quit" : true }); } Ext.extend(Employee, Ext.util.Observable); </code></pre> */ /** * @class Ext.util.Observable * Base class that provides a common interface for publishing events. Subclasses are expected to * to have a property "events" with all the events defined, and, optionally, a property "listeners" * with configured listeners defined.<br> * For example: * <pre><code> Employee = Ext.extend(Ext.util.Observable, { constructor: function(config){ this.name = config.name; this.addEvents({ "fired" : true, "quit" : true }); // Copy configured listeners into *this* object so that the base class&#39;s // constructor will add them. this.listeners = config.listeners; // Call our superclass constructor to complete construction process. Employee.superclass.constructor.call(this, config) } }); </code></pre> * This could then be used like this:<pre><code> var newEmployee = new Employee({ name: employeeName, listeners: { quit: function() { // By default, "this" will be the object that fired the event. alert(this.name + " has quit!"); } } }); </code></pre> */ Ext.util.Observable = Ext.extend(Object, { /** * @cfg {Object} listeners (optional) <p>A config object containing one or more event handlers to be added to this * object during initialization. This should be a valid listeners config object as specified in the * {@link #addListener} example for attaching multiple handlers at once.</p> * <br><p><b><u>DOM events from ExtJs {@link Ext.Component Components}</u></b></p> * <br><p>While <i>some</i> ExtJs Component classes export selected DOM events (e.g. "click", "mouseover" etc), this * is usually only done when extra value can be added. For example the {@link Ext.DataView DataView}'s * <b><code>{@link Ext.DataView#click click}</code></b> event passing the node clicked on. To access DOM * events directly from a Component's HTMLElement, listeners must be added to the <i>{@link Ext.Component#getEl Element}</i> after the Component * has been rendered. A plugin can simplify this step: <pre><code> // Plugin is configured with a listeners config object. // The Component is appended to the argument list of all handler functions. Ext.DomObserver = Ext.extend(Object, { constructor: function(config) { this.listeners = config.listeners ? config.listeners : config; }, // Component passes itself into plugin&#39;s init method init: function(c) { var p, l = this.listeners; for (p in l) { if (Ext.isFunction(l[p])) { l[p] = this.createHandler(l[p], c); } else { l[p].fn = this.createHandler(l[p].fn, c); } } // Add the listeners to the Element immediately following the render call c.render = c.render.{@link Ext.util.Functions.createSequence}(function() { var e = c.getEl(); if (e) { e.on(l); } }); }, createHandler: function(fn, c) { return function(e) { fn.call(this, e, c); }; } }); var text = new Ext.form.Text({ // Collapse combo when its element is clicked on plugins: [ new Ext.DomObserver({ click: function(evt, comp) { comp.collapse(); } })] }); </code></pre></p> */ // @private isObservable: true, constructor: function(config) { var me = this; Ext.apply(me, config); if (me.listeners) { me.on(me.listeners); delete me.listeners; } me.events = me.events || {}; if (this.bubbleEvents) { this.enableBubble(this.bubbleEvents); } }, // @private eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal)$/, /** * <p>Adds listeners to any Observable object (or Element) which are automatically removed when this Component * is destroyed. * @param {Observable|Element} item The item to which to add a listener/listeners. * @param {Object|String} ename The event name, or an object containing event name properties. * @param {Function} fn Optional. If the <code>ename</code> parameter was an event name, this * is the handler function. * @param {Object} scope Optional. If the <code>ename</code> parameter was an event name, this * is the scope (<code>this</code> reference) in which the handler function is executed. * @param {Object} opt Optional. If the <code>ename</code> parameter was an event name, this * is the {@link Ext.util.Observable#addListener addListener} options. */ addManagedListener : function(item, ename, fn, scope, options) { var me = this, managedListeners = me.managedListeners = me.managedListeners || [], config; if (Ext.isObject(ename)) { options = ename; for (ename in options) { if (!options.hasOwnProperty(ename)) { continue; } config = options[ename]; if (!me.eventOptionsRe.test(ename)) { me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options); } } } else { managedListeners.push({ item: item, ename: ename, fn: fn, scope: scope, options: options }); item.on(ename, fn, scope, options); } }, /** * Removes listeners that were added by the {@link #mon} method. * @param {Observable|Element} item The item from which to remove a listener/listeners. * @param {Object|String} ename The event name, or an object containing event name properties. * @param {Function} fn Optional. If the <code>ename</code> parameter was an event name, this * is the handler function. * @param {Object} scope Optional. If the <code>ename</code> parameter was an event name, this * is the scope (<code>this</code> reference) in which the handler function is executed. */ removeManagedListener : function(item, ename, fn, scope) { var me = this, o, config, managedListeners, managedListener, length, i; if (Ext.isObject(ename)) { o = ename; for (ename in o) { if (!o.hasOwnProperty(ename)) { continue; } config = o[ename]; if (!me.eventOptionsRe.test(ename)) { me.removeManagedListener(item, ename, config.fn || config, config.scope || o.scope); } } } managedListeners = this.managedListeners ? this.managedListeners.slice() : []; length = managedListeners.length; for (i = 0; i < length; i++) { managedListener = managedListeners[i]; if (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope)) { this.managedListeners.remove(managedListener); item.un(managedListener.ename, managedListener.fn, managedListener.scope); } } }, /** * <p>Fires the specified event with the passed parameters (minus the event name).</p> * <p>An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) * by calling {@link #enableBubble}.</p> * @param {String} eventName The name of the event to fire. * @param {Object...} args Variable number of parameters are passed to handlers. * @return {Boolean} returns false if any of the handlers return false otherwise it returns true. */ fireEvent: function() { var me = this, a = Ext.toArray(arguments), ename = a[0].toLowerCase(), ret = true, ev = me.events[ename], queue = me.eventQueue, parent; if (me.eventsSuspended === true) { if (queue) { queue.push(a); } return false; } else if (ev && Ext.isObject(ev) && ev.bubble) { if (ev.fire.apply(ev, a.slice(1)) === false) { return false; } parent = me.getBubbleTarget && me.getBubbleTarget(); if (parent && parent.isObservable) { if (!parent.events[ename] || !Ext.isObject(parent.events[ename]) || !parent.events[ename].bubble) { parent.enableBubble(ename); } return parent.fireEvent.apply(parent, a); } } else if (ev && Ext.isObject(ev)) { a.shift(); ret = ev.fire.apply(ev, a); } return ret; }, /** * Appends an event handler to this object. * @param {String} eventName The name of the event to listen for. * @param {Function} handler The method the event invokes. * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed. * <b>If omitted, defaults to the object which fired the event.</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 the object which fired the event.</b></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> * <li><b>target</b> : Observable<div class="sub-desc">Only call the handler if the event was fired on the target Observable, <i>not</i> * if the event was bubbled up from a child Observable.</div></li> * </ul><br> * <p> * <b>Combining Options</b><br> * Using the options argument, it is possible to combine different types of listeners:<br> * <br> * A delayed, one-time listener. * <pre><code> myPanel.on('hide', this.onClick, this, { single: true, delay: 100 });</code></pre> * <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> */ addListener: function(ename, fn, scope, o) { var me = this, config, ev; if (Ext.isObject(ename)) { o = ename; for (ename in o) { if (!o.hasOwnProperty(ename)) { continue; } config = o[ename]; if (!me.eventOptionsRe.test(ename)) { me.addListener(ename, config.fn || config, config.scope || o.scope, config.fn ? config : o); } } } else { ename = ename.toLowerCase(); me.events[ename] = me.events[ename] || true; ev = me.events[ename] || true; if (Ext.isBoolean(ev)) { me.events[ename] = ev = new Ext.util.Event(me, ename); } ev.addListener(fn, scope, Ext.isObject(o) ? o: {}); } }, /** * 移除侦听器Removes a listener * @param {String} eventName 侦听事件的类型The type of event to listen for * @param {Function} handler 移除的处理函数The handler to remove * @param {Object} scope (可选的) 处理函数之作用域(optional) The scope (this object) for the handler */ /** * Removes an event handler. * @param {String} eventName The type of event the handler was associated with. * @param {Function} handler The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b> * @param {Object} scope (optional) The scope originally specified for the handler. */ removeListener: function(ename, fn, scope) { var me = this, config, ev; if (Ext.isObject(ename)) { var o = ename; for (ename in o) { if (!o.hasOwnProperty(ename)) { continue; } config = o[ename]; if (!me.eventOptionsRe.test(ename)) { me.removeListener(ename, config.fn || config, config.scope || o.scope); } } } else { ename = ename.toLowerCase(); ev = me.events[ename]; if (ev.isEvent) { ev.removeListener(fn, scope); } } }, /** * Removes all listeners for this object including the managed listeners */ clearListeners: function() { var events = this.events, ev, key; for (key in events) { if (!events.hasOwnProperty(key)) { continue; } ev = events[key]; if (ev.isEvent) { ev.clearListeners(); } } this.clearManagedListeners(); }, //<debug> purgeListeners : function() { console.warn('MixedCollection: purgeListeners has been deprecated. Please use clearListeners.'); return this.clearListeners.apply(this, arguments); }, //</debug> /** * Removes all managed listeners for this object. */ clearManagedListeners : function() { var managedListeners = this.managedListeners || [], ln = managedListeners.length, i, managedListener; for (i = 0; i < ln; i++) { managedListener = managedListeners[i]; managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope); } this.managedListener = []; }, //<debug> purgeManagedListeners : function() { console.warn('MixedCollection: purgeManagedListeners has been deprecated. Please use clearManagedListeners.'); return this.clearManagedListeners.apply(this, arguments); }, //</debug> /** * Adds the specified events to the list of events which this Observable may fire. * @param {Object|String} o Either an object with event names as properties with a value of <code>true</code> * or the first event name string if multiple event names are being passed as separate parameters. * @param {string} Optional. Event name if multiple event names are being passed as separate parameters. * Usage:<pre><code> this.addEvents('storeloaded', 'storecleared'); </code></pre> */ addEvents: function(o) { var me = this; me.events = me.events || {}; if (Ext.isString(o)) { var a = arguments, i = a.length; while (i--) { me.events[a[i]] = me.events[a[i]] || true; } } else { Ext.applyIf(me.events, o); } }, /** * 检测当前对象是否有指定的事件。 * Checks to see if this object has any listeners for a specified event * @param {String} eventName 要检查的事件名称。The name of the event to check for * @return {Boolean} True表示有事件正在被监听,否则为false。True if the event is being listened for, else false */ /** * Checks to see if this object has any listeners for a specified event * @param {String} eventName The name of the event to check for * @return {Boolean} True if the event is being listened for, else false */ hasListener: function(ename) { var e = this.events[ename]; return e.isEvent === true && e.listeners.length > 0; }, /** * Suspend the firing of all events. (see {@link #resumeEvents}) * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired * after the {@link #resumeEvents} call instead of discarding all suspended events; */ /** * 暂停触发所有的事件(请参阅{@link #resumeEvents})。 * Suspend the firing of all events. (see {@link #resumeEvents}) * @param {Boolean} queueSuspended 传入true的话表示把已经队列且挂起的事件也一并触发。Pass as true to queue up suspended events to be fired * after the {@link #resumeEvents} call instead of discarding all suspended events; */ suspendEvents: function(queueSuspended) { this.eventsSuspended = true; if (queueSuspended && !this.eventQueue) { this.eventQueue = []; } }, /** * 重新触发事件(参阅{@link #suspendEvents})。 * Resume firing events. (see {@link #suspendEvents}) * If events were suspended using the <tt><b>queueSuspended</b></tt> parameter, then all * events fired during event suspension will be sent to any listeners now. */ resumeEvents: function() { var me = this, queued = me.eventQueue || []; me.eventsSuspended = false; delete me.eventQueue; Ext.each(queued, function(e) { me.fireEvent.apply(me, e); }); }, /** * Relays selected events from the specified Observable as if the events were fired by <tt><b>this</b></tt>. * @param {Object} o The Observable whose events this object is to relay. * @param {Array} events Array of event names to relay. */ relayEvents : function(origin, events, prefix) { prefix = prefix || ''; var me = this, len = events.length, i, ename; function createHandler(ename){ return function(){ return me.fireEvent.apply(me, [prefix + ename].concat(Array.prototype.slice.call(arguments, 0, -1))); }; } for(i = 0, len = events.length; i < len; i++){ ename = events[i].substr(prefix.length); me.events[ename] = me.events[ename] || true; origin.on(ename, createHandler(ename), me); } }, /** * <p>Enables events fired by this Observable to bubble up an owner hierarchy by calling * <code>this.getBubbleTarget()</code> if present. There is no implementation in the Observable base class.</p> * <p>This is commonly used by Ext.Components to bubble events to owner Containers. See {@link Ext.Component.getBubbleTarget}. The default * implementation in Ext.Component returns the Component's immediate owner. But if a known target is required, this can be overridden to * access the required target more quickly.</p> * <p>Example:</p><pre><code> Ext.override(Ext.form.Field, { // Add functionality to Field&#39;s initComponent to enable the change event to bubble initComponent : Ext.createSequence(Ext.form.Field.prototype.initComponent, function() { this.enableBubble('change'); }), // We know that we want Field&#39;s events to bubble directly to the FormPanel. getBubbleTarget : function() { if (!this.formPanel) { this.formPanel = this.findParentByType('form'); } return this.formPanel; } }); var myForm = new Ext.formPanel({ title: 'User Details', items: [{ ... }], listeners: { change: function() { // Title goes red if form has been modified. myForm.header.setStyle('color', 'red'); } } }); </code></pre> * @param {String/Array} events The event name to bubble, or an Array of event names. */ enableBubble: function(events) { var me = this; if (!Ext.isEmpty(events)) { events = Ext.isArray(events) ? events: Ext.toArray(arguments); Ext.each(events, function(ename) { ename = ename.toLowerCase(); var ce = me.events[ename] || true; if (Ext.isBoolean(ce)) { ce = new Ext.util.Event(me, ename); me.events[ename] = ce; } ce.bubble = true; }); } } }); Ext.override(Ext.util.Observable, { /** * 为该元素添加事件处理函数(addListener的简写方式)。 * Appends an event handler to this element (shorthand for addListener) * @param {String} eventName 事件名称The type of event to listen for * @param {Function} handler 处理函数The method the event invokes * @param {Object} scope (可选的) 执行处理函数的作用域。“this”对象指针(optional) The scope in which to execute the handler * function. The handler function's "this" context. * @param {Object} options (可选的)(optional) * @method */ /** * Appends an event handler to this object (shorthand for {@link #addListener}.) * @param {String} eventName The type of event to listen for * @param {Function} handler The method the event invokes * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed. * <b>If omitted, defaults to the object which fired the event.</b> * @param {Object} options (optional) An object containing handler configuration. * @method */ on: Ext.util.Observable.prototype.addListener, /** * 移除侦听器(removeListener的快捷方式)Removes a listener (shorthand for removeListener) * @param {String} eventName 侦听事件的类型The type of event to listen for * @param {Function} handler 事件涉及的方法 The handler to remove * @param {Object} scope (可选的) 处理函数的作用域(optional) The scope (this object) for the handler * @method /** * Removes an event handler (shorthand for {@link #removeListener}.) * @param {String} eventName The type of event the handler was associated with. * @param {Function} handler The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b> * @param {Object} scope (optional) The scope originally specified for the handler. * @method */ un: Ext.util.Observable.prototype.removeListener, mon: Ext.util.Observable.prototype.addManagedListener, mun: Ext.util.Observable.prototype.removeManagedListener }); /** * Removes <b>all</b> added captures from the Observable. * @param {Observable} o The Observable to release * @static */ Ext.util.Observable.releaseCapture = function(o) { o.fireEvent = Ext.util.Observable.prototype.fireEvent; }; /** * 开始捕捉特定的观察者。 * 在事件触发<b>之前</b>,所有的事件会以“事件名称+标准签名”的形式传入到函数(传入的参数是function类型)。 * 如果传入的函数执行后返回false,则接下的事件将不会触发。 * Starts capture on the specified Observable. All events will be passed * to the supplied function with the event name + standard signature of the event * <b>before</b> the event is fired. If the supplied function returns false, * the event will not fire. * @param {Observable} o 要捕捉的观察者The Observable to capture * @param {Function} fn 要调用的函数The function to call * @param {Object} scope (可选的) 函数作用域(optional) The scope (this object) for the fn * @static /** * Starts capture on the specified Observable. All events will be passed * to the supplied function with the event name + standard signature of the event * <b>before</b> the event is fired. If the supplied function returns false, * the event will not fire. * @param {Observable} o The Observable to capture events from. * @param {Function} fn The function to call when an event is fired. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Observable firing the event. * @static */ Ext.util.Observable.capture = function(o, fn, scope) { o.fireEvent = Ext.createInterceptor(o.fireEvent, fn, scope); }; /** * Sets observability on the passed class constructor.<p> * <p>This makes any event fired on any instance of the passed class also fire a single event through * the <i>class</i> allowing for central handling of events on many instances at once.</p> * <p>Usage:</p><pre><code> Ext.util.Observable.observe(Ext.data.Connection); Ext.data.Connection.on('beforerequest', function(con, options) { console.log('Ajax request made to ' + options.url); });</code></pre> * @param {Function} c The class constructor to make observable. * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}. * @static */ Ext.util.Observable.observe = function(cls, listeners) { if (cls) { if (!cls.isObservable) { Ext.applyIf(cls, new Ext.util.Observable()); Ext.util.Observable.capture(cls.prototype, cls.fireEvent, cls); } if (typeof listeners == 'object') { cls.on(listeners); } return cls; } }; //deprecated, will be removed in 5.0 Ext.util.Observable.observeClass = Ext.util.Observable.observe; Ext.util.Event = Ext.extend(Object, (function() { function createBuffered(handler, listener, o, scope) { listener.task = new Ext.util.DelayedTask(); return function() { listener.task.delay(o.buffer, handler, scope, Ext.toArray(arguments)); }; }; function createDelayed(handler, listener, o, scope) { return function() { var task = new Ext.util.DelayedTask(); if (!listener.tasks) { listener.tasks = []; } listener.tasks.push(task); task.delay(o.delay || 10, handler, scope, Ext.toArray(arguments)); }; }; function createSingle(handler, listener, o, scope) { return function() { listener.ev.removeListener(listener.fn, scope); return handler.apply(scope, arguments); }; }; return { isEvent: true, constructor: function(observable, name) { this.name = name; this.observable = observable; this.listeners = []; }, addListener: function(fn, scope, options) { var me = this, listener; scope = scope || me.observable; if (!me.isListening(fn, scope)) { listener = me.createListener(fn, scope, options); if (me.firing) { // if we are currently firing this event, don't disturb the listener loop me.listeners = me.listeners.slice(0); } me.listeners.push(listener); } }, createListener: function(fn, scope, o) { o = o || {}; scope = scope || this.observable; var listener = { fn: fn, scope: scope, o: o, ev: this }, handler = fn; if (o.delay) { handler = createDelayed(handler, listener, o, scope); } if (o.buffer) { handler = createBuffered(handler, listener, o, scope); } if (o.single) { handler = createSingle(handler, listener, o, scope); } listener.fireFn = handler; return listener; }, findListener: function(fn, scope) { var listeners = this.listeners, i = listeners.length, listener, s; while (i--) { listener = listeners[i]; if (listener) { s = listener.scope; if (listener.fn == fn && (s == scope || s == this.observable)) { return i; } } } return - 1; }, isListening: function(fn, scope) { return this.findListener(fn, scope) !== -1; }, removeListener: function(fn, scope) { var me = this, index, listener, k; index = me.findListener(fn, scope); if (index != -1) { listener = me.listeners[index]; if (me.firing) { me.listeners = me.listeners.slice(0); } // cancel and remove a buffered handler that hasn't fired yet if (listener.task) { listener.task.cancel(); delete listener.task; } // cancel and remove all delayed handlers that haven't fired yet k = listener.tasks && listener.tasks.length; if (k) { while (k--) { listener.tasks[k].cancel(); } delete listener.tasks; } // remove this listener from the listeners array me.listeners.splice(index, 1); return true; } return false; }, // Iterate to stop any buffered/delayed events clearListeners: function() { var listeners = this.listeners, i = listeners.length; while (i--) { this.removeListener(listeners[i].fn, listeners[i].scope); } }, fire: function() { var me = this, listeners = me.listeners, count = listeners.length, i, args, listener; if (count > 0) { me.firing = true; for (i = 0; i < count; i++) { listener = listeners[i]; args = arguments.length ? Array.prototype.slice.call(arguments, 0) : []; if (listener.o) { args.push(listener.o); } if (listener && listener.fireFn.apply(listener.scope || me.observable, args) === false) { return (me.firing = false); } } } me.firing = false; return true; } }; })());
JavaScript
/** * @class Ext.Template * <p>Represents an HTML fragment template. Templates may be {@link #compile precompiled} * for greater performance.</p> * An instance of this class may be created by passing to the constructor either * a single argument, or multiple arguments: * <div class="mdetail-params"><ul> * <li><b>single argument</b> : String/Array * <div class="sub-desc"> * The single argument may be either a String or an Array:<ul> * <li><tt>String</tt> : </li><pre><code> var t = new Ext.Template("&lt;div>Hello {0}.&lt;/div>"); t.{@link #append}('some-element', ['foo']); </code></pre> * <li><tt>Array</tt> : </li> * An Array will be combined with <code>join('')</code>. <pre><code> var t = new Ext.Template([ '&lt;div name="{id}"&gt;', '&lt;span class="{cls}"&gt;{name:trim} {value:ellipsis(10)}&lt;/span&gt;', '&lt;/div&gt;', ]); t.{@link #compile}(); t.{@link #append}('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'}); </code></pre> * </ul></div></li> * <li><b>multiple arguments</b> : String, Object, Array, ... * <div class="sub-desc"> * Multiple arguments will be combined with <code>join('')</code>. * <pre><code> var t = new Ext.Template( '&lt;div name="{id}"&gt;', '&lt;span class="{cls}"&gt;{name} {value}&lt;/span&gt;', '&lt;/div&gt;', // a configuration object: { compiled: true, // {@link #compile} immediately } ); </code></pre> * <p><b>Notes</b>:</p> * <div class="mdetail-params"><ul> * <li>Formatting and <code>disableFormats</code> are not applicable for Sencha Touch.</li> * <li>For a list of available format functions, see {@link Ext.util.Format}.</li> * <li><code>disableFormats</code> reduces <code>{@link #apply}</code> time * when no formatting is required.</li> * </ul></div> * </div></li> * </ul></div> * @param {Mixed} config */ Ext.Template = Ext.extend(Object, { constructor: function(html) { var me = this, args = arguments, buffer = [], value, i, length; me.initialConfig = {}; if (Ext.isArray(html)) { html = html.join(""); } else if (args.length > 1) { for (i = 0, length = args.length; i < length; i++) { value = args[i]; if (typeof value == 'object') { Ext.apply(me.initialConfig, value); Ext.apply(me, value); } else { buffer.push(value); } } html = buffer.join(''); } // @private me.html = html; if (me.compiled) { me.compile(); } }, isTemplate: true, /** * @cfg {Boolean} disableFormats Ture表示为禁止格式化功能(默认为false)。如果模板不包含转换函数,将该项设为true有助于apply()时的速度提升。true to disable format functions in the template. If the template doesn't contain format functions, setting * disableFormats to true will reduce apply time (defaults to false) */ disableFormats: false, re: /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, /** * 返回HTML片段,这块片断是由数据填充模板之后而成的。 * Returns an HTML fragment of this template with the specified values applied. * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}。The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @return {String} The HTML fragment * @hide repeat doc */ applyTemplate: function(values) { var me = this, useFormat = me.disableFormats !== true, fm = Ext.util.Format, tpl = me; if (me.compiled) { return me.compiled(values); } function fn(m, name, format, args) { if (format && useFormat) { if (args) { args = [values[name]].concat(new Function('return ['+ args +'];')()); } else { args = [values[name]]; } if (format.substr(0, 5) == "this.") { return tpl[format.substr(5)].apply(tpl, args); } else { return fm[format].apply(fm, args); } } else { return values[name] !== undefined ? values[name] : ""; } } return me.html.replace(me.re, fn); }, /** * 使得某段HTML可作用模板使用,也可将其编译。Sets the HTML used as the template and optionally compiles it. * @param {String} html * @param {Boolean} compile (可选的) ture表示为编译模板(默认为undefined)(optional) True to compile the template (defaults to undefined) * @return {Ext.Template} this */ set: function(html, compile) { var me = this; me.html = html; me.compiled = null; return compile ? me.compile() : me; }, compileARe: /\\/g, compileBRe: /(\r\n|\n)/g, compileCRe: /'/g, /** * 将模板编译成内置调用函数,消除刚才的正则表达式。 * Compiles the template into an internal function, eliminating the RegEx overhead. * @return {Ext.Template} this * @hide repeat doc */ compile: function() { var me = this, fm = Ext.util.Format, useFormat = me.disableFormats !== true, body, bodyReturn; function fn(m, name, format, args) { if (format && useFormat) { args = args ? ',' + args: ""; if (format.substr(0, 5) != "this.") { format = "fm." + format + '('; } else { format = 'this.' + format.substr(5) + '('; } } else { args = ''; format = "(values['" + name + "'] == undefined ? '' : "; } return "'," + format + "values['" + name + "']" + args + ") ,'"; } bodyReturn = me.html.replace(me.compileARe, '\\\\').replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn); body = "this.compiled = function(values){ return ['" + bodyReturn + "'].join('');};"; eval(body); return me; }, /** * 填充模板的数据,形成为一个或多个新节点,作为首个子节点插入到e1。 * @param {Mixed} el 上下文的元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ insertFirst: function(el, values, returnElement){ return this.doInsert('afterBegin', el, values, returnElement); }, /** * 填充模板的数据,形成为一个或多个新节点,作为首个子节点插入到e1。 * Applies the supplied values to the template and inserts the new node(s) as the first child of el. * @param {Mixed} el 上下文的元素The context element * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}。The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined)。(optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} 新节点或元素The new node or Element */ insertFirst: function(el, values, returnElement) { return this.doInsert('afterBegin', el, values, returnElement); }, /** * 填充模板的数据,形成为一个或多个新节点,并位于el之前的位置插入。 * Applies the supplied values to the template and inserts the new node(s) before el. * @param {Mixed} el The context element * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}。The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined)。(optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} 新节点或元素The new node or Element */ insertBefore: function(el, values, returnElement) { return this.doInsert('beforeBegin', el, values, returnElement); }, /** * 填充模板的数据,形成为一个或多个新节点,作为首个子节点插入到e1。 * @param {Mixed} el 上下文的元素 * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}. * @param {Boolean} returnElement (可选的)true表示为返回 Ext.Element (默认为undefined) * @return {HTMLElement/Ext.Element} 新节点或元素 */ insertAfter: function(el, values, returnElement) { return this.doInsert('afterEnd', el, values, returnElement); }, /** * Applies the supplied <code>values</code> to the template and appends * the new node(s) to the specified <code>el</code>. * <p>For example usage {@link #Template see the constructor}.</p> * @param {Mixed} el The context element * @param {Object/Array} values * The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>) * or an object (i.e. <code>{foo: 'bar'}</code>). * @param {Boolean} returnElement (optional) true to return an Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ append: function(el, values, returnElement) { return this.doInsert('beforeEnd', el, values, returnElement); }, doInsert: function(where, el, values, returnEl) { el = Ext.getDom(el); var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values)); return returnEl ? Ext.get(newNode, true) : newNode; }, /** * Applies the supplied values to the template and overwrites the content of el with the new node(s). * @param {Mixed} el The context element * @param {Object/Array} values The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @param {Boolean} returnElement (optional) true to return a Ext.Element (defaults to undefined) * @return {HTMLElement/Ext.Element} The new node or Element */ overwrite: function(el, values, returnElement) { el = Ext.getDom(el); el.innerHTML = this.applyTemplate(values); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; } }); /** * Alias for {@link #applyTemplate} * Returns an HTML fragment of this template with the specified <code>values</code> applied. * @param {Object/Array} values * The template values. Can be an array if the params are numeric (i.e. <code>{0}</code>) * or an object (i.e. <code>{foo: 'bar'}</code>). * @return {String} The HTML fragment * @member Ext.Template * @method apply */ Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; /** * 传入一个元素的值的参数,用于创建模板,(推荐<i>display:none</i> textarea)或innerHTML. * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML. * @param {String/HTMLElement} DOM元素或某id。A DOM element or its id * @param {Object} config 一个配置项对象。A configuration object * @returns {Ext.Template} 创建好的模板。The created template * @static */ Ext.Template.from = function(el, config) { el = Ext.getDom(el); return new Ext.Template(el.value || el.innerHTML, config || ''); };
JavaScript
/** * @class Ext.util.Region * @extends Object * * Represents a rectangular region and provides a number of utility methods * to compare regions. */ Ext.util.Region = Ext.extend(Object, { /** * @constructor * @param {Number} top Top * @param {Number} right Right * @param {Number} bottom Bottom * @param {Number} left Left */ constructor : function(t, r, b, l) { var me = this; me.top = t; me[1] = t; me.right = r; me.bottom = b; me.left = l; me[0] = l; }, /** * Checks if this region completely contains the region that is passed in. * @param {Ext.util.Region} region */ contains : function(region) { var me = this; return (region.left >= me.left && region.right <= me.right && region.top >= me.top && region.bottom <= me.bottom); }, /** * Checks if this region intersects the region passed in. * @param {Ext.util.Region} region * @return {Ext.util.Region/Boolean} Returns the intersected region or false if there is no intersection. */ intersect : function(region) { var me = this, t = Math.max(me.top, region.top), r = Math.min(me.right, region.right), b = Math.min(me.bottom, region.bottom), l = Math.max(me.left, region.left); if (b > t && r > l) { return new Ext.util.Region(t, r, b, l); } else { return false; } }, /** * Returns the smallest region that contains the current AND targetRegion. * @param {Ext.util.Region} region */ union : function(region) { var me = this, t = Math.min(me.top, region.top), r = Math.max(me.right, region.right), b = Math.max(me.bottom, region.bottom), l = Math.min(me.left, region.left); return new Ext.util.Region(t, r, b, l); }, /** * Modifies the current region to be constrained to the targetRegion. * @param {Ext.util.Region} targetRegion */ constrainTo : function(r) { var me = this, constrain = Ext.util.Numbers.constrain; me.top = constrain(me.top, r.top, r.bottom); me.bottom = constrain(me.bottom, r.top, r.bottom); me.left = constrain(me.left, r.left, r.right); me.right = constrain(me.right, r.left, r.right); return me; }, /** * Modifies the current region to be adjusted by offsets. * @param {Number} top top offset * @param {Number} right right offset * @param {Number} bottom bottom offset * @param {Number} left left offset */ adjust : function(t, r, b, l) { var me = this; me.top += t; me.left += l; me.right += r; me.bottom += b; return me; }, /** * Get the offset amount of a point outside the region * @param {String} axis optional * @param {Ext.util.Point} p the point * @return {Ext.util.Offset} */ getOutOfBoundOffset: function(axis, p) { if (!Ext.isObject(axis)) { if (axis == 'x') { return this.getOutOfBoundOffsetX(p); } else { return this.getOutOfBoundOffsetY(p); } } else { p = axis; var d = new Ext.util.Offset(); d.x = this.getOutOfBoundOffsetX(p.x); d.y = this.getOutOfBoundOffsetY(p.y); return d; } }, getOutOfBoundOffsetX: function(p) { if (p <= this.left) { return this.left - p; } else if (p >= this.right) { return this.right - p; } return 0; }, getOutOfBoundOffsetY: function(p) { if (p <= this.top) { return this.top - p; } else if (p >= this.bottom) { return this.bottom - p; } return 0; }, isOutOfBound: function(axis, p) { if (!Ext.isObject(axis)) { if (axis == 'x') { return this.isOutOfBoundX(p); } else { return this.isOutOfBoundY(p); } } else { p = axis; return (this.isOutOfBoundX(p.x) || this.isOutOfBoundY(p.y)); } }, isOutOfBoundX: function(p) { return (p < this.left || p > this.right); }, isOutOfBoundY: function(p) { return (p < this.top || p > this.bottom); }, /* * Restrict a point within the region by a certain factor. * @param {String} axis Optional * @param {Ext.util.Point/Ext.util.Offset/Object} p * @param {Number} factor */ restrict: function(axis, p, factor) { if (Ext.isObject(axis)) { var newP; factor = p; p = axis; if (p.copy) { newP = p.copy(); } else { newP = { x: p.x, y: p.y }; } newP.x = this.restrictX(p.x, factor); newP.y = this.restrictY(p.y, factor); return newP; } else { if (axis == 'x') { return this.restrictX(p, factor); } else { return this.restrictY(p, factor); } } }, restrictX : function(p, factor) { if (!factor) { factor = 1; } if (p <= this.left) { p -= (p - this.left) * factor; } else if (p >= this.right) { p -= (p - this.right) * factor; } return p; }, restrictY : function(p, factor) { if (!factor) { factor = 1; } if (p <= this.top) { p -= (p - this.top) * factor; } else if (p >= this.bottom) { p -= (p - this.bottom) * factor; } return p; }, getSize: function() { return { width: this.right - this.left, height: this.bottom - this.top }; }, /** * Copy a new instance * @return {Ext.util.Region} */ copy: function() { return new Ext.util.Region(this.top, this.right, this.bottom, this.left); }, /** * Dump this to an eye-friendly string, great for debugging * @return {String} */ toString: function() { return "Region[" + this.top + "," + this.right + "," + this.bottom + "," + this.left + "]"; }, translateBy: function(offset) { this.left += offset.x; this.right += offset.x; this.top += offset.y; this.bottom += offset.y; }, round: function() { this.top = Math.round(this.top); this.right = Math.round(this.right); this.bottom = Math.round(this.bottom); this.left = Math.round(this.left); return this; } }); /** * @static * @param {Mixed} el A string, DomElement or Ext.Element representing an element * on the page. * @returns {Ext.util.Region} region * Retrieves an Ext.util.Region for a particular element. */ Ext.util.Region.getRegion = function(el) { return Ext.fly(el).getPageBox(true); }; Ext.util.Region.from = function(o) { return new Ext.util.Region(o.top, o.right, o.bottom, o.left); };
JavaScript
/** * @class Ext.util.MixedCollection * @extends Ext.util.Observable * A Collection class that maintains both numeric indexes and keys and exposes events. * @constructor * @param {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll} * function should add function references to the collection. Defaults to * <tt>false</tt>. * @param {Function} keyFn A function that can accept an item of the type(s) stored in this MixedCollection * and return the key value for that item. This is used when available to look up the key on items that * were passed without an explicit key parameter to a MixedCollection method. Passing this parameter is * equivalent to providing an implementation for the {@link #getKey} method. */ Ext.util.MixedCollection = function(allowFunctions, keyFn) { this.items = []; this.map = {}; this.keys = []; this.length = 0; this.addEvents( /** * @event clear * Fires when the collection is cleared. */ 'clear', /** * @event add * Fires when an item is added to the collection. * @param {Number} index The index at which the item was added. * @param {Object} o The item added. * @param {String} key The key associated with the added item. */ 'add', /** * @event replace * Fires when an item is replaced in the collection. * @param {String} key he key associated with the new added. * @param {Object} old The item being replaced. * @param {Object} new The new item. */ 'replace', /** * @event remove * Fires when an item is removed from the collection. * @param {Object} o The item being removed. * @param {String} key (optional) The key associated with the removed item. */ 'remove', 'sort' ); this.allowFunctions = allowFunctions === true; if (keyFn) { this.getKey = keyFn; } Ext.util.MixedCollection.superclass.constructor.call(this); }; Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, { /** * @cfg {Boolean} allowFunctions Specify <tt>true</tt> if the {@link #addAll} * function should add function references to the collection. Defaults to * <tt>false</tt>. */ allowFunctions : false, /** * Adds an item to the collection. Fires the {@link #add} event when complete. * @param {String} key <p>The key to associate with the item, or the new item.</p> * <p>If a {@link #getKey} implementation was specified for this MixedCollection, * or if the key of the stored items is in a property called <tt><b>id</b></tt>, * the MixedCollection will be able to <i>derive</i> the key for the new item. * In this case just pass the new item in this parameter.</p> * @param {Object} o The item to add. * @return {Object} The item added. */ add : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } if(typeof key != 'undefined' && key !== null){ var old = this.map[key]; if(typeof old != 'undefined'){ return this.replace(key, o); } this.map[key] = o; } this.length++; this.items.push(o); this.keys.push(key); this.fireEvent('add', this.length-1, o, key); return o; }, /** * MixedCollection has a generic way to fetch keys if you implement getKey. The default implementation * simply returns <b><code>item.id</code></b> but you can provide your own implementation * to return a different value as in the following examples:<pre><code> // normal way var mc = new Ext.util.MixedCollection(); mc.add(someEl.dom.id, someEl); mc.add(otherEl.dom.id, otherEl); //and so on // using getKey var mc = new Ext.util.MixedCollection(); mc.getKey = function(el){ return el.dom.id; }; mc.add(someEl); mc.add(otherEl); // or via the constructor var mc = new Ext.util.MixedCollection(false, function(el){ return el.dom.id; }); mc.add(someEl); mc.add(otherEl); * </code></pre> * @param {Object} item The item for which to find the key. * @return {Object} The key for the passed item. */ getKey : function(o){ return o.id; }, /** * Replaces an item in the collection. Fires the {@link #replace} event when complete. * @param {String} key <p>The key associated with the item to replace, or the replacement item.</p> * <p>If you supplied a {@link #getKey} implementation for this MixedCollection, or if the key * of your stored items is in a property called <tt><b>id</b></tt>, then the MixedCollection * will be able to <i>derive</i> the key of the replacement item. If you want to replace an item * with one having the same key value, then just pass the replacement item in this parameter.</p> * @param o {Object} o (optional) If the first parameter passed was a key, the item to associate * with that key. * @return {Object} The new item. */ replace : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } var old = this.map[key]; if(typeof key == 'undefined' || key === null || typeof old == 'undefined'){ return this.add(key, o); } var index = this.indexOfKey(key); this.items[index] = o; this.map[key] = o; this.fireEvent('replace', key, old, o); return o; }, /** * Adds all elements of an Array or an Object to the collection. * @param {Object/Array} objs An Object containing properties which will be added * to the collection, or an Array of values, each of which are added to the collection. * Functions references will be added to the collection if <code>{@link #allowFunctions}</code> * has been set to <tt>true</tt>. */ addAll : function(objs){ if(arguments.length > 1 || Ext.isArray(objs)){ var args = arguments.length > 1 ? arguments : objs; for(var i = 0, len = args.length; i < len; i++){ this.add(args[i]); } }else{ for(var key in objs){ if (!objs.hasOwnProperty(key)) { continue; } if(this.allowFunctions || typeof objs[key] != 'function'){ this.add(key, objs[key]); } } } }, /** * Executes the specified function once for every item in the collection, passing the following arguments: * <div class="mdetail-params"><ul> * <li><b>item</b> : Mixed<p class="sub-desc">The collection item</p></li> * <li><b>index</b> : Number<p class="sub-desc">The item's index</p></li> * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the collection</p></li> * </ul></div> * The function should return a boolean value. Returning false from the function will stop the iteration. * @param {Function} fn The function to execute for each item. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current item in the iteration. */ each : function(fn, scope){ var items = [].concat(this.items); // each safe for removal for(var i = 0, len = items.length; i < len; i++){ if(fn.call(scope || items[i], items[i], i, len) === false){ break; } } }, /** * Executes the specified function once for every key in the collection, passing each * key, and its associated item as the first two parameters. * @param {Function} fn The function to execute for each item. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window. */ eachKey : function(fn, scope){ for(var i = 0, len = this.keys.length; i < len; i++){ fn.call(scope || window, this.keys[i], this.items[i], i, len); } }, /** * Returns the first item in the collection which elicits a true return value from the * passed selection function. * @param {Function} fn The selection function to execute for each item. * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window. * @return {Object} The first item in the collection which returned true from the selection function. */ findBy : function(fn, scope) { for(var i = 0, len = this.items.length; i < len; i++){ if(fn.call(scope || window, this.items[i], this.keys[i])){ return this.items[i]; } } return null; }, //<debug> find : function() { throw "Stateful: find has been deprecated. Please use findBy."; }, //</debug> /** * Inserts an item at the specified index in the collection. Fires the {@link #add} event when complete. * @param {Number} index The index to insert the item at. * @param {String} key The key to associate with the new item, or the item itself. * @param {Object} o (optional) If the second parameter was a key, the new item. * @return {Object} The item inserted. */ insert : function(index, key, o){ if(arguments.length == 2){ o = arguments[1]; key = this.getKey(o); } if(this.containsKey(key)){ this.suspendEvents(); this.removeByKey(key); this.resumeEvents(); } if(index >= this.length){ return this.add(key, o); } this.length++; this.items.splice(index, 0, o); if(typeof key != 'undefined' && key !== null){ this.map[key] = o; } this.keys.splice(index, 0, key); this.fireEvent('add', index, o, key); return o; }, /** * Remove an item from the collection. * @param {Object} o The item to remove. * @return {Object} The item removed or false if no item was removed. */ remove : function(o){ return this.removeAt(this.indexOf(o)); }, /** * Remove all items in the passed array from the collection. * @param {Array} items An array of items to be removed. * @return {Ext.util.MixedCollection} this object */ removeAll : function(items){ Ext.each(items || [], function(item) { this.remove(item); }, this); return this; }, /** * Remove an item from a specified index in the collection. Fires the {@link #remove} event when complete. * @param {Number} index The index within the collection of the item to remove. * @return {Object} The item removed or false if no item was removed. */ removeAt : function(index){ if(index < this.length && index >= 0){ this.length--; var o = this.items[index]; this.items.splice(index, 1); var key = this.keys[index]; if(typeof key != 'undefined'){ delete this.map[key]; } this.keys.splice(index, 1); this.fireEvent('remove', o, key); return o; } return false; }, /** * Removed an item associated with the passed key fom the collection. * @param {String} key The key of the item to remove. * @return {Object} The item removed or false if no item was removed. */ removeByKey : function(key){ return this.removeAt(this.indexOfKey(key)); }, //<debug> removeKey : function() { console.warn('MixedCollection: removeKey has been deprecated. Please use removeByKey.'); return this.removeByKey.apply(this, arguments); }, //</debug> /** * Returns the number of items in the collection. * @return {Number} the number of items in the collection. */ getCount : function(){ return this.length; }, /** * Returns index within the collection of the passed Object. * @param {Object} o The item to find the index of. * @return {Number} index of the item. Returns -1 if not found. */ indexOf : function(o){ return this.items.indexOf(o); }, /** * Returns index within the collection of the passed key. * @param {String} key The key to find the index of. * @return {Number} index of the key. */ indexOfKey : function(key){ return this.keys.indexOf(key); }, /** * Returns the item associated with the passed key OR index. * Key has priority over index. This is the equivalent * of calling {@link #key} first, then if nothing matched calling {@link #getAt}. * @param {String/Number} key The key or index of the item. * @return {Object} If the item is found, returns the item. If the item was not found, returns <tt>undefined</tt>. * If an item was found, but is a Class, returns <tt>null</tt>. */ get : function(key) { var mk = this.map[key], item = mk !== undefined ? mk : (typeof key == 'number') ? this.items[key] : undefined; return typeof item != 'function' || this.allowFunctions ? item : null; // for prototype! }, //<debug> item : function() { console.warn('MixedCollection: item has been deprecated. Please use get.'); return this.get.apply(this, arguments); }, //</debug> /** * Returns the item at the specified index. * @param {Number} index The index of the item. * @return {Object} The item at the specified index. */ getAt : function(index) { return this.items[index]; }, //<debug> itemAt : function() { console.warn('MixedCollection: itemAt has been deprecated. Please use getAt.'); return this.getAt.apply(this, arguments); }, //</debug> /** * Returns the item associated with the passed key. * @param {String/Number} key The key of the item. * @return {Object} The item associated with the passed key. */ getByKey : function(key) { return this.map[key]; }, //<debug> key : function() { console.warn('MixedCollection: key has been deprecated. Please use getByKey.'); return this.getByKey.apply(this, arguments); }, //</debug> /** * Returns true if the collection contains the passed Object as an item. * @param {Object} o The Object to look for in the collection. * @return {Boolean} True if the collection contains the Object as an item. */ contains : function(o){ return this.indexOf(o) != -1; }, /** * Returns true if the collection contains the passed Object as a key. * @param {String} key The key to look for in the collection. * @return {Boolean} True if the collection contains the Object as a key. */ containsKey : function(key){ return typeof this.map[key] != 'undefined'; }, /** * Removes all items from the collection. Fires the {@link #clear} event when complete. */ clear : function(){ this.length = 0; this.items = []; this.keys = []; this.map = {}; this.fireEvent('clear'); }, /** * Returns the first item in the collection. * @return {Object} the first item in the collection.. */ first : function() { return this.items[0]; }, /** * Returns the last item in the collection. * @return {Object} the last item in the collection.. */ last : function() { return this.items[this.length-1]; }, /** * @private * Performs the actual sorting based on a direction and a sorting function. Internally, * this creates a temporary array of all items in the MixedCollection, sorts it and then writes * the sorted array data back into this.items and this.keys * @param {String} property Property to sort by ('key', 'value', or 'index') * @param {String} dir (optional) Direction to sort 'ASC' or 'DESC'. Defaults to 'ASC'. * @param {Function} fn (optional) Comparison function that defines the sort order. * Defaults to sorting by numeric value. */ _sort : function(property, dir, fn){ var i, len, dsc = String(dir).toUpperCase() == 'DESC' ? -1 : 1, //this is a temporary array used to apply the sorting function c = [], keys = this.keys, items = this.items; //default to a simple sorter function if one is not provided fn = fn || function(a, b) { return a - b; }; //copy all the items into a temporary array, which we will sort for(i = 0, len = items.length; i < len; i++){ c[c.length] = { key : keys[i], value: items[i], index: i }; } //sort the temporary array c.sort(function(a, b){ var v = fn(a[property], b[property]) * dsc; if(v === 0){ v = (a.index < b.index ? -1 : 1); } return v; }); //copy the temporary array back into the main this.items and this.keys objects for(i = 0, len = c.length; i < len; i++){ items[i] = c[i].value; keys[i] = c[i].key; } this.fireEvent('sort', this); }, /** * Sorts this collection by <b>item</b> value with the passed comparison function. * @param {Array/String} property Set of {@link Ext.util.Sorter} objects to sort by, or a property of each item * in the collection to sort on if using the 2 argument form * @param {String} direction Optional direction (used in the 2 argument signature of this method). Defaults to "ASC" */ sort : function(property, direction) { //in case we were passed an array of sorters var sorters = property; //support for the simple case of sorting by property/direction if (Ext.isString(property)) { sorters = [new Ext.util.Sorter({ property : property, direction: direction || "ASC" })]; } else if (property instanceof Ext.util.Sorter) { sorters = [property]; } else if (Ext.isObject(property)) { sorters = [new Ext.util.Sorter(property)]; } var length = sorters.length; if (length == 0) { return; } //construct an amalgamated sorter function which combines all of the Sorters passed var sorterFn = function(r1, r2) { var result = sorters[0].sort(r1, r2), length = sorters.length, i; //if we have more than one sorter, OR any additional sorter functions together for (i = 1; i < length; i++) { result = result || sorters[i].sort.call(this, r1, r2); } return result; }; this.sortBy(sorterFn); }, /** * Sorts the collection by a single sorter function * @param {Function} sorterFn The function to sort by */ sortBy: function(sorterFn) { var items = this.items, keys = this.keys, length = items.length, temp = [], i; //first we create a copy of the items array so that we can sort it for (i = 0; i < length; i++) { temp[i] = { key : keys[i], value: items[i], index: i }; } temp.sort(function(a, b) { var v = sorterFn(a.value, b.value); if (v === 0) { v = (a.index < b.index ? -1 : 1); } return v; }); //copy the temporary array back into the main this.items and this.keys objects for (i = 0; i < length; i++) { items[i] = temp[i].value; keys[i] = temp[i].key; } this.fireEvent('sort', this); }, /** * Reorders each of the items based on a mapping from old index to new index. Internally this * just translates into a sort. The 'sort' event is fired whenever reordering has occured. * @param {Object} mapping Mapping from old item index to new item index */ reorder: function(mapping) { this.suspendEvents(); var items = this.items, index = 0, length = items.length, order = [], remaining = [], oldIndex; //object of {oldPosition: newPosition} reversed to {newPosition: oldPosition} for (oldIndex in mapping) { order[mapping[oldIndex]] = items[oldIndex]; } for (index = 0; index < length; index++) { if (mapping[index] == undefined) { remaining.push(items[index]); } } for (index = 0; index < length; index++) { if (order[index] == undefined) { order[index] = remaining.shift(); } } this.clear(); this.addAll(order); this.resumeEvents(); this.fireEvent('sort', this); }, /** * Sorts this collection by <b>key</b>s. * @param {String} direction (optional) 'ASC' or 'DESC'. Defaults to 'ASC'. * @param {Function} fn (optional) Comparison function that defines the sort order. * Defaults to sorting by case insensitive string. */ sortByKey : function(dir, fn){ this._sort('key', dir, fn || function(a, b){ var v1 = String(a).toUpperCase(), v2 = String(b).toUpperCase(); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }); }, //<debug> keySort : function() { console.warn('MixedCollection: keySort has been deprecated. Please use sortByKey.'); return this.sortByKey.apply(this, arguments); }, //</debug> /** * Returns a range of items in this collection * @param {Number} startIndex (optional) The starting index. Defaults to 0. * @param {Number} endIndex (optional) The ending index. Defaults to the last item. * @return {Array} An array of items */ getRange : function(start, end){ var items = this.items; if(items.length < 1){ return []; } start = start || 0; end = Math.min(typeof end == 'undefined' ? this.length-1 : end, this.length-1); var i, r = []; if(start <= end){ for(i = start; i <= end; i++) { r[r.length] = items[i]; } }else{ for(i = start; i >= end; i--) { r[r.length] = items[i]; } } return r; }, /** * <p>Filters the objects in this collection by a set of {@link Ext.util.Filter Filter}s, or by a single * property/value pair with optional parameters for substring matching and case sensitivity. See * {@link Ext.util.Filter Filter} for an example of using Filter objects (preferred). Alternatively, * MixedCollection can be easily filtered by property like this:</p> <pre><code> //create a simple store with a few people defined var people = new Ext.util.MixedCollection(); people.addAll([ {id: 1, age: 25, name: 'Ed'}, {id: 2, age: 24, name: 'Tommy'}, {id: 3, age: 24, name: 'Arne'}, {id: 4, age: 26, name: 'Aaron'} ]); //a new MixedCollection containing only the items where age == 24 var middleAged = people.filter('age', 24); </code></pre> * * * @param {Array/String} property A property on your objects, or an array of {@link Ext.util.Filter Filter} objects * @param {String/RegExp} value Either string that the property values * should start with or a RegExp to test against the property * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning * @param {Boolean} caseSensitive (optional) True for case sensitive comparison (defaults to False). * @return {MixedCollection} The new filtered collection */ filter : function(property, value, anyMatch, caseSensitive) { var filters = []; //support for the simple case of filtering by property/value if (Ext.isString(property)) { filters.push(new Ext.util.Filter({ property : property, value : value, anyMatch : anyMatch, caseSensitive: caseSensitive })); } else if (Ext.isArray(property) || property instanceof Ext.util.Filter) { filters = filters.concat(property); } //at this point we have an array of zero or more Ext.util.Filter objects to filter with, //so here we construct a function that combines these filters by ANDing them together var filterFn = function(record) { var isMatch = true, length = filters.length, i; for (i = 0; i < length; i++) { var filter = filters[i], fn = filter.filterFn, scope = filter.scope; isMatch = isMatch && fn.call(scope, record); } return isMatch; }; return this.filterBy(filterFn); }, /** * Filter by a function. Returns a <i>new</i> collection that has been filtered. * The passed function will be called with each object in the collection. * If the function returns true, the value is included otherwise it is filtered. * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key) * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection. * @return {MixedCollection} The new filtered collection */ filterBy : function(fn, scope) { var newMC = new Ext.util.MixedCollection(), keys = this.keys, items = this.items, length = items.length, i; newMC.getKey = this.getKey; for (i = 0; i < length; i++) { if (fn.call(scope||this, items[i], keys[i])) { newMC.add(keys[i], items[i]); } } return newMC; }, /** * Finds the index of the first matching object in this collection by a specific property/value. * @param {String} property The name of a property on your objects. * @param {String/RegExp} value A string that the property values * should start with or a RegExp to test against the property. * @param {Number} start (optional) The index to start searching at (defaults to 0). * @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 {Number} The matched index or -1 */ findIndex : function(property, value, start, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return -1; } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.findIndexBy(function(o){ return o && value.test(o[property]); }, null, start); }, /** * Find the index of the first matching object in this collection by a function. * If the function returns <i>true</i> it is considered a match. * @param {Function} fn The function to be called, it will receive the args o (the object), k (the key). * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this MixedCollection. * @param {Number} start (optional) The index to start searching at (defaults to 0). * @return {Number} The matched index or -1 */ findIndexBy : function(fn, scope, start){ var k = this.keys, it = this.items; for(var i = (start||0), len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } return -1; }, /** * Returns a regular expression based on the given value and matching options. This is used internally for finding and filtering, * and by Ext.data.Store#filter * @private * @param {String} value The value to create the regex for. This is escaped using Ext.escapeRe * @param {Boolean} anyMatch True to allow any match - no regex start/end line anchors will be added. Defaults to false * @param {Boolean} caseSensitive True to make the regex case sensitive (adds 'i' switch to 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. */ createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) { if (!value.exec) { // not a regex var er = Ext.util.Format.escapeRegex; value = String(value); if (anyMatch === true) { value = er(value); } else { value = '^' + er(value); if (exactMatch === true) { value += '$'; } } value = new RegExp(value, caseSensitive ? '' : 'i'); } return value; }, /** * Creates a shallow copy of this collection * @return {MixedCollection} */ clone : function(){ var r = new Ext.util.MixedCollection(); var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ r.add(k[i], it[i]); } r.getKey = this.getKey; return r; } }); /** * This method calls {@link #item item()}. * Returns the item associated with the passed key OR index. Key has priority * over index. This is the equivalent of calling {@link #key} first, then if * nothing matched calling {@link #getAt}. * @param {String/Number} key The key or index of the item. * @return {Object} If the item is found, returns the item. If the item was * not found, returns <tt>undefined</tt>. If an item was found, but is a Class, * returns <tt>null</tt>. */ // Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item;
JavaScript
/** * @class Ext.XTemplate * @extends Ext.Template * <p>支持高级功能的模板类,如:A template class that supports advanced functionality like:<div class="mdetail-params"><ul> * <li>自动数组输出,主模板和子模板均可用。Autofilling arrays using templates and sub-templates</li> * <li>利用基本的比较符进行条件判断。Conditional processing with basic comparison operators</li> * <li>支持基本算术运算。Basic math function support</li> * <li>特殊内建的模板变量。Execute arbitrary inline code with special built-in template variables</li> * <li>自定义成员函数。Custom member functions</li> * <li>XTemplate有些特殊的标签和内建的操作运算符,是模板创建时生成的,不属于API条目的一部分。 * Many special tags and built-in operators that aren't defined as part of * the API, but are supported in the templates that can be created</li> * </ul></div></p> * <p> * 下面的例子就演示了这些特殊部分的用法。每一个例子使用的数据对象如下: * XTemplate provides the templating mechanism built into:<div class="mdetail-params"><ul> * <li>{@link Ext.DataView}</li> * </ul></div></p> * * The {@link Ext.Template} describes * the acceptable parameters to pass to the constructor. The following * examples demonstrate all of the supported features.</p> * * <div class="mdetail-params"><ul> * * <li><b><u>样本数据。Sample Data</u></b> * <div class="sub-desc"> * <p>下面是为每一个例子所使用的数据对象。This is the data object used for reference in each code example:</p> * <pre><code> var data = { name: 'Tommy Maintz', title: 'Lead Developer', company: 'Ext JS, Inc', email: 'tommy@extjs.com', address: '5 Cups Drive', city: 'Palo Alto', state: 'CA', zip: '44102', drinks: ['Coffee', 'Soda', 'Water'], kids: [{ name: 'Joshua', age:3 },{ name: 'Matthew', age:2 },{ name: 'Solomon', age:0 }] }; </code></pre> * </div> * </li> * * * <li><b><u>Auto filling of arrays</u></b> * <div class="sub-desc"> * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>for</tt></b> operator are used * to process the provided data object: * <ul> * <li>If the value specified in <tt>for</tt> is an array, it will auto-fill, * repeating the template block inside the <tt>tpl</tt> tag for each item in the * array.</li> * <li>If <tt>for="."</tt> is specified, the data object provided is examined.</li> * <li>While processing an array, the special variable <tt>{#}</tt> * will provide the current array index + 1 (starts at 1, not 0).</li> * </ul> * </p> * <pre><code> &lt;tpl <b>for</b>=".">...&lt;/tpl> // loop through array at root node &lt;tpl <b>for</b>="foo">...&lt;/tpl> // loop through array at foo node &lt;tpl <b>for</b>="foo.bar">...&lt;/tpl> // loop through array at foo.bar node </code></pre> * Using the sample data above: * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Kids: ', '&lt;tpl <b>for</b>=".">', // process the data.kids node '&lt;p>{#}. {name}&lt;/p>', // use current array index to autonumber '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object </code></pre> * <p>An example illustrating how the <b><tt>for</tt></b> property can be leveraged * to access specified members of the provided data object to populate the template:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Title: {title}&lt;/p>', '&lt;p>Company: {company}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl <b>for="kids"</b>>', // interrogate the kids property within the data '&lt;p>{name}&lt;/p>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); // pass the root node of the data object </code></pre> * <p>Flat arrays that contain values (and not objects) can be auto-rendered * using the special <b><tt>{.}</tt></b> variable inside a loop. This variable * will represent the value of the array at the current index:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>{name}\&#39;s favorite beverages:&lt;/p>', '&lt;tpl for="drinks">', '&lt;div> - {.}&lt;/div>', '&lt;/tpl>' ); tpl.overwrite(panel.body, data); </code></pre> * <p>When processing a sub-template, for example while looping through a child array, * you can access the parent object's members via the <b><tt>parent</tt></b> object:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', '&lt;p>{name}&lt;/p>', '&lt;p>Dad: {<b>parent</b>.name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * * <li><b><u>Conditional processing with basic comparison operators</u></b> * <div class="sub-desc"> * <p>The <b><tt>tpl</tt></b> tag and the <b><tt>if</tt></b> operator are used * to provide conditional checks for deciding whether or not to render specific * parts of the template. Notes:<div class="sub-desc"><ul> * <li>Double quotes must be encoded if used within the conditional</li> * <li>There is no <tt>else</tt> operator &mdash; if needed, two opposite * <tt>if</tt> statements should be used.</li> * </ul></div> * <pre><code> &lt;tpl if="age &gt; 1 &amp;&amp; age &lt; 10">Child&lt;/tpl> &lt;tpl if="age >= 10 && age < 18">Teenager&lt;/tpl> &lt;tpl <b>if</b>="this.isGirl(name)">...&lt;/tpl> &lt;tpl <b>if</b>="id==\'download\'">...&lt;/tpl> &lt;tpl <b>if</b>="needsIcon">&lt;img src="{icon}" class="{iconCls}"/>&lt;/tpl> // no good: &lt;tpl if="name == "Tommy"">Hello&lt;/tpl> // encode &#34; if it is part of the condition, e.g. &lt;tpl if="name == &#38;quot;Tommy&#38;quot;">Hello&lt;/tpl> * </code></pre> * Using the sample data above: * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', '&lt;p>{name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * <li><b><u>基本的算术。Basic math support</u></b> * <div class="sub-desc"> * <p>处理数值类型的数据时候,可支持下列的数学运算符(加减乘除): The following basic math operators may be applied directly on numeric * data values:</p><pre> * + - * / * </pre> * 举例如下:For example: * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="age &amp;gt; 1">', // <-- 注意&gt;要被编码。Note that the &gt; is encoded '&lt;p>{#}: {name}&lt;/p>', // <-- 为每一项自动排号。Auto-number each item '&lt;p>In 5 Years: {age+5}&lt;/p>', // <-- 简单的计算。Basic math '&lt;p>Dad: {parent.name}&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * * <li><b><u>即时执行任意的代码,支持访问模板变量。Execute arbitrary inline code with special built-in template variables</u></b> * <div class="sub-desc"> * <p> * 在XTemplate中,<code>{[ ... ]}</code>范围内的内容会在模板作用域的范围下执行。这里有一些特殊的变量: * Anything between <code>{[ ... ]}</code> is considered code to be executed * in the scope of the template. There are some special variables available in that code: * <ul> * <li><b><tt>values</tt></b>: 当前作用域下的值。若想改变其中的<tt>值</tt>,你可以切换子模板的作用域。 * The values in the current scope. If you are using * scope changing sub-templates, you can change what <tt>values</tt> is.</li> * <li><b><tt>parent</tt></b>: 父级模板的对象。The scope (values) of the ancestor template.</li> * <li><b><tt>xindex</tt></b>: 若是循环模板,这是当前循环的索引index(从1-based开始)。<If you are in a looping template, the index of the * loop you are in (1-based).</li> * <li><b><tt>xcount</tt></b>: 若是循环模板,这是循环的次数。If you are in a looping template, the total length * of the array you are looping.</li> * </ul> * 这是一个例子说明怎么利用这个知识点生成交错行: * This example demonstrates basic row striping using an inline code block and the * <tt>xindex</tt> variable:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Company: {[values.company.toUpperCase() + ", " + values.title]}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;div class="{[xindex % 2 === 0 ? "even" : "odd"]}">', '{name}', '&lt;/div>', '&lt;/tpl>&lt;/p>' ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * <li><b><u>模板成员函数。Template member functions</u></b> * <div class="sub-desc"> * <p> * 对于一些复制的处理,可以配置项对象的方式传入一个或一个以上的成员函数到XTemplate构造器中: * One or more member functions can be specified in a configuration * object passed into the XTemplate constructor for more complex processing:</p> * <pre><code> var tpl = new Ext.XTemplate( '&lt;p>Name: {name}&lt;/p>', '&lt;p>Kids: ', '&lt;tpl for="kids">', '&lt;tpl if="this.isGirl(name)">', '&lt;p>Girl: {name} - {age}&lt;/p>', '&lt;/tpl>', // 使用相反的if语句来模拟“else”的逻辑过程:use opposite if statement to simulate 'else' processing: '&lt;tpl if="this.isGirl(name) == false">', '&lt;p>Boy: {name} - {age}&lt;/p>', '&lt;/tpl>', '&lt;tpl if="this.isBaby(age)">', '&lt;p>{name} is a baby!&lt;/p>', '&lt;/tpl>', '&lt;/tpl>&lt;/p>', { // XTemplate的配置项: XTemplate configuration: compiled: true, // 成员函数:member functions: isGirl: function(name){ return name == 'Sara Grace'; }, isBaby: function(age){ return age < 1; } } ); tpl.overwrite(panel.body, data); </code></pre> * </div> * </li> * * </ul></div> * * @param {Mixed} config */ Ext.XTemplate = Ext.extend(Ext.Template, { argsRe: /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/, nameRe: /^<tpl\b[^>]*?for="(.*?)"/, ifRe: /^<tpl\b[^>]*?if="(.*?)"/, execRe: /^<tpl\b[^>]*?exec="(.*?)"/, constructor: function() { Ext.XTemplate.superclass.constructor.apply(this, arguments); var me = this, html = me.html, argsRe = me.argsRe, nameRe = me.nameRe, ifRe = me.ifRe, execRe = me.execRe, id = 0, tpls = [], VALUES = 'values', PARENT = 'parent', XINDEX = 'xindex', XCOUNT = 'xcount', RETURN = 'return ', WITHVALUES = 'with(values){ ', m, matchName, matchIf, matchExec, exp, fn, exec, name, i; html = ['<tpl>', html, '</tpl>'].join(''); while ((m = html.match(argsRe))) { exp = null; fn = null; exec = null; matchName = m[0].match(nameRe); matchIf = m[0].match(ifRe); matchExec = m[0].match(execRe); exp = matchIf ? matchIf[1] : null; if (exp) { fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + 'try{' + RETURN + Ext.util.Format.htmlDecode(exp) + ';}catch(e){return;}}'); } exp = matchExec ? matchExec[1] : null; if (exp) { exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + Ext.util.Format.htmlDecode(exp) + ';}'); } name = matchName ? matchName[1] : null; if (name) { if (name === '.') { name = VALUES; } else if (name === '..') { name = PARENT; } name = new Function(VALUES, PARENT, 'try{' + WITHVALUES + RETURN + name + ';}}catch(e){return;}'); } tpls.push({ id: id, target: name, exec: exec, test: fn, body: m[1] || '' }); html = html.replace(m[0], '{xtpl' + id + '}'); id = id + 1; } for (i = tpls.length - 1; i >= 0; --i) { me.compileTpl(tpls[i]); } me.master = tpls[tpls.length - 1]; me.tpls = tpls; }, // @private applySubTemplate: function(id, values, parent, xindex, xcount) { var me = this, t = me.tpls[id]; return t.compiled.call(me, values, parent, xindex, xcount); }, /** * @cfg {RegExp} codeRe 用来捕获模板变量的正则表达式(默认格式是<tt>{[expression]}</tt>)。 * The regular expression used to match code variables (default: matches <tt>{[expression]}</tt>). */ codeRe: /\{\[((?:\\\]|.|\n)*?)\]\}/g, re: /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?\}/g, // @private compileTpl: function(tpl) { var fm = Ext.util.Format, me = this, useFormat = me.disableFormats !== true, body, bodyReturn, evaluatedFn; function fn(m, name, format, args, math) { var v; // name is what is inside the {} // Name begins with xtpl, use a Sub Template if (name.substr(0, 4) == 'xtpl') { return "',this.applySubTemplate(" + name.substr(4) + ", values, parent, xindex, xcount),'"; } // name = "." - Just use the values object. if (name == '.') { v = 'typeof values == "string" ? values : ""'; } // name = "#" - Use the xindex else if (name == '#') { v = 'xindex'; } else if (name.substr(0, 7) == "parent.") { v = name; } // name has a . in it - Use object literal notation, starting from values else if (name.indexOf('.') != -1) { v = "values." + name; } // name is a property of values else { v = "values['" + name + "']"; } if (math) { v = '(' + v + math + ')'; } if (format && useFormat) { args = args ? ',' + args : ""; if (format.substr(0, 5) != "this.") { format = "fm." + format + '('; } else { format = 'this.' + format.substr(5) + '('; } } else { args = ''; format = "(" + v + " === undefined ? '' : "; } return "'," + format + v + args + "),'"; } function codeFn(m, code) { // Single quotes get escaped when the template is compiled, however we want to undo this when running code. return "',(" + code.replace(me.compileARe, "'") + "),'"; } bodyReturn = tpl.body.replace(me.compileBRe, '\\n').replace(me.compileCRe, "\\'").replace(me.re, fn).replace(me.codeRe, codeFn); body = "evaluatedFn = function(values, parent, xindex, xcount){return ['" + bodyReturn + "'].join('');};"; eval(body); tpl.compiled = function(values, parent, xindex, xcount) { var vs, length, buffer, i; if (tpl.test && !tpl.test.call(me, values, parent, xindex, xcount)) { return ''; } vs = tpl.target ? tpl.target.call(me, values, parent) : values; if (!vs) { return ''; } parent = tpl.target ? values : parent; if (tpl.target && Ext.isArray(vs)) { buffer = [], length = vs.length; if (tpl.exec) { for (i = 0; i < length; i++) { buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length); tpl.exec.call(me, vs[i], parent, i + 1, length); } } else { for (i = 0; i < length; i++) { buffer[buffer.length] = evaluatedFn.call(me, vs[i], parent, i + 1, length); } } return buffer.join(''); } if (tpl.exec) { tpl.exec.call(me, vs, parent, xindex, xcount); } return evaluatedFn.call(me, vs, parent, xindex, xcount); } return this; }, /** * 返回HTML片断,这块片断是由数据填充模板之后而成的。 * Returns an HTML fragment of this template with the specified values applied. * @param {Object} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @return {String} HTML片断。The HTML fragment */ applyTemplate: function(values) { return this.master.compiled.call(this, values, {}, 1, 1); }, /** * 把这个模板编译为一个函数,推荐多次使用这个模板时用这个方法,以提高性能。 * Compile the template to a function for optimized performance. Recommended if the template will be used frequently. * @return {Function} 编译后的函数。The compiled function */ compile: function() { return this; } }); /** * {@link #applyTemplate}的简写方式。 * 返回HTML片断,这块片断是由数据填充模板之后而成的。 * Returns an HTML fragment of this template with the specified values applied. * @param {Object/Array} values 模板填充值。该参数可以是一个数组(如果参数是数值型,如{0},或是一个对象,如{foo: 'bar'}.The template values. Can be an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}) * @return {String} HTML片断。The HTML fragment * @member Ext.XTemplate * @method apply */ Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate; /** * 从某个元素的value或innerHTML中创建模板(推荐<i>display:none</i> textarea元素)。 * Creates a template from the passed element's value (<i>display:none</i> textarea, preferred) or innerHTML. * @param {String/HTMLElement} el DOM元素或其id。A DOM element or its id * @return {Ext.Template} 模板对象。The created Template. * @static */ Ext.XTemplate.from = function(el, config) { el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML, config || {}); };
JavaScript
/** * @class Ext.util.Functions * @singleton */ Ext.util.Functions = { /** * Creates an interceptor function. The passed function is called before the original one. If it returns false, * the original one is not called. The resulting function returns the results of the original function. * The passed function is called with the parameters of the original function. Example usage: * <pre><code> var sayHi = function(name){ alert('Hi, ' + name); } sayHi('Fred'); // alerts "Hi, Fred" // create a new function that validates input without // directly modifying the original function: var sayHiToFriend = Ext.createInterceptor(sayHi, function(name){ return name == 'Brian'; }); sayHiToFriend('Fred'); // no alert sayHiToFriend('Brian'); // alerts "Hi, Brian" </code></pre> * @param {Function} origFn The original function. * @param {Function} newFn The function to call before the original * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed. * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b> * @param {Mixed} returnValue (optional) The value to return if the passed function return false (defaults to null). * @return {Function} The new function */ createInterceptor: function(origFn, newFn, scope, returnValue) { var method = origFn; if (!Ext.isFunction(newFn)) { return origFn; } else { return function() { var me = this, args = arguments; newFn.target = me; newFn.method = origFn; return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null; }; } }, /** </code></pre> * @param {Function} fn The function to delegate. * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed. * <b>If omitted, defaults to the browser window.</b> * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Function} The new function */ /** * 创建一个委派对象(就是回调),该对象的作用域指向obj。 * 对于任何函数来说都是可以直接调用的。例如:<code>this.myFunction.createDelegate(this)</code> * 将创建一个函数,该函数的作用域会自动指向<tt>this</tt>。 * Creates a delegate (callback) that sets the scope to obj. * Call directly on any function. Example: <code>Ext.createDelegate(this.myFunction, this, [arg1, arg2])</code> * Will create a function that is automatically scoped to obj so that the <tt>this</tt> variable inside the * callback points to obj. Example usage: * <pre><code> var sayHi = function(name){ // Note this use of "this.text" here. This function expects to // execute within a scope that contains a text property. In this // example, the "this" variable is pointing to the btn object that // was passed in createDelegate below. alert('Hi, ' + name + '. You clicked the "' + this.text + '" button.'); } var btn = new Ext.Button({ text: 'Say Hi', renderTo: Ext.getBody() }); // This callback will execute in the scope of the // button instance. Clicking the button alerts // "Hi, Fred. You clicked the "Say Hi" button." btn.on('click', Ext.createDelegate(sayHi, btn, ['Fred'])); </code></pre> * @param {Function} fn 要委托的函数。The function to delegate. * @param {Object} obj (可选的) 自定义的作用域对象。 * (optional) The object for which the scope is set * @param {Array} args (可选的) 覆盖该次调用的参数列表。(默认为该函数的arguments)。 * (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (可选的) 如果该参数为true,将args加载到该函数的后面,如果该参数为数字类型,则args将插入到所指定的位置。 * (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Function} 新产生的函数。The new function */ createDelegate: function(fn, obj, args, appendArgs) { if (!Ext.isFunction(fn)) { return fn; } return function() { var callArgs = args || arguments; if (appendArgs === true) { callArgs = Array.prototype.slice.call(arguments, 0); callArgs = callArgs.concat(args); } else if (Ext.isNumber(appendArgs)) { callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first var applyArgs = [appendArgs, 0].concat(args); // create method call params Array.prototype.splice.apply(callArgs, applyArgs); // splice them in } return fn.apply(obj || window, callArgs); }; }, /** * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: * <pre><code> var sayHi = function(name){ alert('Hi, ' + name); } // executes immediately: sayHi('Fred'); // executes after 2 seconds: Ext.defer(sayHi, 2000, this, ['Fred']); // this syntax is sometimes useful for deferring // execution of an anonymous function: Ext.defer(function(){ alert('Anonymous'); }, 100); </code></pre> * @param {Function} fn The function to defer. * @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately) * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed. * <b>If omitted, defaults to the browser window.</b> * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Number} The timeout id that can be used with clearTimeout */ defer: function(fn, millis, obj, args, appendArgs) { fn = Ext.util.Functions.createDelegate(fn, obj, args, appendArgs); if (millis > 0) { return setTimeout(fn, millis); } fn(); return 0; }, /** * Create a combined function call sequence of the original function + the passed function. * The resulting function returns the results of the original function. * The passed fcn is called with the parameters of the original function. Example usage: * var sayHi = function(name){ alert('Hi, ' + name); } sayHi('Fred'); // alerts "Hi, Fred" var sayGoodbye = Ext.createSequence(sayHi, function(name){ alert('Bye, ' + name); }); sayGoodbye('Fred'); // both alerts show * @param {Function} origFn The original function. * @param {Function} newFn The function to sequence * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed. * If omitted, defaults to the scope in which the original function is called or the browser window. * @return {Function} The new function */ createSequence: function(origFn, newFn, scope) { if (!Ext.isFunction(newFn)) { return origFn; } else { return function() { var retval = origFn.apply(this || window, arguments); newFn.apply(scope || this || window, arguments); return retval; }; } } }; /** * Shorthand for {@link Ext.util.Functions#defer} * @param {Function} fn The function to defer. * @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately) * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed. * <b>If omitted, defaults to the browser window.</b> * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Number} The timeout id that can be used with clearTimeout * @member Ext * @method defer */ Ext.defer = Ext.util.Functions.defer; /** * Shorthand for {@link Ext.util.Functions#createInterceptor} * @param {Function} origFn The original function. * @param {Function} newFn The function to call before the original * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed. * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b> * @return {Function} The new function * @member Ext * @method defer */ Ext.createInterceptor = Ext.util.Functions.createInterceptor; /** * Shorthand for {@link Ext.util.Functions#createSequence} * @param {Function} origFn The original function. * @param {Function} newFn The function to sequence * @param {Object} scope (optional) The scope (this reference) in which the passed function is executed. * If omitted, defaults to the scope in which the original function is called or the browser window. * @return {Function} The new function * @member Ext * @method defer */ Ext.createSequence = Ext.util.Functions.createSequence; /** * Shorthand for {@link Ext.util.Functions#createDelegate} * @param {Function} fn The function to delegate. * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed. * <b>If omitted, defaults to the browser window.</b> * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Function} The new function * @member Ext * @method defer */ Ext.createDelegate = Ext.util.Functions.createDelegate;
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.util.Format * 可复用的数据格式化函数。 * @singleton */ /** * @class Ext.util.Format * 可复用的数据格式化函数。 * Reusable data formatting functions * @singleton */ Ext.util.Format = { defaultDateFormat: 'm/d/Y', escapeRe: /('|\\)/g, trimRe: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g, formatRe: /\{(\d+)\}/g, escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g, /** * 对大于指定长度部分的字符串,进行裁剪,增加省略号(“...”)的显示。 * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length * @param {String} value 要裁剪的字符串。The string to truncate * @param {Number} length 允许的最大长度。The maximum length to allow before truncating * @param {Boolean} word True表示尝试以一个单词来结束。True to try to find a common word break * @return {String} 转换后的文本。The converted text */ ellipsis: function(value, len, word) { if (value && value.length > len) { if (word) { var vs = value.substr(0, len - 2), index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?')); if (index != -1 && index >= (len - 15)) { return vs.substr(0, index) + "..."; } } return value.substr(0, len - 3) + "..."; } return value; }, /** * 转义字符,可以在政治表达式regexp的构造器中使用。 * Escapes the passed string for use in a regular expression * @param {String} str * @return {String} */ escapeRegex : function(s) { return s.replace(Ext.util.Format.escapeRegexRe, "\\$1"); }, /** * Escapes the passed string for ' and \ * @param {String} string 要转义的字符。The string to escape * @return {String} 已转义的字符。The escaped string * @static */ escape : function(string) { return string.replace(Ext.util.Format.escapeRe, "\\$1"); }, /** * 比较并交换字符串的值。 * 参数中的第一个值与当前字符串对象比较,如果相等则返回传入的第一个参数,否则返回第二个参数。 * 注意:这个方法返回新值,但并不改变现有字符串。 * Utility function that allows you to easily switch a string between two alternating values. The passed value * is compared to the current string, and if they are equal, the other value that was passed in is returned. If * they are already different, the first value passed in is returned. Note that this method returns the new value * but does not change the current string. * <pre><code> // 可供选择的排序方向。alternate sort directions sort = Ext.util.Format.toggle(sort, 'ASC', 'DESC'); // 等价判断语句:instead of conditional logic: sort = (sort == 'ASC' ? 'DESC' : 'ASC'); </code></pre> * @param {String} string 当前字符。The current string * @param {String} value 第一个参数,与函数相等则返回。The value to compare to the current string * @param {String} other 传入的第二个参数,不等返回。The new value to use if the string already equals the first value passed in * @return {String} 新值。The new value */ toggle : function(string, value, other) { return string == value ? other : value; }, /** * 裁剪字符串两旁的空白符,保留中间空白符,例如: * Trims whitespace from either end of a string, leaving spaces within the string intact. Example: * <pre><code> var s = ' foo bar '; alert('-' + s + '-'); //alerts "- foo bar -" alert('-' + Ext.util.Format.trim(s) + '-'); //alerts "-foo bar-" </code></pre> * @param {String} string 要裁剪的字符。The string to escape * @return {String} 已裁剪的字符串。The trimmed string */ trim : function(string) { return string.replace(Ext.util.Format.trimRe, ""); }, /** * 在字符串左边填充指定字符。这对于统一字符或日期标准格式非常有用。 * Pads the left side of a string with a specified character. This is especially useful * for normalizing number and date strings. Example usage: * * <pre><code> var s = Ext.util.Format.leftPad('123', 5, '0'); // s 现在是:s now contains the string: '00123' </code></pre> * @param {String} string 源字符串。The original string * @param {Number} size 源+填充字符串的总长度。The total length of the output string * @param {String} char (可选的) 填充字符串(默认是" ")。(optional) The character with which to pad the original string (defaults to empty string " ") * @return {String} 填充后的字符串。The padded string * @static */ leftPad : function (val, size, ch) { var result = String(val); ch = ch || " "; while (result.length < size) { result = ch + result; } return result; }, /** * 定义带标记的字符串,并用传入的字符替换标记。每个标记必须是唯一的,而且必须要像{0},{1}...{n}这样地自增长。 * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each * token must be unique, and must increment in the format {0}, {1}, etc. * 例如:Example usage: * <pre><code> var cls = 'my-class', text = 'Some text'; var s = String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text); //s现在是字符串:s now contains the string: '&lt;div class="my-class">Some text&lt;/div>' </code></pre> * @param {String} string 带标记的字符串。The tokenized string to be formatted * @param {String} value1 第一个值,替换{0}。The value to replace token {0} * @param {String} value2 第二个值,替换{1}...等等(可以有任意多个)。Etc... * @return {String} 转化过的字符串。The formatted string * @static */ format : function (format) { var args = Ext.toArray(arguments, 1); return format.replace(Ext.util.Format.formatRe, function(m, i) { return args[i]; }); }, /** * 为能在HTML显示的字符转义&、<、>以及'。 * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages. * @param {String} value 要编码的字符串。The string to encode * @return {String} 编码后的文本。The encoded text */ htmlEncode: function(value) { return ! value ? value: String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); }, /** * 将&, <, >, and '字符从HTML显示的格式还原。 * Convert certain characters (&, <, >, and ') from their HTML character equivalents. * @param {String} value 解码的字符串。The string to decode * @return {String} 编码后的文本。The decoded text */ htmlDecode: function(value) { return ! value ? value: String(value).replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"').replace(/&amp;/g, "&"); }, /** * 按照特定的格式模式格式化日期。 * Parse a value into a formatted date using the specified format pattern. * @param {String/Date} value 要格式化的值(字符串必须符合JavaScript日期对象的格式要求,参阅<a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a>)The value to format (Strings must conform to the format expected by the javascript * Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method) * @param {String} format (可选的)任意的日期格式化字符串。(默认为'm/d/Y')(optional) Any valid date format string (defaults to 'm/d/Y') * @return {String} 已格式化字符串。The formatted date string */ date: function(v, format) { if (!v) { return ""; } if (!Ext.isDate(v)) { v = new Date(Date.parse(v)); } return v.dateFormat(format || Ext.util.Format.defaultDateFormat); } };
JavaScript
Ext.util.Point = Ext.extend(Object, { constructor: function(x, y) { this.x = (x != null && !isNaN(x)) ? x : 0; this.y = (y != null && !isNaN(y)) ? y : 0; return this; }, copy: function() { return new Ext.util.Point(this.x, this.y); }, copyFrom: function(p) { this.x = p.x; this.y = p.y; }, toString: function() { return "Point[" + this.x + "," + this.y + "]"; }, equals: function(p) { if(!(p instanceof Ext.util.Point)) throw new Error('p must be an instance of Ext.util.Point'); return (this.x == p.x && this.y == p.y); }, isWithin: function(p, threshold) { if(!(p instanceof Ext.util.Point)) throw new Error('p must be an instance of Ext.util.Point'); return (this.x <= p.x + threshold.x && this.x >= p.x - threshold.x && this.y <= p.y + threshold.y && this.y >= p.y - threshold.y); }, translate: function(x, y) { if (x != null && !isNaN(x)) this.x += x; if (y != null && !isNaN(y)) this.y += y; }, roundedEquals: function(p) { return (Math.round(this.x) == Math.round(p.x) && Math.round(this.y) == Math.round(p.y)); } }); Ext.apply(Ext.util.Point, { fromEvent: function(e) { var a = (e.touches && e.touches.length > 0) ? e.touches[0] : e; return new Ext.util.Point(a.screenX, a.screenY); } });
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堂翻译小组 * ---------------------请保留该段信息。------------------------- */ /** * @class Ext.util.DelayedTask * <p> * DelayedTask类提供快捷的方法执行setTimeout,新的超时时限会取消旧的超时时限. * 例如验证表单的时候,键盘按下(keypress)那一瞬,就可用上该类(不会立即验证表单,稍作延时)。 * keypress事件会稍作停顿之后(某个时间)才继续执行。 * The DelayedTask class provides a convenient way to "buffer" the execution of a method, * performing setTimeout where a new timeout cancels the old timeout. When called, the * task will wait the specified time period before executing. If durng that time period, * the task is called again, the original call will be cancelled. This continues so that * the function is only called a single time for each iteration.</p> * <p>This method is especially useful for things like detecting whether a user has finished * typing in a text field. An example would be performing validation on a keypress. You can * use this class to buffer the keypress events for a certain number of milliseconds, and * perform only if they stop for that amount of time. Usage:</p><pre><code> var task = new Ext.util.DelayedTask(function(){ alert(Ext.getDom('myInputField').value.length); }); // Wait 500ms before calling our function. If the user presses another key // during that 500ms, it will be cancelled and we'll wait another 500ms. Ext.get('myInputField').on('keypress', function(){ task.{@link #delay}(500); }); * </code></pre> * <p>Note that we are using a DelayedTask here to illustrate a point. The configuration * option <tt>buffer</tt> for {@link Ext.util.Observable#addListener addListener/on} will * also setup a delayed task for you to buffer events.</p> * @constructor The parameters to this constructor serve as defaults and are not required. * @param {Function} fn (可选的)重写传入到构建器的函数。(optional) The default function to call. * @param {Object} scope (可选的)重写传入到构建器的作用域。请注意如果不指定作用域,那么<code>this</code>就是浏览器的windows对象。The default scope (The <code><b>this</b></code> reference) in which the * function is called. If not specified, <code>this</code> will refer to the browser window. * @param {Array} args (可选的)重写传入到构建器的参数。(optional) The default Array of arguments. */ Ext.util.DelayedTask = function(fn, scope, args) { var me = this, id, call = function() { clearInterval(id); id = null; fn.apply(scope, args || []); }; /** * 取消所有待定的超时(any pending timeout),并重新排列(queues)。 * Cancels any pending timeout and queues a new one * @param {Number} delay 延迟毫秒数。The milliseconds to delay * @param {Function} newFn (可选的)重写传入到构建器的函数。(optional) Overrides function passed to constructor * @param {Object} newScope (可选的)重写传入到构建器的作用域。请注意如果不指定作用域,那么<code>this</code>就是浏览器的windows对象。(optional) Overrides scope passed to constructor. Remember that if no scope * is specified, <code>this</code> will refer to the browser window. * @param {Array} newArgs (可选的)重写传入到构建器的参数。(optional) Overrides args passed to constructor */ this.delay = function(delay, newFn, newScope, newArgs) { me.cancel(); fn = newFn || fn; scope = newScope || scope; args = newArgs || args; id = setInterval(call, delay); }; /** * 取消最后的排列超时。 * Cancel the last queued timeout */ this.cancel = function(){ if (id) { clearInterval(id); id = null; } }; };
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.util.Sorter * @extends Object * 代表可以应用到Store的单个排序器。 * Represents a single sorter that can be applied to a Store */ Ext.util.Sorter = Ext.extend(Object, { /** * @cfg {String} property * 要排序的属性。除非提供了{@link #sorter}。 * The property to sort by. Required unless {@link #sorter} is provided */ /** * @cfg {Function} sorterFn * 特定要执行的排序函数,可以由{@link #property}代替指定。 * A specific sorter function to execute. Can be passed instead of {@link #property} */ /** * @cfg {String} root 可选的根属性。在排序Store时候很有用。 * 我们设置根为“data”使得过滤器提取出每一项的数据对象。 * Optional root property. This is mostly useful when sorting a Store, in which case we set the * root to 'data' to make the filter pull the {@link #property} out of the data object of each item */ /** * @cfg {String} direction 排序的方向,默认是ASC。The direction to sort by. Defaults to ASC */ direction: "ASC", constructor: function(config) { Ext.apply(this, config); if (this.property == undefined && this.sorterFn == undefined) { throw "A Sorter requires either a property or a sorter function"; } this.sort = this.createSortFunction(this.sorterFn || this.defaultSorterFn); }, /** * @private * 指定属性和方向,为数组创建并返回排序的函数。 * Creates and returns a function which sorts an array by the given property and direction * @return {Function} 指定的属性、方向组合而成的排序函数。A function which sorts by the property/direction combination provided */ createSortFunction: function(sorterFn) { var me = this, property = me.property, direction = me.direction, modifier = direction.toUpperCase() == "DESC" ? -1 : 1; //create a comparison function. Takes 2 objects, returns 1 if object 1 is greater, //-1 if object 2 is greater or 0 if they are equal return function(o1, o2) { return modifier * sorterFn.call(me, o1, o2); }; }, /** * @private * 只是比较每个对象已定义的属性的基本默认排序函数。 * Basic default sorter function that just compares the defined property of each object */ defaultSorterFn: function(o1, o2) { var v1 = this.getRoot(o1)[this.property], v2 = this.getRoot(o2)[this.property]; return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }, /** * @private * 返回给定项的根属性,基于已配置好的{@link #root}属性。 * Returns the root property of the given item, based on the configured {@link #root} property * @param {Object} item 哪一项?The item * @return {Object} 对象的根属性。The root property of the object */ getRoot: function(item) { return this.root == undefined ? item : item[this.root]; } });
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.util.Filter * @extends Object * <p> * 表示{@link Ext.data.MixedCollection MixedCollection}的筛选器。 * 你可以简单地只是指定一个属性/值的结对,也可以创建筛选的函数来自定义逻辑。 * 虽然在筛选和搜索记录的时候,{@link Ext.data.Store Store}常常创建筛选器,但筛选器总是在MixedCollections中使用, * Represents a filter that can be applied to a {@link Ext.data.MixedCollection MixedCollection}. Can either simply * filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the context * of MixedCollections, though {@link Ext.data.Store Store}s frequently create them when filtering and searching on their * records. Example usage:</p> <pre><code> // 设置一个虚拟MixedCollection包含一些要筛选的人。 set up a fictional MixedCollection containing a few people to filter on var allNames = new Ext.util.MixedCollection(); allNames.addAll([ {id: 1, name: 'Ed', age: 25}, {id: 2, name: 'Jamie', age: 37}, {id: 3, name: 'Abe', age: 32}, {id: 4, name: 'Aaron', age: 26}, {id: 5, name: 'David', age: 32} ]); var ageFilter = new Ext.util.Filter({ property: 'age', value : 32 }); var longNameFilter = new Ext.util.Filter({ filterFn: function(item) { return item.name.length > 4; } }); // 新的MixedCollection有三个名字长于四个字符的人。a new MixedCollection with the 3 names longer than 4 characters var longNames = allNames.filter(longNameFilter); // 新的MixedCollection有两个24岁的人。a new MixedCollection with the 2 people of age 24: var youngFolk = allNames.filter(ageFilter); </code></pre> * @constructor * @param {Object} config 配置项对象。Config object */ Ext.util.Filter = Ext.extend(Object, { /** * @cfg {String} property 要筛选的属性。除非{@link #filter}已指定否则是必须的。The property to filter on. Required unless a {@link #filter} is passed */ /** * @cfg {Function} filterFn * 一个自定义函数传入{@link Ext.util.MixedCollection} 的每一项。应该要返回true表示接受每一项否则false代表不接受。 * A custom filter function which is passed each item in the {@link Ext.util.MixedCollection} * in turn. Should return true to accept each item or false to reject it */ /** * @cfg {Boolean} anyMatch * True表示为允许任意匹配,没有增加正则的start/end线标记。默认为fasle。 * True to allow any match - no regex start/end line anchors will be added. Defaults to false */ anyMatch: false, /** * @cfg {Boolean} exactMatch * True表示为强制匹配(加入正则的^与$)。默认为false。如果anyMatch为true则忽略。 * True to force exact match (^ and $ characters added to the regex). Defaults to false. * Ignored if anyMatch is true. */ exactMatch: false, /** * @cfg {Boolean} caseSensitive * True表示为要正则大小写敏感(加入正则的“i”)。默认为fasle。 * True to make the regex case sensitive (adds 'i' switch to regex). Defaults to false. */ caseSensitive: false, /** * @cfg {String} root * * Optional root property. * 可选的根属性。在筛选Store时候很有用。 * 我们设置根为“data”使得筛选器提取出每一项的数据对象的{@link #property}。 * This is mostly useful when filtering a Store, in which case we set the * root to 'data' to make the filter pull the {@link #property} out of the data object of each item */ constructor: function(config) { Ext.apply(this, config); //we're aliasing filter to filterFn mostly for API cleanliness reasons, despite the fact it dirties the code here. //Ext.util.Sorter takes a sorterFn property but allows .sort to be called - we do the same here this.filter = this.filter || this.filterFn; if (this.filter == undefined) { if (this.property == undefined || this.value == undefined) { // Commented this out temporarily because it stops us using string ids in models. TODO: Remove this once // Model has been updated to allow string ids // throw "A Filter requires either a property or a filterFn to be set"; } else { this.filter = this.createFilterFn(); } this.filterFn = this.filter; } }, /** * @private * 为该筛选器创建筛选器函数(要配置好属性、值、anyMatch、是否大小写敏感)。 * Creates a filter function for the configured property/value/anyMatch/caseSensitive options for this Filter */ createFilterFn: function() { var me = this, matcher = me.createValueMatcher(), property = me.property; return function(item) { return matcher.test(me.getRoot.call(me, item)[property]); }; }, /** * @private * 根据配置好的{@link #root},返回给定项的根属性。 * Returns the root property of the given item, based on the configured {@link #root} property * @param {Object} item 项。The item * @return {Object} 对象的根属性。The root property of the object */ getRoot: function(item) { return this.root == undefined ? item : item[this.root]; }, /** * @private * 根据给定的值和匹配的选项,返回正则。 * Returns a regular expression based on the given value and matching options */ createValueMatcher : function() { var me = this, value = me.value, anyMatch = me.anyMatch, exactMatch = me.exactMatch, caseSensitive = me.caseSensitive, escapeRe = Ext.util.Format.escapeRegex; if (!value.exec) { // not a regex value = String(value); if (anyMatch === true) { value = escapeRe(value); } else { value = '^' + escapeRe(value); if (exactMatch === true) { value += '$'; } } value = new RegExp(value, caseSensitive ? '' : 'i'); } return value; } });
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.util.Stateful * @extends Ext.util.Observable * 该类表示任意对象其数据都可以被存储的,主要透过{@link Ext.data.Proxy Proxy}来实现。 * Ext.Model和Ext.View都几次于这个类,以便能够实现了记忆状态的功能 * Represents any object whose data can be saved by a {@link Ext.data.Proxy Proxy}. Ext.Model * and Ext.View both inherit from this class as both can save state (Models save field state, * Views save configuration) */ Ext.util.Stateful = Ext.extend(Ext.util.Observable, { /** * 内置的标记,用于跟踪模型实例当前是否正在编辑中。只读的。 * Internal flag used to track whether or not the model instance is currently being edited. Read-only * @property editing * @type Boolean */ editing : false, /** * 只读的标记——true表示为Record已经被修改了。 * Readonly flag - true if this Record has been modified. * @type Boolean */ dirty : false, /** * @cfg {String} persistanceProperty 持久化对象它的哪一个属性是保存的属性。默认为“data”,即表示所有可持久化的数据位于this.data。 The property on this Persistable object that its data is saved to. * Defaults to 'data' (e.g. all persistable data resides in this.data.) */ persistanceProperty: 'data', constructor: function(config) { Ext.applyIf(this, { data: {} }); /** * 表示它的值经过修改过的全体字段的结对组。 * Key: value pairs of all fields whose values have changed * @property modified * @type Object */ this.modified = {}; this[this.persistanceProperty] = {}; Ext.util.Stateful.superclass.constructor.call(this, config); }, /** * 指定字段获取其值。 * Returns the value of the given field * @param {String} fieldName 要获取值得字段名称。The field to fetch the value for * @return {Mixed} 值。The value */ get: function(field) { return this[this.persistanceProperty][field]; }, /** * 设置特定的字段为特定的值,使得实例为脏记录。 * Sets the given field to the given value, marks the instance as dirty * @param {String|Object} fieldName 要设置的字段,或key/value的对象。The field to set, or an object containing key/value pairs * @param {Mixed} value 要设置的值。The value to set */ set: function(fieldName, value) { var fields = this.fields, field, key; if (arguments.length == 1 && Ext.isObject(fieldName)) { for (key in fieldName) { if (!fieldName.hasOwnProperty(key)) { continue; } this.set(key, fieldName[key]); } } else { if (fields) { field = fields.get(fieldName); if (field && field.convert) { value = field.convert(value, this); } } this[this.persistanceProperty][fieldName] = value; this.dirty = true; if (!this.editing) { this.afterEdit(); } } }, /** * 已经创建模型或提交了模型,获取那些已经修改过的字段。 * Gets a hash of only the fields that have been modified since this Model was created or commited. * @return Object */ getChanges : function(){ var modified = this.modified, changes = {}, field; for (field in modified) { if (modified.hasOwnProperty(field)){ changes[field] = this[this.persistanceProperty][field]; } } return changes; }, /** * 返回true表示传入的字段从加载或上次提交起已经<code>{@link #modified}</code>。 * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code> * since the load or last commit. * @param {String} fieldName {@link Ext.data.Field#name} * @return {Boolean} */ isModified : function(fieldName) { return !!(this.modified && this.modified.hasOwnProperty(fieldName)); }, /** * <p> * 使得这个<b>记录</b>为<code>{@link #dirty}</code>脏记录。当添加影子<code>{@link #phantom}</code>记录到{@link Ext.data.Store#writer writer enabled store}的时候,内部会调用这个方法。 * Marks this <b>Record</b> as <code>{@link #dirty}</code>. This method * is used interally when adding <code>{@link #phantom}</code> records to a * {@link Ext.data.Store#writer writer enabled store}.</p> * <br><p> * 控制记录为<code>{@link #dirty}</code>会使得{@link Ext.data.Store#getModifiedRecords}返回影子 * 记录,在{@link Ext.data.Store#save store save}操作进行期间组成一个创建的动作。 * Marking a record <code>{@link #dirty}</code> causes the phantom to * be returned by {@link Ext.data.Store#getModifiedRecords} where it will * have a create action composed for it during {@link Ext.data.Store#save store save} * operations.</p> */ setDirty : function() { this.dirty = true; if (!this.modified) { this.modified = {}; } this.fields.each(function(field) { this.modified[field.name] = this[this.persistanceProperty][field.name]; }, this); }, //<debug> markDirty : function() { throw "Stateful: markDirty has been deprecated. Please use setDirty."; }, //</debug> /** * 通常有其所在的模型实例的{@link Ext.data.Store}来调用。 * 当模型实例创建或最后提交后,就会引起撤销所有变化。 * <p>开发者应订阅{@link Ext.data.Store#update}事件以便能够通知撤销的操作。</p> * Usually called by the {@link Ext.data.Store} to which this model instance has been {@link #join joined}. * Rejects all changes made to the model instance since either creation, or the last commit operation. * Modified fields are reverted to their original values. * <p>Developers should subscribe to the {@link Ext.data.Store#update} event * to have their code notified of reject operations.</p> * @param {Boolean} silent (可选的)True表示为不通知所属的Store进行更改(默认为false)。(optional) True to skip notification of the owning * store of the change (defaults to false) */ reject : function(silent) { var modified = this.modified, field; for (field in modified) { if (!modified.hasOwnProperty(field)) { continue; } if (typeof modified[field] != "function") { this[this.persistanceProperty][field] = modified[field]; } } this.dirty = false; this.editing = false; delete this.modified; if (silent !== true) { this.afterReject(); } }, /** * 通常有其所在的模型实例的{@link Ext.data.Store}来调用。 * 当模型实例创建或最后提交后,就会引起Commit所有变化。 * <p>开发者应订阅{@link Ext.data.Store#update}事件以便能够通知提交的操作。</p> * Usually called by the {@link Ext.data.Store} which owns the model instance. * Commits all changes made to the instance since either creation or the last commit operation. * <p>Developers should subscribe to the {@link Ext.data.Store#update} event * to have their code notified of commit operations.</p> * @param {Boolean} silent (可选的)True表示为不通知所属的Store进行更改(默认为false)。(optional) True to skip notification of the owning * store of the change (defaults to false) */ commit : function(silent) { this.dirty = false; this.editing = false; delete this.modified; if (silent !== true) { this.afterCommit(); } }, /** * 创建模型实例的拷贝 (克隆)。 * Creates a copy (clone) of this Model instance. * @param {String} id (可选的)新id,默认是实例被拷贝的id。参阅(optional)<code>{@link #id}</code>。 * 要生成影子实例,传人新id,采用如下方法: * A new id, defaults to the id * of the instance being copied. See <code>{@link #id}</code>. * To generate a phantom instance with a new id use:<pre><code> var rec = record.copy(); // 克隆record clone the record Ext.data.Model.id(rec); // 自动生成连续不同的id。automatically generate a unique sequential id * </code></pre> * @return {Record} */ copy : function(newId) { return new this.constructor(Ext.apply({}, this[this.persistanceProperty]), newId || this.internalId); } });
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.util.Numbers * @singleton */ Ext.util.Numbers = { // detect toFixed implementation bug in IE toFixedBroken: (0.9).toFixed() != 1, /** * 检查当前数字是否属于某个期望的范围内。 * 若数字是在范围内的就返回数字,否则最小或最大的极限值,那个极限值取决于数字是倾向那一面(最大、最小)。 * 注意返回的极限值并不会影响当前的值。 * Checks whether or not the current number is within a desired range. If the number is already within the * range it is returned, otherwise the min or max value is returned depending on which side of the range is * exceeded. Note that this method returns the constrained value but does not change the current number. * @param {Number} number 要检查的数字。The number to check * @param {Number} min 范围中最小的极限值。The minimum number in the range * @param {Number} max 范围中最大的极限值。The maximum number in the range * @return {Number} 若在范围内,返回原值,否则返回超出那个范围边界的值。The constrained value if outside the range, otherwise the current value */ constrain : function(number, min, max) { number = parseFloat(number); if (!isNaN(min)) { number = Math.max(number, min); } if (!isNaN(max)) { number = Math.min(number, max); } return number; }, /** * 格式定点标记的数字。 * Formats a number using fixed-point notation * @param {Number} value 要格式化的数字。The number to format * @param {Number} precision 小数点后面出现的位数。The number of digits to show after the decimal point */ toFixed : function(value, precision) { if(Ext.util.Numbers.toFixedBroken) { precision = precision || 0; var pow = Math.pow(10, precision); return Math.round(value * pow) / pow; } return value.toFixed(precision); } };
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.AbstractManager * @extends Object * @ignore * 管理器基类。给ComponentMgr或PluginMgr等的类来扩展。 * Base Manager class - extended by ComponentMgr and PluginMgr */ Ext.AbstractManager = Ext.extend(Object, { typeName: 'type', constructor: function(config) { Ext.apply(this, config || {}); /** * 为组件缓存所使用的MixedCollection。可在这个MixedCollection中加入相应的事件,监视增加或移除的情况。只读的。 * Contains all of the items currently managed * @property all * @type Ext.util.MixedCollection */ this.all = new Ext.util.MixedCollection(); this.types = {}; }, /** * 由{@link Ext.Component#id id}返回组件。更多细节请参阅{@link Ext.util.MixedCollection#get}。 * Returns a component by {@link Ext.Component#id id}. * For additional details see {@link Ext.util.MixedCollection#get}. * @param {String} id 组件 {@link Ext.Component#id id}。The component {@link Ext.Component#id id} * @return Ext.Component 如果找不到返回<code>undefined</code>,如果找到返回<code>null</code>。The Component, <code>undefined</code> if not found, or <code>null</code> if a * Class was found. */ get : function(id) { return this.all.get(id); }, /** * 注册一个组件。Registers an item to be managed * @param {Mixed} item 要注册的内容。The item to register */ register: function(item) { this.all.add(item); }, /** * 撤消登记一个组件。 * Unregisters a component by removing it from this manager * @param {Mixed} item 要撤消的内容。The item to unregister */ unregister: function(item) { this.all.remove(item); }, /** * <p> * 输入新的{@link Ext.Component#xtype},登记一个新组件的构造器。 * Registers a new Component constructor, keyed by a new * {@link Ext.Component#xtype}.</p> * <p> * 使用该方法(或其简写方式{@link Ext#reg Ext.reg})登记{@link Ext.Component}的子类以便当指定子组件的xtype时即可延时加载(lazy instantiation)。 * 请参阅{@link Ext.Container#items}。 * Use this method (or its alias {@link Ext#reg Ext.reg}) to register new * subclasses of {@link Ext.Component} so that lazy instantiation may be used when specifying * child Components. * see {@link Ext.Container#items}</p> * @param {String} xtype 组件类的标识字符串。The mnemonic string by which the Component class may be looked up. * @param {Constructor} cls 新的组件类。The new Component class. */ registerType : function(type, cls) { this.types[type] = cls; cls[this.typeName] = type; }, /** * 简单这个组件是否已注册。 * Checks if a Component type is registered. * @param {Ext.Component} xtype 组建类对应的字符串。The mnemonic string by which the Component class may be looked up * @return {Boolean} 是否注册。Whether the type is registered. */ isRegistered : function(type){ return this.types[type] !== undefined; }, /** * 告诉需要哪个组建的{@link Ext.component#xtype xtype},添加适合的配置项对象,就创建新的Component,实际上返回这个类的实例。 * Creates and returns an instance of whatever this manager manages, based on the supplied type and config object * @param {Object} config 你打算创建组件的配置项对象。The config object * @param {String} defaultType 如果第一个参数不包含组件的xtype就在第二个参数中指定,作为默认的组件类型。(如果第一个参数已经有的话这个参数就可选吧)。 * If no type is discovered in the config object, we fall back to this type * @return {Mixed} 刚实例化的组件。The instance of whatever this manager is managing */ create: function(config, defaultType) { var type = config[this.typeName] || config.type || defaultType, 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); }, /** * 当指定组件被加入到ComponentMgr时调用的函数。 * Registers a function that will be called when a Component with the specified id is added to the manager. This will happen on instantiation. * @param {String} id 组件{@link Ext.Component#id id}。The component {@link Ext.Component#id id} * @param {Function} fn 回调函数。The callback function * @param {Object} scope 回调的作用域。指定<code>this</code>引用,默认为该组件。The scope (<code>this</code> reference) in which the callback is executed. Defaults to the Component. */ onAvailable : function(id, fn, scope){ var all = this.all; all.on("add", function(index, o){ if (o.id == id) { fn.call(scope || o, o); all.un("add", fn, scope); } }); } });
JavaScript
/** * @class Ext.util.Date * @singleton */ Ext.util.Date = { /** * 返回date对象创建时间与现在时间的时间差,单位为毫秒。 * Returns the number of milliseconds between this date and date * (译注:)例:var date = new Date(); * var x=0; * while(x<2){ * alert('x'); * x++; * } * * var theTime = date.getElapsed(); * alert(theTime); //将显示间隔的时间,单位是毫秒 * * @param {Date} date (可选的)默认时间是now。(optional) Defaults to now * @return {Number} 间隔毫秒数。The diff in milliseconds * @member Date getElapsed */ getElapsed: function(dateA, dateB) { return Math.abs(dateA - (dateB || new Date)); } };
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.LoadMask * 一个简单的工具类,用于在加载数据时为元素做出类似于遮罩的效果。 * 对于有可用的{@link Ext.data.Store},可将效果与Store的加载达到同步,而mask本身会被缓存以备复用。 * 而对于其他元素,这个遮照类会替换元素本身的UpdateManager加载指示器,并在初始化完毕后销毁。 * A simple utility class for generically masking elements while loading data. If the {@link #store} * config option is specified, the masking will be automatically synchronized with the store's loading * process and the mask element will be cached for reuse. For all other elements, this mask will replace the * element's Updater load indicator and will be destroyed after the initial load. * <p>用法举例:Example usage:</p> *<pre><code> // Basic mask: var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."}); myMask.show(); </code></pre> * @constructor 创建新的LoadMask对象。Create a new LoadMask * @param {Mixed} el 元素、DOM节点或id。The element or DOM node, or its id * @param {Object} config 配置项对象。The config object */ Ext.LoadMask = Ext.extend(Ext.util.Observable, { /** * @cfg {Ext.data.Store} store * 可选地你可以为该蒙板绑定一个Store对象。当Store的load请求被发起就显示该蒙版,不论load成功或失败之后都隐藏该蒙板。 * Optional Store to which the mask is bound. The mask is displayed when a load request is issued, and * hidden on either load sucess, or load fail. */ /** * @cfg {String} msg * 加载信息中显示文字(默认为'Loading...')。 * The text to display in a centered loading message box (defaults to 'Loading...') */ msg : 'Loading...', /** * @cfg {String} msgCls * 加载信息元素的样式(默认为"x-mask-loading")。 * The CSS class to apply to the loading message element (defaults to "x-mask-loading") */ msgCls : 'x-mask-loading', /** * 只读的。True表示为mask已被禁止,所以不会显示出来(默认为false)。 * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false) * @type Boolean */ disabled: false, constructor : function(el, config) { this.el = Ext.get(el); Ext.apply(this, config); this.addEvents('show', 'hide'); if (this.store) { this.bindStore(this.store, true); } Ext.LoadMask.superclass.constructor.call(this); }, /** * 改变LoadMask所绑定的数据Store。 * Changes the data store bound to this LoadMask. * @param {Store} store 要绑定到LoadMask的Store对象。The store to bind to this LoadMask */ bindStore : function(store, initial) { if (!initial && this.store) { this.mun(this.store, { scope: this, beforeload: this.onBeforeLoad, load: this.onLoad, exception: this.onLoad }); if(!store) { this.store = null; } } if (store) { store = Ext.StoreMgr.lookup(store); this.mon(store, { scope: this, beforeload: this.onBeforeLoad, load: this.onLoad, exception: this.onLoad }); } this.store = store; if (store && store.isLoading()) { this.onBeforeLoad(); } }, /** * 禁用遮罩致使遮罩不会被显示。 * Disables the mask to prevent it from being displayed */ disable : function() { this.disabled = true; }, /** * 启用遮罩以显示。 * Enables the mask so that it can be displayed */ enable : function() { this.disabled = false; }, /** * 返回当前的LoadMask可否被禁止。 * Method to determine whether this LoadMask is currently disabled. * @return {Boolean} 是否禁止。the disabled state of this LoadMask. */ isDisabled : function() { return this.disabled; }, // private onLoad : function() { this.el.unmask(); this.fireEvent('hide', this, this.el, this.store); }, // private onBeforeLoad : function() { if (!this.disabled) { this.el.mask(this.msg, this.msgCls, false); this.fireEvent('show', this, this.el, this.store); } }, /** * 在已配置元素之前显示LoadMask。 * Show this LoadMask over the configured Element. */ show: function() { this.onBeforeLoad(); }, /** * 隐藏此LoadMask。 * Hide this LoadMask. */ hide: function() { this.onLoad(); }, // private destroy : function() { this.hide(); this.clearListeners(); } });
JavaScript
Ext.util.Offset = Ext.extend(Object, { constructor: function(x, y) { this.x = (x != null && !isNaN(x)) ? x : 0; this.y = (y != null && !isNaN(y)) ? y : 0; return this; }, copy: function() { return new Ext.util.Offset(this.x, this.y); }, copyFrom: function(p) { this.x = p.x; this.y = p.y; }, toString: function() { return "Offset[" + this.x + "," + this.y + "]"; }, equals: function(offset) { if(!(offset instanceof Ext.util.Offset)) throw new Error('offset must be an instance of Ext.util.Offset'); return (this.x == offset.x && this.y == offset.y); }, round: function(to) { if (!isNaN(to)) { var factor = Math.pow(10, to); this.x = Math.round(this.x * factor) / factor; this.y = Math.round(this.y * factor) / factor; } else { this.x = Math.round(this.x); this.y = Math.round(this.y); } } });
JavaScript
/** * @class Ext.util.Sortable * @extends Ext.util.Observable * @constructor * @param {Mixed} el * @param {Object} config */ Ext.util.Sortable = Ext.extend(Ext.util.Observable, { baseCls: 'x-sortable', /** * @cfg {String} direction * Possible values: 'vertical', 'horizontal' * Defaults to 'vertical' */ direction: 'vertical', /** * @cfg {String} cancelSelector * A simple CSS selector that represents elements within the draggable * that should NOT initiate a drag. */ cancelSelector: null, // not yet implemented //indicator: true, //proxy: true, //tolerance: null, /** * @cfg {Element/Boolean} constrain * An Element to constrain the Sortable dragging to. Defaults to <tt>window</tt>. * If <tt>true</tt> is specified, the dragging will be constrained to the element * of the sortable. */ constrain: window, /** * @cfg {String} group * Draggable and Droppable objects can participate in a group which are * capable of interacting. Defaults to 'base' */ group: 'base', /** * @cfg {Boolean} revert * This should NOT be changed. * @private */ revert: true, /** * @cfg {String} itemSelector * A simple CSS selector that represents individual items within the Sortable. */ itemSelector: null, /** * @cfg {String} handleSelector * A simple CSS selector to indicate what is the handle to drag the Sortable. */ handleSelector: null, /** * @cfg {Boolean} disabled * Passing in true will disable this Sortable. */ disabled: false, /** * @cfg {Number} delay * How many milliseconds a user must hold the draggable before starting a * drag operation. Defaults to 0 or immediate. * @private */ delay: 0, // Properties /** * Read-only property that indicates whether a Sortable is currently sorting. * @type Boolean * @private */ sorting: false, /** * Read-only value representing whether the Draggable can be moved vertically. * This is automatically calculated by Draggable by the direction configuration. * @type Boolean * @private */ vertical: false, /** * Read-only value representing whether the Draggable can be moved horizontally. * This is automatically calculated by Draggable by the direction configuration. * @type Boolean * @private */ vertical: false, constructor : function(el, config) { config = config || {}; Ext.apply(this, config); this.addEvents( /** * @event sortstart * @param {Ext.Sortable} this * @param {Ext.EventObject} e */ 'sortstart', /** * @event sortend * @param {Ext.Sortable} this * @param {Ext.EventObject} e */ 'sortend', /** * @event sortchange * @param {Ext.Sortable} this * @param {Ext.Element} el The Element being dragged. * @param {Number} index The index of the element after the sort change. */ 'sortchange' // not yet implemented. // 'sortupdate', // 'sortreceive', // 'sortremove', // 'sortenter', // 'sortleave', // 'sortactivate', // 'sortdeactivate' ); this.el = Ext.get(el); Ext.util.Sortable.superclass.constructor.call(this); if (this.direction == 'horizontal') { this.horizontal = true; } else if (this.direction == 'vertical') { this.vertical = true; } else { this.horizontal = this.vertical = true; } this.el.addCls(this.baseCls); //this.tapEvent = (this.delay > 0) ? 'taphold' : 'tapstart'; if (!this.disabled) { this.enable(); } }, // @private onTouchStart : function(e, t) { if (this.cancelSelector && e.getTarget(this.cancelSelector)) { return; } if (this.handleSelector && !e.getTarget(this.handleSelector)) { return; } if (!this.sorting) { this.onSortStart(e, t); } }, // @private onSortStart : function(e, t) { this.sorting = true; var draggable = new Ext.util.Draggable(t, { delay: this.delay, revert: this.revert, direction: this.direction, constrain: this.constrain === true ? this.el : this.constrain, animationDuration: 100 }); draggable.on({ dragThreshold: 0, drag: this.onDrag, dragend: this.onDragEnd, scope: this }); this.dragEl = t; this.calculateBoxes(); if (!draggable.dragging) { draggable.onStart(e); } this.fireEvent('sortstart', this, e); }, // @private calculateBoxes : function() { this.items = []; var els = this.el.select(this.itemSelector, false), ln = els.length, i, item, el, box; for (i = 0; i < ln; i++) { el = els[i]; if (el != this.dragEl) { item = Ext.fly(el).getPageBox(true); item.el = el; this.items.push(item); } } }, // @private onDrag : function(draggable, e) { var items = this.items, ln = items.length, region = draggable.region, sortChange = false, i, intersect, overlap, item; for (i = 0; i < ln; i++) { item = items[i]; intersect = region.intersect(item); if (intersect) { if (this.vertical && Math.abs(intersect.top - intersect.bottom) > (region.bottom - region.top) / 2) { if (region.bottom > item.top && item.top > region.top) { draggable.el.insertAfter(item.el); } else { draggable.el.insertBefore(item.el); } sortChange = true; } else if (this.horizontal && Math.abs(intersect.left - intersect.right) > (region.right - region.left) / 2) { if (region.right > item.left && item.left > region.left) { draggable.el.insertAfter(item.el); } else { draggable.el.insertBefore(item.el); } sortChange = true; } if (sortChange) { // We reset the draggable (initializes all the new start values) draggable.reset(); // Move the draggable to its current location (since the transform is now // different) draggable.moveTo(region.left, region.top); // Finally lets recalculate all the items boxes this.calculateBoxes(); this.fireEvent('sortchange', this, draggable.el, this.el.select(this.itemSelector, false).indexOf(draggable.el.dom)); return; } } } }, // @private onDragEnd : function(draggable, e) { draggable.destroy(); this.sorting = false; this.fireEvent('sortend', this, draggable, e); }, /** * Enables sorting for this Sortable. * This method is invoked immediately after construction of a Sortable unless * the disabled configuration is set to true. */ enable : function() { this.el.on('touchstart', this.onTouchStart, this, {delegate: this.itemSelector}); this.disabled = false; }, /** * Disables sorting for this Sortable. */ disable : function() { this.el.un('touchstart', this.onTouchStart, this); this.disabled = true; }, /** * Method to determine whether this Sortable is currently disabled. * @return {Boolean} the disabled state of this Sortable. */ isDisabled : function() { return this.disabled; }, /** * Method to determine whether this Sortable is currently sorting. * @return {Boolean} the sorting state of this Sortable. */ isSorting : function() { return this.sorting; }, /** * 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; } });
JavaScript
/* http://www.JSON.org/json2.js 2010-03-20 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } return v; } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /** * @class Ext.util.JSON * Modified version of Douglas Crockford"s json.js that doesn"t * mess with the Object prototype * http://www.json.org/js.html * @singleton */ Ext.util.JSON = { encode : function(o) { return JSON.stringify(o); }, decode : function(s) { return JSON.parse(s); } }; /** * Shorthand for {@link Ext.util.JSON#encode} * @param {Mixed} o The variable to encode * @return {String} The JSON string * @member Ext * @method encode */ Ext.encode = Ext.util.JSON.encode; /** * Shorthand for {@link Ext.util.JSON#decode} * @param {String} json The JSON string * @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid. * @return {Object} The resulting object * @member Ext * @method decode */ Ext.decode = Ext.util.JSON.decode;
JavaScript
/** * @class Ext.util.JSONP * * Provides functionality to make cross-domain requests with JSONP (JSON with Padding). * http://en.wikipedia.org/wiki/JSON#JSONP * <p> * <b>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, because of the same origin policy.</b><br> * <p> * The content passed back from a server resource requested by a JSONP request<b>must</b> be executable JavaScript * source code because it is used as the source inside a &lt;script> tag.<br> * <p> * In order for the browser to process the returned data, the server must wrap the data object * with a call to a callback function, the name of which is passed as a parameter callbackKey * 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>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>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> * @singleton */ Ext.util.JSONP = { /** * Read-only queue * @type Array */ queue: [], /** * Read-only current executing request * @type Object */ current: null, /** * Make a cross-domain request using JSONP. * @param {Object} config * Valid configurations are: * <ul> * <li>url - {String} - Url to request data from. (required) </li> * <li>params - {Object} - A set of key/value pairs to be url encoded and passed as GET parameters in the request.</li> * <li>callbackKey - {String} - Key specified by the server-side provider.</li> * <li>callback - {Function} - Will be passed a single argument of the result of the request.</li> * <li>scope - {Scope} - Scope to execute your callback in.</li> * </ul> */ request : function(o) { o = o || {}; if (!o.url) { return; } var me = this; o.params = o.params || {}; if (o.callbackKey) { o.params[o.callbackKey] = 'Ext.util.JSONP.callback'; } var params = Ext.urlEncode(o.params); var script = document.createElement('script'); script.type = 'text/javascript'; this.queue.push({ url: o.url, script: script, callback: o.callback || function(){}, scope: o.scope || window, params: params || null }); if (!this.current) { this.next(); } }, // private next : function() { this.current = null; if (this.queue.length) { this.current = this.queue.shift(); this.current.script.src = this.current.url + (this.current.params ? ('?' + this.current.params) : ''); document.getElementsByTagName('head')[0].appendChild(this.current.script); } }, // @private callback: function(json) { this.current.callback.call(this.current.scope, json); document.getElementsByTagName('head')[0].removeChild(this.current.script); this.next(); } };
JavaScript
(function(){ Ext.ScrollManager = new Ext.AbstractManager(); /** * @class Ext.util.ScrollView * @extends Ext.util.Observable * * A wrapper class that listens to scroll events and control the scroll indicators */ Ext.util.ScrollView = Ext.extend(Ext.util.Observable, { useIndicators: true, indicatorConfig: {}, indicatorMargin: 4, constructor: function(el, config) { var indicators = [], directions = ['vertical', 'horizontal']; Ext.util.ScrollView.superclass.constructor.call(this); ['useIndicators', 'indicatorConfig', 'indicatorMargin'].forEach(function(c) { if (config.hasOwnProperty(c)) { this[c] = config[c]; delete config[c]; } }, this); config.scrollView = this; this.scroller = new Ext.util.Scroller(el, config); if (this.useIndicators === true) { directions.forEach(function(d) { if (this.scroller[d]) { indicators.push(d); } }, this); } else if (directions.indexOf(this.useIndicators) !== -1) { indicators.push(this.useIndicators); } this.indicators = {}; indicators.forEach(function(i) { this.indicators[i] = new Ext.util.Scroller.Indicator(this.scroller.container, Ext.apply({}, this.indicatorConfig, {type: i})); }, this); this.mon(this.scroller, { scrollstart: this.onScrollStart, scrollend: this.onScrollEnd, scroll: this.onScroll, scope: this }); }, onScrollStart: function() { this.showIndicators(); }, onScrollEnd: function() { this.hideIndicators(); }, showIndicators : function() { Ext.iterate(this.indicators, function(axis, indicator) { indicator.show(); }, this); }, hideIndicators : function() { Ext.iterate(this.indicators, function(axis, indicator) { indicator.hide(); }, this); }, onScroll: function(scroller) { if (scroller.offsetBoundary == null || (!this.indicators.vertical && !this.indicators.horizontal)) return; var sizeAxis, offsetAxis, offsetMark, boundary = scroller.offsetBoundary, offset = scroller.offset; this.containerSize = scroller.containerBox; this.scrollerSize = scroller.size; this.outOfBoundOffset = boundary.getOutOfBoundOffset(offset); this.restrictedOffset = boundary.restrict(offset); this.boundarySize = boundary.getSize(); if (!this.indicatorSizes) { this.indicatorSizes = { vertical: 0, horizontal: 0 }; } if (!this.indicatorOffsets) { this.indicatorOffsets = { vertical: 0, horizontal: 0 }; } Ext.iterate(this.indicators, function(axis, indicator) { sizeAxis = (axis == 'vertical') ? 'height' : 'width'; offsetAxis = (axis == 'vertical') ? 'y' : 'x'; offsetMark = (axis == 'vertical') ? 'bottom' : 'right'; if (this.scrollerSize[sizeAxis] < this.containerSize[sizeAxis]) { this.indicatorSizes[axis] = this.containerSize[sizeAxis] * (this.scrollerSize[sizeAxis] / this.containerSize[sizeAxis]); } else { this.indicatorSizes[axis] = this.containerSize[sizeAxis] * (this.containerSize[sizeAxis] / this.scrollerSize[sizeAxis]); } this.indicatorSizes[axis] -= Math.abs(this.outOfBoundOffset[offsetAxis]); this.indicatorSizes[axis] = Math.max(this.indicatorMargin * 4, this.indicatorSizes[axis]); if (this.boundarySize[sizeAxis] != 0) { this.indicatorOffsets[axis] = (((boundary[offsetMark] - this.restrictedOffset[offsetAxis]) / this.boundarySize[sizeAxis]) * (this.containerSize[sizeAxis] - this.indicatorSizes[axis])); } else if (offset[offsetAxis] < boundary[offsetMark]) { this.indicatorOffsets[axis] = this.containerSize[sizeAxis] - this.indicatorSizes[axis]; // this.indicatorOffsets[axis] = Math.round(this.indicatorOffsets[axis]); } else { this.indicatorOffsets[axis] = 0; } indicator.setOffset(this.indicatorOffsets[axis] + this.indicatorMargin); indicator.setSize(this.indicatorSizes[axis] - (this.indicatorMargin * 2)); }, this); } }); /** * @class Ext.util.Scroller * @extends Ext.util.Draggable * * Mimic the native scrolling experience on iDevices */ Ext.util.Scroller = Ext.extend(Ext.util.Draggable, { // Inherited baseCls: '', // Inherited draggingCls: '', // Inherited direction: 'both', // Inherited constrain: 'parent', /** * @cfg {Number} outOfBoundRestrictFactor * Determines the offset ratio when the scroller is pulled / pushed out of bound (when it's not decelerating) * A value of 0.5 means 1px allowed for every 2px. Defaults to 0.5 */ outOfBoundRestrictFactor: 0.5, /** * @cfg {Number} acceleration * A higher acceleration gives the scroller more initial velocity. Defaults to 30 */ acceleration: 30, /** * @cfg {Number} fps * The desired fps of the deceleration. Defaults to 100. */ fps: 100, /** * @cfg {Number} friction * The friction of the scroller. * By raising this value the length that momentum scrolls becomes shorter. This value is best kept * between 0 and 1. The default value is 0.5 */ friction: 0.5, /** * @cfg {Number} startMomentumResetTime * The time duration in ms to reset the start time of momentum * Defaults to 350 */ startMomentumResetTime: 350, /** * @cfg {Number} springTension * The tension of the spring that is attached to the scroller when it bounces. * By raising this value the bounce becomes shorter. This value is best kept * between 0 and 1. The default value is 0.3 */ springTension: 0.3, /** * @cfg {Number} minVelocityForAnimation * The minimum velocity to keep animating. Defaults to 1 (1px per second) */ minVelocityForAnimation: 1, /** * @cfg {Boolean/String} bounces * Enable bouncing during scrolling past the bounds. Defaults to true. (Which is 'both'). * You can also specify 'vertical', 'horizontal', or 'both' */ bounces: true, /** * @cfg {Boolean} momentum * Whether or not to enable scrolling momentum. Defaults to true */ momentum: true, cancelRevert: true, threshold: 5, constructor: function(el, config) { el = Ext.get(el); var scroller = Ext.ScrollManager.get(el.id); if (scroller) { return Ext.apply(scroller, config); } // this.eventTarget = el.parent(); Ext.util.Scroller.superclass.constructor.apply(this, arguments); this.addEvents( /** * @event scrollstart * @param {Ext.util.Scroller} this * @param {Ext.EventObject} e */ 'scrollstart', /** * @event scroll * @param {Ext.util.Scroller} this * @param {Object} offsets An object containing the x and y offsets for the scroller. */ 'scroll', /** * @event scrollend * @param {Ext.util.Scroller} this * @param {Object} offsets An object containing the x and y offsets for the scroller. */ 'scrollend', /** * @event bouncestart * @param {Ext.util.Scroller} this * @param {Object} info Object containing information regarding the bounce */ 'bouncestart', /** * @event bouncestart * @param {Ext.util.Scroller} this * @param {Object} info Object containing information regarding the bounce */ 'bounceend' ); this.on({ dragstart: this.onDragStart, scope: this }); Ext.ScrollManager.register(this); this.el.addCls('x-scroller'); this.container.addCls('x-scroller-parent'); if (this.bounces !== false) { var both = this.bounces === 'both' || this.bounces === true, horizontal = both || this.bounces === 'horizontal', vertical = both || this.bounces === 'vertical'; this.bounces = { x: horizontal, y: vertical }; } this.frameDuration = 1000 / this.fps; this.omega = 1 - (this.friction / 10); // this.updateBoundary(); if (!this.decelerationAnimation) { this.decelerationAnimation = {}; } if (!this.bouncingAnimation) { this.bouncingAnimation = {}; } ['x', 'y'].forEach(function(a) { if (!this.decelerationAnimation[a]) { this.decelerationAnimation[a] = new Ext.util.Scroller.Animation.Deceleration({ acceleration: this.acceleration, omega: this.omega }); } if (!this.bouncingAnimation[a]) { this.bouncingAnimation[a] = new Ext.util.Scroller.Animation.Bouncing({ acceleration: this.acceleration, springTension: this.springTension }); } }, this); return this; }, setEnabled: function(enabled) { Ext.util.Scroller.superclass.setEnabled.apply(this, arguments); this.eventTarget[enabled ? 'on' : 'un']('touchstart', this.onTouchStart, this); }, updateBoundary: function() { Ext.util.Scroller.superclass.updateBoundary.apply(this, arguments); this.snapToBoundary(); }, setOffset: function(p) { p.round(); Ext.util.Scroller.superclass.setOffset.apply(this, arguments); this.fireEvent('scroll', this, this.getOffset()); }, onTouchStart: function(e) { this.stopMomentumAnimation(); }, onDragStart: function(e) { this.fireEvent('scrollstart', this, e); }, onStart: function(e) { if (Ext.util.Scroller.superclass.onStart.apply(this, arguments) !== true) return; this.startTime = e.event.timeStamp; this.lastEventTime = e.event.timeStamp; this.startTimeOffset = this.offset.copy(); }, onDrag: function(e) { if (Ext.util.Scroller.superclass.onDrag.apply(this, arguments) !== true) return; this.lastEventTime = e.event.timeStamp; if (this.lastEventTime - this.startTime > this.startMomentumResetTime) { this.startTime = this.lastEventTime; this.startTimeOffset = this.offset.copy(); } }, onDragEnd: function(e) { if (Ext.util.Scroller.superclass.onDragEnd.apply(this, arguments) !== true) return; if (!this.startMomentumAnimation(e)) { this.fireScrollEndEvent(); } }, onOrientationChange: function() { Ext.util.Scroller.superclass.onOrientationChange.apply(this, arguments); this.snapToBoundary(); }, fireScrollEndEvent: function() { this.isAnimating = false; this.snapToBoundary(); this.fireEvent('scrollend', this, this.getOffset()); }, scrollTo: function(pos, animate) { this.stopMomentumAnimation(); var newOffset = this.offsetBoundary.restrict(new Ext.util.Offset(-pos.x, -pos.y)); this.setOffset(newOffset, animate); return this; }, setSnap : function(snap) { this.snap = snap; }, snapToBoundary: function() { var offset = this.offsetBoundary.restrict(this.offset); offset.round(); if (this.snap) { if (this.snap === true) { this.snap = { x: 50, y: 50 }; } else if (Ext.isNumber(this.snap)) { this.snap = { x: this.snap, y: this.snap }; } if (this.snap.y) { offset.y = Math.round(offset.y / this.snap.y) * this.snap.y; } if (this.snap.x) { offset.x = Math.round(offset.x / this.snap.x) * this.snap.x; } if (!this.offset.equals(offset)) { this.scrollTo({x: -offset.x, y: -offset.y}, this.snapDuration); } } else if (!this.offset.equals(offset)) { this.setOffset(offset); } return this; }, startMomentumAnimation: function(e) { if ( (!this.momentum || !((e.event.timeStamp - this.lastEventTime) <= this.startMomentumResetTime)) && !this.offsetBoundary.isOutOfBound(this.offset) ) { return false; } // Determine the duration of the momentum var duration = (e.time - this.startTime), minVelocity = this.minVelocityForAnimation, currentVelocity, currentOffset = this.offset.copy(), restrictedOffset; this.isBouncing = {x: false, y: false}; this.isDecelerating = {x: false, y: false}; // Determine the deceleration velocity this.animationStartVelocity = { x: (this.offset.x - this.startTimeOffset.x) / (duration / this.acceleration), y: (this.offset.y - this.startTimeOffset.y) / (duration / this.acceleration) }; this.animationStartOffset = currentOffset; ['x', 'y'].forEach(function(axis) { this.isDecelerating[axis] = (Math.abs(this.animationStartVelocity[axis]) > minVelocity); if (this.bounces && this.bounces[axis]) { restrictedOffset = this.offsetBoundary.restrict(axis, currentOffset[axis]); if (restrictedOffset != currentOffset[axis]) { currentVelocity = (currentOffset[axis] - restrictedOffset) * this.springTension * Math.E; this.bouncingAnimation[axis].set({ startTime: e.time - ((1 / this.springTension) * this.acceleration), startOffset: restrictedOffset, startVelocity: currentVelocity }); this.isBouncing[axis] = true; this.fireEvent('bouncestart', this, { axis: axis, offset: restrictedOffset, time: e.time, velocity: currentVelocity }); this.isDecelerating[axis] = false; } } if (this.isDecelerating[axis]) { this.decelerationAnimation[axis].set({ startVelocity: this.animationStartVelocity[axis], startOffset: this.animationStartOffset[axis], startTime: e.time }); } }, this); if (this.isDecelerating.x || this.isDecelerating.y || this.isBouncing.x || this.isBouncing.y) { this.isAnimating = true; this.framesHandled = 0; this.fireEvent('momentumanimationstart'); this.animationTimer = Ext.defer(this.handleFrame, this.frameDuration, this); return true; } return false; }, stopMomentumAnimation: function() { if (this.isAnimating) { if (this.animationTimer) { clearTimeout(this.animationTimer); } this.isDecelerating = {}; this.isBouncing = {}; this.fireEvent('momentumanimationend'); this.fireScrollEndEvent(); } return this; }, /** * @private */ handleFrame : function() { if (!this.isAnimating) { return; } this.animationTimer = Ext.defer(this.handleFrame, this.frameDuration, this); var currentTime = (new Date()).getTime(), newOffset = this.offset.copy(), currentVelocity, restrictedOffset, outOfBoundDistance; ['x', 'y'].forEach(function(axis) { if (this.isDecelerating[axis]) { newOffset[axis] = this.decelerationAnimation[axis].getOffset(); currentVelocity = this.animationStartVelocity[axis] * this.decelerationAnimation[axis].getFrictionFactor(); outOfBoundDistance = this.offsetBoundary.getOutOfBoundOffset(axis, newOffset[axis]); // If the new offset is out of boundary, we are going to start a bounce if (outOfBoundDistance != 0) { restrictedOffset = this.offsetBoundary.restrict(axis, newOffset[axis]); if (this.bounces && this.bounces[axis]) { this.bouncingAnimation[axis].set({ startTime: currentTime, startOffset: restrictedOffset, startVelocity: currentVelocity }); this.isBouncing[axis] = true; this.fireEvent('bouncestart', this, { axis: axis, offset: restrictedOffset, time: currentTime, velocity: currentVelocity }); } this.isDecelerating[axis] = false; } else if (Math.abs(currentVelocity) <= 1) { this.isDecelerating[axis] = false; } } else if (this.isBouncing[axis]) { newOffset[axis] = this.bouncingAnimation[axis].getOffset(); restrictedOffset = this.offsetBoundary.restrict(axis, newOffset[axis]); if (Math.abs(newOffset[axis] - restrictedOffset) <= 1) { this.isBouncing[axis] = false; this.fireEvent('bounceend', this, { axis: axis, offset: restrictedOffset, time: currentTime, velocity: 0 }); newOffset[axis] = restrictedOffset; } } }, this); if (!this.isDecelerating.x && !this.isDecelerating.y && !this.isBouncing.x && !this.isBouncing.y) { this.stopMomentumAnimation(); return; } // this.framesHandled++; this.setOffset(newOffset); }, destroy: function() { return Ext.util.Scroller.superclass.destroy.apply(this, arguments); } }); Ext.util.Scroller.Animation = {}; Ext.util.Scroller.Animation.Deceleration = Ext.extend(Ext.util.Draggable.Animation.Abstract, { acceleration: 30, omega: null, startVelocity: null, getOffset: function() { return this.startOffset - ( (this.startVelocity / Math.log(this.omega)) - (this.startVelocity * (this.getFrictionFactor() / Math.log(this.omega))) ); }, getFrictionFactor : function() { var deltaTime = (new Date()).getTime() - this.startTime; return Math.pow(this.omega, deltaTime / this.acceleration); } }); Ext.util.Scroller.Animation.Bouncing = Ext.extend(Ext.util.Draggable.Animation.Abstract, { springTension: 0.3, acceleration: 30, startVelocity: null, getOffset: function() { var deltaTime = ((new Date()).getTime() - this.startTime), powTime = (deltaTime / this.acceleration) * Math.pow(Math.E, -this.springTension * (deltaTime / this.acceleration)); return this.startOffset + (this.startVelocity * powTime); } }); /** * @class Ext.util.Indicator * @extends Object * * Scroll indicator for the ScrollView */ Ext.util.Scroller.Indicator = Ext.extend(Object, { baseCls: 'x-scrollbar', type: 'horizontal', ui: 'dark', constructor: function(container, config) { this.container = container; Ext.apply(this, config); this.el = this.container.createChild({ cls: [this.baseCls, this.baseCls + '-' + this.type, this.baseCls + '-' + this.ui].join(' ') }); this.hide(); }, hide: function() { var me = this; if (this.hideTimer) { clearTimeout(this.hideTimer); } this.hideTimer = setTimeout(function() { me.el.setStyle('opacity', 0); }, 100); return this; }, show: function() { if (this.hideTimer) { clearTimeout(this.hideTimer); } this.el.setStyle('opacity', 1); return this; }, setVisibility: function(isVisible) { this[isVisible ? 'show' : 'hide'](); return this; }, setSize: function(size) { if (this.size && size > this.size) { size = Math.round(size); } // this.el.setStyle(height) is cleaner here but let's save some performance... this.el.dom.style[(this.type == 'horizontal') ? 'width' : 'height'] = size + 'px'; this.size = size; return this; }, setOffset: function(p) { p = Math.round(p); var offset = (this.type == 'vertical') ? [0, p] : [p]; Ext.Element.cssTransform(this.el, {translate: offset}); return this; } }); })();
JavaScript
/** * @class Ext.util.Draggable * @extends Ext.util.Observable * @constructor * @param {Mixed} el The element you want to make draggable. * @param {Object} config The configuration object for this Draggable. */ Ext.util.Draggable = Ext.extend(Ext.util.Observable, { baseCls: 'x-draggable', draggingCls: 'x-dragging', proxyCls: 'x-draggable-proxy', outOfBoundRestrictFactor: 1, /** * @cfg {String} direction * Possible values: 'vertical', 'horizontal', or 'both' * Defaults to 'both' */ direction: 'both', /** * @cfg {Element/Mixed} constrain Can be either an Element, 'parent' or null for no constrain */ constrain: window, /** * The amount of pixels you have to move before the drag operation starts. * Defaults to 0 * @type Number */ threshold: 0, /** * @cfg {Number} delay * How many milliseconds a user must hold the draggable before starting a * drag operation. Defaults to 0 or immediate. */ delay: 0, /** * @cfg {String} cancelSelector * A simple CSS selector that represents elements within the draggable * that should NOT initiate a drag. */ cancelSelector: null, /** * @cfg {Boolean} disabled */ disabled: false, /** * @cfg {Boolean} revert */ revert: false, /** * @cfg {String} group * Draggable and Droppable objects can participate in a group which are * capable of interacting. Defaults to 'base' */ group: 'base', /** * @cfg {Ext.Element/Element} eventTarget * The element to actually bind touch events to, defaults to this class' element itself */ /** * @cfg {Boolean} useCssTransform * Whether or not to translate the element using CSS Transform (much faster) instead of left and top properties, defaults to true */ useCssTransform: true, // not implemented yet. grid: null, snap: null, proxy: null, stack: false, // Properties /** * Read-only Property representing the region that the Draggable * is constrained to. * @type Ext.util.Region */ offsetBoundary: null, /** * Read-only Property representing whether or not the Draggable is currently * dragging or not. * @type Boolean */ dragging: false, /** * Read-only value representing whether the Draggable can be moved vertically. * This is automatically calculated by Draggable by the direction configuration. * @type Boolean */ vertical: false, /** * Read-only value representing whether the Draggable can be moved horizontally. * This is automatically calculated by Draggable by the direction configuration. * @type Boolean */ horizontal: false, monitorOrientation : true, /** * How long animations for this draggable take by default when using setOffset with animate being true. * This defaults to 300. * @type Number */ animationDuration: 300, constructor: function(el, config) { this.el = Ext.get(el); this.id = el.id; config = config || {}; Ext.apply(this, config); this.addEvents( /** * @event offsetchange * @param {Ext.Draggable} this * @param {Ext.util.Offset} offset */ 'offsetchange' ); Ext.util.Draggable.superclass.constructor.call(this, config); this.offset = new Ext.util.Offset(); if (this.eventTarget === 'parent') { this.eventTarget = this.el.parent(); } else { this.eventTarget = (this.eventTarget) ? Ext.get(this.eventTarget) : this.el; } if (this.direction == 'both') { this.horizontal = true; this.vertical = true; } else if (this.direction == 'horizontal') { this.horizontal = true; } else { this.vertical = true; } this.el.addCls(this.baseCls); if (this.proxy) { this.proxy.addCls(this.proxyCls); } this.startEventName = (this.delay > 0) ? 'taphold' : 'dragstart'; this.dragOptions = (this.delay > 0) ? {holdThreshold: this.delay} : { direction: this.direction, dragThreshold: this.threshold }; this.container = window; if (this.constrain) { if (this.constrain == 'parent') { this.container = this.el.parent(); } else if (this.constrain !== window) { this.container = Ext.get(this.constrain); } } this.offset = new Ext.util.Offset(); this.linearAnimation = { x: new Ext.util.Draggable.Animation.Linear(), y: new Ext.util.Draggable.Animation.Linear() }; Ext.EventManager.onOrientationChange(this.onOrientationChange, this); this.updateBoundary(true); this.setDragging(false); if (!this.disabled) { this.enable(); } return this; }, /** * Enable the Draggable. * @return {Ext.util.Draggable} this Returns this draggable instance */ enable: function() { return this.setEnabled(true); }, /** * Disable the Draggable. * @return {Ext.util.Draggable} this Returns this draggable instance */ disable: function() { return this.setEnabled(false); }, /** * Combined method to disable or enable the Draggable. This method is called by the enable and * disable methods. * @param {Boolean} enabled True to enable, false to disable. Defaults to false. * @return {Ext.util.Draggable} this Returns this draggable instance */ setEnabled: function(enabled) { this.eventTarget[enabled ? 'on' : 'un'](this.startEventName, this.onStart, this, this.dragOptions); this.eventTarget[enabled ? 'on' : 'un']('drag', this.onDrag, this, this.dragOptions); this.eventTarget[enabled ? 'on' : 'un']('dragend', this.onDragEnd, this, this.dragOptions); this.disabled = !enabled; return this; }, /** * Change the Draggable to use css transforms instead of style offsets * or the other way around. * @param {Boolean} useCssTransform True to use css transforms instead of style offsets. * @return {Ext.util.Draggable} this Returns this draggable instance * @public */ setUseCssTransform: function(useCssTransform) { if (typeof useCssTransform == 'undefined') { useCssTransform = true; } if (useCssTransform != this.useCssTransform) { this.useCssTransform = useCssTransform; var resetOffset = new Ext.util.Offset(); if (useCssTransform == false) { this.setStyleOffset(this.offset); this.setTransformOffset(resetOffset); } else { this.setTransformOffset(this.offset); this.setStyleOffset(resetOffset); } } return this; }, /** * Sets the offset of this Draggable relative to its original offset. * @param {Ext.util.Point/Object} point An object or Ext.util.Point instance containing the * x and y coordinates. * @param {Boolean/Number} animate Wether or not to animate the setting of the offset. True * to use the default animationDuration, a number to specify the duration for this operation. * @return {Ext.util.Draggable} this Returns this draggable instance */ setOffset: function(point, animate) { if (!this.horizontal) { point.x = 0; } if (!this.vertical) { point.y = 0; } if (animate) { this.startAnimation(point, animate); } else { this.offset = point; this.region = new Ext.util.Region( this.initialRegion.top + point.y, this.initialRegion.right + point.x, this.initialRegion.bottom + point.y, this.initialRegion.left + point.x ); if (this.useCssTransform) { this.setTransformOffset(point); } else { this.setStyleOffset(point); } this.fireEvent('offsetchange', this, this.offset); } return this; }, /** * Internal method that sets the transform of the proxyEl. * @param {Ext.util.Point/Object} point An object or Ext.util.Point instance containing the * x and y coordinates for the transform. * @return {Ext.util.Draggable} this Returns this draggable instance * @private */ setTransformOffset: function(point) { Ext.Element.cssTransform(this.getProxyEl(), {translate: [point.x, point.y]}); return this; }, /** * Internal method that sets the left and top of the proxyEl. * @param {Ext.util.Point/Object} point An object or Ext.util.Point instance containing the * x and y coordinates. * @return {Ext.util.Draggable} this Returns this draggable instance * @private */ setStyleOffset: function(p) { this.getProxyEl().setLeft(p.x); this.getProxyEl().setTop(p.y); return this; }, /** * Internal method that sets the offset of the Draggable using an animation * @param {Ext.util.Point/Object} point An object or Ext.util.Point instance containing the * x and y coordinates for the transform. * @param {Boolean/Number} animate Wether or not to animate the setting of the offset. True * to use the default animationDuration, a number to specify the duration for this operation. * @return {Ext.util.Draggable} this Returns this draggable instance * @private */ startAnimation: function(p, animate) { var currentTime = (new Date()).getTime(); animate = Ext.isNumber(animate) ? animate : this.animationDuration; this.linearAnimation.x.set({ startOffset: this.offset.x, endOffset: p.x, startTime: currentTime, duration: animate }); this.linearAnimation.y.set({ startOffset: this.offset.y, endOffset: p.y, startTime: currentTime, duration: animate }); this.isAnimating = true; this.animationTimer = Ext.defer(this.handleAnimationFrame, 0, this); return this; }, /** * Internal method that stops the current offset animation * @private */ stopAnimation: function() { clearTimeout(this.animationTimer); this.isAnimating = false; this.setDragging(false); return this; }, /** * Internal method that handles a frame of the offset animation. * @private */ handleAnimationFrame: function() { var newOffset = new Ext.util.Offset(); newOffset.x = this.linearAnimation.x.getOffset(); newOffset.y = this.linearAnimation.y.getOffset(); this.setOffset(newOffset); this.animationTimer = Ext.defer(this.handleAnimationFrame, 10, this); if ((newOffset.x === this.linearAnimation.x.endOffset) && (newOffset.y === this.linearAnimation.y.endOffset)) { this.stopAnimation(); } }, /** * Returns the current offset relative to the original location of this Draggable. * @return {Ext.util.Point} offset An Ext.util.Point instance containing the offset. */ getOffset: function() { var offset = this.offset.copy(); offset.y = -offset.y; offset.x = -offset.x; return offset; }, /** * Updates the boundary information for this Draggable. This method shouldn't * have to be called by the developer and is mostly used for internal purposes. * Might be useful when creating subclasses of Draggable. * @return {Ext.util.Draggable} this Returns this draggable instance * @private */ updateBoundary: function(init) { if (typeof init == 'undefined') init = false; this.offsetBoundary = null; this.size = { width: this.el.dom.scrollWidth, height: this.el.dom.scrollHeight }; if (this.container === window) { this.containerBox = { left: 0, top: 0, right: this.container.innerWidth, bottom: this.container.innerHeight, width: this.container.innerWidth, height: this.container.innerHeight }; } else { this.containerBox = this.container.getPageBox(); } var elXY = this.el.getXY(); this.elBox = { left: elXY[0] - this.offset.x, top: elXY[1] - this.offset.y, width: this.size.width, height: this.size.height }; this.elBox.bottom = this.elBox.top + this.elBox.height; this.elBox.right = this.elBox.left + this.elBox.width; this.initialRegion = this.region = new Ext.util.Region( elXY[1], elXY[0] + this.elBox.width, elXY[1] + this.elBox.height, elXY[0] ); var top = 0, right = 0, bottom = 0, left = 0; if (this.elBox.left < this.containerBox.left) { right += this.containerBox.left - this.elBox.left; } else { left -= this.elBox.left - this.containerBox.left; } if (this.elBox.right > this.containerBox.right) { left -= this.elBox.right - this.containerBox.right; } else { right += this.containerBox.right - this.elBox.right; } if (this.elBox.top < this.containerBox.top) { bottom += this.containerBox.top - this.elBox.top; } else { top -= this.elBox.top - this.containerBox.top; } if (this.elBox.bottom > this.containerBox.bottom) { top -= this.elBox.bottom - this.containerBox.bottom; } else { bottom += this.containerBox.bottom - this.elBox.bottom; } this.offsetBoundary = new Ext.util.Region(top, right, bottom, left).round(); var currentComputedOffset; if (this.useCssTransform) { currentComputedOffset = Ext.Element.getComputedTransformOffset(this.getProxyEl()); } else { currentComputedOffset = new Ext.util.Offset(this.getProxyEl().getLeft(), this.getProxyEl().getTop()); } if(!this.offset.equals(currentComputedOffset) || init) { this.setOffset(currentComputedOffset); } return this; }, /** * Fires when the Drag operation starts. Internal use only. * @param {Event} e The event object for the drag operation * @private */ onStart: function(e) { if (e.targetTouches && e.targetTouches.length != 1) return; if (this.dragging) { this.onDragEnd(e); this.stopAnimation(); } this.setDragging(true); this.startTouchPoint = Ext.util.Point.fromEvent(e); this.startOffset = this.offset.copy(); // Quickly check whether the element size has changed. If yes, updateBoundary again if (this.el.dom.scrollWidth != this.size.width || this.el.dom.scrollHeight != this.size.height) { this.updateBoundary(); } this.fireEvent('dragstart', this, e); return true; }, /** * Tets the new offset from a touch point. * @param {Ext.util.Point} touchPoint The touch point instance. * @private */ getNewOffsetFromTouchPoint: function(touchPoint) { var xDelta = touchPoint.x - this.startTouchPoint.x, yDelta = touchPoint.y - this.startTouchPoint.y, newOffset = this.offset.copy(); if(xDelta == 0 && yDelta == 0) { return newOffset; } if (this.horizontal) newOffset.x = this.startOffset.x + xDelta; if (this.vertical) newOffset.y = this.startOffset.y + yDelta; return newOffset; }, /** * Fires when a drag events happens. Internal use only. * @param {Event} e The event object for the drag event * @private */ onDrag: function(e) { if (!this.dragging || (e.targetTouches && e.targetTouches.length != 1)) { return; } this.lastTouchPoint = Ext.util.Point.fromEvent(e); var newOffset = this.getNewOffsetFromTouchPoint(this.lastTouchPoint); if (this.offsetBoundary != null) { newOffset = this.offsetBoundary.restrict(newOffset, this.outOfBoundRestrictFactor); } this.setOffset(newOffset); this.fireEvent('drag', this, e); return true; }, /** * Fires when a dragend event happens. Internal use only. * @param {Event} e The event object for the dragend event * @private */ onDragEnd: function(e) { if (this.dragging) { this.fireEvent('beforedragend', this, e); if (this.revert && !this.cancelRevert) { this.setOffset(this.startOffset, true); } else { this.setDragging(false); } this.fireEvent('dragend', this, e); } return true; }, /** * Fires when the orientation changes. Internal use only. * @private */ onOrientationChange: function() { this.updateBoundary(); }, /** * Sets the dragging flag and adds a dragging class to the element. * @param {Boolean} dragging True to enable dragging, false to disable. * @private */ setDragging: function(dragging) { if (dragging) { if (!this.dragging) { this.dragging = true; this.getProxyEl().addCls(this.draggingCls); } } else { if (this.dragging) { this.dragging = false; this.getProxyEl().removeCls(this.draggingCls); } } return this; }, /** * Returns the element thats is being visually dragged. * @returns {Ext.Element} proxy The proxy element. */ getProxyEl: function() { return this.proxy || this.el; }, /** * Destroys this Draggable instance. */ destroy: function() { Ext.EventManager.orientationEvent.removeListener(this.onOrientationChange, this); this.el.removeCls(this.baseCls); this.clearListeners(); this.disable(); }, /** * This method will reset the initial region of the Draggable. * @private */ reset: function() { this.startOffset = new Ext.util.Offset(0, 0); this.setOffset(this.startOffset); var oldInitialRegion = this.initialRegion.copy(); this.updateBoundary(); this.initialRegion = this.region = this.getProxyEl().getPageBox(true); this.startTouchPoint.x += this.initialRegion.left - oldInitialRegion.left; this.startTouchPoint.y += this.initialRegion.top - oldInitialRegion.top; }, /** * Use this to move the draggable to a coordinate on the screen. * @param {Number} x the vertical coordinate in pixels * @param {Number} y the horizontal coordinate in pixels * @return {Ext.util.Draggable} this This Draggable instance */ moveTo: function(x, y) { this.setOffset(new Ext.util.Offset(x - this.initialRegion.left, y - this.initialRegion.top)); return this; }, /** * Method to determine whether this Draggable is currently dragging. * @return {Boolean} the disabled state of this Draggable. */ isDragging : function() { return this.dragging; }, /** * 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.util.Draggable.Animation = {}; /** * @class Ext.util.Draggable.Animation.Abstract * @extends Object * * Provides the abstract methods for a Draggable animation. * @private * @ignore */ Ext.util.Draggable.Animation.Abstract = Ext.extend(Object, { /** * @cfg {Number} startTime The time the Animation started * @private */ startTime: null, /** * @cfg {Object/Ext.util.Point} startOffset Object containing the x and y coordinates the * Draggable had when the Animation started. * @private */ startOffset: 0, /** * The constructor for an Abstract animation. Applies the config to the Animation. * @param {Object} config Object containing the configuration for this Animation. * @private */ constructor: function(config) { config = config || {}; this.set(config); if (!this.startTime) this.startTime = (new Date()).getTime(); }, /** * Sets a config value for this Animation. * @param {String} name The name of this configuration * @param {Mixed} value The value for this configuration */ set: function(name, value) { if (Ext.isObject(name)) { Ext.apply(this, name); } else { this[name] = value; } return this; }, /** * This method will return the offset of the coordinate that is being animated for any * given point in time based on a different set of variables. Usually these variables are * a combination of the startOffset, endOffset, startTime and duration. * @return {Number} The offset for the coordinate that is being animated */ getOffset: Ext.emptyFn }); /** * @class Ext.util.Draggable.Animation.Linear * @extends Ext.util.Draggable.Animation.Abstract * * A linear animation that is being used by Draggable's setOffset by default. * @private * @ignore */ Ext.util.Draggable.Animation.Linear = Ext.extend(Ext.util.Draggable.Animation.Abstract, { /** * @cfg {Number} duration The duration of this animation in milliseconds. */ duration: 0, /** * @cfg {Object/Ext.util.Point} endOffset Object containing the x and y coordinates the * Draggable is animating to. * @private */ endOffset: 0, getOffset : function() { var distance = this.endOffset - this.startOffset, deltaTime = (new Date()).getTime() - this.startTime, omegaTime = Math.min(1, (deltaTime / this.duration)); return this.startOffset + (omegaTime * distance); } });
JavaScript
/** * @class Date * * The date parsing and formatting syntax contains a subset of * <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are * supported will provide results equivalent to their PHP versions. * * The following is a list of all currently supported formats: * <pre> Format Description Example returned values ------ ----------------------------------------------------------------------- ----------------------- d Day of the month, 2 digits with leading zeros 01 to 31 D A short textual representation of the day of the week Mon to Sun j Day of the month without leading zeros 1 to 31 l A full textual representation of the day of the week Sunday to Saturday N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday) S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday) z The day of the year (starting from 0) 0 to 364 (365 in leap years) W ISO-8601 week number of year, weeks starting on Monday 01 to 53 F A full textual representation of a month, such as January or March January to December m Numeric representation of a month, with leading zeros 01 to 12 M A short textual representation of a month Jan to Dec n Numeric representation of a month, without leading zeros 1 to 12 t Number of days in the given month 28 to 31 L Whether it's a leap year 1 if it is a leap year, 0 otherwise. o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004 belongs to the previous or next year, that year is used instead) Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003 y A two digit representation of a year Examples: 99 or 03 a Lowercase Ante meridiem and Post meridiem am or pm A Uppercase Ante meridiem and Post meridiem AM or PM g 12-hour format of an hour without leading zeros 1 to 12 G 24-hour format of an hour without leading zeros 0 to 23 h 12-hour format of an hour with leading zeros 01 to 12 H 24-hour format of an hour with leading zeros 00 to 23 i Minutes, with leading zeros 00 to 59 s Seconds, with leading zeros 00 to 59 u Decimal fraction of a second Examples: (minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or 100 (i.e. 0.100s) or 999 (i.e. 0.999s) or 999876543210 (i.e. 0.999876543210s) O Difference to Greenwich time (GMT) in hours and minutes Example: +1030 P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00 T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ... Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400 c ISO 8601 date Notes: Examples: 1) If unspecified, the month / day defaults to the current month / day, 1991 or the time defaults to midnight, while the timezone defaults to the 1992-10 or browser's timezone. If a time is specified, it must include both hours 1993-09-20 or and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or are optional. 1995-07-18T17:21:28-02:00 or 2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or date-time granularity which are supported, or see 2000-02-13T21:25:33 http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34 U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463 M$ Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or \/Date(1238606590509+0800)\/ </pre> * * Example usage (note that you must escape format specifiers with '\\' to render them as character literals): * <pre><code> // Sample date: // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)' var dt = new Date('1/10/2007 03:05:01 PM GMT-0600'); document.write(dt.format('Y-m-d')); // 2007-01-10 document.write(dt.format('F j, Y, g:i a')); // January 10, 2007, 3:05 pm document.write(dt.format('l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM </code></pre> * * Here are some standard date/time patterns that you might find helpful. They * are not part of the source of Date.js, but to use them you can simply copy this * block of code into any script that is included after Date.js and they will also become * globally available on the Date object. Feel free to add or remove patterns as needed in your code. * <pre><code> Date.patterns = { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }; </code></pre> * * Example usage: * <pre><code> var dt = new Date(); document.write(dt.format(Date.patterns.ShortDate)); </code></pre> * <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function * which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p> */ /* * Most of the date-formatting functions below are the excellent work of Baron Schwartz. * (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/) * They generate precompiled functions from format patterns instead of parsing and * processing each pattern every time a date is formatted. These functions are available * on every Date object. */ (function() { /** * Global flag which determines if strict date parsing should be used. * Strict date parsing will not roll-over invalid dates, which is the * default behaviour of javascript Date objects. * (see {@link #parseDate} for more information) * Defaults to <tt>false</tt>. * @static * @type Boolean */ Date.useStrict = false; // create private copy of Ext's Ext.util.Format.format() method // - to remove unnecessary dependency // - to resolve namespace conflict with M$-Ajax's implementation function xf(format) { var args = Array.prototype.slice.call(arguments, 1); return format.replace(/\{(\d+)\}/g, function(m, i) { return args[i]; }); } // private Date.formatCodeToRegex = function(character, currentGroup) { // Note: currentGroup - position in regex result array (see notes for Date.parseCodes below) var p = Date.parseCodes[character]; if (p) { p = typeof p == 'function' ? p() : p; Date.parseCodes[character] = p; // reassign function result to prevent repeated execution } return p ? Ext.applyIf({ c: p.c ? xf(p.c, currentGroup || "{0}") : p.c }, p) : { g: 0, c: null, s: Ext.util.Format.escapeRegex(character) // treat unrecognised characters as literals }; }; // private shorthand for Date.formatCodeToRegex since we'll be using it fairly often var $f = Date.formatCodeToRegex; Ext.apply(Date, { /** * <p>An object hash in which each property is a date parsing function. The property name is the * format string which that function parses.</p> * <p>This object is automatically populated with date parsing functions as * date formats are requested for Ext standard formatting strings.</p> * <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on * may be used as a format string to {@link #parseDate}.<p> * <p>Example:</p><pre><code> Date.parseFunctions['x-date-format'] = myDateParser; </code></pre> * <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul> * <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li> * <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing * (i.e. prevent javascript Date "rollover") (The default must be false). * Invalid date strings should return null when parsed.</div></li> * </ul></div></p> * <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding * formatting function must be placed into the {@link #formatFunctions} property. * @property parseFunctions * @static * @type Object */ parseFunctions: { "M$": function(input, strict) { // note: the timezone offset is ignored since the M$ Ajax server sends // a UTC milliseconds-since-Unix-epoch value (negative values are allowed) var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/'); var r = (input || '').match(re); return r ? new Date(((r[1] || '') + r[2]) * 1) : null; } }, parseRegexes: [], /** * <p>An object hash in which each property is a date formatting function. The property name is the * format string which corresponds to the produced formatted date string.</p> * <p>This object is automatically populated with date formatting functions as * date formats are requested for Ext standard formatting strings.</p> * <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on * may be used as a format string to {@link #format}. Example:</p><pre><code> Date.formatFunctions['x-date-format'] = myDateFormatter; </code></pre> * <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul> * <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li> * </ul></div></p> * <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding * parsing function must be placed into the {@link #parseFunctions} property. * @property formatFunctions * @static * @type Object */ formatFunctions: { "M$": function() { // UTC milliseconds since Unix epoch (M$-AJAX serialized date format (MRSF)) return '\\/Date(' + this.getTime() + ')\\/'; } }, y2kYear: 50, /** * Date interval constant * @static * @type String */ MILLI: "ms", /** * Date interval constant * @static * @type String */ SECOND: "s", /** * Date interval constant * @static * @type String */ MINUTE: "mi", /** Date interval constant * @static * @type String */ HOUR: "h", /** * Date interval constant * @static * @type String */ DAY: "d", /** * Date interval constant * @static * @type String */ MONTH: "mo", /** * Date interval constant * @static * @type String */ YEAR: "y", /** * <p>An object hash containing default date values used during date parsing.</p> * <p>The following properties are available:<div class="mdetail-params"><ul> * <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li> * <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li> * <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li> * <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li> * <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li> * <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li> * <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li> * </ul></div></p> * <p>Override these properties to customize the default date values used by the {@link #parseDate} method.</p> * <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt> * and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect. * It is the responsiblity of the developer to account for this.</b></p> * Example Usage: * <pre><code> // set default day value to the first day of the month Date.defaults.d = 1; // parse a February date string containing only year and month values. // setting the default day value to 1 prevents weird date rollover issues // when attempting to parse the following date string on, for example, March 31st 2009. Date.parseDate('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009 </code></pre> * @property defaults * @static * @type Object */ defaults: {}, /** * An array of textual day names. * Override these values for international dates. * Example: * <pre><code> Date.dayNames = [ 'SundayInYourLang', 'MondayInYourLang', ... ]; </code></pre> * @type Array * @static */ dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], /** * An array of textual month names. * Override these values for international dates. * Example: * <pre><code> Date.monthNames = [ 'JanInYourLang', 'FebInYourLang', ... ]; </code></pre> * @type Array * @static */ monthNames: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], /** * An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive). * Override these values for international dates. * Example: * <pre><code> Date.monthNumbers = { 'ShortJanNameInYourLang':0, 'ShortFebNameInYourLang':1, ... }; </code></pre> * @type Object * @static */ monthNumbers: { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }, /** * Get the short month name for the given month number. * Override this function for international dates. * @param {Number} month A zero-based javascript month number. * @return {String} The short month name. * @static */ getShortMonthName: function(month) { return Date.monthNames[month].substring(0, 3); }, /** * Get the short day name for the given day number. * Override this function for international dates. * @param {Number} day A zero-based javascript day number. * @return {String} The short day name. * @static */ getShortDayName: function(day) { return Date.dayNames[day].substring(0, 3); }, /** * Get the zero-based javascript month number for the given short/full month name. * Override this function for international dates. * @param {String} name The short/full month name. * @return {Number} The zero-based javascript month number. * @static */ getMonthNumber: function(name) { // handle camel casing for english month names (since the keys for the Date.monthNumbers hash are case sensitive) return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; }, /** * The base format-code to formatting-function hashmap used by the {@link #format} method. * Formatting functions are strings (or functions which return strings) which * will return the appropriate value when evaluated in the context of the Date object * from which the {@link #format} method is called. * Add to / override these mappings for custom date formatting. * Note: Date.format() treats characters as literals if an appropriate mapping cannot be found. * Example: * <pre><code> Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')"; (new Date()).format("X"); // returns the current day of the month </code></pre> * @type Object * @static */ formatCodes: { d: "Ext.util.Format.leftPad(this.getDate(), 2, '0')", D: "Date.getShortDayName(this.getDay())", // get localised short day name j: "this.getDate()", l: "Date.dayNames[this.getDay()]", N: "(this.getDay() ? this.getDay() : 7)", S: "this.getSuffix()", w: "this.getDay()", z: "this.getDayOfYear()", W: "Ext.util.Format.leftPad(this.getWeekOfYear(), 2, '0')", F: "Date.monthNames[this.getMonth()]", m: "Ext.util.Format.leftPad(this.getMonth() + 1, 2, '0')", M: "Date.getShortMonthName(this.getMonth())", // get localised short month name n: "(this.getMonth() + 1)", t: "this.getDaysInMonth()", L: "(this.isLeapYear() ? 1 : 0)", o: "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))", Y: "this.getFullYear()", y: "('' + this.getFullYear()).substring(2, 4)", a: "(this.getHours() < 12 ? 'am' : 'pm')", A: "(this.getHours() < 12 ? 'AM' : 'PM')", g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)", G: "this.getHours()", h: "Ext.util.Format.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')", H: "Ext.util.Format.leftPad(this.getHours(), 2, '0')", i: "Ext.util.Format.leftPad(this.getMinutes(), 2, '0')", s: "Ext.util.Format.leftPad(this.getSeconds(), 2, '0')", u: "Ext.util.Format.leftPad(this.getMilliseconds(), 3, '0')", O: "this.getGMTOffset()", P: "this.getGMTOffset(true)", T: "this.getTimezone()", Z: "(this.getTimezoneOffset() * -60)", c: function() { // ISO-8601 -- GMT format for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) { var e = c.charAt(i); code.push(e == "T" ? "'T'": Date.getFormatCode(e)); // treat T as a character literal } return code.join(" + "); }, /* c: function() { // ISO-8601 -- UTC format return [ "this.getUTCFullYear()", "'-'", "Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'", "Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')", "'T'", "Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'", "Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'", "Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')", "'Z'" ].join(" + "); }, */ U: "Math.round(this.getTime() / 1000)" }, /** * Checks if the passed Date parameters will cause a javascript Date "rollover". * @param {Number} year 4-digit year * @param {Number} month 1-based month-of-year * @param {Number} day Day of month * @param {Number} hour (optional) Hour * @param {Number} minute (optional) Minute * @param {Number} second (optional) Second * @param {Number} millisecond (optional) Millisecond * @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise. * @static */ isValid: function(y, m, d, h, i, s, ms) { // setup defaults h = h || 0; i = i || 0; s = s || 0; ms = ms || 0; var dt = new Date(y, m - 1, d, h, i, s, ms); return y == dt.getFullYear() && m == dt.getMonth() + 1 && d == dt.getDate() && h == dt.getHours() && i == dt.getMinutes() && s == dt.getSeconds() && ms == dt.getMilliseconds(); }, /** * Parses the passed string using the specified date format. * Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January). * The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond) * which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash, * the current date's year, month, day or DST-adjusted zero-hour time value will be used instead. * Keep in mind that the input date string must precisely match the specified format string * in order for the parse operation to be successful (failed parse operations return a null value). * <p>Example:</p><pre><code> //dt = Fri May 25 2007 (current date) var dt = new Date(); //dt = Thu May 25 2006 (today&#39;s month/day in 2006) dt = Date.parseDate("2006", "Y"); //dt = Sun Jan 15 2006 (all date parts specified) dt = Date.parseDate("2006-01-15", "Y-m-d"); //dt = Sun Jan 15 2006 15:20:01 dt = Date.parseDate("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A"); // attempt to parse Sun Feb 29 2006 03:20:01 in strict mode dt = Date.parseDate("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null </code></pre> * @param {String} input The raw date string. * @param {String} format The expected date string format. * @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover") (defaults to false). Invalid date strings will return null when parsed. * @return {Date} The parsed Date. * @static */ parseDate: function(input, format, strict) { var p = Date.parseFunctions; if (p[format] == null) { Date.createParser(format); } return p[format](input, Ext.isDefined(strict) ? strict: Date.useStrict); }, // private getFormatCode: function(character) { var f = Date.formatCodes[character]; if (f) { f = typeof f == 'function' ? f() : f; Date.formatCodes[character] = f; // reassign function result to prevent repeated execution } // note: unknown characters are treated as literals return f || ("'" + Ext.util.Format.escape(character) + "'"); }, // private createFormat: function(format) { var code = [], special = false, ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; code.push("'" + Ext.util.Format.escape(ch) + "'"); } else { code.push(Date.getFormatCode(ch)); } } Date.formatFunctions[format] = new Function("return " + code.join('+')); }, // private createParser: function() { var code = [ "var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,", "def = Date.defaults,", "results = String(input).match(Date.parseRegexes[{0}]);", // either null, or an array of matched strings "if(results){", "{1}", "if(u != null){", // i.e. unix time is defined "v = new Date(u * 1000);", // give top priority to UNIX time "}else{", // create Date object representing midnight of the current day; // this will provide us with our date defaults // (note: clearTime() handles Daylight Saving Time automatically) "dt = (new Date()).clearTime();", // date calculations (note: these calculations create a dependency on Ext.num()) "y = Ext.num(y, Ext.num(def.y, dt.getFullYear()));", "m = Ext.num(m, Ext.num(def.m - 1, dt.getMonth()));", "d = Ext.num(d, Ext.num(def.d, dt.getDate()));", // time calculations (note: these calculations create a dependency on Ext.num()) "h = Ext.num(h, Ext.num(def.h, dt.getHours()));", "i = Ext.num(i, Ext.num(def.i, dt.getMinutes()));", "s = Ext.num(s, Ext.num(def.s, dt.getSeconds()));", "ms = Ext.num(ms, Ext.num(def.ms, dt.getMilliseconds()));", "if(z >= 0 && y >= 0){", // both the year and zero-based day of year are defined and >= 0. // these 2 values alone provide sufficient info to create a full date object // create Date object representing January 1st for the given year "v = new Date(y, 0, 1, h, i, s, ms);", // then add day of year, checking for Date "rollover" if necessary "v = !strict? v : (strict === true && (z <= 364 || (v.isLeapYear() && z <= 365))? v.add(Date.DAY, z) : null);", "}else if(strict === true && !Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover" "v = null;", // invalid date, so return null "}else{", // plain old Date object "v = new Date(y, m, d, h, i, s, ms);", "}", "}", "}", "if(v){", // favour UTC offset over GMT offset "if(zz != null){", // reset to UTC, then add offset "v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);", "}else if(o){", // reset to GMT, then add offset "v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));", "}", "}", "return v;" ].join('\n'); return function(format) { var regexNum = Date.parseRegexes.length, currentGroup = 1, calc = [], regex = [], special = false, ch = "", i = 0, obj, last; for (; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; regex.push(Ext.util.Format.escape(ch)); } else { obj = $f(ch, currentGroup); currentGroup += obj.g; regex.push(obj.s); if (obj.g && obj.c) { if (obj.last) { last = obj; } else { calc.push(obj.c); } } } } if (last) { calc.push(last); } Date.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$"); Date.parseFunctions[format] = new Function("input", "strict", xf(code, regexNum, calc.join(''))); }; }(), // private parseCodes: { /* * Notes: * g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.) * c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array) * s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c' */ d: { g: 1, c: "d = parseInt(results[{0}], 10);\n", s: "(\\d{2})" // day of month with leading zeroes (01 - 31) }, j: { g: 1, c: "d = parseInt(results[{0}], 10);\n", s: "(\\d{1,2})" // day of month without leading zeroes (1 - 31) }, D: function() { for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); // get localised short day names return { g: 0, c: null, s: "(?:" + a.join("|") + ")" }; }, l: function() { return { g: 0, c: null, s: "(?:" + Date.dayNames.join("|") + ")" }; }, N: { g: 0, c: null, s: "[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday)) }, S: { g: 0, c: null, s: "(?:st|nd|rd|th)" }, w: { g: 0, c: null, s: "[0-6]" // javascript day number (0 (sunday) - 6 (saturday)) }, z: { g: 1, c: "z = parseInt(results[{0}], 10);\n", s: "(\\d{1,3})" // day of the year (0 - 364 (365 in leap years)) }, W: { g: 0, c: null, s: "(?:\\d{2})" // ISO-8601 week number (with leading zero) }, F: function() { return { g: 1, c: "m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number s: "(" + Date.monthNames.join("|") + ")" }; }, M: function() { for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); // get localised short month names return Ext.applyIf({ s: "(" + a.join("|") + ")" }, $f("F")); }, m: { g: 1, c: "m = parseInt(results[{0}], 10) - 1;\n", s: "(\\d{2})" // month number with leading zeros (01 - 12) }, n: { g: 1, c: "m = parseInt(results[{0}], 10) - 1;\n", s: "(\\d{1,2})" // month number without leading zeros (1 - 12) }, t: { g: 0, c: null, s: "(?:\\d{2})" // no. of days in the month (28 - 31) }, L: { g: 0, c: null, s: "(?:1|0)" }, o: function() { return $f("Y"); }, Y: { g: 1, c: "y = parseInt(results[{0}], 10);\n", s: "(\\d{4})" // 4-digit year }, y: { g: 1, c: "var ty = parseInt(results[{0}], 10);\n" + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year s: "(\\d{1,2})" }, a: function(){ return $f("A"); }, A: { // We need to calculate the hour before we apply AM/PM when parsing calcLast: true, g: 1, c: "if (results[{0}] == 'AM') {\n" + "if (!h || h == 12) { h = 0; }\n" + "} else { if (!h || h < 12) { h = (h || 0) + 12; }}", s: "(AM|PM)" }, g: function() { return $f("G"); }, G: { g: 1, c: "h = parseInt(results[{0}], 10);\n", s: "(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23) }, h: function() { return $f("H"); }, H: { g: 1, c: "h = parseInt(results[{0}], 10);\n", s: "(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23) }, i: { g: 1, c: "i = parseInt(results[{0}], 10);\n", s: "(\\d{2})" // minutes with leading zeros (00 - 59) }, s: { g: 1, c: "s = parseInt(results[{0}], 10);\n", s: "(\\d{2})" // seconds with leading zeros (00 - 59) }, u: { g: 1, c: "ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n", s: "(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited) }, O: { g: 1, c: [ "o = results[{0}];", "var sn = o.substring(0,1),", // get + / - sign "hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case) "mn = o.substring(3,5) % 60;", // get minutes "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.util.Format.leftPad(hr, 2, '0') + Ext.util.Format.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs ].join("\n"), s: "([+\-]\\d{4})" // GMT offset in hrs and mins }, P: { g: 1, c: [ "o = results[{0}];", "var sn = o.substring(0,1),", // get + / - sign "hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case) "mn = o.substring(4,6) % 60;", // get minutes "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.util.Format.leftPad(hr, 2, '0') + Ext.util.Format.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs ].join("\n"), s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator) }, T: { g: 0, c: null, s: "[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars }, Z: { g: 1, c: "zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400 + "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n", s: "([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset }, c: function() { var calc = [], arr = [ $f("Y", 1), // year $f("m", 2), // month $f("d", 3), // day $f("h", 4), // hour $f("i", 5), // minute $f("s", 6), // second { c: "ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n" }, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited) { c: [ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified "if(results[8]) {", // timezone specified "if(results[8] == 'Z'){", "zz = 0;", // UTC "}else if (results[8].indexOf(':') > -1){", $f("P", 8).c, // timezone offset with colon separator "}else{", $f("O", 8).c, // timezone offset without colon separator "}", "}" ].join('\n') } ]; for (var i = 0, l = arr.length; i < l; ++i) { calc.push(arr[i].c); } return { g: 1, c: calc.join(""), s: [ arr[0].s, // year (required) "(?:", "-", arr[1].s, // month (optional) "(?:", "-", arr[2].s, // day (optional) "(?:", "(?:T| )?", // time delimiter -- either a "T" or a single blank space arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space "(?::", arr[5].s, ")?", // seconds (optional) "(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional) "(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional) ")?", ")?", ")?" ].join("") }; }, U: { g: 1, c: "u = parseInt(results[{0}], 10);\n", s: "(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch } } }); } ()); Ext.apply(Date.prototype, { // private dateFormat: function(format) { if (Date.formatFunctions[format] == null) { Date.createFormat(format); } return Date.formatFunctions[format].call(this); }, /** * Get the timezone abbreviation of the current date (equivalent to the format specifier 'T'). * * Note: The date string returned by the javascript Date object's toString() method varies * between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America). * For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)", * getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses * (which may or may not be present), failing which it proceeds to get the timezone abbreviation * from the GMT offset portion of the date string. * @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...). */ getTimezone: function() { // the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale: // // Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot // Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF) // FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone // IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev // IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev // // this crazy regex attempts to guess the correct timezone abbreviation despite these differences. // step 1: (?:\((.*)\) -- find timezone in parentheses // step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string // step 3: remove all non uppercase characters found in step 1 and 2 return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); }, /** * Get the offset from GMT of the current date (equivalent to the format specifier 'O'). * @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false). * @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600'). */ getGMTOffset: function(colon) { return (this.getTimezoneOffset() > 0 ? "-": "+") + Ext.util.Format.leftPad(Math.floor(Math.abs(this.getTimezoneOffset()) / 60), 2, "0") + (colon ? ":": "") + Ext.util.Format.leftPad(Math.abs(this.getTimezoneOffset() % 60), 2, "0"); }, /** * Get the numeric day number of the year, adjusted for leap year. * @return {Number} 0 to 364 (365 in leap years). */ getDayOfYear: function() { var num = 0, d = this.clone(), m = this.getMonth(), i; for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) { num += d.getDaysInMonth(); } return num + this.getDate() - 1; }, /** * Get the numeric ISO-8601 week number of the year. * (equivalent to the format specifier 'W', but without a leading zero). * @return {Number} 1 to 53 */ getWeekOfYear: function() { // adapted from http://www.merlyn.demon.co.uk/weekcalc.htm var ms1d = 864e5, // milliseconds in a day ms7d = 7 * ms1d; // milliseconds in a week return function() { // return a closure so constants get calculated only once var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d, // an Absolute Day Number AWN = Math.floor(DC3 / 7), // an Absolute Week Number Wyr = new Date(AWN * ms7d).getUTCFullYear(); return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; }; }(), /** * Checks if the current date falls within a leap year. * @return {Boolean} True if the current date falls within a leap year, false otherwise. */ isLeapYear: function() { var year = this.getFullYear(); return !! ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); }, /** * Get the first day of the current month, adjusted for leap year. The returned value * is the numeric day index within the week (0-6) which can be used in conjunction with * the {@link #monthNames} array to retrieve the textual day name. * Example: * <pre><code> var dt = new Date('1/10/2007'); document.write(Date.dayNames[dt.getFirstDayOfMonth()]); //output: 'Monday' </code></pre> * @return {Number} The day number (0-6). */ getFirstDayOfMonth: function() { var day = (this.getDay() - (this.getDate() - 1)) % 7; return (day < 0) ? (day + 7) : day; }, /** * Get the last day of the current month, adjusted for leap year. The returned value * is the numeric day index within the week (0-6) which can be used in conjunction with * the {@link #monthNames} array to retrieve the textual day name. * Example: * <pre><code> var dt = new Date('1/10/2007'); document.write(Date.dayNames[dt.getLastDayOfMonth()]); //output: 'Wednesday' </code></pre> * @return {Number} The day number (0-6). */ getLastDayOfMonth: function() { return this.getLastDateOfMonth().getDay(); }, /** * Get the date of the first day of the month in which this date resides. * @return {Date} */ getFirstDateOfMonth: function() { return new Date(this.getFullYear(), this.getMonth(), 1); }, /** * Get the date of the last day of the month in which this date resides. * @return {Date} */ getLastDateOfMonth: function() { return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth()); }, /** * Get the number of days in the current month, adjusted for leap year. * @return {Number} The number of days in the month. */ getDaysInMonth: function() { var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; return function() { // return a closure for efficiency var m = this.getMonth(); return m == 1 && this.isLeapYear() ? 29: daysInMonth[m]; }; }(), /** * Get the English ordinal suffix of the current day (equivalent to the format specifier 'S'). * @return {String} 'st, 'nd', 'rd' or 'th'. */ getSuffix: function() { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }, /** * Creates and returns a new Date instance with the exact same date value as the called instance. * Dates are copied and passed by reference, so if a copied date variable is modified later, the original * variable will also be changed. When the intention is to create a new variable that will not * modify the original instance, you should create a clone. * * Example of correctly cloning a date: * <pre><code> //wrong way: var orig = new Date('10/1/2006'); var copy = orig; copy.setDate(5); document.write(orig); //returns 'Thu Oct 05 2006'! //correct way: var orig = new Date('10/1/2006'); var copy = orig.clone(); copy.setDate(5); document.write(orig); //returns 'Thu Oct 01 2006' </code></pre> * @return {Date} The new Date instance. */ clone: function() { return new Date(this.getTime()); }, /** * Checks if the current date is affected by Daylight Saving Time (DST). * @return {Boolean} True if the current date is affected by DST. */ isDST: function() { // adapted from http://extjs.com/forum/showthread.php?p=247172#post247172 // courtesy of @geoffrey.mcgill return new Date(this.getFullYear(), 0, 1).getTimezoneOffset() != this.getTimezoneOffset(); }, /** * Attempts to clear all time information from this Date by setting the time to midnight of the same day, * automatically adjusting for Daylight Saving Time (DST) where applicable. * (note: DST timezone information for the browser's host operating system is assumed to be up-to-date) * @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false). * @return {Date} this or the clone. */ clearTime: function(clone) { if (clone) { return this.clone().clearTime(); } // get current date before clearing time var d = this.getDate(); // clear time this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); if (this.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0) // note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case) // refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule // increment hour until cloned date == current date for (var hr = 1, c = this.add(Date.HOUR, hr); c.getDate() != d; hr++, c = this.add(Date.HOUR, hr)); this.setDate(d); this.setHours(c.getHours()); } return this; }, /** * Provides a convenient method for performing basic date arithmetic. This method * does not modify the Date instance being called - it creates and returns * a new Date instance containing the resulting date value. * * Examples: * <pre><code> // Basic usage: var dt = new Date('10/29/2006').add(Date.DAY, 5); document.write(dt); //returns 'Fri Nov 03 2006 00:00:00' // Negative values will be subtracted: var dt2 = new Date('10/1/2006').add(Date.DAY, -5); document.write(dt2); //returns 'Tue Sep 26 2006 00:00:00' // You can even chain several calls together in one line: var dt3 = new Date('10/1/2006').add(Date.DAY, 5).add(Date.HOUR, 8).add(Date.MINUTE, -30); document.write(dt3); //returns 'Fri Oct 06 2006 07:30:00' </code></pre> * * @param {String} interval A valid date interval enum value. * @param {Number} value The amount to add to the current date. * @return {Date} The new Date instance. */ add: function(interval, value) { var d = this.clone(); if (!interval || value === 0) return d; switch (interval.toLowerCase()) { case Date.MILLI: d.setMilliseconds(this.getMilliseconds() + value); break; case Date.SECOND: d.setSeconds(this.getSeconds() + value); break; case Date.MINUTE: d.setMinutes(this.getMinutes() + value); break; case Date.HOUR: d.setHours(this.getHours() + value); break; case Date.DAY: d.setDate(this.getDate() + value); break; case Date.MONTH: var day = this.getDate(); if (day > 28) { day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate()); } d.setDate(day); d.setMonth(this.getMonth() + value); break; case Date.YEAR: d.setFullYear(this.getFullYear() + value); break; } return d; }, /** * Checks if this date falls on or between the given start and end dates. * @param {Date} start Start date * @param {Date} end End date * @return {Boolean} true if this date falls on or between the given start and end dates. */ between: function(start, end) { var t = this.getTime(); return start.getTime() <= t && t <= end.getTime(); } }); /** * Formats a date given the supplied format string. * @param {String} format The format string. * @return {String} The formatted date. * @method format */ Date.prototype.format = Date.prototype.dateFormat; /* Some basic Date tests... (requires Firebug) Date.parseDate('', 'c'); // call Date.parseDate() once to force computation of regex string so we can console.log() it console.log('Insane Regex for "c" format: %o', Date.parseCodes.c.s); // view the insane regex for the "c" format specifier // standard tests console.group('Standard Date.parseDate() Tests'); console.log('Date.parseDate("2009-01-05T11:38:56", "c") = %o', Date.parseDate("2009-01-05T11:38:56", "c")); // assumes browser's timezone setting console.log('Date.parseDate("2009-02-04T12:37:55.001000", "c") = %o', Date.parseDate("2009-02-04T12:37:55.001000", "c")); // assumes browser's timezone setting console.log('Date.parseDate("2009-03-03T13:36:54,101000Z", "c") = %o', Date.parseDate("2009-03-03T13:36:54,101000Z", "c")); // UTC console.log('Date.parseDate("2009-04-02T14:35:53.901000-0530", "c") = %o', Date.parseDate("2009-04-02T14:35:53.901000-0530", "c")); // GMT-0530 console.log('Date.parseDate("2009-05-01T15:34:52,9876000+08:00", "c") = %o', Date.parseDate("2009-05-01T15:34:52,987600+08:00", "c")); // GMT+08:00 console.groupEnd(); // ISO-8601 format as specified in http://www.w3.org/TR/NOTE-datetime // -- accepts ALL 6 levels of date-time granularity console.group('ISO-8601 Granularity Test (see http://www.w3.org/TR/NOTE-datetime)'); console.log('Date.parseDate("1997", "c") = %o', Date.parseDate("1997", "c")); // YYYY (e.g. 1997) console.log('Date.parseDate("1997-07", "c") = %o', Date.parseDate("1997-07", "c")); // YYYY-MM (e.g. 1997-07) console.log('Date.parseDate("1997-07-16", "c") = %o', Date.parseDate("1997-07-16", "c")); // YYYY-MM-DD (e.g. 1997-07-16) console.log('Date.parseDate("1997-07-16T19:20+01:00", "c") = %o', Date.parseDate("1997-07-16T19:20+01:00", "c")); // YYYY-MM-DDThh:mmTZD (e.g. 1997-07-16T19:20+01:00) console.log('Date.parseDate("1997-07-16T19:20:30+01:00", "c") = %o', Date.parseDate("1997-07-16T19:20:30+01:00", "c")); // YYYY-MM-DDThh:mm:ssTZD (e.g. 1997-07-16T19:20:30+01:00) console.log('Date.parseDate("1997-07-16T19:20:30.45+01:00", "c") = %o', Date.parseDate("1997-07-16T19:20:30.45+01:00", "c")); // YYYY-MM-DDThh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00) console.log('Date.parseDate("1997-07-16 19:20:30.45+01:00", "c") = %o', Date.parseDate("1997-07-16 19:20:30.45+01:00", "c")); // YYYY-MM-DD hh:mm:ss.sTZD (e.g. 1997-07-16T19:20:30.45+01:00) console.log('Date.parseDate("1997-13-16T19:20:30.45+01:00", "c", true)= %o', Date.parseDate("1997-13-16T19:20:30.45+01:00", "c", true)); // strict date parsing with invalid month value console.groupEnd(); */
JavaScript
/** * @class Ext.util.Droppable * @extends Ext.util.Observable * * @constructor */ Ext.util.Droppable = Ext.extend(Ext.util.Observable, { baseCls: 'x-droppable', /** * @cfg {String} activeCls * The CSS added to a Droppable when a Draggable in the same group is being * dragged. Defaults to 'x-drop-active'. */ activeCls: 'x-drop-active', /** * @cfg {String} invalidCls * The CSS class to add to the droppable when dragging a draggable that is * not in the same group. Defaults to 'x-drop-invalid'. */ invalidCls: 'x-drop-invalid', /** * @cfg {String} hoverCls * The CSS class to add to the droppable when hovering over a valid drop. (Defaults to 'x-drop-hover') */ hoverCls: 'x-drop-hover', /** * @cfg {String} validDropMode * Determines when a drop is considered 'valid' whether it simply need to * intersect the region or if it needs to be contained within the region. * Valid values are: 'intersects' or 'contains' */ validDropMode: 'intersect', /** * @cfg {Boolean} disabled */ disabled: false, /** * @cfg {String} group * Draggable and Droppable objects can participate in a group which are * capable of interacting. Defaults to 'base' */ group: 'base', // not yet implemented tolerance: null, // @private monitoring: false, /** * @constructor * @param el {Mixed} String, HtmlElement or Ext.Element representing an * element on the page. * @param config {Object} Configuration options for this class. */ constructor : function(el, config) { config = config || {}; Ext.apply(this, config); this.addEvents( /** * @event dropactivate * @param {Ext.Droppable} this * @param {Ext.Draggable} draggable * @param {Ext.EventObject} e */ 'dropactivate', /** * @event dropdeactivate * @param {Ext.Droppable} this * @param {Ext.Draggable} draggable * @param {Ext.EventObject} e */ 'dropdeactivate', /** * @event dropenter * @param {Ext.Droppable} this * @param {Ext.Draggable} draggable * @param {Ext.EventObject} e */ 'dropenter', /** * @event dropleave * @param {Ext.Droppable} this * @param {Ext.Draggable} draggable * @param {Ext.EventObject} e */ 'dropleave', /** * @event drop * @param {Ext.Droppable} this * @param {Ext.Draggable} draggable * @param {Ext.EventObject} e */ 'drop' ); this.el = Ext.get(el); Ext.util.Droppable.superclass.constructor.call(this); if (!this.disabled) { this.enable(); } this.el.addCls(this.baseCls); }, // @private onDragStart : function(draggable, e) { if (draggable.group === this.group) { this.monitoring = true; this.el.addCls(this.activeCls); this.region = this.el.getPageBox(true); draggable.on({ drag: this.onDrag, beforedragend: this.onBeforeDragEnd, dragend: this.onDragEnd, scope: this }); if (this.isDragOver(draggable)) { this.setCanDrop(true, draggable, e); } this.fireEvent('dropactivate', this, draggable, e); } else { draggable.on({ dragend: function() { this.el.removeCls(this.invalidCls); }, scope: this, single: true }); this.el.addCls(this.invalidCls); } }, // @private isDragOver : function(draggable, region) { return this.region[this.validDropMode](draggable.region); }, // @private onDrag : function(draggable, e) { this.setCanDrop(this.isDragOver(draggable), draggable, e); }, // @private setCanDrop : function(canDrop, draggable, e) { if (canDrop && !this.canDrop) { this.canDrop = true; this.el.addCls(this.hoverCls); this.fireEvent('dropenter', this, draggable, e); } else if (!canDrop && this.canDrop) { this.canDrop = false; this.el.removeCls(this.hoverCls); this.fireEvent('dropleave', this, draggable, e); } }, // @private onBeforeDragEnd: function(draggable, e) { draggable.cancelRevert = this.canDrop; }, // @private onDragEnd : function(draggable, e) { this.monitoring = false; this.el.removeCls(this.activeCls); draggable.un({ drag: this.onDrag, beforedragend: this.onBeforeDragEnd, dragend: this.onDragEnd, scope: this }); if (this.canDrop) { this.canDrop = false; this.el.removeCls(this.hoverCls); this.fireEvent('drop', this, draggable, e); } this.fireEvent('dropdeactivate', this, draggable, e); }, /** * Enable the Droppable target. * This is invoked immediately after constructing a Droppable if the * disabled parameter is NOT set to true. */ enable : function() { if (!this.mgr) { this.mgr = Ext.util.Observable.observe(Ext.util.Draggable); } this.mgr.on({ dragstart: this.onDragStart, scope: this }); this.disabled = false; }, /** * Disable the Droppable target. */ disable : function() { this.mgr.un({ dragstart: this.onDragStart, scope: this }); this.disabled = true; }, /** * Method to determine whether this Component is currently disabled. * @return {Boolean} the disabled state of this Component. */ isDisabled : function() { return this.disabled; }, /** * Method to determine whether this Droppable is currently monitoring drag operations of Draggables. * @return {Boolean} the monitoring state of this Droppable */ isMonitoring : function() { return this.monitoring; } });
JavaScript
/** * @class Ext.util.TapRepeater * @extends Ext.util.Observable * * A wrapper class which can be applied to any element. Fires a "tap" event while * touching the device. The interval between firings may be specified in the config but * defaults to 20 milliseconds. * * @constructor * @param {Mixed} el The element to listen on * @param {Object} config */ Ext.util.TapRepeater = Ext.extend(Ext.util.Observable, { constructor: function(el, config) { this.el = Ext.get(el); Ext.apply(this, config); this.addEvents( /** * @event touchstart * Fires when the touch is started. * @param {Ext.util.TapRepeater} this * @param {Ext.EventObject} e */ "touchstart", /** * @event tap * Fires on a specified interval during the time the element is pressed. * @param {Ext.util.TapRepeater} this * @param {Ext.EventObject} e */ "tap", /** * @event touchend * Fires when the touch is ended. * @param {Ext.util.TapRepeater} this * @param {Ext.EventObject} e */ "touchend" ); this.el.on({ touchstart: this.onTouchStart, touchend: this.onTouchEnd, scope: this }); if (this.preventDefault || this.stopDefault) { this.el.on('tap', this.eventOptions, this); } Ext.util.TapRepeater.superclass.constructor.call(this); }, interval: 10, delay: 250, preventDefault: true, stopDefault: false, timer: 0, // @private eventOptions: function(e) { if (this.preventDefault) { e.preventDefault(); } if (this.stopDefault) { e.stopEvent(); } }, // @private destroy: function() { Ext.destroy(this.el); this.clearListeners(); }, // @private onTouchStart: function(e) { clearTimeout(this.timer); if (this.pressClass) { this.el.addCls(this.pressClass); } this.tapStartTime = new Date(); this.fireEvent("touchstart", this, e); this.fireEvent("tap", this, e); // Do not honor delay or interval if acceleration wanted. if (this.accelerate) { this.delay = 400; } this.timer = Ext.defer(this.tap, this.delay || this.interval, this, [e]); }, // @private tap: function(e) { this.fireEvent("tap", this, e); this.timer = Ext.defer(this.tap, this.accelerate ? this.easeOutExpo(Ext.util.Date.getElapsed(this.tapStartTime), 400, -390, 12000) : this.interval, this, [e]); }, // Easing calculation // @private easeOutExpo: function(t, b, c, d) { return (t == d) ? b + c : c * ( - Math.pow(2, -10 * t / d) + 1) + b; }, // @private onTouchEnd: function(e) { clearTimeout(this.timer); this.el.removeCls(this.pressClass); this.fireEvent("touchend", this, e); } });
JavaScript
/** * These classes are derivatives of the similarly named classes in the YUI Library. * The original license: * Copyright (c) 2006, Yahoo! Inc. All rights reserved. * Code licensed under the BSD License: * http://developer.yahoo.net/yui/license.txt */ (function() { var Event=Ext.EventManager; var Dom=Ext.lib.Dom; /** * 对于可被拖动(drag)或可被放下(drop)的目标,进行接口和各项基本操作的定义。 * 你应该通过继承的方式使用该类,并重写startDrag, onDrag, onDragOver和onDragOut的事件处理器,. * 共有三种html元素可以被关联到DragDrop实例: * <ul> * <li>关联元素(linked element):传入到构造器的元素。 * 这是一个为与其它拖放对象交互定义边界的元素</li> * <li>执行元素(handle element):只有被点击的元素是执行元素, * 这个拖动操作才会发生。默认就是关联元素,不过有情况你只是想关联元素的某一部分 * 来初始化拖动操作。可用setHandleElId()方法重新定义</li> * <li>拖动元素(drag element):表示在拖放过程中,参与和鼠标指针一起的那个元素。 * 默认就是关联元素本身,如{@link Ext.dd.DD},setDragElId()可让你定义一个 * 可移动的独立元素,如{@link Ext.dd.DDProxy}</li> * </ul> */ /** * 必须在onload事件发生之后才能实例化这个类,以保证关联元素已准备可用。 * 下列语句会将拖放对象放进"group1"的组中,与组内其他拖放对象交互: * <pre> * dd = new Ext.dd.DragDrop("div1", "group1"); * </pre> * 由于没有实现任何的事件处理器,所以上面的代码运行后不会有实际的效果发生。 * 通常的做法是你要先重写这个类或者某个默的实现,但是你可以重写你想出现在这个实例上的方法 * <pre> * dd.onDragDrop = function(e, id) { * &nbsp;&nbsp;alert("DD落在" + id+"的身上"); * } * </pre> * @constructor * @param {String} id 关联到这个实例的那个元素的id * @param {String} sGroup 相关拖放对象的组 * @param {object} config 包含可配置的对象属性 * DragDrop的有效属性: * padding, isTarget, maintainOffset, primaryButtonOnly */ Ext.dd.DragDrop = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; Ext.dd.DragDrop.prototype = { /** * 关联该对象元素之id,这便是我们所提及的“关联元素”, * 因为拖动过程中的交互行为取决于该元素的大小和尺寸。 * @property id * @type String */ id: null, /** * 传入构造器的配置项对象 * @property config * @type object */ config: null, /** * 被拖动的元素id,默认与关联元素相同,但可替换为其他元素,如:Ext.dd.DDProxy * @property dragElId * @type String * @private */ dragElId: null, /** * 初始化拖动操作的元素id,这是一个关联元素,但可改为这个元素的子元素。 * @property handleElId * @type String * @private */ handleElId: null, /** * 点击时要忽略的HTML标签名称。 * @property invalidHandleTypes * @type {string: string} */ invalidHandleTypes: null, /** * 点击时要忽略的元素id。 * @property invalidHandleIds * @type {string: string} */ invalidHandleIds: null, /** * 点击时要忽略的元素的css样式类名称所组成的数组。 * @property invalidHandleClasses * @type string[] */ invalidHandleClasses: null, /** * 拖动开始时的x绝对位置 * @property startPageX * @type int * @private */ startPageX: 0, /** * 拖动开始时的y绝对位置 * @property startPageY * @type int * @private */ startPageY: 0, /** * 组(Group)定义,相关拖放对象的逻辑集合。 * 实例只能通过事件与同一组下面的其他拖放对象交互。 * 这使得我们可以将多个组定义在同一个子类下面。 * @property groups * @type {string: string} */ groups: null, /** * 每个拖动/落下的实例可被锁定。 * 这会禁止onmousedown开始拖动。 * @property locked * @type boolean * @private */ locked: false, /** * 锁定实例 * @method lock */ lock: function() { this.locked = true; }, /** * 解锁实例 * @method unlock */ unlock: function() { this.locked = false; }, /** * 默认地,所有实例可以是降落目标。 * 该项可设置isTarget为false来禁止。 * @method isTarget * @type boolean */ isTarget: true, /** * 当拖放对象与落下区域交互时的外补丁配置。 * @method padding * @type int[] */ padding: null, /** * 缓存关联元素的引用。 * @property _domRef * @private */ _domRef: null, /** * Internal typeof flag * @property __ygDragDrop * @private */ __ygDragDrop: true, /** * 当水平约束应用时为true。 * @property constrainX * @type boolean * @private */ constrainX: false, /** * 当垂直约束应用时为false。 * @property constrainY * @type boolean * @private */ constrainY: false, /** * 左边坐标 * @property minX * @type int * @private */ minX: 0, /** * 右边坐标 * @property maxX * @type int * @private */ maxX: 0, /** * 上方坐标 * @property minY * @type int * @type int * @private */ minY: 0, /** * 下方坐标 * @property maxY * @type int * @private */ maxY: 0, /** * 当重置限制时(constraints)修正偏移。 * 如果你想在页面变动时,元素的位置与其父级元素的位置不发生变化,可设为true。 * @property maintainOffset * @type boolean */ maintainOffset: false, /** * 如果我们指定一个垂直的间隔值,元素会作一个象素位置的取样,放到数组中。 * 如果你定义了一个tick interval,该数组将会自动生成。 * @property xTicks * @type int[] */ xTicks: null, /** * 如果我们指定一个水平的间隔值,元素会作一个象素位置的取样,放到数组中。 * 如果你定义了一个tick interval,该数组将会自动生成。 * @property yTicks * @type int[] */ yTicks: null, /** * 默认下拖放的实例只会响应主要的按钮键(左键和右键)。 * 设置为true表示开放其他的鼠标的键,只要是浏览器支持的。 * @property primaryButtonOnly * @type boolean */ primaryButtonOnly: true, /** * 关联的dom元素访问之后该属性才为false。 * @property available * @type boolean */ available: false, /** * 默认状态下,拖动只会是mousedown发生在关联元素的区域才会初始化。 * 但是因为某些浏览器的bug,如果之前的mouseup发生在window外部地方,浏览器会漏报告这个事件。 * 如果已定义外部的处理,这个属性应该设置为true. * @property hasOuterHandles * @type boolean * @default false */ hasOuterHandles: false, /** * 在startDrag时间之前立即执行的代码。 * @method b4StartDrag * @private */ b4StartDrag: function(x, y) { }, /** * 抽象方法:在拖放对象被点击后和已跨入拖动或mousedown启动时间的时候调用。 * @method startDrag * @param {int} X 方向点击位置 * @param {int} Y 方向点击位置 */ startDrag: function(x, y) { /* override this */ }, /** * onDrag事件发生之前执行的代码。 * @method b4Drag * @private */ b4Drag: function(e) { }, /** * 抽象方法:当拖动某个对象时发生onMouseMove时调用。 * @method onDrag * @param {Event} e mousemove事件 */ onDrag: function(e) { /* override this */ }, /** * 抽象方法:在这个元素刚刚开始悬停在其他DD对象身上时调用。 * @method onDragEnter * @param {Event} e mousemove事件 * @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组 */ onDragEnter: function(e, id) { /* override this */ }, /** * onDragOver事件发生在前执行的代码。 * @method b4DragOver * @private */ b4DragOver: function(e) { }, /** * 抽象方法:在这个元素悬停在其他DD对象范围内的调用。 * @method onDragOver * @param {Event} e mousemove事件 * @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组 */ onDragOver: function(e, id) { /* override this */ }, /** * onDragOut事件发生之前执行的代码。 * @method b4DragOut * @private */ b4DragOut: function(e) { }, /** * 抽象方法:当不再有任何悬停DD对象的时候调用。 * @method onDragOut * @param {Event} e mousemove事件 * @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, DD项不再悬浮。 */ onDragOut: function(e, id) { /* override this */ }, /** * onDragDrop事件发生之前执行的代码。 * @method b4DragDrop * @private */ b4DragDrop: function(e) { }, /** * 抽象方法:该项在另外一个DD对象上落下的时候调用。 * @method onDragDrop * @param {Event} e mouseup事件 * @param {String|DragDrop[]} id 在POINT模式中, 是悬浮中的元素id;在INTERSECT模式中, 是DD项组成的数组 */ onDragDrop: function(e, id) { /* override this */ }, /** * 抽象方法:当各项在一个没有置下目标的地方置下时调用。 * @method onInvalidDrop * @param {Event} e mouseup事件 */ onInvalidDrop: function(e) { /* override this */ }, /** * 在endDrag事件触发之前立即执行的代码。 * @method b4EndDrag * @private */ b4EndDrag: function(e) { }, /** * 当我们完成拖动对象时触发的事件。 * @method endDrag * @param {Event} e mouseup事件 */ endDrag: function(e) { /* override this */ }, /** * 在onMouseDown事件触发之前立即执行的代码。 * @method b4MouseDown * @param {Event} e mousedown事件 * @private */ b4MouseDown: function(e) { }, /** * 当拖放对象mousedown触发时的事件处理器。 * @method onMouseDown * @param {Event} e mousedown事件 */ onMouseDown: function(e) { /* override this */ }, /** * 当DD对象发生mouseup事件时的事件处理器。 * @method onMouseUp * @param {Event} e mouseup事件 */ onMouseUp: function(e) { /* override this */ }, /** * 重写onAvailable的方法以便我们在初始化之后做所需要的事情 * position was determined. * @method onAvailable */ onAvailable: function () { }, /* * 为“constrainTo”的元素提供默认的外补丁限制。默认为{left: 0, right:0, top:0, bottom:0} * @type Object */ defaultPadding : {left:0, right:0, top:0, bottom:0}, /** * * 初始化拖放对象的限制,以便控制在某个元的范围内移动 * 举例: <pre><code> var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest", { dragElId: "existingProxyDiv" }); dd.startDrag = function(){ this.constrainTo("parent-id"); }; </code></pre> *或者你可以使用 {@link Ext.Element}对象初始化它: <pre><code> Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, { startDrag : function(){ this.constrainTo("parent-id"); } }); </code></pre> * @param {String/HTMLElement/Element} constrainTo 要限制的元素 * @param {Object/Number} pad (可选的) Pad提供了指定“外补丁”的限制的一种方式。 * 例如 {left:4, right:4, top:4, bottom:4})或{right:10, bottom:10} * @param {Boolean} inContent (可选的) 限制在元素的正文内容内拖动(包含外补丁和边框) */ constrainTo : function(constrainTo, pad, inContent){ if(typeof pad == "number"){ pad = {left: pad, right:pad, top:pad, bottom:pad}; } pad = pad || this.defaultPadding; var b = Ext.get(this.getEl()).getBox(); var ce = Ext.get(constrainTo); var s = ce.getScroll(); var c, cd = ce.dom; if(cd == document.body){ c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight()}; }else{ xy = ce.getXY(); c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight}; } var topSpace = b.y - c.y; var leftSpace = b.x - c.x; this.resetConstraints(); this.setXConstraint(leftSpace - (pad.left||0), // left c.width - leftSpace - b.width - (pad.right||0) //right ); this.setYConstraint(topSpace - (pad.top||0), //top c.height - topSpace - b.height - (pad.bottom||0) //bottom ); }, /** * 返回关联元素的引用 * @method getEl * @return {HTMLElement} html元素 */ getEl: function() { if (!this._domRef) { this._domRef = Ext.getDom(this.id); } return this._domRef; }, /** * 返回实际拖动元素的引用,默认时和html element一样,不过它可分配给其他元素,可在这里找到。 * @method getDragEl * @return {HTMLElement} html元素 */ getDragEl: function() { return Ext.getDom(this.dragElId); }, /** * 设置拖放对象,须在Ext.dd.DragDrop子类的构造器调用。 * @method init * @param id 关联元素之id * @param {String} sGroup 相关项的组 * @param {object} config 配置属性 */ init: function(id, sGroup, config) { this.initTarget(id, sGroup, config); Event.on(this.id, "mousedown", this.handleMouseDown, this); // Event.on(this.id, "selectstart", Event.preventDefault); }, /** * 只是有针对性的初始化目标...对象获取不了mousedown handler * @method initTarget * @param id 关联元素之id * @param {String} sGroup 相关项的组 * @param {object} config 配置属性 */ initTarget: function(id, sGroup, config) { // configuration attributes this.config = config || {}; // create a local reference to the drag and drop manager this.DDM = Ext.dd.DDM; // initialize the groups array this.groups = {}; // assume that we have an element reference instead of an id if the // parameter is not a string if (typeof id !== "string") { id = Ext.id(id); } // set the id this.id = id; // add to an interaction group this.addToGroup((sGroup) ? sGroup : "default"); // We don't want to register this as the handle with the manager // so we just set the id rather than calling the setter. this.handleElId = id; // the linked element is the element that gets dragged by default this.setDragElId(id); // by default, clicked anchors will not start drag operations. this.invalidHandleTypes = { A: "A" }; this.invalidHandleIds = {}; this.invalidHandleClasses = []; this.applyConfig(); this.handleOnAvailable(); }, /** * 将配置参数应用到构造器。该方法应该在继承链上的每一个环节调用。 * 所以为了获取每个对象的可用参数,配置将会由DDPRoxy实现应用在DDProxy, DD,DragDrop身上。 * @method applyConfig */ applyConfig: function() { // configurable properties: // padding, isTarget, maintainOffset, primaryButtonOnly this.padding = this.config.padding || [0, 0, 0, 0]; this.isTarget = (this.config.isTarget !== false); this.maintainOffset = (this.config.maintainOffset); this.primaryButtonOnly = (this.config.primaryButtonOnly !== false); }, /** * 当关联元素有效时执行。 * @method handleOnAvailable * @private */ handleOnAvailable: function() { this.available = true; this.resetConstraints(); this.onAvailable(); }, /** * 配置目标区域的外补丁(px)。 * @method setPadding * @param {int} iTop Top pad * @param {int} iRight Right pad * @param {int} iBot Bot pad * @param {int} iLeft Left pad */ setPadding: function(iTop, iRight, iBot, iLeft) { // this.padding = [iLeft, iRight, iTop, iBot]; if (!iRight && 0 !== iRight) { this.padding = [iTop, iTop, iTop, iTop]; } else if (!iBot && 0 !== iBot) { this.padding = [iTop, iRight, iTop, iRight]; } else { this.padding = [iTop, iRight, iBot, iLeft]; } }, /** * 储存关联元素的初始位置。 * @method setInitialPosition * @param {int} diffX X偏移,默认为0 * @param {int} diffY Y偏移,默认为0 */ setInitPosition: function(diffX, diffY) { var el = this.getEl(); if (!this.DDM.verifyEl(el)) { return; } var dx = diffX || 0; var dy = diffY || 0; var p = Dom.getXY( el ); this.initPageX = p[0] - dx; this.initPageY = p[1] - dy; this.lastPageX = p[0]; this.lastPageY = p[1]; this.setStartPosition(p); }, /** * 设置元素的开始位置。对象初始化时便设置,拖动开始时复位。 * @method setStartPosition * @param pos 当前位置(利用刚才的lookup) * @private */ setStartPosition: function(pos) { var p = pos || Dom.getXY( this.getEl() ); this.deltaSetXY = null; this.startPageX = p[0]; this.startPageY = p[1]; }, /** * 将该对象加入到相关的拖放组之中。 * 所有组实例至少要分配到一个组,也可以是多个组。 * @method addToGroup * @param sGroup {string} 组名称 */ addToGroup: function(sGroup) { this.groups[sGroup] = true; this.DDM.regDragDrop(this, sGroup); }, /** * 传入一个“交互组” interaction group的参数,从中删除该实例。 * @method removeFromGroup * @param {string} sGroup 组名称 */ removeFromGroup: function(sGroup) { if (this.groups[sGroup]) { delete this.groups[sGroup]; } this.DDM.removeDDFromGroup(this, sGroup); }, /** * 允许你指定一个不是被移动的关联元素的元素作为拖动处理。 * @method setDragElId * @param id {string} 将会用于初始拖动的元素id */ setDragElId: function(id) { this.dragElId = id; }, /** * 允许你指定一个关联元素下面的子元素以初始化拖动操作。 * 一个例子就是假设你有一段套着div文本和若干连接,点击正文的区域便引发拖动的操作。 * 使用这个方法来指定正文内的div元素,然后拖动操作就会从这个元素开始了。 * @method setHandleElId * @param id {string} 将会用于初始拖动的元素id */ setHandleElId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } this.handleElId = id; this.DDM.regHandle(this.id, id); }, /** * 允许你在关联元素之外设置一个元素作为拖动处理。 * @method setOuterHandleElId * @param id 将会用于初始拖动的元素id */ setOuterHandleElId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } Event.on(id, "mousedown", this.handleMouseDown, this); this.setHandleElId(id); this.hasOuterHandles = true; }, /** * 移除所有钩在该元素身上的拖放对象。 * @method unreg */ unreg: function() { Event.un(this.id, "mousedown", this.handleMouseDown); this._domRef = null; this.DDM._remove(this); }, destroy : function(){ this.unreg(); }, /** * 返回true表示为该实例已被锁定,或者说是拖放控制器(DD Mgr)被锁定。 * @method isLocked * @return {boolean} true表示禁止页面上的所有拖放操作,反之为false */ isLocked: function() { return (this.DDM.isLocked() || this.locked); }, /** * 当对象单击时触发。 * @method handleMouseDown * @param {Event} e * @param {Ext.dd.DragDrop} 单击的 DD 对象(this DD obj) * @private */ handleMouseDown: function(e, oDD){ if (this.primaryButtonOnly && e.button != 0) { return; } if (this.isLocked()) { return; } this.DDM.refreshCache(this.groups); var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e)); if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) { } else { if (this.clickValidator(e)) { // set the initial element position this.setStartPosition(); this.b4MouseDown(e); this.onMouseDown(e); this.DDM.handleMouseDown(e, this); this.DDM.stopEvent(e); } else { } } }, clickValidator: function(e) { var target = e.getTarget(); return ( this.isValidHandleChild(target) && (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) ); }, /** * 指定某个标签名称(tag Name),这个标签的元素单击时便不会引发拖动的操作。 * 这个设计目的在于某个拖动区域中同时又有链接(links)避免执行拖动的动作。 * @method addInvalidHandleType * @param {string} tagName 避免执行元素的类型 */ addInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); this.invalidHandleTypes[type] = type; }, /** * 可指定某个元素的id,则这个id下的子元素将不会引发拖动的操作。 * @method addInvalidHandleId * @param {string} id 你希望会被忽略的元素id */ addInvalidHandleId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } this.invalidHandleIds[id] = id; }, /** * 可指定某个css样式类,则这个css样式类的子元素将不会引发拖动的操作。 * @method addInvalidHandleClass * @param {string} cssClass 你希望会被忽略的css样式类 */ addInvalidHandleClass: function(cssClass) { this.invalidHandleClasses.push(cssClass); }, /** * 移除由addInvalidHandleType方法所执行的标签名称。 * @method removeInvalidHandleType * @param {string} tagName 元素类型 */ removeInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); // this.invalidHandleTypes[type] = null; delete this.invalidHandleTypes[type]; }, /** * 移除一个无效的handle id * @method removeInvalidHandleId * @param {string} id 要再“激活”的元素id */ removeInvalidHandleId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } delete this.invalidHandleIds[id]; }, /** * 移除一个无效的css class * @method removeInvalidHandleClass * @param {string} cssClass 你希望要再“激活”的元素id * re-enable */ removeInvalidHandleClass: function(cssClass) { for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) { if (this.invalidHandleClasses[i] == cssClass) { delete this.invalidHandleClasses[i]; } } }, /** * 检查这次单击是否属于在标签排除列表里。 * @method isValidHandleChild * @param {HTMLElement} node 检测的HTML元素 * @return {boolean} true 表示为这是一个有效的标签类型,反之为false */ isValidHandleChild: function(node) { var valid = true; // var n = (node.nodeName == "#text") ? node.parentNode : node; var nodeName; try { nodeName = node.nodeName.toUpperCase(); } catch(e) { nodeName = node.nodeName; } valid = valid && !this.invalidHandleTypes[nodeName]; valid = valid && !this.invalidHandleIds[node.id]; for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) { valid = !Dom.hasClass(node, this.invalidHandleClasses[i]); } return valid; }, /** * 若指定了间隔(interval),将会创建水平点击的标记(horizontal tick marks)的数组。 * @method setXTicks * @private */ setXTicks: function(iStartX, iTickSize) { this.xTicks = []; this.xTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } this.xTicks.sort(this.DDM.numericSort) ; }, /** * 若指定了间隔(interval),将会创建垂直点击的标记(horizontal tick marks)的数组。 * @method setYTicks * @private */ setYTicks: function(iStartY, iTickSize) { this.yTicks = []; this.yTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } this.yTicks.sort(this.DDM.numericSort) ; }, /** * 默认情况下,元素可被拖动到屏幕的任何一个位置。 * 使用该方法能限制元素的水平方向上的摇动。 * 如果打算只限制在Y轴的拖动,可传入0,0的参数。 * @method setXConstraint * @param {int} iLeft 元素向左移动的像素值 * @param {int} iRight 元素向右移动的像素值 * @param {int} iTickSize (可选项)指定每次元素移动的步幅。 */ setXConstraint: function(iLeft, iRight, iTickSize) { this.leftConstraint = iLeft; this.rightConstraint = iRight; this.minX = this.initPageX - iLeft; this.maxX = this.initPageX + iRight; if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); } this.constrainX = true; }, /** * 清除该实例的所有坐标。 * 也清除ticks,因为这时候已不存在任何的坐标。 * @method clearConstraints */ clearConstraints: function() { this.constrainX = false; this.constrainY = false; this.clearTicks(); }, /** * 清除该实例的所有tick间歇定义。 * @method clearTicks */ clearTicks: function() { this.xTicks = null; this.yTicks = null; this.xTickSize = 0; this.yTickSize = 0; }, /** * 默认情况下,元素可被拖动到屏幕的任何一个位置。 * 使用该方法能限制元素的水平方向上的摇动。 * 如果打算只限制在X轴的拖动,可传入0,0的参数。 * @method setYConstraint * @param {int} iUp 元素向上移动的像素值 * @param {int} iDown 元素向下移动的像素值 * @param {int} iTickSize (可选项)指定每次元素移动的步幅。 */ setYConstraint: function(iUp, iDown, iTickSize) { this.topConstraint = iUp; this.bottomConstraint = iDown; this.minY = this.initPageY - iUp; this.maxY = this.initPageY + iDown; if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); } this.constrainY = true; }, /** * 坐标复位需在你手动重新定位一个DD元素是调用。 * @method resetConstraints * @param {boolean} maintainOffset */ resetConstraints: function() { // Maintain offsets if necessary if (this.initPageX || this.initPageX === 0) { // figure out how much this thing has moved var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0; var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0; this.setInitPosition(dx, dy); // This is the first time we have detected the element's position } else { this.setInitPosition(); } if (this.constrainX) { this.setXConstraint( this.leftConstraint, this.rightConstraint, this.xTickSize ); } if (this.constrainY) { this.setYConstraint( this.topConstraint, this.bottomConstraint, this.yTickSize ); } }, /** * 通常情况下拖动元素是逐个像素地移动的。 * 不过我们也可以指定一个移动的数值。 * @method getTick * @param {int} val 打算将对象放到的地方 * @param {int[]} tickArray 已排序的有效点 * @return {int} 最近的点 * @private */ getTick: function(val, tickArray) { if (!tickArray) { // If tick interval is not defined, it is effectively 1 pixel, // so we return the value passed to us. return val; } else if (tickArray[0] >= val) { // The value is lower than the first tick, so we return the first // tick. return tickArray[0]; } else { for (var i=0, len=tickArray.length; i<len; ++i) { var next = i + 1; if (tickArray[next] && tickArray[next] >= val) { var diff1 = val - tickArray[i]; var diff2 = tickArray[next] - val; return (diff2 > diff1) ? tickArray[i] : tickArray[next]; } } // The value is larger than the last tick, so we return the last // tick. return tickArray[tickArray.length - 1]; } }, /** * toString方法 * @method toString * @return {string} string 表示DD对象之字符 */ toString: function() { return ("DragDrop " + this.id); } }; })(); /** * The drag and drop utility provides a framework for building drag and drop * applications. In addition to enabling drag and drop for specific elements, * the drag and drop elements are tracked by the manager class, and the * interactions between the various elements are tracked during the drag and * the implementing code is notified about these important moments. */ // Only load the library once. Rewriting the manager class would orphan // existing drag and drop instances. if (!Ext.dd.DragDropMgr) { /** * @class Ext.dd.DragDropMgr * DragDropMgr是一个对窗口内所有拖放项跟踪元素交互过程的单例。 * 一般来说你不会直接调用该类,但是你所实现的拖放中,会提供一些有用的方法。 * @singleton */ Ext.dd.DragDropMgr = function() { var Event = Ext.EventManager; return { /** * 已登记拖放对象的二维数组。 * 第一维是拖放项的组,第二维是拖放对象。 * @property ids * @type {string: string} * @private * @static */ ids: {}, /** * 元素id组成的数组,由拖动处理定义。 * 如果元素触发了mousedown事件实际上是一个处理(handle)而非html元素本身。 * @property handleIds * @type {string: string} * @private * @static */ handleIds: {}, /** * 正在被拖放的DD对象。 * @property dragCurrent * @type DragDrop * @private * @static **/ dragCurrent: null, /** * 正被悬浮着的拖放对象。 * @property dragOvers * @type Array * @private * @static */ dragOvers: {}, /** * 正被拖动对象与指针之间的X间距。 * @property deltaX * @type int * @private * @static */ deltaX: 0, /** * 正被拖动对象与指针之间的Y间距。 * @property deltaY * @type int * @private * @static */ deltaY: 0, /** * 一个是否应该阻止我们所定义的默认行为的标识。 * 默认为true,如需默认的行为可设为false(但不推荐)。 * @property preventDefault * @type boolean * @static */ preventDefault: true, /** * 一个是否在该停止事件繁殖的标识(events propagation)。 * 默认下为true,但如果HTML元素包含了其他mouse点击的所需功能,就可设为false。 * @property stopPropagation * @type boolean * @static */ stopPropagation: true, /** * 一个内置使用的标识,True说明拖放已被初始化。 * @property initialized * @private * @static */ initalized: false, /** * 所有拖放的操作可被禁用。 * @property locked * @private * @static */ locked: false, /** * 元素首次注册时调用。 * @method init * @private * @static */ init: function() { this.initialized = true; }, /** * 由拖放过程中的鼠标指针来定义拖放的交互操作。 * @property POINT * @type int * @static */ POINT: 0, /** * Intersect模式下,拖放的交互是由两个或两个以上的拖放对象的重叠来定义。 * @property INTERSECT * @type int * @static */ INTERSECT: 1, /** * 当前拖放的模式,默认为:POINT * @property mode * @type int * @static */ mode: 0, /** * 在拖放对象上运行方法 * @method _execOnAll * @private * @static */ _execOnAll: function(sMethod, args) { for (var i in this.ids) { for (var j in this.ids[i]) { var oDD = this.ids[i][j]; if (! this.isTypeOfDD(oDD)) { continue; } oDD[sMethod].apply(oDD, args); } } }, /** * 拖放的初始化,设置全局的事件处理器。 * @method _onLoad * @private * @static */ _onLoad: function() { this.init(); Event.on(document, "mouseup", this.handleMouseUp, this, true); Event.on(document, "mousemove", this.handleMouseMove, this, true); Event.on(window, "unload", this._onUnload, this, true); Event.on(window, "resize", this._onResize, this, true); // Event.on(window, "mouseout", this._test); }, /** * 重置拖放对象身上的全部限制。 * @method _onResize * @private * @static */ _onResize: function(e) { this._execOnAll("resetConstraints", []); }, /** * 锁定拖放的功能。 * @method lock * @static */ lock: function() { this.locked = true; }, /** * 解锁拖放的功能。 * @method unlock * @static */ unlock: function() { this.locked = false; }, /** * 拖放是否已锁定? * @method isLocked * @return {boolean} True 表示为拖放已锁定,反之为false。 * @static */ isLocked: function() { return this.locked; }, /** * 拖动一开始,就会有“局部缓存”伴随着拖放对象,而拖动完毕就会清除。 * @property locationCache * @private * @static */ locationCache: {}, /** * 设置useCache为false的话,表示你想强制对象不断在每个拖放关联对象中轮询。 * @property useCache * @type boolean * @static */ useCache: true, /** * 在mousedown之后,拖动初始化之前,鼠标需要移动的像素值。默认值为3 * @property clickPixelThresh * @type int * @static */ clickPixelThresh: 3, /** * 在mousedown事件触发之后,接着开始拖动但不想触发mouseup的事件的毫秒数。默认值为1000 * @property clickTimeThresh * @type int * @static */ clickTimeThresh: 350, /** * 每当满足拖动像素或mousedown时间的标识。 * @property dragThreshMet * @type boolean * @private * @static */ dragThreshMet: false, /** * 开始点击的超时时限。 * @property clickTimeout * @type Object * @private * @static */ clickTimeout: null, /** * 拖动动作刚开始,保存mousedown事件的X位置。 * @property startX * @type int * @private * @static */ startX: 0, /** * 拖动动作刚开始,保存mousedown事件的Y位置。 * @property startY * @type int * @private * @static */ startY: 0, /** * 每个拖放实例必须在DragDropMgr登记好的。 * @method regDragDrop * @param {DragDrop} oDD 要登记的拖动对象 * @param {String} sGroup 元素所属的组名称 * @static */ regDragDrop: function(oDD, sGroup) { if (!this.initialized) { this.init(); } if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } this.ids[sGroup][oDD.id] = oDD; }, /** * 传入两个参数oDD、sGroup,从传入的组之中删除DD实例。 * 由DragDrop.removeFromGroup执行,所以不会直接调用这个函数。 * @method removeDDFromGroup * @private * @static */ removeDDFromGroup: function(oDD, sGroup) { if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } var obj = this.ids[sGroup]; if (obj && obj[oDD.id]) { delete obj[oDD.id]; } }, /** * 注销拖放项,由DragDrop.unreg所调用,直接使用那个方法即可。 * @method _remove * @private * @static */ _remove: function(oDD) { for (var g in oDD.groups) { if (g && this.ids[g][oDD.id]) { delete this.ids[g][oDD.id]; } } delete this.handleIds[oDD.id]; }, /** * 每个拖放处理元素必须先登记。 * 执行DragDrop.setHandleElId()时会自动完成这工作。 * @method regHandle * @param {String} sDDId 处理拖放对象的id * @param {String} sHandleId 在拖动的元素id * handle * @static */ regHandle: function(sDDId, sHandleId) { if (!this.handleIds[sDDId]) { this.handleIds[sDDId] = {}; } this.handleIds[sDDId][sHandleId] = sHandleId; }, /** * 确认一个元素是否属于已注册的拖放项的实用函数。 * @method isDragDrop * @param {String} id 要检查的元素id * @return {boolean} true 表示为该元素是一个拖放项,反之为false * @static */ isDragDrop: function(id) { return ( this.getDDById(id) ) ? true : false; }, /** * 传入一个拖放实例的参数,返回在这个实例“组”下面的全部其他拖放实例。 * @method getRelated * @param {DragDrop} p_oDD 获取相关数据的对象 * @param {boolean} bTargetsOnly if true 表示为只返回目标对象 * @return {DragDrop[]} 相关的实例 * @static */ getRelated: function(p_oDD, bTargetsOnly) { var oDDs = []; for (var i in p_oDD.groups) { for (j in this.ids[i]) { var dd = this.ids[i][j]; if (! this.isTypeOfDD(dd)) { continue; } if (!bTargetsOnly || dd.isTarget) { oDDs[oDDs.length] = dd; } } } return oDDs; }, /** * 针对某些特定的拖动对象,如果传入的dd目标是合法的目标,返回ture。 * @method isLegalTarget * @param {DragDrop} 拖动对象 * @param {DragDrop} 目标 * @return {boolean} true 表示为目标是dd对象合法 * @static */ isLegalTarget: function (oDD, oTargetDD) { var targets = this.getRelated(oDD, true); for (var i=0, len=targets.length;i<len;++i) { if (targets[i].id == oTargetDD.id) { return true; } } return false; }, /** * My goal is to be able to transparently determine if an object is * typeof DragDrop, and the exact subclass of DragDrop. typeof * returns "object", oDD.constructor.toString() always returns * "DragDrop" and not the name of the subclass. So for now it just * evaluates a well-known variable in DragDrop. * @method isTypeOfDD * @param {Object} 要计算的对象 * @return {boolean} true 表示为typeof oDD = DragDrop * @static */ isTypeOfDD: function (oDD) { return (oDD && oDD.__ygDragDrop); }, /** * 指定拖放对象,检测给出的元素是否属于已登记的拖放处理中的一员。 * @method isHandle * @param {String} id 要检测的对象 * @return {boolean} True表示为元素是拖放的处理 * @static */ isHandle: function(sDDId, sHandleId) { return ( this.handleIds[sDDId] && this.handleIds[sDDId][sHandleId] ); }, /** * 指定一个id,返回该id的拖放实例。 * @method getDDById * @param {String} id 拖放对象的id * @return {DragDrop} 拖放对象,null表示为找不到 * @static */ getDDById: function(id) { for (var i in this.ids) { if (this.ids[i][id]) { return this.ids[i][id]; } } return null; }, /** * 在一个已登记的拖放对象上发生mousedown事件之后触发。 * @method handleMouseDown * @param {Event} e 事件 * @param oDD 被拖动的拖放对象 * @private * @static */ handleMouseDown: function(e, oDD) { if(Ext.QuickTips){ Ext.QuickTips.disable(); } this.currentTarget = e.getTarget(); this.dragCurrent = oDD; var el = oDD.getEl(); // track start position this.startX = e.getPageX(); this.startY = e.getPageY(); this.deltaX = this.startX - el.offsetLeft; this.deltaY = this.startY - el.offsetTop; this.dragThreshMet = false; this.clickTimeout = setTimeout( function() { var DDM = Ext.dd.DDM; DDM.startDrag(DDM.startX, DDM.startY); }, this.clickTimeThresh ); }, /** * 当拖动象素开始启动或mousedown保持事件正好发生的时候发生。 * @method startDrag * @param x {int} 原始mousedown发生的X位置 * @param y {int} 原始mousedown发生的Y位置 * @static */ startDrag: function(x, y) { clearTimeout(this.clickTimeout); if (this.dragCurrent) { this.dragCurrent.b4StartDrag(x, y); this.dragCurrent.startDrag(x, y); } this.dragThreshMet = true; }, /** * 处理MouseUp事件的内置函数,会涉及文档的上下文内容。 * @method handleMouseUp * @param {Event} e 事件 * @private * @static */ handleMouseUp: function(e) { if(Ext.QuickTips){ Ext.QuickTips.enable(); } if (! this.dragCurrent) { return; } clearTimeout(this.clickTimeout); if (this.dragThreshMet) { this.fireEvents(e, true); } else { } this.stopDrag(e); this.stopEvent(e); }, /** * 如果停止事件值和默认(event propagation)的一项被打开,要执行的实用函数。 * @method stopEvent * @param {Event} e 由this.getEvent()返回的事件 * @static */ stopEvent: function(e){ if(this.stopPropagation) { e.stopPropagation(); } if (this.preventDefault) { e.preventDefault(); } }, /** * 内置函数,用于在拖动操作完成后清理事件处理器(event handlers) * @method stopDrag * @param {Event} e 事件 * @private * @static */ stopDrag: function(e) { // Fire the drag end event for the item that was dragged if (this.dragCurrent) { if (this.dragThreshMet) { this.dragCurrent.b4EndDrag(e); this.dragCurrent.endDrag(e); } this.dragCurrent.onMouseUp(e); } this.dragCurrent = null; this.dragOvers = {}; }, /** * 处理mousemove事件的内置函数,会涉及html元素的上下文内容。 * @TODO figure out what we can do about mouse events lost when the * user drags objects beyond the window boundary. Currently we can * detect this in internet explorer by verifying that the mouse is * down during the mousemove event. Firefox doesn't give us the * button state on the mousemove event. * @method handleMouseMove * @param {Event} e 事件 * @private * @static */ handleMouseMove: function(e) { if (! this.dragCurrent) { return true; } // var button = e.which || e.button; // check for IE mouseup outside of page boundary if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) { this.stopEvent(e); return this.handleMouseUp(e); } if (!this.dragThreshMet) { var diffX = Math.abs(this.startX - e.getPageX()); var diffY = Math.abs(this.startY - e.getPageY()); if (diffX > this.clickPixelThresh || diffY > this.clickPixelThresh) { this.startDrag(this.startX, this.startY); } } if (this.dragThreshMet) { this.dragCurrent.b4Drag(e); this.dragCurrent.onDrag(e); if(!this.dragCurrent.moveOnly){ this.fireEvents(e, false); } } this.stopEvent(e); return true; }, /** * 遍历所有的拖放对象找出我们悬浮或落下的那一个。 * @method fireEvents * @param {Event} e 事件 * @param {boolean} isDrop 是drop还是mouseover? * @private * @static */ fireEvents: function(e, isDrop) { var dc = this.dragCurrent; // If the user did the mouse up outside of the window, we could // get here even though we have ended the drag. if (!dc || dc.isLocked()) { return; } var pt = e.getPoint(); // cache the previous dragOver array var oldOvers = []; var outEvts = []; var overEvts = []; var dropEvts = []; var enterEvts = []; // Check to see if the object(s) we were hovering over is no longer // being hovered over so we can fire the onDragOut event for (var i in this.dragOvers) { var ddo = this.dragOvers[i]; if (! this.isTypeOfDD(ddo)) { continue; } if (! this.isOverTarget(pt, ddo, this.mode)) { outEvts.push( ddo ); } oldOvers[i] = true; delete this.dragOvers[i]; } for (var sGroup in dc.groups) { if ("string" != typeof sGroup) { continue; } for (i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (! this.isTypeOfDD(oDD)) { continue; } if (oDD.isTarget && !oDD.isLocked() && oDD != dc) { if (this.isOverTarget(pt, oDD, this.mode)) { // look for drop interactions if (isDrop) { dropEvts.push( oDD ); // look for drag enter and drag over interactions } else { // initial drag over: dragEnter fires if (!oldOvers[oDD.id]) { enterEvts.push( oDD ); // subsequent drag overs: dragOver fires } else { overEvts.push( oDD ); } this.dragOvers[oDD.id] = oDD; } } } } } if (this.mode) { if (outEvts.length) { dc.b4DragOut(e, outEvts); dc.onDragOut(e, outEvts); } if (enterEvts.length) { dc.onDragEnter(e, enterEvts); } if (overEvts.length) { dc.b4DragOver(e, overEvts); dc.onDragOver(e, overEvts); } if (dropEvts.length) { dc.b4DragDrop(e, dropEvts); dc.onDragDrop(e, dropEvts); } } else { // fire dragout events var len = 0; for (i=0, len=outEvts.length; i<len; ++i) { dc.b4DragOut(e, outEvts[i].id); dc.onDragOut(e, outEvts[i].id); } // fire enter events for (i=0,len=enterEvts.length; i<len; ++i) { // dc.b4DragEnter(e, oDD.id); dc.onDragEnter(e, enterEvts[i].id); } // fire over events for (i=0,len=overEvts.length; i<len; ++i) { dc.b4DragOver(e, overEvts[i].id); dc.onDragOver(e, overEvts[i].id); } // fire drop events for (i=0, len=dropEvts.length; i<len; ++i) { dc.b4DragDrop(e, dropEvts[i].id); dc.onDragDrop(e, dropEvts[i].id); } } // notify about a drop that did not find a target if (isDrop && !dropEvts.length) { dc.onInvalidDrop(e); } }, /** * 当INTERSECT模式时,通过拖放事件返回拖放对象的列表。 * 这个辅助函数的作用是在这份列表中获取最适合的配对。 * 有时返回指鼠标下方的第一个对象,有时返回与拖动对象重叠的最大一个对象。 * @method getBestMatch * @param {DragDrop[]} dds 拖放对象之数组 * targeted * @return {DragDrop} 最佳的单个配对 * @static */ getBestMatch: function(dds) { var winner = null; // Return null if the input is not what we expect //if (!dds || !dds.length || dds.length == 0) { // winner = null; // If there is only one item, it wins //} else if (dds.length == 1) { var len = dds.length; if (len == 1) { winner = dds[0]; } else { // Loop through the targeted items for (var i=0; i<len; ++i) { var dd = dds[i]; // If the cursor is over the object, it wins. If the // cursor is over multiple matches, the first one we come // to wins. if (dd.cursorIsOver) { winner = dd; break; // Otherwise the object with the most overlap wins } else { if (!winner || winner.overlap.getArea() < dd.overlap.getArea()) { winner = dd; } } } } return winner; }, /** * 在指定组中,刷新位于左上方和右下角的点的缓存。 * 这是保存在拖放实例中的格式。所以典型的用法是: * <code> * Ext.dd.DragDropMgr.refreshCache(ddinstance.groups); * </code> * 也可这样: * <code> * Ext.dd.DragDropMgr.refreshCache({group1:true, group2:true}); * </code> * @TODO this really should be an indexed array. Alternatively this * method could accept both. * @method refreshCache * @param {Object} groups 要刷新的关联组的数组 * @static */ refreshCache: function(groups) { for (var sGroup in groups) { if ("string" != typeof sGroup) { continue; } for (var i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (this.isTypeOfDD(oDD)) { // if (this.isTypeOfDD(oDD) && oDD.isTarget) { var loc = this.getLocation(oDD); if (loc) { this.locationCache[oDD.id] = loc; } else { delete this.locationCache[oDD.id]; // this will unregister the drag and drop object if // the element is not in a usable state // oDD.unreg(); } } } } }, /** * 检验一个元素是否存在DOM树中,该方法用于innerHTML。 * @method verifyEl * @param {HTMLElement} el 要检测的元素 * @return {boolean} true 表示为元素似乎可用 * @static */ verifyEl: function(el) { if (el) { var parent; if(Ext.isIE){ try{ parent = el.offsetParent; }catch(e){} }else{ parent = el.offsetParent; } if (parent) { return true; } } return false; }, /** * 返回一个区域对象(Region Object)。 * 这个区域包含拖放元素位置、大小、和针对其配置好的内补丁(padding) * @method getLocation * @param {DragDrop} oDD 要获取所在位置的拖放对象 * @return {Ext.lib.Region} 区域对象,包括元素占位,该实例配置的外补丁。 * @static */ getLocation: function(oDD) { if (! this.isTypeOfDD(oDD)) { return null; } var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l; try { pos= Ext.lib.Dom.getXY(el); } catch (e) { } if (!pos) { return null; } x1 = pos[0]; x2 = x1 + el.offsetWidth; y1 = pos[1]; y2 = y1 + el.offsetHeight; t = y1 - oDD.padding[0]; r = x2 + oDD.padding[1]; b = y2 + oDD.padding[2]; l = x1 - oDD.padding[3]; return new Ext.lib.Region( t, r, b, l ); }, /** * 检查鼠标指针是否位于目标的上方。 * @method isOverTarget * @param {Ext.lib.Point} pt 要检测的点 * @param {DragDrop} oTarget 要检测的拖放对象 * @return {boolean} true 表示为鼠标位于目标上方 * @private * @static */ isOverTarget: function(pt, oTarget, intersect) { // use cache if available var loc = this.locationCache[oTarget.id]; if (!loc || !this.useCache) { loc = this.getLocation(oTarget); this.locationCache[oTarget.id] = loc; } if (!loc) { return false; } oTarget.cursorIsOver = loc.contains( pt ); // DragDrop is using this as a sanity check for the initial mousedown // in this case we are done. In POINT mode, if the drag obj has no // contraints, we are also done. Otherwise we need to evaluate the // location of the target as related to the actual location of the // dragged element. var dc = this.dragCurrent; if (!dc || !dc.getTargetCoord || (!intersect && !dc.constrainX && !dc.constrainY)) { return oTarget.cursorIsOver; } oTarget.overlap = null; // Get the current location of the drag element, this is the // location of the mouse event less the delta that represents // where the original mousedown happened on the element. We // need to consider constraints and ticks as well. var pos = dc.getTargetCoord(pt.x, pt.y); var el = dc.getDragEl(); var curRegion = new Ext.lib.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ); var overlap = curRegion.intersect(loc); if (overlap) { oTarget.overlap = overlap; return (intersect) ? true : oTarget.cursorIsOver; } else { return false; } }, /** * 卸下事件处理器。 * @method _onUnload * @private * @static */ _onUnload: function(e, me) { Ext.dd.DragDropMgr.unregAll(); }, /** * 清除拖放事件和对象。 * @method unregAll * @private * @static */ unregAll: function() { if (this.dragCurrent) { this.stopDrag(); this.dragCurrent = null; } this._execOnAll("unreg", []); for (i in this.elementCache) { delete this.elementCache[i]; } this.elementCache = {}; this.ids = {}; }, /** * DOM元素的缓存。 * @property elementCache * @private * @static */ elementCache: {}, /** * 返回DOM元素所指定的包装器。 * @method getElWrapper * @param {String} id 要获取的元素id * @return {Ext.dd.DDM.ElementWrapper} 包装好的元素 * @private * @deprecated 该包装器用途较小 * @static */ getElWrapper: function(id) { var oWrapper = this.elementCache[id]; if (!oWrapper || !oWrapper.el) { oWrapper = this.elementCache[id] = new this.ElementWrapper(Ext.getDom(id)); } return oWrapper; }, /** * 返回实际的DOM元素。 * @method getElement * @param {String} id 要获取的元素的id * @return {Object} 元素 * @deprecated 推荐使用Ext.lib.Ext.getDom * @static */ getElement: function(id) { return Ext.getDom(id); }, /** * 返回该DOM元素的样式属性。 * @method getCss * @param {String} id 要获取元素的id * @return {Object} 元素样式属性 * @deprecated 推荐使用Ext.lib.Dom * @static */ getCss: function(id) { var el = Ext.getDom(id); return (el) ? el.style : null; }, /** * 缓冲元素的内置类 * @class DragDropMgr.ElementWrapper * @for DragDropMgr * @private * @deprecated */ ElementWrapper: function(el) { /** * The element * @property el */ this.el = el || null; /** * The element id * @property id */ this.id = this.el && el.id; /** * A reference to the style property * @property css */ this.css = this.el && el.style; }, /** * 返回html元素的X坐标。 * @method getPosX * @param el 指获取坐标的元素 * @return {int} x坐标 * @for DragDropMgr * @deprecated 推荐使用Ext.lib.Dom.getX * @static */ getPosX: function(el) { return Ext.lib.Dom.getX(el); }, /** * 返回html元素的Y坐标。 * @method getPosY * @param el 指获取坐标的元素 * @return {int} y坐标 * @deprecated 推荐使用Ext.lib.Dom.getY * @static */ getPosY: function(el) { return Ext.lib.Dom.getY(el); }, /** * 调换两个节点,对于IE,我们使用原生的方法。 * @method swapNode * @param n1 要调换的第一个节点 * @param n2 要调换的其他节点 * @static */ swapNode: function(n1, n2) { if (n1.swapNode) { n1.swapNode(n2); } else { var p = n2.parentNode; var s = n2.nextSibling; if (s == n1) { p.insertBefore(n1, n2); } else if (n2 == n1.nextSibling) { p.insertBefore(n2, n1); } else { n1.parentNode.replaceChild(n2, n1); p.insertBefore(n1, s); } } }, /** * 返回当前滚动位置。 * @method getScroll * @private * @static */ getScroll: function () { var t, l, dde=document.documentElement, db=document.body; if (dde && (dde.scrollTop || dde.scrollLeft)) { t = dde.scrollTop; l = dde.scrollLeft; } else if (db) { t = db.scrollTop; l = db.scrollLeft; } else { } return { top: t, left: l }; }, /** * 指定一个元素,返回其样式的某个属性。 * @method getStyle * @param {HTMLElement} el 元素 * @param {string} styleProp 样式名称 * @return {string} 样式值 * @deprecated use Ext.lib.Dom.getStyle * @static */ getStyle: function(el, styleProp) { return Ext.fly(el).getStyle(styleProp); }, /** * 获取scrollTop * @method getScrollTop * @return {int} 文档的scrollTop * @static */ getScrollTop: function () { return this.getScroll().top; }, /** * 获取scrollLeft * @method getScrollLeft * @return {int} 文档的scrollTop * @static */ getScrollLeft: function () { return this.getScroll().left; }, /** * 根据目标元素的位置,设置元素的X/Y位置。 * @method moveToEl * @param {HTMLElement} moveEl 要移动的元素 * @param {HTMLElement} targetEl 引用元素的位置 * @static */ moveToEl: function (moveEl, targetEl) { var aCoord = Ext.lib.Dom.getXY(targetEl); Ext.lib.Dom.setXY(moveEl, aCoord); }, /** * 数组排列函数 * @method numericSort * @static */ numericSort: function(a, b) { return (a - b); }, /** * 局部计算器 * @property _timeoutCount * @private * @static */ _timeoutCount: 0, /** * 试着押后加载,这样便不会在Event Utility文件加载之前出现的错误。 * @method _addListeners * @private * @static */ _addListeners: function() { var DDM = Ext.dd.DDM; if ( Ext.lib.Event && document ) { DDM._onLoad(); } else { if (DDM._timeoutCount > 2000) { } else { setTimeout(DDM._addListeners, 10); if (document && document.body) { DDM._timeoutCount += 1; } } } }, /** * 递归搜索最靠近的父、子元素,以便确定处理的元素是否被单击。 * @method handleWasClicked * @param node 要检测的html元素 * @static */ handleWasClicked: function(node, id) { if (this.isHandle(id, node.id)) { return true; } else { // check to see if this is a text node child of the one we want var p = node.parentNode; while (p) { if (this.isHandle(id, p.id)) { return true; } else { p = p.parentNode; } } } return false; } }; }(); // shorter alias, save a few bytes Ext.dd.DDM = Ext.dd.DragDropMgr; Ext.dd.DDM._addListeners(); } /** * @class Ext.dd.DD * 在拖动过程中随伴鼠标指针关联元素的一个播放实现。 * @extends Ext.dd.DragDrop * @constructor * @param {String} id 关联元素的id * @param {String} sGroup 关联拖放项的组 * @param {object} config 包含DD的有效配置属性: * scroll */ Ext.dd.DD = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, { /** * 设置为true时,游览器窗口会自动滚动,如果拖放元素被拖到视图的边界,默认为true。 * @property scroll * @type boolean */ scroll: true, /** * 在关联元素的左上角和元素点击所在位置之间设置一个指针偏移的距离。 * @method autoOffset * @param {int} iPageX 点击的X坐标 * @param {int} iPageY 点击的Y坐标 */ autoOffset: function(iPageX, iPageY) { var x = iPageX - this.startPageX; var y = iPageY - this.startPageY; this.setDelta(x, y); }, /** * 设置指针偏移,你可以直接调用以强制偏移到新特殊的位置(像传入0,0,即设置成为对象的一角)。 * @method setDelta * @param {int} iDeltaX 从左边算起的距离 * @param {int} iDeltaY 从上面算起的距离 */ setDelta: function(iDeltaX, iDeltaY) { this.deltaX = iDeltaX; this.deltaY = iDeltaY; }, /** * 设置拖动元素到mousedown或点击事件的位置继续保持指针相关联元素点击的位置。 * 如果打算将元素放到某个位置而非指针位置,你可重写该方法。 * @method setDragElPos * @param {int} iPageX mousedown或拖动事件的X坐标 * @param {int} iPageY mousedown或拖动事件的Y坐标 */ setDragElPos: function(iPageX, iPageY) { // the first time we do this, we are going to check to make sure // the element has css positioning var el = this.getDragEl(); this.alignElWithMouse(el, iPageX, iPageY); }, /** * 设置元素到mousedown或点击事件的位置继续保持指针相关联元素点击的位置。 * 如果打算将元素放到某个位置而非指针位置,你可重写该方法。 * @method alignElWithMouse * @param {HTMLElement} el the element to move * @param {int} iPageX mousedown或拖动事件的X坐标 * @param {int} iPageY mousedown或拖动事件的Y坐标 */ alignElWithMouse: function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); var fly = el.dom ? el : Ext.fly(el); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; fly.setXY(aCoord); var newLeft = fly.getLeft(true); var newTop = fly.getTop(true); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]); } this.cachePosition(oCoord.x, oCoord.y); this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); return oCoord; }, /** * 保存最近的位置,以便我们重量限制和所需要的点击标记。 * 我们需要清楚这些以便计算元素偏移原来位置的像素值。 * @method cachePosition * @param iPageX 当前X位置(可选的),只要为了以后不用再查询 * @param iPageY 当前Y位置(可选的),只要为了以后不用再查询 */ cachePosition: function(iPageX, iPageY) { if (iPageX) { this.lastPageX = iPageX; this.lastPageY = iPageY; } else { var aCoord = Ext.lib.Dom.getXY(this.getEl()); this.lastPageX = aCoord[0]; this.lastPageY = aCoord[1]; } }, /** * 如果拖动对象移动到可视窗口之外的区域,就自动滚动window。 * @method autoScroll * @param {int} x 拖动元素X坐标 * @param {int} y 拖动元素Y坐标 * @param {int} h 拖动元素的高度 * @param {int} w 拖动元素的宽度 * @private */ autoScroll: function(x, y, h, w) { if (this.scroll) { // The client height var clientH = Ext.lib.Dom.getViewWidth(); // The client width var clientW = Ext.lib.Dom.getViewHeight(); // The amt scrolled down var st = this.DDM.getScrollTop(); // The amt scrolled right var sl = this.DDM.getScrollLeft(); // Location of the bottom of the element var bot = h + y; // Location of the right of the element var right = w + x; // The distance from the cursor to the bottom of the visible area, // adjusted so that we don't scroll if the cursor is beyond the // element drag constraints var toBot = (clientH + st - y - this.deltaY); // The distance from the cursor to the right of the visible area var toRight = (clientW + sl - x - this.deltaX); // How close to the edge the cursor must be before we scroll // var thresh = (document.all) ? 100 : 40; var thresh = 40; // How many pixels to scroll per autoscroll op. This helps to reduce // clunky scrolling. IE is more sensitive about this ... it needs this // value to be higher. var scrAmt = (document.all) ? 80 : 30; // Scroll down if we are near the bottom of the visible page and the // obj extends below the crease if ( bot > clientH && toBot < thresh ) { window.scrollTo(sl, st + scrAmt); } // Scroll up if the window is scrolled down and the top of the object // goes above the top border if ( y < st && st > 0 && y - st < thresh ) { window.scrollTo(sl, st - scrAmt); } // Scroll right if the obj is beyond the right border and the cursor is // near the border. if ( right > clientW && toRight < thresh ) { window.scrollTo(sl + scrAmt, st); } // Scroll left if the window has been scrolled to the right and the obj // extends past the left border if ( x < sl && sl > 0 && x - sl < thresh ) { window.scrollTo(sl - scrAmt, st); } } }, /** * 找到元素应该放下的位置。 * @method getTargetCoord * @param {int} iPageX 点击的X坐标 * @param {int} iPageY 点击的Y坐标 * @return 包含坐标的对象(Object.x和Object.y) * @private */ getTargetCoord: function(iPageX, iPageY) { var x = iPageX - this.deltaX; var y = iPageY - this.deltaY; if (this.constrainX) { if (x < this.minX) { x = this.minX; } if (x > this.maxX) { x = this.maxX; } } if (this.constrainY) { if (y < this.minY) { y = this.minY; } if (y > this.maxY) { y = this.maxY; } } x = this.getTick(x, this.xTicks); y = this.getTick(y, this.yTicks); return {x:x, y:y}; }, /* * 为该类配置指定的选项,这样重写Ext.dd.DragDrop,注意该方法的所有版本都会被调用。 */ applyConfig: function() { Ext.dd.DD.superclass.applyConfig.call(this); this.scroll = (this.config.scroll !== false); }, /* * 触发优先的onMouseDown事件。 * 重写Ext.dd.DragDrop. */ b4MouseDown: function(e) { // this.resetConstraints(); this.autoOffset(e.getPageX(), e.getPageY()); }, /* * 触发优先的onDrag事件。 * 重写Ext.dd.DragDrop. */ b4Drag: function(e) { this.setDragElPos(e.getPageX(), e.getPageY()); }, toString: function() { return ("DD " + this.id); } ////////////////////////////////////////////////////////////////////////// // Debugging ygDragDrop events that can be overridden ////////////////////////////////////////////////////////////////////////// /* startDrag: function(x, y) { }, onDrag: function(e) { }, onDragEnter: function(e, id) { }, onDragOver: function(e, id) { }, onDragOut: function(e, id) { }, onDragDrop: function(e, id) { }, endDrag: function(e) { } */ }); /** * @class Ext.dd.DDProxy * 一种拖放的实现,把一个空白的、带边框的div插入到文档,并会伴随着鼠标指针移动。 * 当点击那一下发生,边框div会调整大小到关联html元素的尺寸大小,然后移动到关联元素的位置。 * “边框”元素的引用指的是页面上我们创建能够被DDProxy元素拖动到的地方的单个代理元素。 * @extends Ext.dd.DD * @constructor * @param {String} id 关联html元素之id * @param {String} sGroup 相关拖放对象的组 * @param {object} config 配置项对象属性 * DDProxy可用的属性有: * resizeFrame, centerFrame, dragElId */ Ext.dd.DDProxy = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); this.initFrame(); } }; /** * 默认的拖动框架div之id * @property Ext.dd.DDProxy.dragElId * @type String * @static */ Ext.dd.DDProxy.dragElId = "ygddfdiv"; Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, { /** * 默认下,我们将实际拖动元素调整大小到与打算拖动的那个元素的大小一致(这就是加边框的效果)。 * 但如果我们想实现另外一种效果可关闭选项。 * @property resizeFrame * @type boolean */ resizeFrame: true, /** * 默认下,frame是正好处于拖动元素的位置。 * 因此我们可使Ext.dd.DD来偏移指针。 * 另外一个方法就是,你没有让做任何限制在对象上,然后设置center Frame为true。 * @property centerFrame * @type boolean */ centerFrame: false, /** * 如果代理元素仍然不存在,就创建一个。 * @method createFrame */ createFrame: function() { var self = this; var body = document.body; if (!body || !body.firstChild) { setTimeout( function() { self.createFrame(); }, 50 ); return; } var div = this.getDragEl(); if (!div) { div = document.createElement("div"); div.id = this.dragElId; var s = div.style; s.position = "absolute"; s.visibility = "hidden"; s.cursor = "move"; s.border = "2px solid #aaa"; s.zIndex = 999; // appendChild can blow up IE if invoked prior to the window load event // while rendering a table. It is possible there are other scenarios // that would cause this to happen as well. body.insertBefore(div, body.firstChild); } }, /** * 拖动框架元素的初始化,必须在子类的构造器里调用。 * @method initFrame */ initFrame: function() { this.createFrame(); }, applyConfig: function() { Ext.dd.DDProxy.superclass.applyConfig.call(this); this.resizeFrame = (this.config.resizeFrame !== false); this.centerFrame = (this.config.centerFrame); this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId); }, /** * 调查拖动frame的大小到点击对象的尺寸大小、位置,最后显示它。 * @method showFrame * @param {int} iPageX 点击X位置 * @param {int} iPageY 点击Y位置 * @private */ showFrame: function(iPageX, iPageY) { var el = this.getEl(); var dragEl = this.getDragEl(); var s = dragEl.style; this._resizeProxy(); if (this.centerFrame) { this.setDelta( Math.round(parseInt(s.width, 10)/2), Math.round(parseInt(s.height, 10)/2) ); } this.setDragElPos(iPageX, iPageY); Ext.fly(dragEl).show(); }, /** * 拖动开始时,代理与关联元素自适应尺寸,除非resizeFrame设为false。 * @method _resizeProxy * @private */ _resizeProxy: function() { if (this.resizeFrame) { var el = this.getEl(); Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight); } }, // overrides Ext.dd.DragDrop b4MouseDown: function(e) { var x = e.getPageX(); var y = e.getPageY(); this.autoOffset(x, y); this.setDragElPos(x, y); }, // overrides Ext.dd.DragDrop b4StartDrag: function(x, y) { // show the drag frame this.showFrame(x, y); }, // overrides Ext.dd.DragDrop b4EndDrag: function(e) { Ext.fly(this.getDragEl()).hide(); }, // overrides Ext.dd.DragDrop // By default we try to move the element to the last location of the frame. // This is so that the default behavior mirrors that of Ext.dd.DD. endDrag: function(e) { var lel = this.getEl(); var del = this.getDragEl(); // Show the drag frame briefly so we can get its position del.style.visibility = ""; this.beforeMove(); // Hide the linked element before the move to get around a Safari // rendering bug. lel.style.visibility = "hidden"; Ext.dd.DDM.moveToEl(lel, del); del.style.visibility = "hidden"; lel.style.visibility = ""; this.afterDrag(); }, beforeMove : function(){ }, afterDrag : function(){ }, toString: function() { return ("DDProxy " + this.id); } }); /** * @class Ext.dd.DDTarget * 一种拖放的实现,不能移动,但可以置下目标,对于事件回调,省略一些简单的实现也可得到相同的结果。 * 但这样降低了event listener和回调的处理成本。 * @extends Ext.dd.DragDrop * @constructor * @param {String} id 置下目标的那个元素的id * @param {String} sGroup 相关拖放对象的组 * @param {object} config 包括配置属性的对象 * 可用的DDTarget属性有DragDrop: * none */ Ext.dd.DDTarget = function(id, sGroup, config) { if (id) { this.initTarget(id, sGroup, config); } }; // Ext.dd.DDTarget.prototype = new Ext.dd.DragDrop(); Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, { toString: function() { return ("DDTarget " + this.id); } });
JavaScript
/** * @class Ext.dd.DragSource * @extends Ext.dd.DDProxy * 一个简单的基础类,该实现使得任何元素变成为拖动,以便让拖动的元素放到其身上。 * @constructor * @param {Mixed} el 容器元素 * @param {Object} config */ Ext.dd.DragSource = function(el, config){ this.el = Ext.get(el); if(!this.dragData){ this.dragData = {}; } Ext.apply(this, config); if(!this.proxy){ this.proxy = new Ext.dd.StatusProxy(); } Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group, {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true}); this.dragging = false; }; Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, { /** * @cfg {String} dropAllowed * 当落下被允许的时候返回到拖动源的样式(默认为"x-dd-drop-ok")。 */ dropAllowed : "x-dd-drop-ok", /** * @cfg {String} dropNotAllowed * 当落下不允许的时候返回到拖动源的样式(默认为"x-dd-drop-nodrop")。 */ dropNotAllowed : "x-dd-drop-nodrop", /** * 返回与拖动源关联的数据对象 * @return {Object} data 包含自定义数据的对象 */ getDragData : function(e){ return this.dragData; }, // private onDragEnter : function(e, id){ var target = Ext.dd.DragDropMgr.getDDById(id); this.cachedTarget = target; if(this.beforeDragEnter(target, e, id) !== false){ if(target.isNotifyTarget){ var status = target.notifyEnter(this, e, this.dragData); this.proxy.setStatus(status); }else{ this.proxy.setStatus(this.dropAllowed); } if(this.afterDragEnter){ /** * 默认为一空函数,但你可提供一个自定义动作的实现,这个实现在拖动条目进入落下目标的时候。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @method afterDragEnter */ this.afterDragEnter(target, e, id); } } }, /** * 默认是一个空函数,在拖动项进入落下目标时,你应该提供一个自定义的动作。 * 该动作可被取消onDragEnter。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消 */ beforeDragEnter : function(target, e, id){ return true; }, // private alignElWithMouse: function() { Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments); this.proxy.sync(); }, // private onDragOver : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragOver(target, e, id) !== false){ if(target.isNotifyTarget){ var status = target.notifyOver(this, e, this.dragData); this.proxy.setStatus(status); } if(this.afterDragOver){ /** * 默认是一个空函数,在拖动项位于落下目标上方时(由实现促成的),你应该提供一个自定义的动作。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @method afterDragOver */ this.afterDragOver(target, e, id); } } }, /** * 默认是一个空函数,在拖动项位于落下目标上方时,你应该提供一个自定义的动作。 * 该动作可被取消。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消 */ beforeDragOver : function(target, e, id){ return true; }, // private onDragOut : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragOut(target, e, id) !== false){ if(target.isNotifyTarget){ target.notifyOut(this, e, this.dragData); } this.proxy.reset(); if(this.afterDragOut){ /** * 默认是一个空函数,在拖动项离开目标而没有落下之前,你应该提供一个自定义的动作。 * 该动作可被取消。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @method afterDragOut */ this.afterDragOut(target, e, id); } } this.cachedTarget = null; }, /** * 默认是一个空函数,在拖动项离开目标而没有落下之前,你应该提供一个自定义的动作。 * 该动作可被取消。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消 */ beforeDragOut : function(target, e, id){ return true; }, // private onDragDrop : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragDrop(target, e, id) !== false){ if(target.isNotifyTarget){ if(target.notifyDrop(this, e, this.dragData)){ // valid drop? this.onValidDrop(target, e, id); }else{ this.onInvalidDrop(target, e, id); } }else{ this.onValidDrop(target, e, id); } if(this.afterDragDrop){ /** * 默认是一个空函数,在由实现促成的有效拖放发生之后,你应该提供一个自定义的动作。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 落下元素的id * @method afterDragDrop */ this.afterDragDrop(target, e, id); } } }, /** * 默认是一个空函数,在拖动项被放下到目标之前,你应该提供一个自定义的动作。 * 该动作可被取消。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 被拖动元素之id * @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消 */ beforeDragDrop : function(target, e, id){ return true; }, // private onValidDrop : function(target, e, id){ this.hideProxy(); if(this.afterValidDrop){ /** * 默认是一个空函数,在由实现促成的有效落下发生之后,你应该提供一个自定义的动作。 * @param {Object} target DD目标 * @param {Event} e 事件对象 * @param {String} id 落下元素的id * @method afterInvalidDrop */ this.afterValidDrop(target, e, id); } }, // private getRepairXY : function(e, data){ return this.el.getXY(); }, // private onInvalidDrop : function(target, e, id){ this.beforeInvalidDrop(target, e, id); if(this.cachedTarget){ if(this.cachedTarget.isNotifyTarget){ this.cachedTarget.notifyOut(this, e, this.dragData); } this.cacheTarget = null; } this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this); if(this.afterInvalidDrop){ /** * 默认是一个空函数,在由实现促成的无效落下发生之后,你应该提供一个自定义的动作。 * @param {Event} e 事件对象 * @param {String} id 落下元素的id * @method afterInvalidDrop */ this.afterInvalidDrop(e, id); } }, // private afterRepair : function(){ if(Ext.enableFx){ this.el.highlight(this.hlColor || "c3daf9"); } this.dragging = false; }, /** * 默认是一个空函数,在一次无效的落下发生之后,你应该提供一个自定义的动作。 * @param {Ext.dd.DragDrop} target 落下目标 * @param {Event} e 事件对象 * @param {String} id 拖动元素的id * @return {Boolean} isValid true的话说明拖动事件是有效的,false代表取消 */ beforeInvalidDrop : function(target, e, id){ return true; }, // private handleMouseDown : function(e){ if(this.dragging) { return; } var data = this.getDragData(e); if(data && this.onBeforeDrag(data, e) !== false){ this.dragData = data; this.proxy.stop(); Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments); } }, /** * 默认是一个空函数,在初始化拖动事件之前,你应该提供一个自定义的动作。 * 该动作可被取消。 * @param {Object} data 与落下目标共享的自定义数据对象 * @param {Event} e 事件对象 * @return {Boolean} isValid True的话拖动事件有效,否则false取消 */ onBeforeDrag : function(data, e){ return true; }, /** * 默认是一个空函数,一旦拖动事件开始,你应该提供一个自定义的动作。 * 不能在该函数中取消拖动。 * @param {Number} x 在拖动对象身上单击点的x值 * @param {Number} y 在拖动对象身上单击点的y值 */ onStartDrag : Ext.emptyFn, // private - YUI override startDrag : function(x, y){ this.proxy.reset(); this.dragging = true; this.proxy.update(""); this.onInitDrag(x, y); this.proxy.show(); }, // private onInitDrag : function(x, y){ var clone = this.el.dom.cloneNode(true); clone.id = Ext.id(); // prevent duplicate ids this.proxy.update(clone); this.onStartDrag(x, y); return true; }, /** * 返回拖动源所在的{@link Ext.dd.StatusProxy} * @return {Ext.dd.StatusProxy} proxy StatusProxy对象 */ getProxy : function(){ return this.proxy; }, /** * 隐藏拖动源的{@link Ext.dd.StatusProxy} */ hideProxy : function(){ this.proxy.hide(); this.proxy.reset(true); this.dragging = false; }, // private triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); }, // private - override to prevent hiding b4EndDrag: function(e) { }, // private - override to prevent moving endDrag : function(e){ this.onEndDrag(this.dragData, e); }, // private onEndDrag : function(data, e){ }, // private - pin to cursor autoOffset : function(x, y) { this.setDelta(-12, -20); } });
JavaScript
/** * @class Ext.dd.ScrollManager * 执行拖动操作时,自动在页面溢出的区域滚动 * <b>注:该类使用的是”Point模式”,而"Interest模式"未经测试。</b> * @singleton */ Ext.dd.ScrollManager = function(){ var ddm = Ext.dd.DragDropMgr; var els = {}; var dragEl = null; var proc = {}; var onStop = function(e){ dragEl = null; clearProc(); }; var triggerRefresh = function(){ if(ddm.dragCurrent){ ddm.refreshCache(ddm.dragCurrent.groups); } }; var doScroll = function(){ if(ddm.dragCurrent){ var dds = Ext.dd.ScrollManager; var inc = proc.el.ddScrollConfig ? proc.el.ddScrollConfig.increment : dds.increment; if(!dds.animate){ if(proc.el.scroll(proc.dir, inc)){ triggerRefresh(); } }else{ proc.el.scroll(proc.dir, inc, true, dds.animDuration, triggerRefresh); } } }; var clearProc = function(){ if(proc.id){ clearInterval(proc.id); } proc.id = 0; proc.el = null; proc.dir = ""; }; var startProc = function(el, dir){ clearProc(); proc.el = el; proc.dir = dir; proc.id = setInterval(doScroll, Ext.dd.ScrollManager.frequency); }; var onFire = function(e, isDrop){ if(isDrop || !ddm.dragCurrent){ return; } var dds = Ext.dd.ScrollManager; if(!dragEl || dragEl != ddm.dragCurrent){ dragEl = ddm.dragCurrent; // refresh regions on drag start dds.refreshCache(); } var xy = Ext.lib.Event.getXY(e); var pt = new Ext.lib.Point(xy[0], xy[1]); for(var id in els){ var el = els[id], r = el._region; var c = el.ddScrollConfig ? el.ddScrollConfig : dds; if(r && r.contains(pt) && el.isScrollable()){ if(r.bottom - pt.y <= c.vthresh){ if(proc.el != el){ startProc(el, "down"); } return; }else if(r.right - pt.x <= c.hthresh){ if(proc.el != el){ startProc(el, "left"); } return; }else if(pt.y - r.top <= c.vthresh){ if(proc.el != el){ startProc(el, "up"); } return; }else if(pt.x - r.left <= c.hthresh){ if(proc.el != el){ startProc(el, "right"); } return; } } } clearProc(); }; ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm); ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm); return { /** * 登记新溢出元素,以准备自动滚动 * @param {Mixed} el 要被滚动的元素id或是数组 */ register : function(el){ if(el instanceof Array){ for(var i = 0, len = el.length; i < len; i++) { this.register(el[i]); } }else{ el = Ext.get(el); els[el.id] = el; } }, /** * 注销溢出元素,不可再被滚动 * @param {Mixed} el 要被滚动的元素id或是数组 */ unregister : function(el){ if(el instanceof Array){ for(var i = 0, len = el.length; i < len; i++) { this.unregister(el[i]); } }else{ el = Ext.get(el); delete els[el.id]; } }, /** * 需要指针翻转滚动的容器顶部或底部边缘的像素(默认为25) * @type Number */ vthresh : 25, /** * 需要指针翻转滚动的容器左边或右边边缘的像素(默认为25) * @type Number */ hthresh : 25, /** * 每次滚动的幅度,单位:像素(默认为50) * @type Number */ increment : 100, /** * 滚动的频率,单位:毫秒(默认为500) * @type Number */ frequency : 500, /** * 是否有动画效果(默认为true) * @type Boolean */ animate: true, /** * 动画持续时间,单位:秒 * 改值勿少于Ext.dd.ScrollManager.frequency!(默认为.4) * @type Number */ animDuration: .4, /** * 手动切换刷新缓冲。 */ refreshCache : function(){ for(var id in els){ if(typeof els[id] == 'object'){ // for people extending the object prototype els[id]._region = els[id].getRegion(); } } } }; }();
JavaScript
/* * Ext JS Library 1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * licensing@extjs.com * * http://www.extjs.com/license */ /** * @class Ext.dd.StatusProxy * 一个特殊的拖动代理,可支持落下状态时的图标,{@link Ext.Layer} 样式和自动修复。 * Ext.dd components缺省下使用这个代理 * @constructor * @param {Object} config */ Ext.dd.StatusProxy = function(config){ Ext.apply(this, config); this.id = this.id || Ext.id(); this.el = new Ext.Layer({ dh: { id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [ {tag: "div", cls: "x-dd-drop-icon"}, {tag: "div", cls: "x-dd-drag-ghost"} ] }, shadow: !config || config.shadow !== false }); this.ghost = Ext.get(this.el.dom.childNodes[1]); this.dropStatus = this.dropNotAllowed; }; Ext.dd.StatusProxy.prototype = { /** * @cfg {String} dropAllowed * 当拖动源到达落下目标上方时的CSS样式类 */ dropAllowed : "x-dd-drop-ok", /** * @cfg {String} dropNotAllowed * 当不可以被落下时拖动源的样式(默认为"x-dd-drop-nodrop")。 */ dropNotAllowed : "x-dd-drop-nodrop", /** * 更新代理的可见元素,用来指明在当前元素上可否落下的状态。 * @param {String} cssClass 对指示器图象的新CSS样式 */ setStatus : function(cssClass){ cssClass = cssClass || this.dropNotAllowed; if(this.dropStatus != cssClass){ this.el.replaceClass(this.dropStatus, cssClass); this.dropStatus = cssClass; } }, /** * 对默认dropNotAllowed值的状态提示器进行复位 * @param {Boolean} clearGhost true的话移除所有ghost的内容,false的话保留 */ reset : function(clearGhost){ this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed; this.dropStatus = this.dropNotAllowed; if(clearGhost){ this.ghost.update(""); } }, /** * 更新ghost元素的内容 * @param {String} html 替换当前ghost元素的innerHTML的那个html */ update : function(html){ if(typeof html == "string"){ this.ghost.update(html); }else{ this.ghost.update(""); html.style.margin = "0"; this.ghost.dom.appendChild(html); } }, /** * 返回所在的代理{@link Ext.Layer} * @return {Ext.Layer} el */ getEl : function(){ return this.el; }, /** * 返回ghost元素 * @return {Ext.Element} el */ getGhost : function(){ return this.ghost; }, /** * 隐藏代理 * @param {Boolean} clear True的话复位状态和清除ghost内容,false的话就保留 */ hide : function(clear){ this.el.hide(); if(clear){ this.reset(true); } }, /** * 如果运行中就停止修复动画 */ stop : function(){ if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){ this.anim.stop(); } }, /** * 显示代理 */ show : function(){ this.el.show(); }, /** * 迫使层同步阴影和闪烁元素的位置 */ sync : function(){ this.el.sync(); }, /** * 通过动画让代理返回到原来位置。 * 应由拖动项在完成一次无效的落下动作之后调用. * @param {Array} xy 元素的XY位置([x, y]) * @param {Function} callback 完成修复之后的回调函数 * @param {Object} scope 执行回调函数的作用域 */ repair : function(xy, callback, scope){ this.callback = callback; this.scope = scope; if(xy && this.animRepair !== false){ this.el.addClass("x-dd-drag-repair"); this.el.hideUnders(true); this.anim = this.el.shift({ duration: this.repairDuration || .5, easing: 'easeOut', xy: xy, stopFx: true, callback: this.afterRepair, scope: this }); }else{ this.afterRepair(); } }, // private afterRepair : function(){ this.hide(true); if(typeof this.callback == "function"){ this.callback.call(this.scope || this); } this.callback = null; this.scope = null; } };
JavaScript
/** * @class Ext.dd.DropTarget * @extends Ext.dd.DDTarget. * 一个简单的基础类,该实现使得任何元素变成为可落下的目标,以便让拖动的元素放到其身上。 * 落下(drop)过程没有特别效果,除非提供了notifyDrop的实现 * @constructor * @param {Mixed} el 容器元素 * @param {Object} config */ Ext.dd.DropTarget = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.el); } Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group, {isTarget: true}); }; Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, { /** * @cfg {String} overClass * 当拖动源到达落下目标上方时的CSS class */ /** * @cfg {String} dropAllowed * 当可以被落下时拖动源的样式(默认为"x-dd-drop-ok")。 */ dropAllowed : "x-dd-drop-ok", /** * @cfg {String} dropNotAllowed * 当不可以被落下时拖动源的样式(默认为"x-dd-drop-nodrop")。 */ dropNotAllowed : "x-dd-drop-nodrop", // private isTarget : true, // private isNotifyTarget : true, /** * 当源{@link Ext.dd.DragSource}进入到目标的范围内,它执行通知落下目标的那个函数。 * 默认的实现是,如存在overClass(或其它)的样式,将其加入到落下元素(drop element),并返回dropAllowed配置的值。 * 如需对落下验证(drop validation)的话可重写该方法。 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。 */ notifyEnter : function(dd, e, data){ if(this.overClass){ this.el.addClass(this.overClass); } return this.dropAllowed; }, /** * 当源{@link Ext.dd.DragSource}进入到目标的范围内,每一下移动鼠标,它不断执行通知落下目标的那个函数。 * 默认的实现是返回dropAllowed配置值而已 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。 */ notifyOver : function(dd, e, data){ return this.dropAllowed; }, /**. * 当源{@link Ext.dd.DragSource}移出落下目标的范围后,它执行通知落下目标的那个函数。 * 默认的实现仅是移除由overClass(或其它)指定的CSS class。 * @param {Ext.dd.DragSource} dd 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 */ notifyOut : function(dd, e, data){ if(this.overClass){ this.el.removeClass(this.overClass); } }, /** * 当源{@link Ext.dd.DragSource}在落下目标身上完成落下动作后,它执行通知落下目标的那个函数。 * 该方法没有默认的实现并返回false,所以你必须提供处理落下事件的实现并返回true,才能修复拖动源没有运行的动作。 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {Boolean} True 有效的落下返回true否则为false */ notifyDrop : function(dd, e, data){ return false; } });
JavaScript
Ext.dd.DragTracker = function(config){ Ext.apply(this, config); this.addEvents( 'mousedown', 'mouseup', 'mousemove', 'dragstart', 'dragend', 'drag' ); this.dragRegion = new Ext.lib.Region(0,0,0,0); if(this.el){ this.initEl(this.el); } } Ext.extend(Ext.dd.DragTracker, Ext.util.Observable, { active: false, tolerance: 5, autoStart: false, initEl: function(el){ this.el = Ext.get(el); el.on('mousedown', this.onMouseDown, this, this.delegate ? {delegate: this.delegate} : undefined); }, destroy : function(){ this.el.un('mousedown', this.onMouseDown, this); }, onMouseDown: function(e, target){ if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){ this.startXY = this.lastXY = e.getXY(); this.dragTarget = this.delegate ? target : this.el.dom; e.preventDefault(); var doc = Ext.getDoc(); doc.on('mouseup', this.onMouseUp, this); doc.on('mousemove', this.onMouseMove, this); doc.on('selectstart', this.stopSelect, this); if(this.autoStart){ this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this); } } }, onMouseMove: function(e, target){ e.preventDefault(); var xy = e.getXY(), s = this.startXY; this.lastXY = xy; if(!this.active){ if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){ this.triggerStart(); }else{ return; } } this.fireEvent('mousemove', this, e); this.onDrag(e); this.fireEvent('drag', this, e); }, onMouseUp: function(e){ var doc = Ext.getDoc(); doc.un('mousemove', this.onMouseMove, this); doc.un('mouseup', this.onMouseUp, this); doc.un('selectstart', this.stopSelect, this); e.preventDefault(); this.clearStart(); this.active = false; delete this.elRegion; this.fireEvent('mouseup', this, e); this.onEnd(e); this.fireEvent('dragend', this, e); }, triggerStart: function(isTimer){ this.clearStart(); this.active = true; this.onStart(this.startXY); this.fireEvent('dragstart', this, this.startXY); }, clearStart : function(){ if(this.timer){ clearTimeout(this.timer); delete this.timer; } }, stopSelect : function(e){ e.stopEvent(); return false; }, onBeforeStart : function(e){ }, onStart : function(xy){ }, onDrag : function(e){ }, onEnd : function(e){ }, getDragTarget : function(){ return this.dragTarget; }, getDragCt : function(){ return this.el; }, getXY : function(constrain){ return constrain ? this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY; }, getOffset : function(constrain){ var xy = this.getXY(constrain); var s = this.startXY; return [s[0]-xy[0], s[1]-xy[1]]; }, constrainModes: { 'point' : function(xy){ if(!this.elRegion){ this.elRegion = this.getDragCt().getRegion(); } var dr = this.dragRegion; dr.left = xy[0]; dr.top = xy[1]; dr.right = xy[0]; dr.bottom = xy[1]; dr.constrainTo(this.elRegion); return [dr.left, dr.top]; } } });
JavaScript
/** * @class Ext.dd.DropZone * @extends Ext.dd.DropTarget * 对于多个子节点的目标,该类提供一个DD实例的容器(扮演代理角色)。<br /> * 默认地,该类需要一个可拖动的子节点,并且需在{@link Ext.dd.Registry}登记好的。 * @constructor * @param {Mixed} el * @param {Object} config */ Ext.dd.DropZone = function(el, config){ Ext.dd.DropZone.superclass.constructor.call(this, el, config); }; Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, { /** * 返回一个自定义数据对象,与事件对象的那个DOM节点关联。 * 默认地,该方法会在事件目标{@link Ext.dd.Registry}中查找对象, * 但是你亦可以根据自身的需求,重写该方法。 * @param {Event} e 事件对象 * @return {Object} data 自定义数据 */ getTargetFromEvent : function(e){ return Ext.dd.Registry.getTargetFromEvent(e); }, /** * 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource}, * 已经进入一个已登记的落下节点(drop node)的范围内,就会调用。 * 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。 * @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样) * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 */ onNodeEnter : function(n, dd, e, data){ }, /** * 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource}, * 已经位于一个已登记的落下节点(drop node)的上方时,就会调用。 * 默认的实现是返回this.dropAllowed。因此应该重写它以便提供合适的反馈。 * @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样) * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。 */ onNodeOver : function(n, dd, e, data){ return this.dropAllowed; }, /** * 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource}, * 已经离开一个已登记的落下节点(drop node)的范围内,就会调用。 * 该方法没有默认的实现。如需为某些指定的节点处理,则要重写该方法。 * @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样) * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 */ onNodeOut : function(n, dd, e, data){ }, /** * 内部调用。当DropZone确定有一个{@link Ext.dd.DragSource}, * 已经在一个已登记的落下节点(drop node)落下的时候,就会调用。 * 默认的方法返回false,应提供一个合适的实现来处理落下的事件,重写该方法, * 并返回true值,说明拖放行为有效,拖动源的修复动作便不会进行。 * @param {Object} nodeData 自定义数据对象,包含有落下节点(drop node)的内容(其节点的内容与用{@link #getTargetFromEvent}方法得到的值一样) * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {Boolean} True 有效的落下返回true否则为false */ onNodeDrop : function(n, dd, e, data){ return false; }, /** * 内部调用。当DrapZone发现有一个{@link Ext.dd.DragSource}正处于其上方时,但是没有放下任何落下的节点时调用。 * 默认的实现是返回this.dropNotAllowed,如需提供一些合适的反馈,应重写该函数。 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。 */ onContainerOver : function(dd, e, data){ return this.dropNotAllowed; }, /** * 内部调用。当DrapZone确定{@link Ext.dd.DragSource}落下的动作已经执行,但是没有放下任何落下的节点时调用。 * 欲将DropZone本身也可接收落下的行为,应提供一个合适的实现来处理落下的事件,重写该方法,并返回true值, * 说明拖放行为有效,拖动源的修复动作便不会进行。默认的实现返回false。 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {Boolean} True 有效的落下返回true否则为false */ onContainerDrop : function(dd, e, data){ return false; }, /** * 通知DropZone源已经在Zone上方的函数。 * 默认的实现返回this.dropNotAllowed,一般说只有登记的落下节点可以处理拖放操作。 * 欲将DropZone本身也可接收落下的行为,应提供一个自定义的实现,重写该方法, * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。 */ notifyEnter : function(dd, e, data){ return this.dropNotAllowed; }, /** * 当{@link Ext.dd.DragSource}在DropZone范围内时,拖动过程中不断调用的函数。 * 拖动源进入DropZone后,进入每移动一下鼠标都会调用该方法。 * 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onNodeOver}, * 如果拖动源进入{@link #onNodeEnter}, {@link #onNodeOut}这样已登记的节点,通知过程会按照需要自动进行指定的节点处理, * 如果拖动源当前在已登记的节点上,通知过程会调用{@link #onContainerOver}。 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {String} status 由落下状态反馈到源的CSS class,使得所在的{@link Ext.dd.StatusProxy}可被更新。 */ notifyOver : function(dd, e, data){ var n = this.getTargetFromEvent(e); if(!n){ // 不在有效的drop target上 if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } return this.onContainerOver(dd, e, data); } if(this.lastOverNode != n){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); } this.onNodeEnter(n, dd, e, data); this.lastOverNode = n; } return this.onNodeOver(n, dd, e, data); }, /** * 通知DropZone源已经离开Zone上方{@link Ext.dd.DragSource}所调用的函数。 * 如果拖动源当前在已登记的节点上,通知过程会委托{@link #onNodeOut}进行指定的节点处理, * 否则的话会被忽略。 * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 */ notifyOut : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } }, /** * 通知DropZone源已经在Zone放下item后{@link Ext.dd.DragSource}所调用的函数。 * 传入事件的参数,DragZone以此查找目标节点,若是事件已登记的节点的话,便会委托{@link #onNodeDrop}进行指定的节点处理。 * 否则的话调用{@link #onContainerDrop}. * @param {Ext.dd.DragSource} source 处于落下目标上方的拖动源 * @param {Event} e 事件对象 * @param {Object} data 由拖动源规定格式的数据对象 * @return {Boolean} True 有效的落下返回true否则为false */ notifyDrop : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } var n = this.getTargetFromEvent(e); return n ? this.onNodeDrop(n, dd, e, data) : this.onContainerDrop(dd, e, data); }, // private triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); } });
JavaScript
/** * @class Ext.dd.Registry * 为在页面上已登记好的拖放组件提供简易的访问。 * 可按照DOM节点的id的方式直接提取组件,或者是按照传入的拖放事件,事件触发后,在事件目标(event target)里查找。 * @singleton */ Ext.dd.Registry = function(){ var elements = {}; var handles = {}; var autoIdSeed = 0; var getId = function(el, autogen){ if(typeof el == "string"){ return el; } var id = el.id; if(!id && autogen !== false){ id = "extdd-" + (++autoIdSeed); el.id = id; } return id; }; return { /** * 登记一个拖放元素 * @param {String/HTMLElement) element 要登记的id或DOM节点 * @param {Object} data (optional) 在拖放过程中,用于在各元素传递的这么一个自定义数据对象 * 你可以按自身需求定义这个对象,另外有些特定的属性是便于与Registry交互的(如可以的话): * <pre> 值 描述<br /> --------- ------------------------------------------<br /> handles 由DOM节点组成的数组,即被拖动元素,都是已登记好的<br /> isHandle True表示元素传入后已是翻转的拖动本身,否则false<br /> </pre> */ register : function(el, data){ data = data || {}; if(typeof el == "string"){ el = document.getElementById(el); } data.ddel = el; elements[getId(el)] = data; if(data.isHandle !== false){ handles[data.ddel.id] = data; } if(data.handles){ var hs = data.handles; for(var i = 0, len = hs.length; i < len; i++){ handles[getId(hs[i])] = data; } } }, /** * 注销一个拖放元素 * @param {String/HTMLElement) element 要注销的id或DOM节点 */ unregister : function(el){ var id = getId(el, false); var data = elements[id]; if(data){ delete elements[id]; if(data.handles){ var hs = data.handles; for(var i = 0, len = hs.length; i < len; i++){ delete handles[getId(hs[i], false)]; } } } }, /** * 按id返回已登记的DOM节点处理 * @param {String/HTMLElement} id 要查找的id或DOM节点 * @return {Object} handle 自定义处理数据 */ getHandle : function(id){ if(typeof id != "string"){ // must be element? id = id.id; } return handles[id]; }, /** * 按事件目标返回已登记的DOM节点处理 * @param {Event} e 事件对象 * @return {Object} handle 自定义处理数据 */ getHandleFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); return t ? handles[t.id] : null; }, /** * 按id返回已登记的自定义处理对象 * @param {String/HTMLElement} id 要查找的id或DOM节点 * @return {Object} handle 自定义处理数据 */ getTarget : function(id){ if(typeof id != "string"){ // must be element? id = id.id; } return elements[id]; }, /** * 按事件目标返回已登记的自定义处理对象 * @param {Event} e 事件对象 * @return {Object} handle 自定义处理数据 */ getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); return t ? elements[t.id] || handles[t.id] : null; } }; }();
JavaScript
/** * @class Ext.dd.DragZone * 该类继承了{@link Ext.dd.DragSource},对于多节点的源,该类提供了一个DD实理容器来代理。<br/> * 默认情况下,该类要求可拖动的子节点已在{@link Ext.dd.Registry}类中全部注册 * @constructor * @param {Mixed} el 第一个参数为容器元素 * @param {Object} config 第二个参数为配置对象 */ Ext.dd.DragZone = function(el, config){ Ext.dd.DragZone.superclass.constructor.call(this, el, config); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.el); } }; Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, { /** * @cfg {Boolean} containerScroll * 第一个参数:containerScroll 设为True 用来将此容器在Scrollmanager上注册,使得在拖动操作发生时可以自动卷动. */ /** * @cfg {String} hlColor * 第二个参数:hlColor 用于在一次失败的拖动操作后调用afterRepair方法会用在此设定的颜色(默认颜色为亮蓝"c3daf9")来标识可见的拽源<br/> */ /** * 该方法会在鼠标位于该容器内按下时触发,个中机制可参照类{@link Ext.dd.Registry},因为有效的拖动目标是以获取鼠标按下事件为前提的。<br/> * 如果想实现自己的查找方式(如根据类名查找子对象),可以重载这个方法,但是必须确保该方法返回的对象有一个"ddel"属性(属性的值是一个HTML元素),以便函数能正常工作。<br/> * @param {EventObject} e 鼠标按下事件 * @return {Object} 被拖拽对象 */ getDragData : function(e){ return Ext.dd.Registry.getHandleFromEvent(e); }, /** * 该方法在拖拽动作开始,初始化代理元素时调用,默认情况下,它克隆了this.dragData.ddel. * @param {Number} x 被点击的拖拽对象的X坐标 * @param {Number} y 被点击的拖拽对象的y坐标 * @return {Boolean} 该方法返回一个布尔常量,当返回true时,表示继续(保持)拖拽,返回false时,表示取消拖拽<br/> */ onInitDrag : function(x, y){ this.proxy.update(this.dragData.ddel.cloneNode(true)); this.onStartDrag(x, y); return true; }, /** * 该方法在修复无效的drop操作后调用。默认情况下,高亮显示this.dragData.ddel。 */ afterRepair : function(){ if(Ext.enableFx){ Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9"); } this.dragging = false; }, /** * 该方法在修复无效的drop操作之前调用,用来获取XY对象来激活(使用对象),默认情况下返回this.dragData.ddel的XY属性 * @param {EventObject} e 鼠标松开事件 * @return {Array} 区域的xy位置 (例如: [100, 200]) */ getRepairXY : function(e){ return Ext.Element.fly(this.dragData.ddel).getXY(); } });
JavaScript
/** * @class Ext.data.Tree * @extends Ext.util.Observable * 该对象抽象了一棵树的结构和树节点的事件上报。树包含的节点拥有大部分的DOM功能。 * @constructor * @param {Node} root (可选的) 根节点 */ Ext.data.Tree = function(root){ this.nodeHash = {}; /** * 该树的根节点 * @type Node */ this.root = null; if(root){ this.setRootNode(root); } this.addEvents( /** * @event append * 当有新的节点添加到这棵树的时候触发。 * @param {Tree} tree 主树 * @param {Node} parent 父节点 * @param {Node} node 新增加的节点 * @param {Number} index 新增加的节点的索引 */ "append", /** * @event remove * 当树中有子节点从一个节点那里移动开来的时候触发。 * @param {Tree} tree 主树 * @param {Node} parent 父节点 * @param {Node} node 要移除的节点 */ "remove", /** * @event move * 当树中有节点被移动到新的地方时触发。 * @param {Tree} tree 主树 * @param {Node} node 移动的节点 * @param {Node} oldParent 该节点的旧父节点 * @param {Node} newParent 该节点的新父节点 * @param {Number} index 被移动的原索引 */ "move", /** * @event insert * 当树中有一个新的节点添加到某个节点上的时候触发。 * @param {Tree} tree 主树 * @param {Node} parent 父节点 * @param {Node} node 插入的子节点 * @param {Node} refNode 节点之前插入的子节点 */ "insert", /** * @event beforeappend * 当树中有新的子节点添加到某个节点上之前触发,返回false表示取消这个添加行动。 * @param {Tree} tree 主树 * @param {Node} parent 父节点 * @param {Node} node 要被添加的子节点 */ "beforeappend", /** * @event beforeremove * 当树中有新的子节点移除到某个节点上之前触发,返回false表示取消这个移除行动。 * @param {Tree} tree 主树 * @param {Node} parent 父节点 * @param {Node} node 要被移除的子节点 */ "beforeremove", /** * @event beforemove * 当树中有节点移动到新的地方之前触发,返回false表示取消这个移动行动。 * @param {Tree} tree 主树 * @param {Node} node 被移动的节点 * @param {Node} oldParent 节点的父节点 * @param {Node} newParent 要移动到的新的父节点 * @param {Number} index 要被移动到的索引 */ "beforemove", /** * @event beforeinsert * 当树中有新的子节点插入某个节点之前触发,返回false表示取消这个插入行动。 * @param {Tree} tree 主树 * @param {Node} parent 父节点 * @param {Node} node 要被插入的子节点 * @param {Node} refNode 在插入之前节点所在的那个子节点 */ "beforeinsert" ); Ext.data.Tree.superclass.constructor.call(this); }; Ext.extend(Ext.data.Tree, Ext.util.Observable, { /** * @cfg {String} pathSeparator * 分割节点Id的标识符(默认为"/")。 */ pathSeparator: "/", // private proxyNodeEvent : function(){ return this.fireEvent.apply(this, arguments); }, /** * 为这棵树返回根节点。 * @return {Node} */ getRootNode : function(){ return this.root; }, /** * 设置这棵树的根节点。 * @param {Node} node 节点 * @return {Node} */ setRootNode : function(node){ this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); return node; }, /** * 根据ID查找节点。 * @param {String} id * @return {Node} */ getNodeById : function(id){ return this.nodeHash[id]; }, // private registerNode : function(node){ this.nodeHash[node.id] = node; }, // private unregisterNode : function(node){ delete this.nodeHash[node.id]; }, toString : function(){ return "[Tree"+(this.id?" "+this.id:"")+"]"; } }); /** * @class Ext.data.Node * @extends Ext.util.Observable * @cfg {Boolean} leaf true表示该节点是树叶节点没有子节点 * @cfg {String} id 该节点的Id。如不指定一个,会生成一个。 * @constructor * @param {Object} attributes 节点的属性/配置项 */ Ext.data.Node = function(attributes){ /** * The attributes supplied for the node. You can use this property to access any custom attributes you supplied. * @type {Object} */ this.attributes = attributes || {}; this.leaf = this.attributes.leaf; /** * 节点ID。 @type String */ this.id = this.attributes.id; if(!this.id){ this.id = Ext.id(null, "ynode-"); this.attributes.id = this.id; } /** * 此节点的所有子节点。 @type Array */ this.childNodes = []; if(!this.childNodes.indexOf){ // indexOf is a must this.childNodes.indexOf = function(o){ for(var i = 0, len = this.length; i < len; i++){ if(this[i] == o) return i; } return -1; }; } /** * 此节点的父节点. @type Node */ this.parentNode = null; /** * The first direct child node of this node, or null if this node has no child nodes. @type Node */ this.firstChild = null; /** * The last direct child node of this node, or null if this node has no child nodes. @type Node */ this.lastChild = null; /** * The node immediately preceding this node in the tree, or null if there is no sibling node. @type Node */ this.previousSibling = null; /** * The node immediately following this node in the tree, or null if there is no sibling node. @type Node */ this.nextSibling = null; this.addEvents({ /** * @event append * Fires when a new child node is appended * @param {Tree} tree 主树 * @param {Node} this 此节点 * @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 主树 * @param {Node} this 此节点 * @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 主树 * @param {Node} this 此节点 * @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 主树 * @param {Node} this 此节点 * @param {Node} node The child node inserted * @param {Node} refNode The child node the node was inserted before */ "insert" : true, /** * @event beforeappend * Fires before a new child is appended, return false to cancel the append. * @param {Tree} tree 主树 * @param {Node} this 此节点 * @param {Node} node The child node to be appended */ "beforeappend" : true, /** * @event beforeremove * Fires before a child is removed, return false to cancel the remove. * @param {Tree} tree 主树 * @param {Node} this 此节点 * @param {Node} node The child node to be removed */ "beforeremove" : true, /** * @event beforemove * Fires before this node is moved to a new location in the tree. Return false to cancel the move. * @param {Tree} tree 主树 * @param {Node} this 此节点 * @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 * Fires before a new child is inserted, return false to cancel the insert. * @param {Tree} tree 主树 * @param {Node} this This node * @param {Node} node The child node to be inserted * @param {Node} refNode The child node the node is being inserted before */ "beforeinsert" : true }); this.listeners = this.attributes.listeners; Ext.data.Node.superclass.constructor.call(this); }; Ext.extend(Ext.data.Node, Ext.util.Observable, { // private fireEvent : function(evtName){ // first do standard event for this node if(Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false){ return false; } // then bubble it up to the tree if the event wasn't cancelled var ot = this.getOwnerTree(); if(ot){ if(ot.proxyNodeEvent.apply(ot, arguments) === false){ return false; } } return true; }, /** * 若节点是叶子节点的话返回true。 * @return {Boolean} */ isLeaf : function(){ return this.leaf === true; }, // private setFirstChild : function(node){ this.firstChild = node; }, //private setLastChild : function(node){ this.lastChild = node; }, /** * 如果这个节点是其父节点下面的最后一个节点的话返回true。 * @return {Boolean} */ isLast : function(){ return (!this.parentNode ? true : this.parentNode.lastChild == this); }, /** * 如果这个节点是其父节点下面的第一个节点的话返回true。 * @return {Boolean} */ isFirst : function(){ return (!this.parentNode ? true : this.parentNode.firstChild == this); }, hasChildNodes : function(){ return !this.isLeaf() && this.childNodes.length > 0; }, /** * 在该节点里面最后的位置上插入节点,可以多个。 * @param {Node/Array} node 要加入的节点或节点数组 * @return {Node} 如果是单个节点,加入后返回true,如果是数组返回null。 */ appendChild : function(node){ var multi = false; if(node instanceof Array){ multi = node; }else if(arguments.length > 1){ multi = arguments; } // if passed an array or multiple args do them one by one if(multi){ for(var i = 0, len = multi.length; i < len; i++) { this.appendChild(multi[i]); } }else{ if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){ return false; } var index = this.childNodes.length; var oldParent = node.parentNode; // it's a move, make sure we move it cleanly 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; } }, /** * 从该节点中移除一个子节点。 * @param {Node} node 要移除的节点 * @return {Node} 移除后的节点 */ removeChild : function(node){ var index = this.childNodes.indexOf(node); if(index == -1){ return false; } if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){ return false; } // remove it from childNodes collection this.childNodes.splice(index, 1); // update siblings if(node.previousSibling){ node.previousSibling.nextSibling = node.nextSibling; } if(node.nextSibling){ node.nextSibling.previousSibling = node.previousSibling; } // update child refs if(this.firstChild == node){ this.setFirstChild(node.nextSibling); } if(this.lastChild == node){ this.setLastChild(node.previousSibling); } node.setOwnerTree(null); // clear any references from the node node.parentNode = null; node.previousSibling = null; node.nextSibling = null; this.fireEvent("remove", this.ownerTree, this, node); return node; }, /** * 在当前节点的子节点的集合中,位于第一个节点之前插入节点(第二个参数)。 * @param {Node} node 要插入的节点 * @param {Node} refNode 前面插入的节点(如果为null表示节点是追加的) * @return {Node} 插入的节点 */ insertBefore : function(node, refNode){ if(!refNode){ // like standard Dom, refNode can be null for append return this.appendChild(node); } // nothing to do if(node == refNode){ return false; } if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){ return false; } var index = this.childNodes.indexOf(refNode); var oldParent = node.parentNode; var refIndex = index; // when moving internally, indexes will change after remove if(oldParent == this && this.childNodes.indexOf(node) < index){ refIndex--; } // it's a move, make sure we move it cleanly 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; }, /** * 从父节点上移除子节点 * @return {Node} this */ remove : function(){ this.parentNode.removeChild(this); return this; }, /** * 指定索引,在自节点中查找匹配索引的节点。 * @param {Number} index * @return {Node} */ item : function(index){ return this.childNodes[index]; }, /** * 把下面的某个子节点替换为其他节点。 * @param {Node} newChild 进来的节点 * @param {Node} oldChild 去掉的节点 * @return {Node} 去掉的节点 */ replaceChild : function(newChild, oldChild){ this.insertBefore(newChild, oldChild); this.removeChild(oldChild); return oldChild; }, /** * 返回某个子节点的索引。 * @param {Node} node 节点 * @return {Number} 节点的索引或是-1表示找不到 */ indexOf : function(child){ return this.childNodes.indexOf(child); }, /** * 返回节点所在的树对象。 * @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) * @return {Number} */ getDepth : function(){ var depth = 0; var p = this; while(p.parentNode){ ++depth; p = p.parentNode; } return depth; }, // private setOwnerTree : function(tree){ // if it's move, we need to update everyone if(tree != this.ownerTree){ if(this.ownerTree){ this.ownerTree.unregisterNode(this); } this.ownerTree = tree; var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].setOwnerTree(tree); } if(tree){ tree.registerNode(this); } } }, /** * 返回该节点的路径,以方便控制这个节点展开或选择。 * @param {String} attr (可选的)The attr to use for the path (defaults to the node's id) * @return {String} 路径 */ getPath : function(attr){ attr = attr || "id"; var p = this.parentNode; var b = [this.attributes[attr]]; while(p){ b.unshift(p.attributes[attr]); p = p.parentNode; } var sep = this.getOwnerTree().pathSeparator; return sep + b.join(sep); }, /** * 从该节点开始逐层上报(Bubbles up)节点,上报过程中对每个节点执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。函数的参数可经由args指定或当前节点, * 如果函数在某一个层次上返回false,上升将会停止。 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的) 函数的作用域(默认为当前节点) * @param {Array} args(可选的) 调用的函数要送入的参数(不指定就默认为遍历过程中当前的节点) */ bubble : function(fn, scope, args){ var p = this; while(p){ if(fn.apply(scope || p, args || [p]) === false){ break; } p = p.parentNode; } }, /** * 从该节点开始逐层下报(Bubbles up)节点,上报过程中对每个节点执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。函数的参数可经由args指定或当前节点, * 如果函数在某一个层次上返回false,下升到那个分支的位置将会停止。 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的) 函数的作用域(默认为当前节点) * @param {Array} args(可选的) 调用的函数要送入的参数(不指定就默认为遍历过程中当前的节点) */ cascade : function(fn, scope, args){ if(fn.apply(scope || this, args || [this]) !== false){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].cascade(fn, scope, args); } } }, /** * 遍历该节点下的子节点,枚举过程中对每个节点执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数scope传入或是当前节点。函数的参数可经由args指定或当前节点, * 如果函数走到某处地方返回false,遍历将会停止。 * @param {Function} fn 要调用的函数 * @param {Object} scope (可选的) 函数的作用域(默认为当前节点) * @param {Array} args (可选的) 调用的函数要送入的参数(不指定就默认为遍历过程中当前的节点) */ eachChild : function(fn, scope, args){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(fn.apply(scope || this, args || [cs[i]]) === false){ break; } } }, /** * 根据送入的值,如果子节点身上指定属性的值是送入的值,就返回那个节点。 * @param {String} attribute 属性名称 * @param {Mixed} value 要查找的值 * @return {Node} 已找到的子节点或null表示找不到 */ findChild : function(attribute, value){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(cs[i].attributes[attribute] == value){ return cs[i]; } } return null; }, /** * 通过自定义的函数查找子节点,找到第一个合适的就返回。要求的条件是函数返回true。 * @param {Function} fn 函数 * @param {Object} scope 函数作用域(可选的) * @return {Node} 找到的子元素或null就代表没找到 */ findChildBy : function(fn, scope){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(fn.call(scope||cs[i], cs[i]) === true){ return cs[i]; } } return null; }, /** * 用自定义的排序函数对节点的子函数进行排序。 * @param {Function} fn 函数 * @param {Object} scope 函数(可选的) */ sort : function(fn, scope){ var cs = this.childNodes; var len = cs.length; if(len > 0){ var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn; cs.sort(sortFn); for(var i = 0; i < len; i++){ var n = cs[i]; n.previousSibling = cs[i-1]; n.nextSibling = cs[i+1]; if(i == 0){ this.setFirstChild(n); } if(i == len-1){ this.setLastChild(n); } } } }, /** * 返回true表示为该节点是送入节点的祖先节点(无论在哪那一级的) * @param {Node} node 节点 * @return {Boolean} */ contains : function(node){ return node.isAncestor(this); }, /** * 返回true表示为送入的节点是该的祖先节点(无论在哪那一级的) * @param {Node} node 节点 * @return {Boolean} */ isAncestor : function(node){ var p = this.parentNode; while(p){ if(p == node){ return true; } p = p.parentNode; } return false; }, toString : function(){ return "[Node"+(this.id?" "+this.id:"")+"]"; } });
JavaScript
/** * @class Ext.data.DataProxy * @extends Ext.util.Observable * 一个抽象的基类,只提供获取未格式化的原始数据。 * <br> * <p> * DataProxy的实现通常用于连接Ext.data.DataReader的实现(以适当的类型去解析数据对象) * 来一同协作向一{@link Ext.data.Store}提供{@link Ext.data.Records}块。<br> * 自定义子类的实现必须符合{@link Ext.data.HttpProxy#load}方法那般。</p> */ Ext.data.DataProxy = function(){ this.addEvents( /** * @event beforeload * 在达致一次成功的网络请求之后,获取数据之前触发。 * @param {Object} this 此DataProxy对象 * @param {Object} params {@link #load}事件处理函数的参数 */ 'beforeload', /** * @event load * 在load方法的回调函数被调用之前触发该事件。 * @param {Object} this 此DataProxy对象 * @param {Object} o 数据对象 * @param {Object} arg 送入到{@link #load}事件处理函数的那个回调函数的参数 */ 'load' ); Ext.data.DataProxy.superclass.constructor.call(this); }; Ext.extend(Ext.data.DataProxy, Ext.util.Observable);
JavaScript
/** * @class Ext.data.Store * @extends Ext.util.Observable * Store类封装了一个客户端的{@link Ext.data.Record Record}对象的缓存, * 为诸如{@link Ext.grid.GridPanel GridPanel}、{@link Ext.form.ComboBox ComboBox}和{@link Ext.DataView DataView}的小部件等提供了数据的入口。<br> * <p>Store对象使用一个 {@link Ext.data.DataProxy DataProxy}的实现来访问数据对象,该Proxy对象在{@link #proxy configured}定义。不过你可以调用{@link #loadData}直接地传入你的数据.<br> * </p> * <p>A Store对没有Proxy返回数据格式的信息。</p> * <p>在{@link Ext.data.DataReader DataReader}实现的帮助下,从该类提供的数据对象来创建{@link Ext.data.Record Record}实例。 * 你可在{@link #reader configured}指定这个DataReader对象。这些records都被缓存的并且通过访问器函数可利用到。</p> * @constructor * 创建Store对象。 * @param {Object} config 一配置对象,包含了Store用来访问数据,及读数据至Records的对象。(原文:A config object containing the objects needed for the Store to access data, * and read the data into Records) */ Ext.data.Store = function(config){ this.data = new Ext.util.MixedCollection(false); this.data.getKey = function(o){ return o.id; }; /** * 该属性是HTTP请求所携带的参数。如果Store的参数有改变那么这个属性也会改变。 * @property */ this.baseParams = {}; // private this.paramNames = { "start" : "start", "limit" : "limit", "sort" : "sort", "dir" : "dir" }; if(config && config.data){ this.inlineData = config.data; delete config.data; } Ext.apply(this, config); if(this.url && !this.proxy){ this.proxy = new Ext.data.HttpProxy({url: this.url}); } if(this.reader){ // reader passed if(!this.recordType){ this.recordType = this.reader.recordType; } if(this.reader.onMetaChange){ this.reader.onMetaChange = this.onMetaChange.createDelegate(this); } } if(this.recordType){ this.fields = this.recordType.prototype.fields; } this.modified = []; this.addEvents( /** * @event datachanged * * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a * widget that is using this Store as a Record cache should refresh its view. * @param {Store} this */ 'datachanged', /** * @event metachange * 当store的reader 提供新的元数据字段时触发。这目前仅支持jsonReader。 * @param {Store} this * @param {Object} meta JSON元数据 */ 'metachange', /** * @event add * 当Records被添加到store时触发。 * @param {Store} this * @param {Ext.data.Record[]} records The 要被加入的Record数组 * @param {Number} index 被添加进去的record的索引 */ 'add', /** * @event remove * 当一个record被从store里移出时触发。 * @param {Store} this * @param {Ext.data.Record} record 被移出的对Record象 * @param {Number} index 被移出的record的索引值 */ 'remove', /** * @event update * 当有record被更新时触发。 * @param {Store} this * @param {Ext.data.Record} record 被更新的记录 * @param {String} operation 将要执行的更新操作。可能是下列值: * <pre><code> Ext.data.Record.EDIT Ext.data.Record.REJECT Ext.data.Record.COMMIT * </code></pre> */ 'update', /** * @event clear * 当数据缓存被清除时触发。 * @param {Store} this */ 'clear', /** * @event beforeload * 在一个新的数据请求发起之前触发,如果beforeload事件处理函数返回false。加载动作将会被取消。 * @param {Store} this * @param {Object} options 指定的loading选项(从 {@link #load} 查看更多细节) */ 'beforeload', /** * @event load * 在一个新的数据集被加载之后触发该事件 * @param {Store} this * @param {Ext.data.Record[]} records 被载入的记录集 * @param {Object} options The 指定的loading选项(从 {@link #load} 查看更多细节) */ 'load', /** * @event loadexception * 到Proxy对象进行加载的时候,遇到异常随即会触发该事件。这是与Proxy的“loadexception”事件一起联动的。 */ 'loadexception' ); if(this.proxy){ this.relayEvents(this.proxy, ["loadexception"]); } this.sortToggle = {}; if(this.sortInfo){ this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction); } Ext.data.Store.superclass.constructor.call(this); if(this.storeId || this.id){ Ext.StoreMgr.register(this); } if(this.inlineData){ this.loadData(this.inlineData); delete this.inlineData; }else if(this.autoLoad){ this.load.defer(10, this, [ typeof this.autoLoad == 'object' ? this.autoLoad : undefined]); } }; Ext.extend(Ext.data.Store, Ext.util.Observable, { /** * @cfg {String} storeId 如果有值传入,该ID用于在StoreMgr登记时用。 */ /** * @cfg {String} url 如果有值传入,会为该URL创建一个HttpProxy对象。 */ /** * @cfg {Boolean/Object} autoLoad 如果有值传入,那么store的load会自动调用,发生在autoLoaded对象创建之后。 */ /** * @cfg {Ext.data.DataProxy} proxy Proxy对象,用于访问数据对象。 */ /** * @cfg {Array} data 表示store初始化后,要加载的内联数据。 */ /** * @cfg {Ext.data.DataReader} reader * 处理数据对象的DataReader会返回一个Ext.data.Record对象的数组。其中的<em>id</em>属性会是一个缓冲了的键。 * (原文:The DataReader object which processes the data object and returns an Array of Ext.data.Record objects which are cached keyed by their property.) */ /** * @cfg {Object} baseParams 每次HTTP请求都会带上这个参数,本来它是一个对象的形式,请求时会转化为参数的字符串。 */ /** * @cfg {Object} sortInfo 如何排序的对象,格式如下:{field: "fieldName", direction: "ASC|DESC"}。排序方向的大小写敏感的。 */ /** * @cfg {boolean} remoteSort True表示在roxy配合下,要求服务器提供一个更新版本的数据对象以便排序,反之就是在Record缓存中排序(默认是false)。 * <p> * 如果开启远程排序,那么点击头部时就会使当前页面向服务器请求排序,会有以下的参数: * <div class="mdetail-params"><ul> * <li><b>sort</b> : String<p class="sub-desc">要排序的字段字符串(即 在Record对象内的字段定义)</p></li> * <li><b>dir</b> : String<p class="sub-desc">排序的方向,“ASC”或“DESC”(一定要大写)</p></li> * </ul></div></p> */ remoteSort : false, /** * @cfg {boolean} pruneModifiedRecords True表示为,每次Store加载后,清除所有修改过的记录信息;record被移除时也会这样(默认为false)。 */ pruneModifiedRecords : false, /** * 保存了上次load方法执行时,发出去的参数是什么。参阅{@link #load}了解这些是什么的参数。 * 加载当前的Record缓存的时候,清楚用了哪些的参数有时是非常有用的。 * @property */ lastOptions : null, destroy : function(){ if(this.id){ Ext.StoreMgr.unregister(this); } this.data = null; this.purgeListeners(); }, /** * 往Store对象添加Records,并触发{@link #add}事件。 * @param {Ext.data.Record[]} records Ext.data.Record对象数组,在缓存中 */ add : function(records){ records = [].concat(records); if(records.length < 1){ return; } for(var i = 0, len = records.length; i < len; i++){ records[i].join(this); } var index = this.data.length; this.data.addAll(records); if(this.snapshot){ this.snapshot.addAll(records); } this.fireEvent("add", this, records, index); }, /** * (只限本地排序) 传入一个Record,按照队列(以固定的排序顺序)插入到Store对象中。 * @param {Ext.data.Record} record */ addSorted : function(record){ var index = this.findInsertIndex(record); this.insert(index, record); }, /** * 从Store中移除一Record对象,并触发{@link #remove}移除事件。 * @param {Ext.data.Record} record 被从缓存中移除的Ext.data.Record对象 */ remove : function(record){ var index = this.data.indexOf(record); this.data.removeAt(index); if(this.pruneModifiedRecords){ this.modified.remove(record); } if(this.snapshot){ this.snapshot.remove(record); } this.fireEvent("remove", this, record, index); }, /** * 从Store中清空所有Record对象,并触发{@link #clear}事件。 */ removeAll : function(){ this.data.clear(); if(this.snapshot){ this.snapshot.clear(); } if(this.pruneModifiedRecords){ this.modified = []; } this.fireEvent("clear", this); }, /** * 触发添加事件时插入records到指定的store位置 * @param {Number} index 传入的Records插入的开始位置 * @param {Ext.data.Record[]} records 加入到缓存中的Ext.data.Record对象 */ insert : function(index, records){ records = [].concat(records); for(var i = 0, len = records.length; i < len; i++){ this.data.insert(index, records[i]); records[i].join(this); } this.fireEvent("add", this, records, index); }, /** * 传入一个记录,根据记录在缓存里查询的匹配的记录,返回其索引。 * @param {Ext.data.Record} record 要找寻的Ext.data.Record * @return {Number} 被传入的Record的索引,如果未找到返回-1 */ indexOf : function(record){ return this.data.indexOf(record); }, /** * 传入一个id,根据id查询缓存里的Record,返回其索引。 * @param {String} id 要找到Record的id * @return {Number} 被找到的Record的索引,如果未找到返回-1 */ indexOfId : function(id){ return this.data.indexOfKey(id); }, /** * 根据指定的id找到Record。 * @param {String} id 要找的Record的id * @return {Ext.data.Record} 返回匹配id的Record,如果未找到则返回undefined */ getById : function(id){ return this.data.key(id); }, /** * 根据指定的索引找到Record。 * @param {Number} index 要找的Record的索引 * @return {Ext.data.Record} 返回匹配索引的Record,如果未找到则返回undefined */ getAt : function(index){ return this.data.itemAt(index); }, /** * 查找指定范围里的Records。 * @param {Number} startIndex (可选项)开始索引 (默认为 0) * @param {Number} endIndex (可选项)结束的索引 (默认是Store中最后一个Record的索引) * @return {Ext.data.Record[]} 返回一个Record数组 */ getRange : function(start, end){ return this.data.getRange(start, end); }, // private storeOptions : function(o){ o = Ext.apply({}, o); delete o.callback; delete o.scope; this.lastOptions = o; }, /** * 采用配置好的Reader格式去加载Record缓存,具体请求的任务由配置好的Proxy对象完成。 * <p>如果使用服务器分页,那么必须指定在options.params中<tt>start</tt>和<tt>limit</tt>两个参数。 * start参数表明了从记录集(dataset)的哪一个位置开始读取,limit是读取多少笔的记录。Proxy负责送出参数。 * </p> * <p><b> * 由于采用了异步加载,因此该方法执行完毕后,数据不是按照load()方法下一个语句的顺序可以获取得到的。 * 应该登记一个回调函数,或者“load”的事件,登记一个处理函数</b></p> * @param {Object} options 传入以下属性的对象,或影响加载的选项:<ul> * <li><b>params</b> :Object<p class="sub-desc">送出的HTTP参数,格式是JS对象</p></li> * <li><b>callback</b> : Function<p class="sub-desc">回调函数,这个函数会有以下的参数传入:<ul> * <li>r : Ext.data.Record[]</li> * <li>options: Options 加载的选项</li> * <li>success: Boolean 是否成功</li></ul></p></li> * <li><b>scope</b> : Object<p class="sub-desc">回调函数的作用域(默认为Store对象)</p></li> * <li><b>add</b> : Boolean<p class="sub-desc">表示到底是追加数据,还是替换数据</p></li> * </ul> * @return {Boolean} load是否执行了(受beforeload的影响,参见源码) */ load : function(options){ options = options || {}; if(this.fireEvent("beforeload", this, options) !== false){ this.storeOptions(options); var p = Ext.apply(options.params || {}, this.baseParams); if(this.sortInfo && this.remoteSort){ var pn = this.paramNames; p[pn["sort"]] = this.sortInfo.field; p[pn["dir"]] = this.sortInfo.direction; } this.proxy.load(p, this.reader, this.loadRecords, this, options); return true; } else { return false; } }, /** * 依据上一次的load操作的参数的Reader制订的格式,再一次向Proxy对象要求施以加载(Reload)Record缓存的操作。 * @param {Object} options (可选的)该对象包含的属性会覆盖上次load操作的参数。参阅{@link #load}了解详细内容(默认为null,即就是复用上次的选项参数)。 */ reload : function(options){ this.load(Ext.applyIf(options||{}, this.lastOptions)); }, // private // Called as a callback by the Reader during a load operation. loadRecords : function(o, options, success){ if(!o || success === false){ if(success !== false){ this.fireEvent("load", this, [], options); } if(options.callback){ options.callback.call(options.scope || this, [], options, false); } return; } var r = o.records, t = o.totalRecords || r.length; if(!options || options.add !== true){ if(this.pruneModifiedRecords){ this.modified = []; } for(var i = 0, len = r.length; i < len; i++){ r[i].join(this); } if(this.snapshot){ this.data = this.snapshot; delete this.snapshot; } this.data.clear(); this.data.addAll(r); this.totalLength = t; this.applySort(); this.fireEvent("datachanged", this); }else{ this.totalLength = Math.max(t, this.data.length+r.length); this.add(r); } this.fireEvent("load", this, r, options); if(options.callback){ options.callback.call(options.scope || this, r, options, true); } }, /** * 从传入的数据块中装载数据,并触发{@link #load}事件。传入的数据格式是Reader必须能够读取理解的,Reader是在构造器 * 中配置好的。 * @param {Object} data 要被转化为Records的数据块。数据类型会是由这个Reader的配置所决定的,并且符合Reader对象的readRecord参数的要求。 * @param {Boolean} add (Optional) True表示为是在缓存中追加新的Records而不是进行替换。<b> * 切记Store中的Record是按照{@link Ext.data.Record#id id}记录的,所以新加的Records如果id一样的话就会<i>替换</i>Stroe里面原有的,新的就会追加。 * </b> */ loadData : function(o, append){ var r = this.reader.readRecords(o); this.loadRecords(r, {add: append}, true); }, /** * <p>如果使用了分页,那么这就是当前分页的总数,而不是全部记录的总数。 * 要获取记录总数应使用{@link #getTotalCount}方法,才能从Reader身上获取正确的全部记录数。</p> * @return {Number} Store缓存中记录总数 */ getCount : function(){ return this.data.length || 0; }, /** * 获取作为服务端返回的数据集中记录的总数。 * <p> * 如果分页,该值必须声明存在才能成功分页。Reader对象处理数据对象该值不能或缺。 * 对于远程数据而言,这是有服务器查询的结果。</p> * @return {Number} 数据对象由Proxy传给Reader对象,这个数据对象包含Record记录的总数 * <p><b>如果是在本地更新Store的内容,那么该值是不会发生变化的。</b></p> */ getTotalCount : function(){ return this.totalLength || 0; }, /** * 以对象的形式返回当前排序的状态。 * @return {Object} 当前排序的状态:它是一个对象,有以下两个属性:<ul> * <li><b>field : String<p class="sub-desc"> 一个是排序字段</p></li> * <li><b>direction : String<p class="sub-desc">一个是排序方向,"ASC"或"DESC" (一定要大写)</p></li> * </ul> */ getSortState : function(){ return this.sortInfo; }, // private applySort : function(){ if(this.sortInfo && !this.remoteSort){ var s = this.sortInfo, f = s.field; this.sortData(f, s.direction); } }, // private sortData : function(f, direction){ direction = direction || 'ASC'; var st = this.fields.get(f).sortType; var fn = function(r1, r2){ var v1 = st(r1.data[f]), v2 = st(r2.data[f]); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }; this.data.sort(direction, fn); if(this.snapshot && this.snapshot != this.data){ this.snapshot.sort(direction, fn); } }, /** * 设置默认的列排序,以便下次load操作时使用 * @param {String} fieldName 要排序的字段 * @param {String} dir (可选的) 排序顺序,“ASC”或“DESC”(默认为“ASC”) */ setDefaultSort : function(field, dir){ dir = dir ? dir.toUpperCase() : "ASC"; this.sortInfo = {field: field, direction: dir}; this.sortToggle[field] = dir; }, /** * 对记录排序。 * 如果使用远程排序,排序是在服务端中进行的,缓存就会重新加载;如果使用本地排序,缓存就会内部排序。 * @param {String} fieldName 要排序的字段的字符串 * @param {String} dir (optional) 排序方向,“ASC”或“DESC”(大小写敏感的,默认为“ASC”) */ sort : function(fieldName, dir){ var f = this.fields.get(fieldName); if(!f){ return false; } if(!dir){ if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC"); }else{ dir = f.sortDir; } } var st = (this.sortToggle) ? this.sortToggle[f.name] : null; var si = (this.sortInfo) ? this.sortInfo : null; this.sortToggle[f.name] = dir; this.sortInfo = {field: f.name, direction: dir}; if(!this.remoteSort){ this.applySort(); this.fireEvent("datachanged", this); }else{ if (!this.load(this.lastOptions)) { if (st) { this.sortToggle[f.name] = st; } if (si) { this.sortInfo = si; } } } }, /** * 对缓存中每个记录调用特点的函数。 * @param {Function} fn 要调用的函数。Record对象将是第一个参数。如果返回<tt>false</tt>就中止或推出循环。 * @param {Object} scope 函数的作用域(默认为Record对象)(可选的) */ each : function(fn, scope){ this.data.each(fn, scope); }, /** * 距离上次提交之后,把所有修改过的、变化的记录收集起来。 * 通过加载(load)的操作来持久化这些修改的记录。(例如在分页期间) * @return {Ext.data.Record[]} 包含了显注修改的Record数组. */ getModifiedRecords : function(){ return this.modified; }, // private createFilterFn : function(property, value, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return false; } value = this.data.createValueMatcher(value, anyMatch, caseSensitive); return function(r){ return value.test(r.data[property]); }; }, /** * Sums the value of <i>property</i> for each record between start and end and returns the result. * @param {String} property 记录集中要统计的字段名称 * @param {Number} start 计算的记录开始索引(默认为0) * @param {Number} end 计算的记录结尾索引(默认为length - 1,从零开始算) * @return {Number} 总数 */ sum : function(property, start, end){ var rs = this.data.items, v = 0; start = start || 0; end = (end || end === 0) ? end : rs.length-1; for(var i = start; i <= end; i++){ v += (rs[i].data[property] || 0); } return v; }, /** * 由指定的属性筛选记录。 * @param {String} field 你查询的字段 * @param {String/RegExp} value 既可以是字段开头的字符串,也可以是针对该字段的正则表达式 * @param {Boolean} anyMatch (可选的)True表示不一定要开头的,当中包含的亦可 * @param {Boolean} caseSensitive (可选的)True表示大小写敏感 */ filter : function(property, value, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.filterBy(fn) : this.clearFilter(); }, /** * 由外部函数进行筛选。Store里面的每个记录都经过这个函数内部使用。 * 如果函数返回<tt>true</tt>的话,就引入(included)到匹配的结果集中,否则就会被过滤掉。 * @param {Function} fn 要执行的函数。它会被传入以下的参数:<ul> * <li><b>record</b> : Ext.data.Record<p class="sub-desc"> {@link Ext.data.Record record} * 对象用来测试过滤结果的。访问字段值就用{@link Ext.data.Record#get}方法。</p></li> * <li><b>id</b> : Object<p class="sub-desc">所传入的Record的ID</p></li> * </ul> * @param {Object} scope (可选的)函数作用域(默认为this) */ filterBy : function(fn, scope){ this.snapshot = this.snapshot || this.data; this.data = this.queryBy(fn, scope||this); this.fireEvent("datachanged", this); }, /** * 由指定的属性查询记录。 * @param {String} field 你查询的字段 * @param {String/RegExp} value 既可以是字段开头的字符串,也可以是针对该字段的正则表达式 * @param {Boolean} anyMatch (可选的)True表示不一定要开头的,当中包含的亦可 * @param {Boolean} caseSensitive (可选的)True表示大小写敏感 * @return {MixedCollection} 返回一个Ext.util.MixedCollection实例,包含了匹配的记录 */ query : function(property, value, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.queryBy(fn) : this.data.clone(); }, /** * 由外部函数进行该Store缓存记录的筛选。Store里面的每个记录都经过这个函数内部使用。 * 如果函数返回<tt>true</tt>的话,就引入(included)到匹配的结果集中。 * @param {Function} fn 要执行的函数。它会被传入以下的参数:<ul> * <li><b>record</b> : Ext.data.Record<p class="sub-desc"> {@link Ext.data.Record record} * 对象用来测试过滤结果的。访问字段值就用{@link Ext.data.Record#get}方法。</p></li> * <li><b>id</b> : Object<p class="sub-desc">所传入的Record的ID</p></li> * </ul> * @param {Object} scope (可选的)函数作用域(默认为this) * @return {MixedCollection} 返回一个Ext.util.MixedCollection实例,包含了匹配的记录 */ queryBy : function(fn, scope){ var data = this.snapshot || this.data; return data.filterBy(fn, scope||this); }, /** * 由指定的属性、值来查询记录,返回的是记录的索引值。只考虑第一次匹配的结果。 * @param {String} property 你查询对象的属性 * @param {String/RegExp} value 既可以是字段开头的字符串,也可以是针对该字段的正则表达式 * @param {Number} startIndex (可选的) 查询的开始索引 * @param {Boolean} anyMatch (可选的)True表示不一定要开头的,当中包含的亦可 * @param {Boolean} caseSensitive (可选的)True表示大小写敏感 * @return {Number} 匹配的索引或-1 */ find : function(property, value, start, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.data.findIndexBy(fn, null, start) : -1; }, /** * 由外部函数从某个索引开始进行筛选。只考虑第一次匹配的结果。 * 如果函数返回<tt>true</tt>的话,就被认为是一个匹配的结果。 * @param {Function} fn 要执行的函数。它会被传入以下的参数:<ul> * <li><b>record</b> : Ext.data.Record<p class="sub-desc"> {@link Ext.data.Record record} * 对象用来测试过滤结果的。访问字段值就用{@link Ext.data.Record#get}方法。</p></li> * <li><b>id</b> : Object<p class="sub-desc">所传入的Record的ID</p></li> * </ul> * @param {Object} scope (可选的) 函数作用域(默认为this) * @param {Number} startIndex (可选的) 查询的开始索引 * @return {Number} 匹配的索引或-1 */ findBy : function(fn, scope, start){ return this.data.findIndexBy(fn, scope, start); }, /** * 从这个Store身上收集由dataIndex指定的惟一的值。 * @param {String} dataIndex 要收集的属性 * @param {Boolean} allowNull (可选的) 送入true表示允许null、undefined或空白字符串这些无意义的值 * @param {Boolean} bypassFilter (可选的)送入true表示收集所有记录,哪怕是被经过筛选的记录 * @return {Array} 惟一值的数组 **/ collect : function(dataIndex, allowNull, bypassFilter){ var d = (bypassFilter === true && this.snapshot) ? this.snapshot.items : this.data.items; var v, sv, r = [], l = {}; for(var i = 0, len = d.length; i < len; i++){ v = d[i].data[dataIndex]; sv = String(v); if((allowNull || !Ext.isEmpty(v)) && !l[sv]){ l[sv] = true; r[r.length] = v; } } return r; }, /** * 恢复到Record缓存的视图,这是没有经过筛选的Record。 * @param {Boolean} suppressEvent 如果设置为true,该筛选器会低调地清空,而不会通知监听器 */ clearFilter : function(suppressEvent){ if(this.isFiltered()){ this.data = this.snapshot; delete this.snapshot; if(suppressEvent !== true){ this.fireEvent("datachanged", this); } } }, /** * 返回true表明这个store当前是在筛选的。 * @return {Boolean} */ isFiltered : function(){ return this.snapshot && this.snapshot != this.data; }, // private afterEdit : function(record){ if(this.modified.indexOf(record) == -1){ this.modified.push(record); } this.fireEvent("update", this, record, Ext.data.Record.EDIT); }, // private afterReject : function(record){ this.modified.remove(record); this.fireEvent("update", this, record, Ext.data.Record.REJECT); }, // private afterCommit : function(record){ this.modified.remove(record); this.fireEvent("update", this, record, Ext.data.Record.COMMIT); }, /** * 提交全部有变化的Record集。在实际处理这些更新的编码中, * 应该登记Store的“update”事件,事件的处理函数中的第三个参数就是Ext.data.Record.COMMIT,用它来进行更新。 */ commitChanges : function(){ var m = this.modified.slice(0); this.modified = []; for(var i = 0, len = m.length; i < len; i++){ m[i].commit(); } }, /** * 放弃所有的变更。 */ rejectChanges : function(){ var m = this.modified.slice(0); this.modified = []; for(var i = 0, len = m.length; i < len; i++){ m[i].reject(); } }, // private onMetaChange : function(meta, rtype, o){ this.recordType = rtype; this.fields = rtype.prototype.fields; delete this.snapshot; this.sortInfo = meta.sortInfo; this.modified = []; this.fireEvent('metachange', this, this.reader.meta); }, // private findInsertIndex : function(record){ this.suspendEvents(); var data = this.data.clone(); this.data.add(record); this.applySort(); var index = this.data.indexOf(record); this.data = data; this.resumeEvents(); return index; } });
JavaScript
// private // Field objects are not intended to be created directly, but are created // behind the scenes when defined for Record objects. See Record.js for details. Ext.data.Field = function(config){ if(typeof config == "string"){ config = {name: config}; } Ext.apply(this, config); if(!this.type){ this.type = "auto"; } var st = Ext.data.SortTypes; // named sortTypes are supported, here we look them up //支持指定的排序类型,这里我们来查找它们 if(typeof this.sortType == "string"){ this.sortType = st[this.sortType]; } // set default sortType for strings and dates // 为strings和dates设置默认的排序类型 if(!this.sortType){ switch(this.type){ case "string": this.sortType = st.asUCString; break; case "date": this.sortType = st.asDate; break; default: this.sortType = st.none; } } // define once var stripRe = /[\$,%]/g; // prebuilt conversion function for this field, instead of // switching every time we're reading a value // 为字段预先建立转换函数,来代替每次我们读取值时再选择 if(!this.convert){ var cv, dateFormat = this.dateFormat; switch(this.type){ case "": case "auto": case undefined: cv = function(v){ return v; }; break; case "string": cv = function(v){ return (v === undefined || v === null) ? '' : String(v); }; break; case "int": cv = function(v){ return v !== undefined && v !== null && v !== '' ? parseInt(String(v).replace(stripRe, ""), 10) : ''; }; break; case "float": cv = function(v){ return v !== undefined && v !== null && v !== '' ? parseFloat(String(v).replace(stripRe, ""), 10) : ''; }; break; case "bool": case "boolean": cv = function(v){ return v === true || v === "true" || v == 1; }; break; case "date": cv = function(v){ if(!v){ return ''; } if(v instanceof Date){ return v; } if(dateFormat){ if(dateFormat == "timestamp"){ return new Date(v*1000); } if(dateFormat == "time"){ return new Date(parseInt(v, 10)); } return Date.parseDate(v, dateFormat); } var parsed = Date.parse(v); return parsed ? new Date(parsed) : null; }; break; } this.convert = cv; } }; Ext.data.Field.prototype = { dateFormat: null, defaultValue: "", mapping: null, sortType : null, sortDir : "ASC" };
JavaScript
/** * @class Ext.data.MemoryProxy * @extends Ext.data.DataProxy * 一个Ext.data.DataProxy的实现类,当其load方法调用时就是用送入Reader来读取那个在构造器中传入的数据。 * @constructor * @param {Object} data Reader用这个数据对象来构造Ext.data.Records块。 */ Ext.data.MemoryProxy = function(data){ Ext.data.MemoryProxy.superclass.constructor.call(this); this.data = data; }; Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, { /** * @event loadexception * 在加载数据期间有异常发生时触发该事件。注意该事件是与{@link Ext.data.Store}对象联动的,所以你只监听其中一个事件就可以的了。 * @param {Object} this 此DataProxy 对象. * @param {Object} o 数据对象. * @param {Object} arg 传入{@link #load}函数的回调参数对象 * @param {Object} null 使用MemoryProxy的这就一直是null * @param {Error} e 如果Reader不能读取数据就抛出一个JavaScript Error对象 */ /** * 根据数据源加载数据(本例中是客户端内存中的数据对象,透过构造器传入的),由指定的Ext.data.DataReader实例来解析这个Ext.data.Records块,并由指定的回调来处理这个块。 * @param {Object} params 这个参数对MemoryProxy类不起作用 * @param {Ext.data.DataReader} reader 能转换数据为Ext.data.Records块的Reader对象 * @param {Function} callback 会送入Ext.data.records块的函数。函数一定会传入:<ul> * <li>Record对象t</li> * <li>从load函数那里来的参数"arg"</li> * <li>是否成功的标识符</li> * </ul> * @param {Object} scope 回调函数的作用域 * @param {Object} arg 送入到回调函数的参数,在参数第二个位置中出现(可选的) */ load : function(params, reader, callback, scope, arg){ params = params || {}; var result; try { result = reader.readRecords(this.data); }catch(e){ this.fireEvent("loadexception", this, arg, null, e); callback.call(scope, null, arg, false); return; } callback.call(scope, result, arg, true); }, // private update : function(params, records){ } });
JavaScript
/** * @class Ext.data.XmlReader * @extends Ext.data.DataReader * Data reader类接受一个XML文档响应结果后,创建一个由{@link Ext.data.Record}对象组成的数组, * 数组内的每个对象都是{@link Ext.data.Record}构造器负责映射(mappings)的结果。<br><br> * <p> * <em>注意:为了浏览器能成功解析返回来的XML document对象,HHTP Response的content-type 头必须被设成text/xml。</em> * <p> * 示例代码: * <pre><code> var Employee = Ext.data.Record.create([ {name: 'name', mapping: 'name'}, // 如果名称相同就不需要"mapping"属性的啦 {name: 'occupation'} // 进行"occupation"的映射 ]); var myReader = new Ext.data.XmlReader({ totalProperty: "results", // 该属性是指定记录集的总数(可选的) root: "rows", // 该属性是指定包含所有行对象的数组 id: "id" // 该属性是指定每一个行对象中究竟哪一个是记录的ID字段(可选的) }, Employee); </code></pre> * <p> * 形成这种形式的XML文件: * <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?> &lt;dataset> &lt;results>2&lt;/results> &lt;row> &lt;id>1&lt;/id> &lt;name>Bill&lt;/name> &lt;occupation>Gardener&lt;/occupation> &lt;/row> &lt;row> &lt;id>2&lt;/id> &lt;name>Ben&lt;/name> &lt;occupation>Horticulturalist&lt;/occupation> &lt;/row> &lt;/dataset> </code></pre> * @cfg {String} totalRecords 记录集的总数的DomQuery查询路径。如果是需要分页的话该属性就必须指定。 * @cfg {String} record 指明一个DomQuery查询路径,指定包含所有行对象的信息 * @cfg {String} success 指明一个DomQuery查询路径,The DomQuery path to the success attribute used by forms. * @cfg {String} id 指明一个DomQuery查询路径,用于获取每一个行对象中究竟哪一个是记录的ID字段(可选的) * @constructor * 创建XmlReader对象 * @param {Object} meta 元数据配置参数 * @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由 * {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象 */ Ext.data.XmlReader = function(meta, recordType){ meta = meta || {}; Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, { /** * 从远端服务器取得数据后,仅供DataProxy对象所使用的方法。 * @param {Object} response 包含可被解析的XML文档数据在<tt>responseXML</tt>属性中的XHR的对象 * @return {Object} data 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存 */ read : function(response){ var doc = response.responseXML; if(!doc) { throw {message: "XmlReader.read: XML Document not available"}; } return this.readRecords(doc); }, /** * 由一个XML文档产生一个包含Ext.data.Records的对象块。 * @param {Object} o 一个可被解析的XML文档 * @return {Object} data 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存 */ readRecords : function(doc){ /** * 异步通信完毕和读取之后,保留原始XML文档数据以便将来由必要的用途。 * @type XMLDocument */ this.xmlData = doc; var root = doc.documentElement || doc; var q = Ext.DomQuery; var recordType = this.recordType, fields = recordType.prototype.fields; var sid = this.meta.id; var totalRecords = 0, success = true; if(this.meta.totalRecords){ totalRecords = q.selectNumber(this.meta.totalRecords, root, 0); } if(this.meta.success){ var sv = q.selectValue(this.meta.success, root, true); success = sv !== false && sv !== 'false'; } var records = []; var ns = q.select(this.meta.record, root); for(var i = 0, len = ns.length; i < len; i++) { var n = ns[i]; var values = {}; var id = sid ? q.selectValue(sid, n) : undefined; for(var j = 0, jlen = fields.length; j < jlen; j++){ var f = fields.items[j]; var v = q.selectValue(f.mapping || f.name, n, f.defaultValue); v = f.convert(v, n); values[f.name] = v; } var record = new recordType(values, id); record.node = n; records[records.length] = record; } return { success : success, records : records, totalRecords : totalRecords || records.length }; } });
JavaScript
/** * @class Ext.data.Record * Record类不但封装了Record的<em>相关定义</em>信息,还封装了在{@link Ext.data.Store}里使用的Recrod对象的值信息, * 并且在任何代码里需要访问Records的缓存{@link Ext.data.Store}的信息<br> * <p> * 该对象的静态方法{@link #create}会接受一个字段定义的数组参数来生成一个构造器。 * 只当{@link Ext.data.Reader}处理未格式化的数据对象时,才会创建Record的实例。<br> * <p> * 该构建器不能被用来创建Record对象。取而代之的,是用{@link #create}方法生成的构建器。参数都是相同的。 * @constructor * @param {Array} data 对象数组,提供了每一个Record实例所需的字段属性定义。 * @param {Object} id (可选的)记录的id,应当是独一无二的。 * {@link Ext.data.Store}会用这个id表示来标识记录里面的Record对象,如不指定就生成一个。 */ Ext.data.Record = function(data, id){ this.id = (id || id === 0) ? id : ++Ext.data.Record.AUTO_ID; this.data = data; }; /** * 生成一个构造函数,该函数能产生符合特定规划的Record对象。 * @param {Array} o * 数组。各个字段的定义,包括字段名、数据类型(可选的)、映射项(用于在{@link Ext.data.Reader}的数据对象中提取真实的数据)。 * 每一个字段的定义对象可包含以下的属性:<ul> * <li><b>name</b> : String<div class="sub-desc">Record对象所引用的字段名称。通常是一标识作它者引用, * 例如,在列定义中,该值会作为{@link Ext.grid.ColumnModel}的<em>dataIndex</em>属性。</div></li> * <li><b>mapping</b> : String<div class="sub-desc">(可选的) 如果使用的是{@link Ext.data.Reader},这是一个Reader能够获取数据对象的数组值创建到Record对象下面的对应的映射项; * 如果使用的是{@link Ext.data.JsonReader},那么这是一个javascript表达式的字符串, * 能够获取数据的引用到Record对象的下面; * 如果使用的是{@link Ext.data.XmlReader},这是一个{@link Ext.DomQuery}路径, * 能够获取数据元素的引用到Record对象的下面; * 如果映射名与字段名都是相同的,那么映射名可以省略。 * </div></li> * <li><b>type</b> : String<div class="sub-desc">(可选的) 指明数据类型,转化为可显示的值。有效值是: * <ul><li>auto (auto是默认的,不声明就用auto。不作转换)</li> * <li>string</li> * <li>int</li> * <li>float</li> * <li>boolean</li> * <li>date</li></ul></div></li> * <li><b>sortType</b> : Mixed<div class="sub-desc">(可选的) {@link Ext.data.SortTypes}的成语。</div></li> * <li><b>sortDir</b> : String<div class="sub-desc">(可选的) 初始化的排序方向,“ASC”或“DESC”。</div></li> * <li><b>convert</b> : Function<div class="sub-desc">(可选的) 由Reader提供的用于转换值的函数,将值变为Record下面的对象。它会送入以下的参数:<ul> * <li><b>v</b> : Mixed<div class="sub-desc">数据值,和Reader读取的一样。</div></li> * <li><b>rec</b> : Mixed<div class="sub-desc">包含行的数据对象,和Reader读取的一样。 * 这可以是数组,对象,XML元素对象,这取决于Reader对象的类型。</div></li> * </ul></div></li> * <li><b>dateFormat</b> : String<div class="sub-desc">(可选的) 字符串格式的{@link Date#parseDate Date.parseDate}函数, * 或“timestamp”表示Reader读取UNIX格式的timestamp,或“time”是Reader读取的是javascript毫秒的timestamp。</div></li> * <li><b>defaultValue</b> : Mixed<div class="sub-desc">(可选的)默认值。<b> * 当经过{@link Ext.data.Reader Reader}创建Record时会使用该值;</b> 当<b><tt>mapping</tt></b>的引用项不存在的时候,典型的情况为undefined时候会使用该值(默认为'') * </div></li> * </ul> * 透过create方法会返回一个构造器的函数,这样就可以用来创建一个一个Record对象了。 * 数据对象(在第一个参数上)一定要有一个属性,是名为<b>names</b>的属性,以说明是什么字段。 * <br>用法:<br><pre><code> var TopicRecord = Ext.data.Record.create([ {name: 'title', mapping: 'topic_title'}, {name: 'author', mapping: 'username'}, {name: 'totalPosts', mapping: 'topic_replies', type: 'int'}, {name: 'lastPost', mapping: 'post_time', type: 'date'}, {name: 'lastPoster', mapping: 'user2'}, {name: 'excerpt', mapping: 'post_text'} ]); var myNewRecord = new TopicRecord({ title: 'Do my job please', author: 'noobie', totalPosts: 1, lastPost: new Date(), lastPoster: 'Animal', excerpt: 'No way dude!' }); myStore.add(myNewRecord); </code></pre> * <p> * 简单地说,除了 <tt>name</tt>属性是必须的外,其他属性是可以不要的,因此,你只要传入一个字符串就可满足最低条件了,因为它就代表字段名称。</p> * @method create * @return {function} 根据定义创建新Records的构造器。 * @static */ Ext.data.Record.create = function(o){ var f = Ext.extend(Ext.data.Record, {}); var p = f.prototype; p.fields = new Ext.util.MixedCollection(false, function(field){ return field.name; }); for(var i = 0, len = o.length; i < len; i++){ p.fields.add(new Ext.data.Field(o[i])); } f.getField = function(name){ return p.fields.get(name); }; return f; }; Ext.data.Record.AUTO_ID = 1000; Ext.data.Record.EDIT = 'edit'; Ext.data.Record.REJECT = 'reject'; Ext.data.Record.COMMIT = 'commit'; Ext.data.Record.prototype = { /** * Record的数据对象 * @property data * @type {Object} */ /** * 惟一的ID,在Record创建时分派此值。 * @property id * @type {Object} */ /** * 只读。true表示为Record有修改。 * @type Boolean */ dirty : false, editing : false, error: null, /** * * 该对象保存了所有修改过的字段的原始值数据(键和值key and Value)。 * 如果没有字段被修改的话,该值是null。 * @property modified * @type {Object} */ modified: null, // private join : function(store){ this.store = store; }, /** * 根据字段设置值。 * @param {String} name 字段名称的字符串 * @return {Object} 值 */ set : function(name, value){ if(String(this.data[name]) == String(value)){ return; } this.dirty = true; if(!this.modified){ this.modified = {}; } if(typeof this.modified[name] == 'undefined'){ this.modified[name] = this.data[name]; } this.data[name] = value; if(!this.editing && this.store){ this.store.afterEdit(this); } }, /** * 根据字段返回值。 * @param {String} name 字段名称的字符串 * @return {Object} 值 */ get : function(name){ return this.data[name]; }, /** * 开始进入编辑。编辑期间,没有与所在的store任何关联的事件。 */ beginEdit : function(){ this.editing = true; this.modified = {}; }, /** * 取消所有已修改过的数据。 */ cancelEdit : function(){ this.editing = false; delete this.modified; }, /** * 结束编辑。如数据有变动,则会通知所在的store。 */ endEdit : function(){ this.editing = false; if(this.dirty && this.store){ this.store.afterEdit(this); } }, /** * 这个方法通常给Record对象所在的那个{@link Ext.data.Store}对象调用。 * 创建Record、或上一次提交的操作都会使得Record对象执行reject撤销方法。 * 原始值会变化为已修改的值。 * <p> * 要根据提交(commit)操作而传达的通知,开发人员应该登记{@link Ext.data.Store#update}事件来编码来执行特定的撤销操作。</p> * @param {Boolean} silent (可选的)True表示不通知自身的store对象有所改变(默认为false) */ reject : function(silent){ var m = this.modified; for(var n in m){ if(typeof m[n] != "function"){ this.data[n] = m[n]; } } this.dirty = false; delete this.modified; this.editing = false; if(this.store && silent !== true){ this.store.afterReject(this); } }, /** * 这个方法通常给Record对象所在的那个{@link Ext.data.Store}对象调用。 * 创建Record、或上一次提交的操作都会使得Record对象执行commit提交方法。 * <p> * 要根据提交(commit)操作而传达的通知,开发人员应该登记{@link Ext.data.Store#update}事件来编码来执行特定的更新操作。</p> * @param {Boolean} silent (可选的) True表示不通知自身的store对象有所改变(默认为false) */ commit : function(silent){ this.dirty = false; delete this.modified; this.editing = false; if(this.store && silent !== true){ this.store.afterCommit(this); } }, /** * 该对象被创建或提交之后,用来获取字段的哈希值(hash) * @return Object */ getChanges : function(){ var m = this.modified, cs = {}; for(var n in m){ if(m.hasOwnProperty(n)){ cs[n] = this.data[n]; } } return cs; }, // private hasError : function(){ return this.error != null; }, // private clearError : function(){ this.error = null; }, /** * 创建记录的副本。 * @param {String} id (可选的)创建新的ID如果你不想在ID上也雷同 * @return {Record} */ copy : function(newId) { return new this.constructor(Ext.apply({}, this.data), newId || this.id); }, /** * 如果传入的字段是修改过的(load或上一次提交)就返回true。 * @param {String} fieldName * @return {Boolean} */ isModified : function(fieldName){ return !!(this.modified && this.modified.hasOwnProperty(fieldName)); } };
JavaScript
/** * @class Ext.StoreMgr * @extends Ext.util.MixedCollection * 缺省的全局store对象组 * @singleton */ Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), { /** * @cfg {Object} listeners @hide */ /** * 登记更多的Store对象到StoreMgr。一般情况下你不需要手动加入。任何透过{@link Ext.data.Store#storeId}初始化的Store都会自动登记。 * @param {Ext.data.Store} store1 Store实例 * @param {Ext.data.Store} store2 (可选的) * @param {Ext.data.Store} etc... (可选的) */ register : function(){ for(var i = 0, s; s = arguments[i]; i++){ this.add(s); } }, /** * 注销一个或多个Stores * @param {String/Object} id1 Store的id或是Store对象 * @param {String/Object} id2 (可选的) * @param {String/Object} etc... (可选的) */ unregister : function(){ for(var i = 0, s; s = arguments[i]; i++){ this.remove(this.lookup(s)); } }, /** * 由id返回一个已登记的Store * @param {String/Object} id Store的id或是Store对象 * @return {Ext.data.Store} */ lookup : function(id){ return typeof id == "object" ? id : this.get(id); }, // getKey implementation for MixedCollection getKey : function(o){ return o.storeId || o.id; } });
JavaScript
/** * @class Ext.data.SortTypes * @singleton * 定义一些缺省的比较函数,供排序时使用。 */ Ext.data.SortTypes = { /** * 默认的排序即什么也不做 * @param {Mixed} s 将被转换的值 * @return {Mixed} 用来比较的值 */ none : function(s){ return s; }, /** * 用来去掉标签的规则表达式 * @type {RegExp} * @property */ stripTagsRE : /<\/?[^>]+>/gi, /** * 去掉所有html标签来基于纯文本排序 * @param {Mixed} s 将被转换的值 * @return {String} 用来比较的值 */ asText : function(s){ return String(s).replace(this.stripTagsRE, ""); }, /** * 去掉所有html标签来基于无大小写区别的文本的排序 * @param {Mixed} s 将被转换的值 * @return {String} 所比较的值 */ asUCText : function(s){ return String(s).toUpperCase().replace(this.stripTagsRE, ""); }, /** * 无分大小写的字符串 * @param {Mixed} s 将被转换的值 * @return {String} 所比较的值 */ asUCString : function(s) { return String(s).toUpperCase(); }, /** * 对日期排序 * @param {Mixed} s 将被转换的值 * @return {Number} 所比较的值 */ asDate : function(s) { if(!s){ return 0; } if(s instanceof Date){ return s.getTime(); } return Date.parse(String(s)); }, /** * 浮点数的排序 * @param {Mixed} s 将被转换的值 * @return {Float} 所比较的值 */ asFloat : function(s) { var val = parseFloat(String(s).replace(/,/g, "")); if(isNaN(val)) val = 0; return val; }, /** * 整数的排序 * @param {Mixed} s 将被转换的值 * @return {Number} 所比较的值 */ asInt : function(s) { var val = parseInt(String(s).replace(/,/g, "")); if(isNaN(val)) val = 0; return val; } };
JavaScript
/** * @class Ext.data.JsonStore * @extends Ext.data.Store * 使得从远程JSON数据创建stores更为方便的简单辅助类。 * JsonStore合成了{@link Ext.data.HttpProxy}与{@link Ext.data.JsonReader}两者。 * 如果你需要其他类型的proxy或reader组合,那么你要创建以 {@link Ext.data.Store}为基类的配置。 * <br/> <pre><code> var store = new Ext.data.JsonStore({ url: 'get-images.php', root: 'images', fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}] }); </code></pre> * 形成这种形式的对象: <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> * 这种形式的数据(对象实字,object literal)会用在 {@link #data}配置项上。 * <b>注意:尽管未有列出,该类继承了Store对象、JsonReader对象的所有的配置项。</b> * @cfg {String} url HttpProxy对象的URL地址。可以从这里指定,也可以从{@link #data}配置中指定。不能缺少。 * @cfg {Object} data 能够被该对象所属的JsonReader解析的数据对象。可以从这里指定,也可以从{@link #url}配置中指定。不能缺少。 * @cfg {Array} fields 既可以是字段的定义对象组成的数组,会作为{@link Ext.data.Record#create}方法的参数用途,也可以是一个 * {@link Ext.data.Record Record}构造器,来给{@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象 * @constructor * @param {Object} config */ Ext.data.JsonStore = function(c){ /** * @cfg {Ext.data.DataReader} reader @hide */ /** * @cfg {Ext.data.DataProxy} proxy @hide */ Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(c, { proxy: c.proxy || (!c.data ? new Ext.data.HttpProxy({url: c.url}) : undefined), reader: new Ext.data.JsonReader(c, c.fields) })); }; Ext.extend(Ext.data.JsonStore, Ext.data.Store);
JavaScript
/** * @class Ext.data.Connection * @extends Ext.util.Observable * 此类封装了一个页面到当前域的连接,以响应(来自配置文件中的url或请求时指定的url)请求 * <p>通过该类产生的请求都是异步的,并且会立刻返回,紧根其后的{@link #request}调用将得不到数据 * 可以使用在request配置项一个回调函数,或事件临听器来处理返回来的数据。<br></p><br> * <p> * 注意:如果你正在上传文件,你将得不到一个正常的响应对象送回到你的回调或事件名柄中,原因是上传利用iframe来处理的. * 这里没有xmlhttpRequest对象。response对象是通过iframe的document的innerTHML作为responseText属性,如果存在, * 该iframe的xml document作为responseXML属性</p><p> * 这意味着一个有效的xml或html document必须被返回,如果需要json数据,这次意味着它将放到 * @constructor * @param {Object} config a configuration object. 配置对象 */ Ext.data.Connection = function(config){ Ext.apply(this, config); this.addEvents( /** * @ beforrequest * 在网络请求要求返回数据对象之前触发该事件 * @param {Connection} conn 该Connection对象 * @param {Object} options 传入{@link #request}方法的配置项对象 */ "beforerequest", /** * @ requestcomplete * 当请求成功完成时触发该事件 * @param {Connection} conn 该Connection对象 * @param {Object} response 包含返回数据的XHR对象。去{@link http://www.w3.org/TR/XMLHttpRequest/} 获取更多信息 * @param {Object} options 传入{@link #request}方法的配置对象 */ "requestcomplete", /** * @event requestexception * 当服务器端返回的错误http状态代码时触发该事件 * 去 {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} 获取更多关于HTTP status codes信息. * @param {Connection} conn 该Connection对象 * @param {Object} response 包含返回数据的XHR对象。到{@link http://www.w3.org/TR/XMLHttpRequest/} 获取更多信息. * @param {Object} 传入{@link #request}方法的配置对象. */ "requestexception" ); Ext.data.Connection.superclass.constructor.call(this); }; Ext.extend(Ext.data.Connection, Ext.util.Observable, { /** * @cfg {String} url (可选项) 被用来向服务发起请求默认的url,默认值为undefined */ /** * @cfg {Object} extraParams (可选项) 一个包含属性值的对象(这些属性在该Connection发起的每次请求中作为外部参数)。默认值为undefined */ /** * @cfg {Object} defaultHeaders (可选项) 一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中) 默认值为undefined */ /** * @cfg {String} method (可选项) 请求时使用的默认的http方法(默认为undefined;如果存在参数但没有设值.则值为post,否则为get) */ /** * @cfg {Number} timeout (可选项) 一次请求超时的毫秒数.(默认为30秒钟) */ timeout : 30000, /** * @cfg {Boolean} autoAbort (可选项) 该request是否应当中断挂起的请求.(默认值为false) * @type Boolean */ autoAbort:false, /** * @cfg {Boolean} disableCaching (可选项) 设置为true就会添加一个独一无二的cache-buster参数来获取请求(默认值为true) * @type Boolean */ disableCaching: true, /** * 向远程服务器发送一http请求 * @param {Object} options 包含如下属性的一对象<ul> * <li><b>url</b> {String} (可选项) 发送请求的url.默认为配置的url</li> * <li><b>params</b> {Object/String/Function} (可选项) 一包含属性的对象(这些属性被用作request的参数)或一个编码后的url字串或一个能调用其中任一一属性的函数.</li> * <li><b>method</b> {String} (可选项) 该请求所用的http方面,默认值为配置的方法,或者当没有方法被配置时,如果没有发送参数时用get,有参数时用post.</li> * <li><b>callback</b> {Function} (可选项) 该方法被调用时附上返回的http response 对象. * 不管成功还是失败,该回调函数都将被调用,该函数中传入了如下参数:<ul> * <li>options {Object} 该request调用的参数.</li> * <li>success {Boolean} 请求成功则为true.</li> * <li>response {Object} 包含返回数据的xhr对象.</li> * </ul></li> * <li><b>success</b> {Function} (可选项) 该函数被调用取决于请求成功. * 该回调函数被传入如下参数:<ul> * <li>response {Object} 包含了返回数据的xhr对象.</li> * <li>options {Object} 请求所调用的参数.</li> * </ul></li> * <li><b>failure</b> {Function} (可选项) 该函数被调用取决于请求失败. * 该回调函数被传入如下参数:<ul> * <li>response {Object} 包含了数据的xhr对象.</li> * <li>options {Object} 请求所调用的参数.</li> * </ul></li> * <li><b>scope</b> {Object} (可选项) 回调函数的作用域: "this" 指代回调函数本身 * 默认值为浏览器窗口</li> * <li><b>form</b> {Object/String} (可选项) 用来压入参数的一个form对象或 form的标识</li> * <li><b>isUpload</b> {Boolean} (可选项)如果该form对象是上传form,为true, (通常情况下会自动探测).</li> * <li><b>headers</b> {Object} (可选项) 为请求所加的请求头.</li> * <li><b>xmlData</b> {Object} (可选项) 用于发送的xml document.注意:它将会被用来在发送数据中代替参数 * 任务参数将会被追加在url中.</li> * <li><b>disableCaching</b> {Boolean} (可选项) 设置为True,则添加一个独一无二的 cache-buster参数来获取请求.</li> * </ul> */ request : function(o){ if(this.fireEvent("beforerequest", this, o) !== false){ var p = o.params; if(typeof p == "function"){ p = p.call(o.scope||window, o); } if(typeof p == "object"){ p = Ext.urlEncode(p); } if(this.extraParams){ var extras = Ext.urlEncode(this.extraParams); p = p ? (p + '&' + extras) : extras; } var url = o.url || this.url; if(typeof url == 'function'){ url = url.call(o.scope||window, o); } if(o.form){ var form = Ext.getDom(o.form); url = url || form.action; var enctype = form.getAttribute("enctype"); if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){ return this.doFormUpload(o, p, url); } var f = Ext.lib.Ajax.serializeForm(form); p = p ? (p + '&' + f) : f; } var hs = o.headers; if(this.defaultHeaders){ hs = Ext.apply(hs || {}, this.defaultHeaders); if(!o.headers){ o.headers = hs; } } var cb = { success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {options: o}, timeout : o.timeout || this.timeout }; var method = o.method||this.method||(p ? "POST" : "GET"); if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){ url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime()); } if(typeof o.autoAbort == 'boolean'){ // options gets top priority if(o.autoAbort){ this.abort(); } }else if(this.autoAbort !== false){ this.abort(); } if((method == 'GET' && p) || o.xmlData || o.jsonData){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; p = ''; } this.transId = Ext.lib.Ajax.request(method, url, cb, p, o); return this.transId; }else{ Ext.callback(o.callback, o.scope, [o, null, null]); return null; } }, /** * 确认该对象是否有正在的请求 * @param {Number} transactionId (可选项) 默认是最后一次通讯 * @return {Boolean} 如果这是个正在的请求的话,返回true. */ isLoading : function(transId){ if(transId){ return Ext.lib.Ajax.isCallInProgress(transId); }else{ return this.transId ? true : false; } }, /** * 中断任何正在的请求. * @param {Number} transactionId (或选项) 默认值为最后一次事务 */ abort : function(transId){ if(transId || this.isLoading()){ Ext.lib.Ajax.abort(transId || this.transId); } }, // private handleResponse : function(response){ this.transId = false; var options = response.argument.options; response.argument = options ? options.argument : null; this.fireEvent("requestcomplete", this, response, options); Ext.callback(options.success, options.scope, [response, options]); Ext.callback(options.callback, options.scope, [options, true, response]); }, // private handleFailure : function(response, e){ this.transId = false; var options = response.argument.options; response.argument = options ? options.argument : null; this.fireEvent("requestexception", this, response, options, e); Ext.callback(options.failure, options.scope, [response, options]); Ext.callback(options.callback, options.scope, [options, false, response]); }, // private doFormUpload : function(o, ps, url){ var id = Ext.id(); var frame = document.createElement('iframe'); frame.id = id; frame.name = id; frame.className = 'x-hidden'; if(Ext.isIE){ frame.src = Ext.SSL_SECURE_URL; } document.body.appendChild(frame); if(Ext.isIE){ document.frames[id].name = id; } var form = Ext.getDom(o.form); form.target = id; form.method = 'POST'; form.enctype = form.encoding = 'multipart/form-data'; if(url){ form.action = url; } var hiddens, hd; if(ps){ // add dynamic params hiddens = []; ps = Ext.urlDecode(ps, false); for(var k in ps){ if(ps.hasOwnProperty(k)){ hd = document.createElement('input'); hd.type = 'hidden'; hd.name = k; hd.value = ps[k]; form.appendChild(hd); hiddens.push(hd); } } } function cb(){ var r = { // bogus response object responseText : '', responseXML : null }; r.argument = o ? o.argument : null; try { // var doc; if(Ext.isIE){ doc = frame.contentWindow.document; }else { doc = (frame.contentDocument || window.frames[id].document); } if(doc && doc.body){ r.responseText = doc.body.innerHTML; } if(doc && doc.XMLDocument){ r.responseXML = doc.XMLDocument; }else { r.responseXML = doc; } } catch(e) { // ignore } Ext.EventManager.removeListener(frame, 'load', cb, this); this.fireEvent("requestcomplete", this, r, o); Ext.callback(o.success, o.scope, [r, o]); Ext.callback(o.callback, o.scope, [o, true, r]); setTimeout(function(){Ext.removeNode(frame);}, 100); } Ext.EventManager.on(frame, 'load', cb, this); form.submit(); if(hiddens){ // remove dynamic params for(var i = 0, len = hiddens.length; i < len; i++){ Ext.removeNode(hiddens[i]); } } } }); /** * @class Ext.Ajax * @extends Ext.data.Connection * Ext.Ajax类继承了Ext.data.Connection,为Ajax的请求提供了最大灵活性的操作方式。示例代码: * <pre><code> // Basic request Ext.Ajax.request({ url: 'foo.php', success: someFn, failure: otherFn, headers: { 'my-header': 'foo' }, params: { foo: 'bar' } }); // Simple ajax form submission Ext.Ajax.request({ form: 'some-form', params: 'foo=bar' }); // Default headers to pass in every request Ext.Ajax.defaultHeaders = { 'Powered-By': 'Ext' }; // Global Ajax events can be handled on every request! Ext.Ajax.on('beforerequest', this.showSpinner, this); </code></pre> * @singleton */ Ext.Ajax = new Ext.data.Connection({ /** * @cfg {String} url @hide */ /** * @cfg {String} url @hide */ /** * @cfg {Object} extraParams @hide */ /** * @cfg {Object} 外部参数 @hide */ /** * @cfg {Object} 默认请求头 @hide */ /** * @cfg {String} 请求的方法 (可选项) @hide */ /** * @cfg {Number} 超时时间 (可选项) @hide */ /** * @cfg {Boolean} 自动中断 (可选项) @hide */ /** * @cfg {Boolean} 不启用缓存 (可选项) @hide */ /** * @property disableCaching * 设置为true使得增加一cache-buster参数来获取请求. (默认为true) * @type Boolean */ /** * @property url * 默认的被用来向服务器发起请求的url. (默认为 undefined) * @type String */ /** * @property 外部参数 * 一个包含属性的对象(这些属性在该Connection发起的每次请求中作为外部参数) * @type Object */ /** * @property 默认的请求头 * 一个包含请求头信息的对象(此请求头被附加在该Connection对象的每次请求中) * @type Object */ /** * @property method * 请求时使用的默认的http方法(默认为undefined; * 如果存在参数但没有设值.则值为post,否则为get) * @type String */ /** * @property timeout * 请求的超时豪秒数. (默认为30秒) * @type Number */ /** * @property autoAbort * 该request是否应当中断挂起的请求.(默认值为false) * @type Boolean */ autoAbort : false, /** * 序列化传入的form为编码后的url字符串 * @param {String/HTMLElement} form * @return {String} */ serializeForm : function(form){ return Ext.lib.Ajax.serializeForm(form); } });
JavaScript
/** * @class Ext.data.SimpleStore * @extends Ext.data.Store * 使得从数组创建stores更为方便的简单辅助类。 * @cfg {Number} id 记录索引的数组ID。不填则自动生成 * @cfg {Array} fields 字段定义对象的数组,或字段名字符串 * @cfg {Array} data 多维数据数组 * @constructor * @param {Object} config */ Ext.data.SimpleStore = function(config){ Ext.data.SimpleStore.superclass.constructor.call(this, Ext.apply(config, { reader: new Ext.data.ArrayReader({ id: config.id }, Ext.data.Record.create(config.fields) ) })); }; Ext.extend(Ext.data.SimpleStore, Ext.data.Store, { loadData : function(data, append){ if(this.expandData === true){ var r = []; for(var i = 0, len = data.length; i < len; i++){ r[r.length] = [data[i]]; } data = r; } Ext.data.SimpleStore.superclass.loadData.call(this, data, append); } });
JavaScript
/** * @class Ext.data.JsonReader * @extends Ext.data.DataReader * Data reader类接受一个JSON响应结果后,创建一个由{@link Ext.data.Record}对象组成的数组, * 数组内的每个对象都是{@link Ext.data.Record}构造器负责映射(mappings)的结果。 * <br> * <p> * 示例代码: * <pre><code> var Employee = Ext.data.Record.create([ {name: 'firstname'}, // 映射了Record的"firstname" 字段为行对象的同名键名称 {name: 'job', mapping: 'occupation'} // 映射了"job"字段为行对象的"occupation"键 ]); var myReader = new Ext.data.JsonReader({ totalProperty: "results", // 该属性是指定记录集的总数(可选的) root: "rows", // 该属性是指定包含所有行对象的数组 id: "id" // 该属性是指定每一个行对象中究竟哪一个是记录的ID字段(可选的) }, Employee); </code></pre> * <p> * 形成这种形式的JSON对象: * <pre><code> { results: 2, rows: [ { id: 1, firstname: 'Bill', occupation: 'Gardener' }, // 行对象 { id: 2, firstname: 'Ben' , occupation: 'Horticulturalist' } // 另外一个行对象 ] } </code></pre> * <p> * 随时都可以改变JsonReader的元数据,只要在数据对象中放置一个<b><tt>metaData</tt></b>的属性。 * 一旦将该属性对象检测出来,就会触发Reader所使用的{@link Ext.data.Store Store}对象身上的{@link Ext.data.Store#metachange metachange}事件。</p> * <p>属性<b><tt>metaData</tt></b>可包含任何为该类服务的配置选项。 * 还可以包含<b><tt>fields</tt></b>的属性,会给JsonReader用作{@link Ext.data.Record#create}的参数,以便配置所产生的Records布局。<p> * 配合使用<b><tt>metaData</tt></b>属性,和Store的{@link Ext.data.Store#metachange metachange}事件, * 就可产生“基于Store”控制的自我初始化。 * metachange的处理函数会解析<b><tt>metaData</tt></b>属性(包含了任意的用户制定属性)来执行所需的配置操作, * 当然还有用于定义字段的<b><tt>metaData.fields</tt></b>数组。</p> * <p> * 要创建无须好像上一例那样配置的Record构造器的JsonReader对象,你可以采取这样的机制: * </p><pre><code> var myReader = new Ext.data.JsonReader(); </code></pre> * <p> * 可由数据库返回reader所需的配置信息,叫做metaData属性,只需要在第一次请求的时候返回便可,而且metaData属性可以实际数据并列放在一起: * </p><pre><code> { metaData: { totalProperty: 'results', root: 'rows', id: 'id', fields: [ {name: 'name'}, {name: 'occupation'} ] }, results: 2, rows: [ { 'id': 1, 'name': 'Bill', occupation: 'Gardener' }, { 'id': 2, 'name': 'Ben', occupation: 'Horticulturalist' } ] } </code></pre> * @cfg {String} totalProperty 记录集的总数的属性名称。如果是需要分页的话该属性就必须指定。 * @cfg {String} successProperty Name of the property from which to retrieve the success attribute used by forms. * @cfg {String} root 指定包含所有行对象的数组 * @cfg {String} id 指定每一个行对象中究竟哪一个是记录的ID字段(可选的) * @constructor * 创建JsonReader对象 * @param {Object} meta 元数据配置参数 * @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由 * {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象 */ Ext.data.JsonReader = function(meta, recordType){ meta = meta || {}; Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, { /** * 送入到构造器的JsonReader的元数据,或由数据包携带的<b><tt>metaData</tt></b>属性。 * @type Mixed * @property meta */ /** * 从远端服务器取得数据后,仅供DataProxy对象所使用的方法。 * @param {Object} response 包含JSON的数据在responseText属性的XHR的对象 * @return {Object} data 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存 */ read : function(response){ var json = response.responseText; var o = eval("("+json+")"); if(!o) { throw {message: "JsonReader.read: Json object not found"}; } return this.readRecords(o); }, // private function a store will implement onMetaChange : function(meta, recordType, o){ }, /** * @ignore */ simpleAccess: function(obj, subsc) { return obj[subsc]; }, /** * @ignore */ getJsonAccessor: function(){ var re = /[\[\.]/; return function(expr) { try { return(re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){ return obj[expr]; }; } catch(e){} return Ext.emptyFn; }; }(), /** * 由一个JSON对象产生一个包含Ext.data.Records的对象块。 * @param {Object} o 该对象包含以下属性:root指定包含所有行对象的数组;totalProperty制定了记录集的总数的属性名称(可选的) * @return {Object} data 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存 */ readRecords : function(o){ /** * 异步通信完毕后,保留原始JSON数据以便将来由必要的用途。如果没有数据加载,那么会抛出一个load异常,该属性为undefined。 * @type Object */ this.jsonData = o; if(o.metaData){ delete this.ef; this.meta = o.metaData; this.recordType = Ext.data.Record.create(o.metaData.fields); this.onMetaChange(this.meta, this.recordType, o); } var s = this.meta, Record = this.recordType, f = Record.prototype.fields, fi = f.items, fl = f.length; // Generate extraction functions for the totalProperty, the root, the id, and for each field if (!this.ef) { if(s.totalProperty) { this.getTotal = this.getJsonAccessor(s.totalProperty); } if(s.successProperty) { this.getSuccess = this.getJsonAccessor(s.successProperty); } this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;}; if (s.id) { var g = this.getJsonAccessor(s.id); this.getId = function(rec) { var r = g(rec); return (r === undefined || r === "") ? null : r; }; } else { this.getId = function(){return null;}; } this.ef = []; for(var i = 0; i < fl; i++){ f = fi[i]; var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name; this.ef[i] = this.getJsonAccessor(map); } } var root = this.getRoot(o), c = root.length, totalRecords = c, success = true; if(s.totalProperty){ var v = parseInt(this.getTotal(o), 10); if(!isNaN(v)){ totalRecords = v; } } if(s.successProperty){ var v = this.getSuccess(o); if(v === false || v === 'false'){ success = false; } } var records = []; for(var i = 0; i < c; i++){ var n = root[i]; var values = {}; var id = this.getId(n); for(var j = 0; j < fl; j++){ f = fi[j]; var v = this.ef[j](n); values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, n); } var record = new Record(values, id); record.json = n; records[i] = record; } return { success : success, records : records, totalRecords : totalRecords }; } });
JavaScript
/** * @class Ext.data.ArrayReader * @extends Ext.data.JsonReader * 这个Data reader透过一个数组的数据转化为{@link Ext.data.Record}对象组成的数组, * 数组内的每个元素代表一行数据。通过使用下标来把字段抽取到Record对象, * 字段定义中,属性<em>mapping</em>用于指定下标,如果不指定就按照定义的先后顺序。 * <br> * <p> * 示例代码: * <pre><code> var Employee = Ext.data.Record.create([ {name: 'name', mapping: 1}, // 属性<em>mapping</em>用于指定下标 {name: 'occupation', mapping: 2} // 如果不指定就按照定义的先后顺序 ]); var myReader = new Ext.data.ArrayReader({ id: 0 // 提供数组的下标位置存放记录的ID(可选的) }, Employee); </code></pre> * <p> * 形成这种形式的数组: * <pre><code> [ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ] </code></pre> * @cfg {String} id 提供数组的下标位置存放记录的ID(可选的) * @constructor * 创建一个ArrayReader对象 * @param {Object} meta 元数据配置参数 * @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由 * {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象 */ Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, { /** * 由一个数组产生一个包含Ext.data.Records的对象块。 * @param {Object} o 包含行对象的数组,就是记录集 * @return {Object} data 给Ext.data.Store对象用的数据块,Ext.data.Records会用它作为缓存 */ readRecords : function(o){ var sid = this.meta ? this.meta.id : null; var recordType = this.recordType, fields = recordType.prototype.fields; var records = []; var root = o; for(var i = 0; i < root.length; i++){ var n = root[i]; var values = {}; var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null); for(var j = 0, jlen = fields.length; j < jlen; j++){ var f = fields.items[j]; var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j; var v = n[k] !== undefined ? n[k] : f.defaultValue; v = f.convert(v, n); values[f.name] = v; } var record = new recordType(values, id); record.json = n; records[records.length] = record; } return { records : records, totalRecords : records.length }; } });
JavaScript
/** * @class Ext.data.DataReader * 用于读取结构化数据(来自数据源)然后转换为{@link Ext.data.Record}对象集合和元数据{@link Ext.data.Store}这二者合成的对象。 * 这个类应用于被扩展而最好不要直接使用。要了解当前的实现,可参阅{@link Ext.data.ArrayReader}, * {@link Ext.data.JsonReader}以及{@link Ext.data.XmlReader}。 * @constructor 创建DataReader对象 * @param {Object} meta 配置选项的元数据(由实现指定的) * @param {Object} recordType 既可以是字段的定义对象组成的数组,如{@link Ext.data.Record#create}那般,也可以是一个由 * {@link Ext.data.Record#create}创建的{@link Ext.data.Record}对象。 */ Ext.data.DataReader = function(meta, recordType){ /** * 送入构造器的DataReader的配置元数据。 * @type Mixed * @property meta */ this.meta = meta; this.recordType = Ext.isArray(recordType) ? Ext.data.Record.create(recordType) : recordType; }; Ext.data.DataReader.prototype = { };
JavaScript
/** * @class Ext.data.GroupingStore * @extends Ext.data.Store * 一个特殊的Store实现,提供由字段中提取某一个来划分记录的功能。 * @constructor * 创建一个新的GroupingStore对象。 * @param {Object} config 一配置对象,包含了Store用来访问数据,及读数据至Records的对象。 */ Ext.data.GroupingStore = Ext.extend(Ext.data.Store, { /** * @cfg {String} groupField * Store中哪一个字段的数据是要排序的(默认为"")。 */ /** * @cfg {Boolean} remoteGroup * True表示让服务端进行排序,false就表示本地排序(默认为false) * 如果是本地的排序,那么数据会立即发生变化。 * 如果是远程的, 那么这仅仅是一个辅助类,它会向服务器发出“groupBy”的参数。 */ remoteGroup : false, /** * @cfg {Boolean} groupOnSort * True表示为当分组操作发起时,在分组字段上进行数据排序,false表示为只根据当前排序的信息来排序。(默认为false). */ groupOnSort:false, /** * 清除当前的组,并使用默认排序来刷新数据。 */ clearGrouping : function(){ this.groupField = false; if(this.remoteGroup){ if(this.baseParams){ delete this.baseParams.groupBy; } this.reload(); }else{ this.applySort(); this.fireEvent('datachanged', this); } }, /** * 对特定的字段进行分组。 * @param {String} field Store中哪一个字段的数据是要排序的名称 * @param {Boolean} forceRegroup (可选的) True表示为强制必须刷新组,即使传入的组与当前在分组的字段同名;false表示跳过同名字段的分组。(默认为false) */ groupBy : function(field, forceRegroup){ if(this.groupField == field && !forceRegroup){ return; // already grouped by this field } this.groupField = field; if(this.remoteGroup){ if(!this.baseParams){ this.baseParams = {}; } this.baseParams['groupBy'] = field; } if(this.groupOnSort){ this.sort(field); return; } if(this.remoteGroup){ this.reload(); }else{ var si = this.sortInfo || {}; if(si.field != field){ this.applySort(); }else{ this.sortData(field); } this.fireEvent('datachanged', this); } }, // private applySort : function(){ Ext.data.GroupingStore.superclass.applySort.call(this); if(!this.groupOnSort && !this.remoteGroup){ var gs = this.getGroupState(); if(gs && gs != this.sortInfo.field){ this.sortData(this.groupField); } } }, // private applyGrouping : function(alwaysFireChange){ if(this.groupField !== false){ this.groupBy(this.groupField, true); return true; }else{ if(alwaysFireChange === true){ this.fireEvent('datachanged', this); } return false; } }, // private getGroupState : function(){ return this.groupOnSort && this.groupField !== false ? (this.sortInfo ? this.sortInfo.field : undefined) : this.groupField; } });
JavaScript
/** * @class Ext.data.HttpProxy * @extends Ext.data.DataProxy * 一个{@link Ext.data.DataProxy}所实现的子类,能从{@link Ext.data.Connection Connection}(针对某个URL地址)对象读取数据。<br> * <b> * 注意这个类不能跨域(Cross Domain)获取数据。<br> * 要进行跨域获取数据,请使用{@link Ext.data.ScriptTagProxy ScriptTagProxy}。</b><br> * <em>为了浏览器能成功解析返回来的XML document对象,HHTP Response的content-type 头必须被设成text/xml。</em> * @constructor * @param {Object} conn 一个{@link Ext.data.Connection}对象,或像{@link Ext.Ajax#request}那样的配置项。 * 如果是配置项,那么就会创建一个为这次请求服务的{@link Ext.Ajax}单件对象。 */ Ext.data.HttpProxy = function(conn){ Ext.data.HttpProxy.superclass.constructor.call(this); /** * Connection对象(或是{@link Ext.Ajax.request}配置项)。这个HttpProxy实例会使用这个Connection对象对服务端发起请求。 * 该对象的属性可能会随着请求的数据改变而改变。 * @property */ this.conn = conn; this.useAjax = !conn || !conn.events; /** * @event loadexception * Proxy在加载数据期间,有异常发生时就触发该事件。注意该事件是与{@link Ext.data.Store}对象联动的,所以你只监听其中一个事件就可以的了。 * @param {Object} this 此DataProxy 对象. * @param {Object} o 数据对象. * @param {Object} arg 传入{@link #load}函数的回调参数对象 * @param {Object} null 使用MemoryProxy的这就一直是null * @param {Error} e 如果Reader不能读取数据就抛出一个JavaScript Error对象 */ /** * @event loadexception * Fires if an exception occurs in the Proxy during data loading. This event can be fired for one of two reasons: * <ul><li><b>The load call returned success: false.</b> This means the server logic returned a failure * status and there is no data to read. In this case, this event will be raised and the * fourth parameter (read error) will be null.</li> * <li><b>The load succeeded but the reader could not read the response.</b> This means the server returned * data, but the configured Reader threw an error while reading the data. In this case, this event will be * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul> * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly * on any Store instance. * @param {Object} this * @param {Object} options The loading options that were specified (see {@link #load} for details) * @param {Object} response The XMLHttpRequest object containing the response data * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data. * If the load call returned success: false, this parameter will be null. */ }; Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, { /** * 返回这个Proxy所调用的{@link Ext.data.Connection}。 * @return {Connection} Connection对象。该对象可以被用来订阅事件,而且比DataProxy事件更细微的颗粒度 */ getConnection : function(){ return this.useAjax ? Ext.Ajax : this.conn; }, /** * 根据指定的URL位置加载数据 * 由指定的Ext.data.DataReader实例来解析这个Ext.data.Records块,并由指定的回调来处理这个块。 * @param {Object} params 一个对象,其属性用于向远端服务器作HTTP请求时所用的参数 * @param {Ext.data.DataReader} reader 能转换数据为Ext.data.Records块的Reader对象 * @param {Function} callback 会送入Ext.data.records块的函数。函数一定会传入:<ul> * <li>Record对象t</li> * <li>从load函数那里来的参数"arg"</li> * <li>是否成功的标识符</li> * </ul> * @param {Object} scope 回调函数的作用域 * @param {Object} arg 送入到回调函数的参数,在参数第二个位置中出现(可选的) */ load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var o = { params : params || {}, request: { callback : callback, scope : scope, arg : arg }, reader: reader, callback : this.loadResponse, scope: this }; if(this.useAjax){ Ext.applyIf(o, this.conn); if(this.activeRequest){ Ext.Ajax.abort(this.activeRequest); } this.activeRequest = Ext.Ajax.request(o); }else{ this.conn.request(o); } }else{ callback.call(scope||this, null, arg, false); } }, // private loadResponse : function(o, success, response){ delete this.activeRequest; if(!success){ this.fireEvent("loadexception", this, o, response); o.request.callback.call(o.request.scope, null, o.request.arg, false); return; } var result; try { result = o.reader.read(response); }catch(e){ this.fireEvent("loadexception", this, o, response, e); o.request.callback.call(o.request.scope, null, o.request.arg, false); return; } this.fireEvent("load", this, o, o.request.arg); o.request.callback.call(o.request.scope, result, o.request.arg, true); }, // private update : function(dataSet){ }, // private updateResponse : function(dataSet){ } });
JavaScript
/** * @class Ext.data.ScriptTagProxy * @extends Ext.data.DataProxy * 一个{@link Ext.data.DataProxy}所实现的子类,能从一个与本页不同的域的URL地址上读取数据对象。<br> * <p> * <b> * 注意如果你从与一个本页所在域不同的地方获取数据的话,应该使用这个类,而非HttpProxy。</b><br> * </p> * 服务端返回的<b>必须是</b>JSON格式的数据,这是因为ScriptTagProxy是把返回的数据放在一个&lt;script>标签中保存的。<br> * <p> * 为了浏览器能够自动处理返回的数据,服务器应该在打包数据对象的同时,指定一个回调函数的函数名称,这个名称从ScriptTagProxy发出的参数送出。 * 下面是一个Java中的Servlet例子,可适应ScriptTagProxy或者HttpProxy的情况,取决于是否有callback的参数送入: * </p> * <pre><code> boolean scriptTag = false; String cb = request.getParameter("callback"); if (cb != null) { scriptTag = true; response.setContentType("text/javascript"); } else { response.setContentType("application/x-json"); } Writer out = response.getWriter(); if (scriptTag) { out.write(cb + "("); } out.print(dataBlock.toJsonString()); if (scriptTag) { out.write(");"); } </code></pre> * * @constructor * @param {Object} config 配置项对象 */ Ext.data.ScriptTagProxy = function(config){ Ext.data.ScriptTagProxy.superclass.constructor.call(this); Ext.apply(this, config); this.head = document.getElementsByTagName("head")[0]; /** * @event loadexception * Fires if an exception occurs in the Proxy during data loading. This event can be fired for one of two reasons: * <ul><li><b>The load call timed out.</b> This means the load callback did not execute within the time limit * specified by {@link #timeout}. In this case, this event will be raised and the * fourth parameter (read error) will be null.</li> * <li><b>The load succeeded but the reader could not read the response.</b> This means the server returned * data, but the configured Reader threw an error while reading the data. In this case, this event will be * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul> * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly * on any Store instance. * @param {Object} this * @param {Object} options The loading options that were specified (see {@link #load} for details). If the load * call timed out, this parameter will be null. * @param {Object} arg The callback's arg object passed to the {@link #load} function * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data. * If the load call returned success: false, this parameter will be null. */ }; Ext.data.ScriptTagProxy.TRANS_ID = 1000; Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, { /** * @cfg {String} url 请求数据对象的URL地址 */ /** * @cfg {Number} timeout (optional) 响应的超时限制。默认为30秒 */ timeout : 30000, /** * @cfg {String} callbackParam * (可选的)这个值会作为参数传到服务端方面。默认是“callback”。 * 得到返回的数据后,客户端方面会执行callbackParam指定名称的函数,因此这个值必须要让服务端进行处理。这个函数将有一个唯一的参数,就是数据对象本身。 */ callbackParam : "callback", /** * @cfg {Boolean} nocache (可选的)默认值为true,在请求中添加一个独一无二的参数来禁用缓存 */ nocache : true, /** * 根据指定的URL位置加载数据 * 由指定的Ext.data.DataReader实例来解析这个Ext.data.Records块,并由指定的回调来处理这个块。 * @param {Object} params 一个对象,其属性用于向远端服务器作HTTP请求时所用的参数 * @param {Ext.data.DataReader} reader 能转换数据为Ext.data.Records块的Reader对象 * @param {Function} callback 会送入Ext.data.records块的函数。函数一定会传入这些参数:<ul> * <li>Record对象t</li> * <li>从load函数那里来的参数"arg"</li> * <li>是否成功的标识符</li> * </ul> * @param {Object} scope 回调函数的作用域 * @param {Object} arg 送入到回调函数的参数,在参数第二个位置中出现(可选的) */ load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var p = Ext.urlEncode(Ext.apply(params, this.extraParams)); var url = this.url; url += (url.indexOf("?") != -1 ? "&" : "?") + p; if(this.nocache){ url += "&_dc=" + (new Date().getTime()); } var transId = ++Ext.data.ScriptTagProxy.TRANS_ID; var trans = { id : transId, cb : "stcCallback"+transId, scriptId : "stcScript"+transId, params : params, arg : arg, url : url, callback : callback, scope : scope, reader : reader }; var conn = this; window[trans.cb] = function(o){ conn.handleResponse(o, trans); }; url += String.format("&{0}={1}", this.callbackParam, trans.cb); if(this.autoAbort !== false){ this.abort(); } trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]); var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("type", "text/javascript"); script.setAttribute("id", trans.scriptId); this.head.appendChild(script); this.trans = trans; }else{ callback.call(scope||this, null, arg, false); } }, // private isLoading : function(){ return this.trans ? true : false; }, /** * Abort the current server request. */ abort : function(){ if(this.isLoading()){ this.destroyTrans(this.trans); } }, // private destroyTrans : function(trans, isLoaded){ this.head.removeChild(document.getElementById(trans.scriptId)); clearTimeout(trans.timeoutId); if(isLoaded){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }else{ // if hasn't been loaded, wait for load to remove it to prevent script error window[trans.cb] = function(){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }; } }, // private handleResponse : function(o, trans){ this.trans = false; this.destroyTrans(trans, true); var result; try { result = trans.reader.readRecords(o); }catch(e){ this.fireEvent("loadexception", this, o, trans.arg, e); trans.callback.call(trans.scope||window, null, trans.arg, false); return; } this.fireEvent("load", this, o, trans.arg); trans.callback.call(trans.scope||window, result, trans.arg, true); }, // private handleFailure : function(trans){ this.trans = false; this.destroyTrans(trans, false); this.fireEvent("loadexception", this, null, trans.arg); trans.callback.call(trans.scope||window, null, trans.arg, false); } }); /** * @class Ext.data.ScriptTagProxy * @extends Ext.data.DataProxy * Ext.data.DataProxy实现类,从原始域(原始域指当前运行页所在的域)而是其它域读取数据对象<br><br> * <p> * <em>注意:如果你从一非本域运行的页面获取的数据与从本域获取数据不同,你必须使用此类来操作,而不是使用DataProxy.</em><br><br> * <p> * 被一ScriptTagProxy请求的从服务器资源传回的内容是可执行的javascript脚本,在<script>标签中被当作源.<br><br> * <p> * 为了使浏览器能处理返回的数据,服务器必须用对回调函数的调用来封装数据对象.它的名字为作为参数被scriptTagProxy传入 * 下面是一个java的小程序例子.它将返回数据到scriptTagProxy或httpProxy,取决于是否有回调函数名 * <p> * <pre><code> boolean scriptTag = false; String cb = request.getParameter("callback"); if (cb != null) { scriptTag = true; response.setContentType("text/javascript"); } else { response.setContentType("application/x-json"); } Writer out = response.getWriter(); if (scriptTag) { out.write(cb + "("); } out.print(dataBlock.toJsonString()); if (scriptTag) { out.write(");"); } </code></pre> * * @constructor * @param {Object} config 配置项对象 */ Ext.data.ScriptTagProxy = function(config){ Ext.data.ScriptTagProxy.superclass.constructor.call(this); Ext.apply(this, config); this.head = document.getElementsByTagName("head")[0]; }; Ext.data.ScriptTagProxy.TRANS_ID = 1000; Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, { /** * @cfg {String} url从该处请求数据的url. */ /** * @cfg {Number} timeout (可选项) 等待响应的毫秒数.默认为30秒 */ timeout : 30000, /** * @cfg {String} callbackParam (可选项) 传到服务器的参数的名字.通过这名字告诉服各器回调函数的名字,装载时装配该函数来 * 处理返回的数据对象,默认值为"callback". 服务器端处理必须读取该参数值.然后生成javascript输出.该javascript调用 * 该名字的函数作为自己的参数传递数据对象 */ callbackParam : "callback", /** * @cfg {Boolean} nocache (可选项) 默认值为true,添加一个独一无二的参数名到请求中来取消缓存 */ nocache : true, /** * 从配置的url中加载数据,使用传入的Ext.data.DataReader实现来读取数据对象到Ext.data.Records块中. * 并通过传入的回调函数处理该数据块 * @param {Object} params 一包含属性的对象,这些属性被用来当作向远程服务器发送的请求http 参数. * @param {Ext.data.DataReader} reader 转换数据对象到Ext.data.Records块的Reader对象. * @param {Function} callback 传入Ext.data.Record的函数. * 该函数必须被传入<ul> * <li>记录块对象</li> * <li>来自load函数的参数</li> * <li>布尔值的成功指示器</li> * </ul> * @param {Object} scope 回调函数的作用域 * @param {Object} arg 被传到回调函数中作为第二参数的可选参数. */ load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var p = Ext.urlEncode(Ext.apply(params, this.extraParams)); var url = this.url; url += (url.indexOf("?") != -1 ? "&" : "?") + p; if(this.nocache){ url += "&_dc=" + (new Date().getTime()); } var transId = ++Ext.data.ScriptTagProxy.TRANS_ID; var trans = { id : transId, cb : "stcCallback"+transId, scriptId : "stcScript"+transId, params : params, arg : arg, url : url, callback : callback, scope : scope, reader : reader }; var conn = this; window[trans.cb] = function(o){ conn.handleResponse(o, trans); }; url += String.format("&{0}={1}", this.callbackParam, trans.cb); if(this.autoAbort !== false){ this.abort(); } trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]); var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("type", "text/javascript"); script.setAttribute("id", trans.scriptId); this.head.appendChild(script); this.trans = trans; }else{ callback.call(scope||this, null, arg, false); } }, // private isLoading : function(){ return this.trans ? true : false; }, /** * Abort the current server request. */ abort : function(){ if(this.isLoading()){ this.destroyTrans(this.trans); } }, // private destroyTrans : function(trans, isLoaded){ this.head.removeChild(document.getElementById(trans.scriptId)); clearTimeout(trans.timeoutId); if(isLoaded){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }else{ // if hasn't been loaded, wait for load to remove it to prevent script error window[trans.cb] = function(){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }; } }, // private handleResponse : function(o, trans){ this.trans = false; this.destroyTrans(trans, true); var result; try { result = trans.reader.readRecords(o); }catch(e){ this.fireEvent("loadexception", this, o, trans.arg, e); trans.callback.call(trans.scope||window, null, trans.arg, false); return; } this.fireEvent("load", this, o, trans.arg); trans.callback.call(trans.scope||window, result, trans.arg, true); }, // private handleFailure : function(trans){ this.trans = false; this.destroyTrans(trans, false); this.fireEvent("loadexception", this, null, trans.arg); trans.callback.call(trans.scope||window, null, trans.arg, false); } });
JavaScript
/** * @class Ext.Window * @extends Ext.Panel * 一种特殊的面板,专用于程序中的"视窗"(window)。Windows默认下是 * 可拖动的、浮动的,并提供若干特定的行为如:最大化、复原(伴随最小化的 * 事件,由于最小化行为是应用程序指定的。Windows既可关联到 {@link Ext.WindowGroup} * 或由 {@link Ext.WindowManager} 管理,提供组(grouping),活动(activation),置前/置后(to front/back) * 和其它应用程序特定的功能. * @constructor * @param {Object} 配置项对象 */ Ext.Window = Ext.extend(Ext.Panel, { /** * @cfg {Boolean} modal * True 表示为当window显示时对其后面的一切内容进行遮罩,false表示为限制 * 对其它UI元素的语法 (默认为 false). */ /** * @cfg {String/Element} animateTarget * 当指定一个id或元素,window打开时会与元素之间产生动画效果(缺省为null即没有动画效果). */ /** * @cfg {String} resizeHandles * 一个有效的 {@link Ext.Resizable} 手柄的配置字符串(默认为 'all'). 只当 resizable = true时有效. */ /** * @cfg {Ext.WindowGroup} manager * 管理该window的WindowGroup引用(默认为 {@link Ext.WindowMgr}). */ /** * @cfg {String/Number/Button} defaultButton * 按钮的id / index或按钮实例,当window接收到焦点此按钮也会得到焦点. */ /** * @cfg {Function} onEsc * 允许重写该句柄以替代escape键的内建控制句柄.默认的动作句柄是关闭window * (执行 {@link #closeAction}所指的动作).若按下escape键不关闭window, * 可指定此项为 {@link Ext#emptyFn}). */ /** * @cfg {String} baseCls * 作用在面板元素上的CSS样式类(默认为 'x-window'). */ baseCls : 'x-window', /** * @cfg {Boolean} resizable * True 表示为允许用户从window的四边和四角改变window的大小(默认为 true). */ resizable:true, /** * @cfg {Boolean} draggable * True 表示为window可被拖动,false表示禁止拖动(默认为true).注意,默认下 * window会在视图中居中显示(因为可拖动),所以如果禁止可拖动的话意味着window * 生成之后应用一定代码定义(如 myWindow.setPosition(100, 100);). */ draggable:true, /** * @cfg {Boolean} closable * True 表示为显示 'close' 的工具按钮可让用户关闭window, * false表示为隐藏按钮,并不允许关闭window(默认为 true). */ closable : true, /** * @cfg {Boolean} constrain * True 表示为将window约束在视图中显示,false表示为允许 * window在视图之外的地方显示(默认为 false).可迭地设置 {@link #constrainHeader}. */ constrain:false, /** * @cfg {Boolean} constrainHeader * True 表示为将 window header约束在视图中显示, * false表示为允许header在视图之外的地方显示(默认为 false).可迭地设置{@link #constrain}. */ constrainHeader:false, /** * @cfg {Boolean} plain * True 表示为渲染window body的背景为透明的背景,这样看来window body * 与边框元素(framing elements)融为一体,false表示为加入浅色的背景, * 使得在视觉上body元素与外围边框清晰地分辨出来(默认为 false). */ plain:false, /** * @cfg {Boolean} minimizable * True 表示为显示'最小化minimize'的工具按钮,允许用户最小化window,false表示隐藏 * 按钮,禁止window最小化的功能(默认为 false),注意最小化window是实现具体特定的(implementation-specific), * 该按钮不提供最小化window的实现,所以必须提供一个最小化的事件来制定最小化的行为,这样该项 * 才有用的. */ minimizable : false, /** * @cfg {Boolean} maximizable * True 表示为显示'最大化maximize'的工具按钮,允许用户最大化window(默认为false) * 注意当window最大化时,这个工具按钮会自动变为'restore'按钮.相应的行为也变成内建的 * 复原(restore)行为,即window可回变之前的尺寸. */ maximizable : false, /** * @cfg {Number} minHeight * window高度的最小值,单位为象素(缺省为 100). 只当 resizable 为 true时有效. */ minHeight: 100, /** * @cfg {Number} minWidth * window宽度的最小值,单位为象素(缺省为 200). 只当 resizable 为 true时有效. */ minWidth: 200, /** * @cfg {Boolean} expandOnShow * True 表示为window显示时总是展开window,false则表示为按照 * 打开时的状态显示(有可能是闭合的)(默认为 true). */ expandOnShow: true, /** * @cfg {String} closeAction * 当关闭按钮被点击时执行的动作. 'close'缺省的动作是从DOM树 * 中移除window并彻底销毁.'hide'是另外一个有效的选项,只是在 * 视觉上通过偏移到零下(negative)的区域的手法来隐藏,这样使得 * window可通过{@link #show} 的方法再显示. */ closeAction: 'close', // inherited docs, same default collapsible:false, // private initHidden : true, /** * @cfg {Boolean} monitorResize @hide * This is automatically managed based on the value of constrain and constrainToHeader */ monitorResize : true, // The following configs are set to provide the basic functionality of a window. // Changing them would require additional code to handle correctly and should // usually only be done in subclasses that can provide custom behavior. Changing them // may have unexpected or undesirable results. /** @cfg {String} elements @hide */ elements: 'header,body', /** @cfg {Boolean} frame @hide */ frame:true, /** @cfg {Boolean} floating @hide */ floating:true, // private initComponent : function(){ Ext.Window.superclass.initComponent.call(this); this.addEvents( /** * @event activate * 当通过{@link setActive}的方法视觉上激活window后触发的事件。 * @param {Ext.Window} this */ /** * @event deactivate * 当通过{@link setActive}的方法视觉上使window不活动后触发的事件。 * @param {Ext.Window} this */ /** * @event resize * 调整window大小后触发 * @param {Ext.Window} this * @param {Number} width window的新宽度 * @param {Number} height window的新高度 */ 'resize', /** * @event maximize * 当window完成最大化后触发。 * @param {Ext.Window} this */ 'maximize', /** * @event maximize * 当window完成最小化后触发。 * @param {Ext.Window} this */ 'minimize', /** * @event restore * 当window复原到原始的尺寸大小时触发。 * @param {Ext.Window} this */ 'restore' ); }, // private getState : function(){ return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox()); }, // private onRender : function(ct, position){ Ext.Window.superclass.onRender.call(this, ct, position); if(this.plain){ this.el.addClass('x-window-plain'); } // this element allows the Window to be focused for keyboard events this.focusEl = this.el.createChild({ tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1", html: "&#160;"}); this.focusEl.swallowEvent('click', true); this.proxy = this.el.createProxy("x-window-proxy"); this.proxy.enableDisplayMode('block'); if(this.modal){ this.mask = this.container.createChild({cls:"ext-el-mask"}, this.el.dom); this.mask.enableDisplayMode("block"); this.mask.hide(); } }, // private initEvents : function(){ Ext.Window.superclass.initEvents.call(this); if(this.animateTarget){ this.setAnimateTarget(this.animateTarget); } if(this.resizable){ this.resizer = new Ext.Resizable(this.el, { minWidth: this.minWidth, minHeight:this.minHeight, handles: this.resizeHandles || "all", pinned: true, resizeElement : this.resizerAction }); this.resizer.window = this; this.resizer.on("beforeresize", this.beforeResize, this); } if(this.draggable){ this.header.addClass("x-window-draggable"); } this.initTools(); this.el.on("mousedown", this.toFront, this); this.manager = this.manager || Ext.WindowMgr; this.manager.register(this); this.hidden = true; if(this.maximized){ this.maximized = false; this.maximize(); } if(this.closable){ var km = this.getKeyMap(); km.on(27, this.onEsc, this); km.disable(); } }, initDraggable : function(){ this.dd = new Ext.Window.DD(this); }, // private onEsc : function(){ this[this.closeAction](); }, // private beforeDestroy : function(){ Ext.destroy( this.resizer, this.dd, this.proxy ); Ext.Window.superclass.beforeDestroy.call(this); }, // private onDestroy : function(){ if(this.manager){ this.manager.unregister(this); } Ext.Window.superclass.onDestroy.call(this); }, // private initTools : function(){ if(this.minimizable){ this.addTool({ id: 'minimize', handler: this.minimize.createDelegate(this, []) }); } if(this.maximizable){ this.addTool({ id: 'maximize', handler: this.maximize.createDelegate(this, []) }); this.addTool({ id: 'restore', handler: this.restore.createDelegate(this, []), hidden:true }); this.header.on('dblclick', this.toggleMaximize, this); } if(this.closable){ this.addTool({ id: 'close', handler: this[this.closeAction].createDelegate(this, []) }); } }, // private resizerAction : function(){ var box = this.proxy.getBox(); this.proxy.hide(); this.window.handleResize(box); return box; }, // private beforeResize : function(){ this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); // 40 is a magic minimum content size? this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40); this.resizeBox = this.el.getBox(); }, // private updateHandles : function(){ if(Ext.isIE && this.resizer){ this.resizer.syncHandleHeight(); this.el.repaint(); } }, // private handleResize : function(box){ var rz = this.resizeBox; if(rz.x != box.x || rz.y != box.y){ this.updateBox(box); }else{ this.setSize(box); } this.focus(); this.updateHandles(); this.saveState(); this.fireEvent("resize", this, box.width, box.height); }, /** * Focuses the window. If a defaultButton is set, it will receive focus, otherwise the * window itself will receive focus. */ /** * 焦点这个window. 若有defaultButton,它就会接送到一个焦点,否则是window本身接收到焦点. */ focus : function(){ var f = this.focusEl, db = this.defaultButton, t = typeof db; if(t != 'undefined'){ if(t == 'number'){ f = this.buttons[db]; }else if(t == 'string'){ f = Ext.getCmp(db); }else{ f = db; } } f.focus.defer(10, f); }, /** * 设置window目标动画元素,当window打开是产生动画效果. * @param {String/Element} el 目标元素或 id */ setAnimateTarget : function(el){ el = Ext.get(el); this.animateTarget = el; }, // private beforeShow : function(){ delete this.el.lastXY; delete this.el.lastLT; if(this.x === undefined || this.y === undefined){ var xy = this.el.getAlignToXY(this.container, 'c-c'); var pos = this.el.translatePoints(xy[0], xy[1]); this.x = this.x === undefined? pos.left : this.x; this.y = this.y === undefined? pos.top : this.y; } this.el.setLeftTop(this.x, this.y); if(this.expandOnShow){ this.expand(false); } if(this.modal){ Ext.getBody().addClass("x-body-masked"); this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.mask.show(); } }, /** * 显示window,或者会先进行渲染,或者会设为活动,又或者会从隐藏变为置顶显示. * @param {String/Element} animateTarget (可选的) window产生动画的那个目标元素 * 或id (默认为null即没有动画). * @param {Function} callback (可选的) window显示后执行的回调函数. * @param {Object} scope (可选的) 回调函数的作用域. */ show : function(animateTarget, cb, scope){ if(!this.rendered){ this.render(Ext.getBody()); } if(this.hidden === false){ this.toFront(); return; } if(this.fireEvent("beforeshow", this) === false){ return; } if(cb){ this.on('show', cb, scope, {single:true}); } this.hidden = false; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } this.beforeShow(); if(this.animateTarget){ this.animShow(); }else{ this.afterShow(); } }, // private afterShow : function(){ this.proxy.hide(); this.el.setStyle('display', 'block'); this.el.show(); if(this.maximized){ this.fitContainer(); } if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.onWindowResize(this.onWindowResize, this); } this.doConstrain(); if(this.layout){ this.doLayout(); } if(this.keyMap){ this.keyMap.enable(); } this.toFront(); this.updateHandles(); this.fireEvent("show", this); }, // private animShow : function(){ this.proxy.show(); this.proxy.setBox(this.animateTarget.getBox()); this.proxy.setOpacity(0); var b = this.getBox(false); b.callback = this.afterShow; b.scope = this; b.duration = .25; b.easing = 'easeNone'; b.opacity = .5; b.block = true; this.el.setStyle('display', 'none'); this.proxy.shift(b); }, /** * 隐藏 window, 设其为不可视并偏移到零下的区域. * @param {String/Element} animateTarget (可选的) window产生动画的那个目标元素 * 或id (默认为null即没有动画). * @param {Function} callback (可选的) window显示后执行的回调函数. * @param {Object} scope (可选的) 回调函数的作用域. */ hide : function(animateTarget, cb, scope){ if(this.hidden || this.fireEvent("beforehide", this) === false){ return; } if(cb){ this.on('hide', cb, scope, {single:true}); } this.hidden = true; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } if(this.animateTarget){ this.animHide(); }else{ this.el.hide(); this.afterHide(); } }, // private afterHide : function(){ this.proxy.hide(); if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.removeResizeListener(this.onWindowResize, this); } if(this.modal){ this.mask.hide(); Ext.getBody().removeClass("x-body-masked"); } if(this.keyMap){ this.keyMap.disable(); } this.fireEvent("hide", this); }, // private animHide : function(){ this.proxy.setOpacity(.5); this.proxy.show(); var tb = this.getBox(false); this.proxy.setBox(tb); this.el.hide(); var b = this.animateTarget.getBox(); b.callback = this.afterHide; b.scope = this; b.duration = .25; b.easing = 'easeNone'; b.block = true; b.opacity = 0; this.proxy.shift(b); }, // private onWindowResize : function(){ if(this.maximized){ this.fitContainer(); } if(this.modal){ this.mask.setSize('100%', '100%'); var force = this.mask.dom.offsetHeight; this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); } this.doConstrain(); }, // private doConstrain : function(){ if(this.constrain || this.constrainHeader){ var offsets; if(this.constrain){ offsets = { right:this.el.shadowOffset, left:this.el.shadowOffset, bottom:this.el.shadowOffset }; }else { var s = this.getSize(); offsets = { right:-(s.width - 100), bottom:-(s.height - 25) }; } var xy = this.el.getConstrainToXY(this.container, true, offsets); if(xy){ this.setPosition(xy[0], xy[1]); } } }, // private - used for dragging ghost : function(cls){ var ghost = this.createGhost(cls); var box = this.getBox(true); ghost.setLeftTop(box.x, box.y); ghost.setWidth(box.width); this.el.hide(); this.activeGhost = ghost; return ghost; }, // private unghost : function(show, matchPosition){ if(show !== false){ this.el.show(); this.focus(); } if(matchPosition !== false){ this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true)); } this.activeGhost.hide(); this.activeGhost.remove(); delete this.activeGhost; }, /** * window最小化方法的载体 (Placeholder),默认下,该方法简单地触发最小化事件,因为 * 最小化的行为是应用程序特定的,要实现自定义的最小化行为,应提供一个最小化事件句柄或重写该方法. */ minimize : function(){ this.fireEvent('minimize', this); }, /** * 关闭window,在DOM中移除并摧毁window对象.在关闭动作发生之前触发beforeclose事件, * 如返回false则取消close动作. */ close : function(){ if(this.fireEvent("beforeclose", this) !== false){ this.hide(null, function(){ this.fireEvent('close', this); this.destroy(); }, this); } }, /** * 自适应window尺寸到其当前的容器,并将'最大化'按钮换成'复原'按钮. */ maximize : function(){ if(!this.maximized){ this.expand(false); this.restoreSize = this.getSize(); this.restorePos = this.getPosition(true); this.tools.maximize.hide(); this.tools.restore.show(); this.maximized = true; this.el.disableShadow(); if(this.dd){ this.dd.lock(); } if(this.collapsible){ this.tools.toggle.hide(); } this.el.addClass('x-window-maximized'); this.container.addClass('x-window-maximized-ct'); this.setPosition(0, 0); this.fitContainer(); this.fireEvent('maximize', this); } }, /** * 把已最大化window复原到原始的尺寸,并将'复原'按钮换成'最大化'按钮. */ restore : function(){ if(this.maximized){ this.el.removeClass('x-window-maximized'); this.tools.restore.hide(); this.tools.maximize.show(); this.setPosition(this.restorePos[0], this.restorePos[1]); this.setSize(this.restoreSize.width, this.restoreSize.height); delete this.restorePos; delete this.restoreSize; this.maximized = false; this.el.enableShadow(true); if(this.dd){ this.dd.unlock(); } if(this.collapsible){ this.tools.toggle.show(); } this.container.removeClass('x-window-maximized-ct'); this.doConstrain(); this.fireEvent('restore', this); } }, /** * 根据当前window的最大化状态轮换 {@link #maximize} 和 {@link #restore} 的快捷方法. */ toggleMaximize : function(){ this[this.maximized ? 'restore' : 'maximize'](); }, // private fitContainer : function(){ var vs = this.container.getViewSize(); this.setSize(vs.width, vs.height); }, // private // z-index is managed by the WindowManager and may be overwritten at any time setZIndex : function(index){ if(this.modal){ this.mask.setStyle("z-index", index); } this.el.setZIndex(++index); index += 5; if(this.resizer){ this.resizer.proxy.setStyle("z-index", ++index); } this.lastZIndex = index; }, /** * 对齐window到特定的元素. * @param {Mixed} element 要对齐的元素. * @param {String} position 对齐的位置(参阅 {@link Ext.Element#alignTo} 细节). * @param {Array} offsets (可选的) 偏移位置 [x, y] * @return {Ext.Window} this */ alignTo : function(element, position, offsets){ var xy = this.el.getAlignToXY(element, position, offsets); this.setPagePosition(xy[0], xy[1]); return this; }, /** * 当window大小变化时或滚动时,固定此window到另外一个元素和重新对齐. * @param {Mixed} element 对齐的元素. * @param {String} position 对齐的位置(参阅 {@link Ext.Element#alignTo} 细节). * @param {Array} offsets (可选的) 偏移位置 [x, y] * @param {Boolean/Number} monitorScroll (可选的) true 表示为随着body的变化而重新 * 定位,如果此参数是一个数字,那么将用于缓冲的延时(默认为 50ms). * @return {Ext.Window} this */ anchorTo : function(el, alignment, offsets, monitorScroll, _pname){ var action = function(){ this.alignTo(el, alignment, offsets); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); this[_pname] = action; return this; }, /** * 使用window先于其它window显示. * @return {Ext.Window} this */ toFront : function(){ if(this.manager.bringToFront(this)){ this.focus(); } return this; }, /** * 激活此window并出现投影效果.或'反激活'并隐藏投影效果,此方法会触发相应的激活/反激活事件. * @param {Boolean} active True 表示为激活window(默认为 false) */ setActive : function(active){ if(active){ if(!this.maximized){ this.el.enableShadow(true); } this.fireEvent('activate', this); }else{ this.el.disableShadow(); this.fireEvent('deactivate', this); } }, /** * 让这个window居后显示(设其 z-index 稍低). * @return {Ext.Window} this */ toBack : function(){ this.manager.sendToBack(this); return this; }, /** * 使window在视图居中. * @return {Ext.Window} this */ center : function(){ var xy = this.el.getAlignToXY(this.container, 'c-c'); this.setPagePosition(xy[0], xy[1]); return this; } }); Ext.reg('window', Ext.Window); // private - custom Window DD implementation Ext.Window.DD = function(win){ this.win = win; Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-'+win.id); this.setHandleElId(win.header.id); this.scroll = false; }; Ext.extend(Ext.Window.DD, Ext.dd.DD, { moveOnly:true, headerOffsets:[100, 25], startDrag : function(){ var w = this.win; this.proxy = w.ghost(); if(w.constrain !== false){ var so = w.el.shadowOffset; this.constrainTo(w.container, {right: so, left: so, bottom: so}); }else if(w.constrainHeader !== false){ var s = this.proxy.getSize(); this.constrainTo(w.container, {right: -(s.width-this.headerOffsets[0]), bottom: -(s.height-this.headerOffsets[1])}); } }, b4Drag : Ext.emptyFn, onDrag : function(e){ this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY()); }, endDrag : function(e){ this.win.unghost(); this.win.saveState(); } });
JavaScript
/** * @class Ext.menu.Item * @extends Ext.menu.BaseItem * 所有与菜单功能相关的(如:子菜单)以及非静态显示的菜单项的基类。Item 类继承了 {@link Ext.menu.BaseItem} * 类的基本功能,并添加了菜单所特有的动作和点击事件的处理方法 * @constructor * 创建一个 Item 对象 * @param {Object} config 配置选项对象 */ Ext.menu.Item = function(config){ Ext.menu.Item.superclass.constructor.call(this, config); if(this.menu){ this.menu = Ext.menu.MenuMgr.get(this.menu); } }; Ext.extend(Ext.menu.Item, Ext.menu.BaseItem, { /** * @cfg {String} icon * 指定该菜单项显示的图标的路径(默认为 Ext.BLANK_IMAGE_URL)如果icon指定了{@link #iconCls}就不应存在 */ /** * @cfg {String} iconCls 定义了背景图的CSS样式类,用于该项的图标显示。(默认为 '') * 如果iconCls指定了{@link #icon}就不应存在 */ /** * @cfg {String} text 此项显示的文本 (默认为 ''). */ /** * @cfg {String} href 要使用的那个连接的href属性 (默认为 '#'). */ /** * @cfg {String} hrefTarget 要使用的那个连接的target属性 (defaults to ''). */ /** * @cfg {String} itemCls The 菜单项使用的默认CSS样式类(默认为 "x-menu-item") */ itemCls : "x-menu-item", /** * @cfg {Boolean} canActivate 值为 True 时该选项能够在可见的情况下被激活(默认为 true) */ canActivate : true, /** * @cfg {Number} showDelay 菜单项显示之前的延时时间(默认为200) */ showDelay: 200, // doc'd in BaseItem hideDelay: 200, // private ctype: "Ext.menu.Item", // private onRender : function(container, position){ var el = document.createElement("a"); el.hideFocus = true; el.unselectable = "on"; el.href = this.href || "#"; if(this.hrefTarget){ el.target = this.hrefTarget; } el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : ""); el.innerHTML = String.format( '<img src="{0}" class="x-menu-item-icon {2}" />{1}', this.icon || Ext.BLANK_IMAGE_URL, this.text, this.iconCls || ''); this.el = el; Ext.menu.Item.superclass.onRender.call(this, container, position); }, /** * 设置该菜单项显示的文本 * @param {String} text 显示的文本 */ setText : function(text){ this.text = text; if(this.rendered){ this.el.update(String.format( '<img src="{0}" class="x-menu-item-icon {2}">{1}', this.icon || Ext.BLANK_IMAGE_URL, this.text, this.iconCls || '')); this.parentMenu.autoWidth(); } }, /** * 把CSS样式类得效果应用在items的图标元素上 * @param {String} cls The CSS class to apply */ setIconClass : function(cls){ var oldCls = this.iconCls; this.iconCls = cls; if(this.rendered){ this.el.child('img.x-menu-item-icon').replaceClass(oldCls, this.iconCls); } }, // private handleClick : function(e){ if(!this.href){ // if no link defined, stop the event automatically e.stopEvent(); } Ext.menu.Item.superclass.handleClick.apply(this, arguments); }, // private activate : function(autoExpand){ if(Ext.menu.Item.superclass.activate.apply(this, arguments)){ this.focus(); if(autoExpand){ this.expandMenu(); } } return true; }, // private shouldDeactivate : function(e){ if(Ext.menu.Item.superclass.shouldDeactivate.call(this, e)){ if(this.menu && this.menu.isVisible()){ return !this.menu.getEl().getRegion().contains(e.getPoint()); } return true; } return false; }, // private deactivate : function(){ Ext.menu.Item.superclass.deactivate.apply(this, arguments); this.hideMenu(); }, // private expandMenu : function(autoActivate){ if(!this.disabled && this.menu){ clearTimeout(this.hideTimer); delete this.hideTimer; if(!this.menu.isVisible() && !this.showTimer){ this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]); }else if (this.menu.isVisible() && autoActivate){ this.menu.tryActivate(0, 1); } } }, // private deferExpand : function(autoActivate){ delete this.showTimer; this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu); if(autoActivate){ this.menu.tryActivate(0, 1); } }, // private hideMenu : function(){ clearTimeout(this.showTimer); delete this.showTimer; if(!this.hideTimer && this.menu && this.menu.isVisible()){ this.hideTimer = this.deferHide.defer(this.hideDelay, this); } }, // private deferHide : function(){ delete this.hideTimer; this.menu.hide(); } }); } }, // private deferHide : function(){ delete this.hideTimer; this.menu.hide(); } });
JavaScript
/** * @class Ext.menu.ColorMenu * @extends Ext.menu.Menu * 一个包含 {@link Ext.menu.ColorItem} 组件的菜单(提供了基本的颜色选择器)。 * @constructor * 创建一个 ColorMenu 对象 * @param {Object} config 配置选项对象 */ Ext.menu.ColorMenu = function(config){ Ext.menu.ColorMenu.superclass.constructor.call(this, config); this.plain = true; var ci = new Ext.menu.ColorItem(config); this.add(ci); /** * 该菜单中 {@link Ext.ColorPalette} 类的实例 * @type ColorPalette */ this.palette = ci.palette; /** * @event select * @param {ColorPalette} palette * @param {String} color */ this.relayEvents(ci, ["select"]); }; Ext.extend(Ext.menu.ColorMenu, Ext.menu.Menu);
JavaScript
/** * @class Ext.menu.DateItem * @extends Ext.menu.Adapter * 一个通过封装 {@link Ext.DatPicker} 组件而成的菜单项。 * @constructor * 创建一个 DateItem 对象 * @param {Object} config 配置选项对象 */ Ext.menu.DateItem = function(config){ Ext.menu.DateItem.superclass.constructor.call(this, new Ext.DatePicker(config), config); /** The Ext.DatePicker object @type Ext.DatePicker */ this.picker = this.component; this.addEvents('select'); this.picker.on("render", function(picker){ picker.getEl().swallowEvent("click"); picker.container.addClass("x-menu-date-item"); }); this.picker.on("select", this.onSelect, this); }; Ext.extend(Ext.menu.DateItem, Ext.menu.Adapter, { // private onSelect : function(picker, date){ this.fireEvent("select", this, date, picker); Ext.menu.DateItem.superclass.handleClick.call(this); } });
JavaScript
/** * @class Ext.menu.TextItem * @extends Ext.menu.BaseItem * 添加一个静态文本到菜单中,通常用来作为标题或者组分隔符。 * @constructor * 创建一个 TextItem 对象 * @param {String} text 要显示的文本 */ Ext.menu.TextItem = function(text){ this.text = text; Ext.menu.TextItem.superclass.constructor.call(this); }; Ext.extend(Ext.menu.TextItem, Ext.menu.BaseItem, { /** * @cfg {String} text 此项所显示的文本(默认为'') */ /** * @cfg {Boolean} hideOnClick 值为 True 时该项被点击后隐藏包含的菜单(默认为 false) */ hideOnClick : false, /** * @cfg {String} itemCls 文本项使用的默认CSS样式类(默认为 "x-menu-text") */ itemCls : "x-menu-text", // private onRender : function(){ var s = document.createElement("span"); s.className = this.itemCls; s.innerHTML = this.text; this.el = s; Ext.menu.TextItem.superclass.onRender.apply(this, arguments); } });
JavaScript
/** * @class Ext.menu.MenuMgr * 提供一个页面中所有菜单项的公共注册表,以便于能够很容易地通过ID来访问这些菜单对象。 * @singleton */ Ext.menu.MenuMgr = function(){ var menus, active, groups = {}, attached = false, lastShow = new Date(); // private - called when first menu is created function init(){ menus = {}; active = new Ext.util.MixedCollection(); Ext.getDoc().addKeyListener(27, function(){ if(active.length > 0){ hideAll(); } }); } // private function hideAll(){ if(active && active.length > 0){ var c = active.clone(); c.each(function(m){ m.hide(); }); } } // private function onHide(m){ active.remove(m); if(active.length < 1){ Ext.getDoc().un("mousedown", onMouseDown); attached = false; } } // private function onShow(m){ var last = active.last(); lastShow = new Date(); active.add(m); if(!attached){ Ext.getDoc().on("mousedown", onMouseDown); attached = true; } if(m.parentMenu){ m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3); m.parentMenu.activeChild = m; }else if(last && last.isVisible()){ m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3); } } // private function onBeforeHide(m){ if(m.activeChild){ m.activeChild.hide(); } if(m.autoHideTimer){ clearTimeout(m.autoHideTimer); delete m.autoHideTimer; } } // private function onBeforeShow(m){ var pm = m.parentMenu; if(!pm && !m.allowOtherMenus){ hideAll(); }else if(pm && pm.activeChild){ pm.activeChild.hide(); } } // private function onMouseDown(e){ if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){ hideAll(); } } // private function onBeforeCheck(mi, state){ if(state){ var g = groups[mi.group]; for(var i = 0, l = g.length; i < l; i++){ if(g[i] != mi){ g[i].setChecked(false); } } } } return { /** * 隐藏所有当前可见的菜单 */ hideAll : function(){ hideAll(); }, // private register : function(menu){ if(!menus){ init(); } menus[menu.id] = menu; menu.on("beforehide", onBeforeHide); menu.on("hide", onHide); menu.on("beforeshow", onBeforeShow); menu.on("show", onShow); var g = menu.group; if(g && menu.events["checkchange"]){ if(!groups[g]){ groups[g] = []; } groups[g].push(menu); menu.on("checkchange", onCheck); } }, /** * 返回一个 {@link Ext.menu.Menu} 对象 * @param {String/Object} menu 如果值为字符串形式的菜单ID,则返回存在的对象引用。如果是 Menu 类的配置选项对象,则被用来生成并返回一个新的 Menu 实例。 * @return {Ext.menu.Menu} 指定的菜单 */ get : function(menu){ if(typeof menu == "string"){ // menu id return menus[menu]; }else if(menu.events){ // menu instance return menu; }else if(typeof menu.length == 'number'){ // array of menu items? return new Ext.menu.Menu({items:menu}); }else{ // otherwise, must be a config return new Ext.menu.Menu(menu); } }, // private unregister : function(menu){ delete menus[menu.id]; menu.un("beforehide", onBeforeHide); menu.un("hide", onHide); menu.un("beforeshow", onBeforeShow); menu.un("show", onShow); var g = menu.group; if(g && menu.events["checkchange"]){ groups[g].remove(menu); menu.un("checkchange", onCheck); } }, // private registerCheckable : function(menuItem){ var g = menuItem.group; if(g){ if(!groups[g]){ groups[g] = []; } groups[g].push(menuItem); menuItem.on("beforecheckchange", onBeforeCheck); } }, // private unregisterCheckable : function(menuItem){ var g = menuItem.group; if(g){ groups[g].remove(menuItem); menuItem.un("beforecheckchange", onBeforeCheck); } }, getCheckedItem : function(groupId){ var g = groups[groupId]; if(g){ for(var i = 0, l = g.length; i < l; i++){ if(g[i].checked){ return g[i]; } } } return null; }, setCheckedItem : function(groupId, itemId){ var g = groups[groupId]; if(g){ for(var i = 0, l = g.length; i < l; i++){ if(g[i].id == itemId){ g[i].setChecked(true); } } } return null; } }; }();
JavaScript
/** * @class Ext.menu.CheckItem * @extends Ext.menu.Item * 添加一个默认为多选框的菜单选项,也可以是单选框组中的一个组员。 * @constructor * 创建一个 CheckItem 对象 * @param {Object} config 配置选项对象 */ Ext.menu.CheckItem = function(config){ Ext.menu.CheckItem.superclass.constructor.call(this, config); this.addEvents( /** * @event beforecheckchange * 在 checked 属性被设定之前触发,提供一次取消的机会(如果需要的话) * @param {Ext.menu.CheckItem} this * @param {Boolean} checked 将被设置的新的 checked 属性值 */ "beforecheckchange" , /** * @event checkchange * checked 属性被设置后触发 * @param {Ext.menu.CheckItem} this * @param {Boolean} checked 被设置的 checked 属性值 */ "checkchange" ); /** * 为checkchange事件准备的函数。 * 缺省下这个函数是不存在的,如实例有提供这个函数那么将登记到checkchange事件中,一触发该事件就会执行这个函数。 * @param {Ext.menu.CheckItem} this * @param {Boolean} checked 是否选中 * @method checkHandler */ if(this.checkHandler){ this.on('checkchange', this.checkHandler, this.scope); } Ext.menu.MenuMgr.registerCheckable(this); }; Ext.extend(Ext.menu.CheckItem, Ext.menu.Item, { /** * @cfg {String} group * 所有 group 设置相同的选择项将被自动地组织到一个单选按钮组中(默认为 '') */ /** * @cfg {String} itemCls 选择项使用的默认CSS样式类(默认为 "x-menu-item x-menu-check-item") */ itemCls : "x-menu-item x-menu-check-item", /** * @cfg {String} groupClass 单选框组中选择项使用的默认CSS样式类(默认为 "x-menu-group-item") */ groupClass : "x-menu-group-item", /** * @cfg {Boolean} checked 值为 True 时该选项初始为选中状态(默认为 false)。 * 注意:如果选择项为单选框组中的一员(group 为 true时)则只有最后的选择项才被初始为选中状态。 */ checked: false, // private ctype: "Ext.menu.CheckItem", // private onRender : function(c){ Ext.menu.CheckItem.superclass.onRender.apply(this, arguments); if(this.group){ this.el.addClass(this.groupClass); } if(this.checked){ this.checked = false; this.setChecked(true, true); } }, // private destroy : function(){ Ext.menu.MenuMgr.unregisterCheckable(this); Ext.menu.CheckItem.superclass.destroy.apply(this, arguments); }, /** * 设置该选项的 checked 属性状态 * @param {Boolean} checked 新的 checked 属性值 * @param {Boolean} suppressEvent (可选项) 值为 True 时将阻止 checkchange 事件的触发(默认为 false) */ setChecked : function(state, suppressEvent){ if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){ if(this.container){ this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked"); } this.checked = state; if(suppressEvent !== true){ this.fireEvent("checkchange", this, state); } } }, // private handleClick : function(e){ if(!this.disabled && !(this.checked && this.group)){// disable unselect on radio item this.setChecked(!this.checked); } Ext.menu.CheckItem.superclass.handleClick.apply(this, arguments); } });
JavaScript
/** * @class Ext.menu.Menu * @extends Ext.util.Observable * 一个菜单对象。它是所有你添加的菜单项的容器。Menu 类也可以当作是你根据其他组件生成的菜单的基类(例如:{@link Ext.menu.DateMenu})。 * @constructor * 创建一个 Menu 对象 * @param {Object} config 配置选项对象 */ Ext.menu.Menu = function(config){ if(config instanceof Array){ config = {items:config}; } Ext.apply(this, config); this.id = this.id || Ext.id(); this.addEvents( /** * @event beforeshow * 在该菜单显示之前触发 * @param {Ext.menu.Menu} this */ beforeshow : true, /** * @event beforehide * 在该菜单隐藏之前触发 * @param {Ext.menu.Menu} this */ beforehide : true, /** * @event show * 在该菜单显示之后触发 * @param {Ext.menu.Menu} this */ show : true, /** * @event hide * 在该菜单隐藏之后触发 * @param {Ext.menu.Menu} this */ hide : true, /** * @event click * 当点击该菜单时触发(或者当该菜单处于活动状态且回车键被按下时触发) * @param {Ext.menu.Menu} this * @param {Ext.menu.Item} menuItem 被点击的 Item 对象 * @param {Ext.EventObject} e */ click : true, /** * @event mouseover * 当鼠标经过该菜单时触发 * @param {Ext.menu.Menu} this * @param {Ext.EventObject} e * @param {Ext.menu.Item} menuItem 被点击的 Item 对象 */ mouseover : true, /** * @event mouseout * 当鼠标离开该菜单时触发 * @param {Ext.menu.Menu} this * @param {Ext.EventObject} e * @param {Ext.menu.Item} menuItem 被点击的 Item 对象 */ mouseout : true, /** * @event itemclick * 当该菜单所包含的菜单项被点击时触发 * @param {Ext.menu.BaseItem} baseItem 被点击的 BaseItem 对象 * @param {Ext.EventObject} e */ 'mouseout', /** * @event itemclick * 当此菜单的子菜单被点击时触发。 * @param {Ext.menu.BaseItem} baseItem 单击的BaseItem * @param {Ext.EventObject} e */ 'itemclick' ); Ext.menu.MenuMgr.register(this); Ext.menu.Menu.superclass.constructor.call(this); var mis = this.items; this.items = new Ext.util.MixedCollection(); if(mis){ this.add.apply(this, mis); } }; Ext.extend(Ext.menu.Menu, Ext.util.Observable, { /** * @cfg {Object} defaults * 作用到全体item的配置项对象,无论是通过{@link #items}定义的抑或是{@link #add}方法加入的。 * 默认配置项可以是任意数量的name/value组合,只要是能够被菜单使用的项就可以。 */ /** * @cfg {Mixed} items * 添加到菜单的Item,类型为Array。参阅 {@link #add}了解有效的类型。 */ /** * @cfg {Number} minWidth 以象素为单位设置的菜单最小宽度值(默认为 120) */ minWidth : 120, /** * @cfg {Boolean/String} shadow 当值为 True 或者 "sides" 时为默认效果,"frame" 时为4方向有阴影,"drop" 时为右下角有阴影(默认为 "sides") */ shadow : "sides", /** * @cfg {String} subMenuAlign 该菜单中子菜单的 {@link Ext.Element#alignTo} 定位锚点的值(默认为 "tl-tr?") */ subMenuAlign : "tl-tr?", /** * @cfg {String} defaultAlign 该菜单相对于它的原始元素的 {@link Ext.Element#alignTo) 定位锚点的默认值(默认为 "tl-bl?") */ defaultAlign : "tl-bl?", /** * @cfg {Boolean} allowOtherMenus 值为 True 时允许同时显示多个菜单(默认为 false) */ allowOtherMenus : false, hidden:true, createEl : function(){ return new Ext.Layer({ cls: "x-menu", shadow:this.shadow, constrain: false, parentEl: this.parentEl || document.body, zindex:15000 }); }, // private render : function(){ if(this.el){ return; } var el = this.el = this.createEl(); this.keyNav = new Ext.menu.MenuNav(this); if(this.plain){ el.addClass("x-menu-plain"); } if(this.cls){ el.addClass(this.cls); } // generic focus element this.focusEl = el.createChild({ tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1" }); var ul = el.createChild({tag: "ul", cls: "x-menu-list"}); ul.on("click", this.onClick, this); ul.on("mouseover", this.onMouseOver, this); ul.on("mouseout", this.onMouseOut, this); this.items.each(function(item){ var li = document.createElement("li"); li.className = "x-menu-list-item"; ul.dom.appendChild(li); item.render(li, this); }, this); this.ul = ul; this.autoWidth(); }, // private autoWidth : function(){ var el = this.el, ul = this.ul; if(!el){ return; } var w = this.width; if(w){ el.setWidth(w); }else if(Ext.isIE){ el.setWidth(this.minWidth); var t = el.dom.offsetWidth; // force recalc el.setWidth(ul.getWidth()+el.getFrameWidth("lr")); } }, // private delayAutoWidth : function(){ if(this.el){ if(!this.awTask){ this.awTask = new Ext.util.DelayedTask(this.autoWidth, this); } this.awTask.delay(20); } }, // private findTargetItem : function(e){ var t = e.getTarget(".x-menu-list-item", this.ul, true); if(t && t.menuItemId){ return this.items.get(t.menuItemId); } }, // private onClick : function(e){ var t; if(t = this.findTargetItem(e)){ t.onClick(e); this.fireEvent("click", this, t, e); } }, // private setActiveItem : function(item, autoExpand){ if(item != this.activeItem){ if(this.activeItem){ this.activeItem.deactivate(); } this.activeItem = item; item.activate(autoExpand); }else if(autoExpand){ item.expandMenu(); } }, // private tryActivate : function(start, step){ var items = this.items; for(var i = start, len = items.length; i >= 0 && i < len; i+= step){ var item = items.get(i); if(!item.disabled && item.canActivate){ this.setActiveItem(item, false); return item; } } return false; }, // private onMouseOver : function(e){ var t; if(t = this.findTargetItem(e)){ if(t.canActivate && !t.disabled){ this.setActiveItem(t, true); } } this.fireEvent("mouseover", this, e, t); }, // private onMouseOut : function(e){ var t; if(t = this.findTargetItem(e)){ if(t == this.activeItem && t.shouldDeactivate(e)){ this.activeItem.deactivate(); delete this.activeItem; } } this.fireEvent("mouseout", this, e, t); }, /** * 只读。如果当前显示的是该菜单则返回 true,否则返回 false。 * @type {Boolean} */ isVisible : function(){ return this.el && !this.hidden; }, /** * 相对于其他元素显示该菜单 * @param {Mixed} element 要对齐到的元素 * @param {String} position (可选) 对齐元素时使用的{@link Ext.Element#alignTo} 定位锚点(默认为 this.defaultAlign) * @param {Ext.menu.Menu} parentMenu (可选) 该菜单的父级菜单,如果有的话(默认为 undefined) */ show : function(el, pos, parentMenu){ this.parentMenu = parentMenu; if(!this.el){ this.render(); } this.fireEvent("beforeshow", this); this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false); }, /** * 在指定的位置显示该菜单 * @param {Array} xyPosition 显示菜单时所用的包含 X 和 Y [x, y] 的坐标值(坐标是基于页面的) * @param {Ext.menu.Menu} parentMenu (可选) 该菜单的父级菜单,如果有的话(默认为 undefined) */ showAt : function(xy, parentMenu, /* private: */_e){ this.parentMenu = parentMenu; if(!this.el){ this.render(); } if(_e !== false){ this.fireEvent("beforeshow", this); xy = this.el.adjustForConstraints(xy); } this.el.setXY(xy); this.el.show(); this.hidden = false; this.focus(); this.fireEvent("show", this); }, focus : function(){ if(!this.hidden){ this.doFocus.defer(50, this); } }, doFocus : function(){ if(!this.hidden){ this.focusEl.focus(); } }, /** * 隐藏该菜单及相关连的父级菜单 * @param {Boolean} deep (可选) 值为 True 时则递归隐藏所有父级菜单,如果有的话(默认为 false) */ hide : function(deep){ if(this.el && this.isVisible()){ this.fireEvent("beforehide", this); if(this.activeItem){ this.activeItem.deactivate(); this.activeItem = null; } this.el.hide(); this.hidden = true; this.fireEvent("hide", this); } if(deep === true && this.parentMenu){ this.parentMenu.hide(true); } }, /** * 添加一个或多个 Menu 类支持的菜单项,或者可以被转换为菜单项的对象。 * 满足下列任一条件即可: * <ul> * <li>任何基于 {@link Ext.menu.Item} 的菜单项对象</li> * <li>可以被转换为菜单项的 HTML 元素对象</li> * <li>可以被创建为一个菜单项对象的菜单项配置选项对象</li> * <li>任意字符串对象,值为 '-' 或 'separator' 时会在菜单中添加一个分隔栏,其他的情况下会被转换成为一个 {@link Ext.menu.TextItem} 对象并被添加到菜单中</li> * </ul> * 用法: * <pre><code> // 创建一个菜单 var menu = new Ext.menu.Menu(); // 通过构造方法创建一个菜单项 var menuItem = new Ext.menu.Item({ text: 'New Item!' }); // 通过不同的方法一次添加一组菜单项。 // 最后被添加的菜单项才会被返回。 var item = menu.add( menuItem, // 添加一个已经定义过的菜单项 'Dynamic Item', // 添加一个 TextItem 对象 '-', // 添加一个分隔栏 { text: 'Config Item' } // 由配置选项对象生成的菜单项 ); </code></pre> * @param {Mixed} args 一个或多个菜单项,菜单项配置选项或其他可以被转换为菜单项的对象 * @return {Ext.menu.Item} 被添加的菜单项,或者多个被添加的菜单项中的最后一个 */ add : function(){ var a = arguments, l = a.length, item; for(var i = 0; i < l; i++){ var el = a[i]; if(el.render){ // some kind of Item item = this.addItem(el); }else if(typeof el == "string"){ // string if(el == "separator" || el == "-"){ item = this.addSeparator(); }else{ item = this.addText(el); } }else if(el.tagName || el.el){ // element item = this.addElement(el); }else if(typeof el == "object"){ // must be menu item config? Ext.applyIf(el, this.defaults); item = this.addMenuItem(el); } } return item; }, /** * 返回该菜单所基于的 {@link Ext.Element} 对象 * @return {Ext.Element} 元素对象 */ getEl : function(){ if(!this.el){ this.render(); } return this.el; }, /** * 添加一个分隔栏到菜单 * @return {Ext.menu.Item} 被添加的菜单项 */ addSeparator : function(){ return this.addItem(new Ext.menu.Separator()); }, /** * 添加一个 {@link Ext.Element} 对象到菜单 * @param {Mixed} el 被添加的元素或者 DOM 节点,或者它的ID * @return {Ext.menu.Item} 被添加的菜单项 */ addElement : function(el){ return this.addItem(new Ext.menu.BaseItem(el)); }, /** * 添加一个已经存在的基于 {@link Ext.menu.Item} 的对象到菜单 * @param {Ext.menu.Item} item 被添加的菜单项 * @return {Ext.menu.Item} 被添加的菜单项 */ addItem : function(item){ this.items.add(item); if(this.ul){ var li = document.createElement("li"); li.className = "x-menu-list-item"; this.ul.dom.appendChild(li); item.render(li, this); this.delayAutoWidth(); } return item; }, /** * 根据给出的配置选项创建一个 {@link Ext.menu.Item} 对象并添加到菜单 * @param {Object} config 菜单配置选项对象 * @return {Ext.menu.Item} 被添加的菜单项 */ addMenuItem : function(config){ if(!(config instanceof Ext.menu.Item)){ if(typeof config.checked == "boolean"){ // must be check menu item config? config = new Ext.menu.CheckItem(config); }else{ config = new Ext.menu.Item(config); } } return this.addItem(config); }, /** * 根据给出的文本创建一个 {@link Ext.menu.Item} 对象并添加到菜单 * @param {String} text 菜单项中显示的文本 * @return {Ext.menu.Item} 被添加的菜单项 */ addText : function(text){ return this.addItem(new Ext.menu.TextItem(text)); }, /** * 在指定的位置插入一个已经存在的基于 {@link Ext.menu.Item} 的对象到菜单 * @param {Number} index 要插入的对象在菜单中菜单项列表的位置的索引值 * @param {Ext.menu.Item} item 要添加的菜单项 * @return {Ext.menu.Item} 被添加的菜单项 */ insert : function(index, item){ this.items.insert(index, item); if(this.ul){ var li = document.createElement("li"); li.className = "x-menu-list-item"; this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]); item.render(li, this); this.delayAutoWidth(); } return item; }, /** * 从菜单中删除并销毁一个 {@link Ext.menu.Item} 对象 * @param {Ext.menu.Item} item 要删除的菜单项 */ remove : function(item){ this.items.removeKey(item.id); item.destroy(); }, /** * 从菜单中删除并销毁所有菜单项 */ removeAll : function(){ var f; while(f = this.items.first()){ this.remove(f); } } }); //MenuNav 是一个由 Menu 使用的内部私有类 Ext.menu.MenuNav = function(menu){ Ext.menu.MenuNav.superclass.constructor.call(this, menu.el); this.scope = this.menu = menu; }; Ext.extend(Ext.menu.MenuNav, Ext.KeyNav, { doRelay : function(e, h){ var k = e.getKey(); if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){ this.menu.tryActivate(0, 1); return false; } return h.call(this.scope || this, e, this.menu); }, up : function(e, m){ if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){ m.tryActivate(m.items.length-1, -1); } }, down : function(e, m){ if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){ m.tryActivate(0, 1); } }, right : function(e, m){ if(m.activeItem){ m.activeItem.expandMenu(true); } }, left : function(e, m){ m.hide(); if(m.parentMenu && m.parentMenu.activeItem){ m.parentMenu.activeItem.activate(); } }, enter : function(e, m){ if(m.activeItem){ e.stopPropagation(); m.activeItem.onClick(e); m.fireEvent("click", this, m.activeItem); return true; } } });
JavaScript
/** * @class Ext.menu.DateMenu * @extends Ext.menu.Menu * 一个包含 {@link Ext.menu.DateItem} 组件的菜单(提供了日期选择器)。 * @constructor * 创建一个 DateMenu 对象 * @param {Object} config 配置选项对象 */ Ext.menu.DateMenu = function(config){ Ext.menu.DateMenu.superclass.constructor.call(this, config); this.plain = true; var di = new Ext.menu.DateItem(config); this.add(di); /** * 此菜单中 {@link Ext.DatePicker} 类的实例 * @type DatePicker */ this.picker = di.picker; /** * @event select * @param {DatePicker} picker * @param {Date} date */ this.relayEvents(di, ["select"]); this.on('beforeshow', function(){ if(this.picker){ this.picker.hideMonthPicker(true); } }, this); }; Ext.extend(Ext.menu.DateMenu, Ext.menu.Menu, { cls:'x-date-menu' });
JavaScript
/** * @class Ext.menu.BaseItem * @extends Ext.Component * 菜单组件中包含的所有选项的基类。BaseItem 提供默认的渲染、活动状态管理和由菜单组件共享的基本配置。 * @constructor * 创建一个 BaseItem 对象 * @param {Object} config 配置选项对象 */ Ext.menu.BaseItem = function(config){ Ext.menu.BaseItem.superclass.constructor.call(this, config); this.addEvents( /** * @event click * 当该选项被点击时触发 * @param {Ext.menu.BaseItem} this * @param {Ext.EventObject} e */ 'click', /** * @event activate * 当该选项被激活时触发 * @param {Ext.menu.BaseItem} this */ 'activate', /** * @event deactivate * 当该选项被释放里触发 * @param {Ext.menu.BaseItem} this */ 'deactivate' ); if(this.handler){ this.on("click", this.handler, this.scope); } }; Ext.extend(Ext.menu.BaseItem, Ext.Component, { /** * @cfg {Function} handler * 用来处理该选项单击事件的函数(默认为 undefined) */ /** * @cfg {Object} scope * 句柄函数内的作用域会被调用 */ /** * @cfg {Boolean} canActivate 值为 True 时该选项能够在可见的情况下被激活 */ canActivate : false, /** * @cfg {String} activeClass 当该选项成为激活状态时所使用的CSS样式类(默认为 "x-menu-item-active") */ activeClass : "x-menu-item-active", /** * @cfg {Boolean} hideOnClick 值为 True 时该选项单击后隐藏所包含的菜单(默认为 true) */ hideOnClick : true, /** * @cfg {Number} hideDelay 以毫秒为单位表示的单击后隐藏的延迟时间(默认为 100) */ hideDelay : 100, // private ctype: "Ext.menu.BaseItem", // private actionMode : "container", // private render : function(container, parentMenu){ this.parentMenu = parentMenu; Ext.menu.BaseItem.superclass.render.call(this, container); this.container.menuItemId = this.id; }, // private onRender : function(container, position){ this.el = Ext.get(this.el); container.dom.appendChild(this.el.dom); }, /** * 为该项设置单击事件的句柄(相当于传入一个{@link #handler}配置项属性) * 如果该句柄以登记,那么先会把它卸掉。 * @param {Function} handler 单击时所执行的函数 * @param {Object} scope 句柄所在的作用域 */ setHandler : function(handler, scope){ if(this.handler){ this.un("click", this.handler, this.scope); } this.on("click", this.handler = handler, this.scope = scope); }, // private onClick : function(e){ if(!this.disabled && this.fireEvent("click", this, e) !== false && this.parentMenu.fireEvent("itemclick", this, e) !== false){ this.handleClick(e); }else{ e.stopEvent(); } }, // private activate : function(){ if(this.disabled){ return false; } var li = this.container; li.addClass(this.activeClass); this.region = li.getRegion().adjust(2, 2, -2, -2); this.fireEvent("activate", this); return true; }, // private deactivate : function(){ this.container.removeClass(this.activeClass); this.fireEvent("deactivate", this); }, // private shouldDeactivate : function(e){ return !this.region || !this.region.contains(e.getPoint()); }, // private handleClick : function(e){ if(this.hideOnClick){ this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]); } }, // private expandMenu : function(autoActivate){ // do nothing }, // private hideMenu : function(){ // do nothing } });
JavaScript
/** * @class Ext.menu.ColorItem * @extends Ext.menu.Adapter * 一个通过封装 {@link Ext.ColorPalette} 组件而成的菜单项。 * @constructor * 创建一个 ColorItem 对象 * @param {Object} config 配置选项对象 */ Ext.menu.ColorItem = function(config){ Ext.menu.ColorItem.superclass.constructor.call(this, new Ext.ColorPalette(config), config); /** The Ext.ColorPalette object @type Ext.ColorPalette */ this.palette = this.component; this.relayEvents(this.palette, ["select"]); if(this.selectHandler){ this.on('select', this.selectHandler, this.scope); } }; Ext.extend(Ext.menu.ColorItem, Ext.menu.Adapter);
JavaScript
/** * @class Ext.menu.Adapter * @extends Ext.menu.BaseItem * 一个公共的基类,用来使原本无菜单的组件能够被菜单选项封装起来并被添加到菜单中去。 * 它提供了菜单组件所必须的基本的渲染、活动管理和启用/禁用逻辑功能。 * @constructor * 创建一个 Adapter 对象 * @param {Ext.Component} component 渲染到菜单的那个组件 * @param {Object} config 配置选项对象 */ Ext.menu.Adapter = function(component, config){ Ext.menu.Adapter.superclass.constructor.call(this, config); this.component = component; }; Ext.extend(Ext.menu.Adapter, Ext.menu.BaseItem, { // private canActivate : true, // private onRender : function(container, position){ this.component.render(container); this.el = this.component.getEl(); }, // private activate : function(){ if(this.disabled){ return false; } this.component.focus(); this.fireEvent("activate", this); return true; }, // private deactivate : function(){ this.fireEvent("deactivate", this); }, // private disable : function(){ this.component.disable(); Ext.menu.Adapter.superclass.disable.call(this); }, // private enable : function(){ this.component.enable(); Ext.menu.Adapter.superclass.enable.call(this); } });
JavaScript
/** * @class Ext.menu.Separator * @extends Ext.menu.BaseItem * 添加一个分隔栏到菜单中,用来区分菜单项的逻辑分组。通常你可以在调用 add()方法时或者在菜单项的配置选项中使用 "-" 参数直接创建一个分隔栏。 * @constructor * 创建一个Separator对象 * @param {Object} config 配置选项对象 */ Ext.menu.Separator = function(config){ Ext.menu.Separator.superclass.constructor.call(this, config); }; Ext.extend(Ext.menu.Separator, Ext.menu.BaseItem, { /** * @cfg {String} itemCls 分隔栏使用的默认CSS样式类(默认为 "x-menu-sep") */ itemCls : "x-menu-sep", /** * @cfg {Boolean} hideOnClick 值为 True 时该项被点击后隐藏包含的菜单(默认为 false) */ hideOnClick : false, // private onRender : function(li){ var s = document.createElement("span"); s.className = this.itemCls; s.innerHTML = "&#160;"; this.el = s; li.addClass("x-menu-sep-li"); Ext.menu.Separator.superclass.onRender.apply(this, arguments); } });
JavaScript
/** * @class Ext.Container * @extends Ext.BoxComponent * {@link Ext.BoxComponent}的子类,用于承载其它任何组件,容器负责一些基础性的行为,也就是装载子项、添加、插入和移除子项。 * 根据容纳子项的不同,所产生的可视效果,需委托任意布局类{@link #layout}中的一种来指点特定的布局逻辑(layout logic)。 * 此类被于继承而且一般情况下不应通过关键字new来直接实例化。 */ Ext.Container = Ext.extend(Ext.BoxComponent, { /** @cfg {Boolean} monitorResize * Ture表示为自动监视window resize的事件,以处理接下来一切的事情,包括对视见区(viewport)当前大小的感知,一般情况该值由{@link #layout}调控,而无须手动设置。 */ /** * @cfg {String} layout * 此容器所使用的布局类型。如不指定,则使用缺省的{@link Ext.layout.ContainerLayout}类型。 * 当中有效的值可以是:accordion、anchor、border、cavd、column、fit、form和table。 * 针对所选择布局类型,可指定{@link #layoutConfig}进一步配置。 */ /** * @cfg {Object} layoutConfig * 选定好layout布局后,其相应的配置属性就在这个对象上进行设置。 * (即与{@link #layout}配置联合使用)有关不同类型布局有效的完整配置信息,参阅对应的布局类: * <ul class="mdetail-params"> * <li>{@link Ext.layout.Accordion}</li> * <li>{@link Ext.layout.AnchorLayout}</li> * <li>{@link Ext.layout.BorderLayout}</li> * <li>{@link Ext.layout.CardLayout}</li> * <li>{@link Ext.layout.ColumnLayout}</li> * <li>{@link Ext.layout.FitLayout}</li> * <li>{@link Ext.layout.FormLayout}</li> * <li>{@link Ext.layout.TableLayout}</li></ul> */ /** * @cfg {Boolean/Number} bufferResize * When set to true (100 milliseconds) or a number of milliseconds, * 当设置为true(100毫秒)或输入一个毫秒数,为此容器所分配的布局会缓冲其计算的频率和缓冲组件的重新布局。 * 如容器包含大量的子组件或这样重型容器,在频繁进行高开销的布局时,该项尤为有用。 */ /** * @cfg {String/Number} activeItem * 组件id的字符串,或组件的索引,用于在容器布局渲染时候的设置为活动。例如,activeItem: 'item-1'或activeItem: 0 * index 0 = 容器集合中的第一项)。只有某些风格的布局可设置activeItem(如{@link Ext.layout.Accordion}、{@link Ext.layout.CardLayout}和 * {@link Ext.layout.FitLayout}),以在某个时刻中显示一项内容。相关内容请参阅{@link Ext.layout.ContainerLayout#activeItem}。 */ /** * @cfg {Mixed} items * 一个单独项,或子组件组成的数组,加入到此容器中。 * 每一项的对象类型是基于{@link Ext.Component}的<br><br> * 你可传入一个组件的配置对象即是lazy-rendering的做法,这样做的好处是组件不会立即渲染,减低直接构建组件对象带来的开销。 * 要发挥"lazy instantiation延时初始化"的特性,应对组件所属的登记类型的{@link Ext.Component#xtype}属性进行配置。<br><br> * 要了解所有可用的xtyps,可参阅{@link Ext.Component}。如传入的单独一个项,应直接传入一个对象的引用( * 如items: {...})。多个项应以数组的类型传入(如items: [{...}, {...}])。 */ /** * @cfg {Object} defaults * 应用在全体组件上的配置项对象,无论组件是由{@link #items}指定,抑或是通过{@link #add}、{@link #insert}的方法加入,都可支持。 * 缺省的配置可以是任意多个容器能识别的“名称/值”, * 假设要自动为每一个{@link Ext.Panel}项设置padding内补丁,你可以传入defaults: {bodyStyle:'padding:15px'}。 */ /** @cfg {Boolean} autoDestroy * 若为true容器会自动销毁容器下面全部的组件,否则的话必须手动执行销毁过程(默认为true)。 */ autoDestroy: true, /** @cfg {Boolean} hideBorders * True表示为隐藏容器下每个组件的边框,false表示保留组件现有的边框设置(默认为false)。 */ /** @cfg {String} defaultType * 容器的默认类型,用于在{@link Ext.ComponentMgr}中表示它的对象。(默认为'panel') */ defaultType: 'panel', // private initComponent : function(){ Ext.Container.superclass.initComponent.call(this); this.addEvents( /** * @event afterlayout * 由关联的布局管理器(layout manager)分配好容器上的组件后触发 * @param {Ext.Container} this * @param {ContainerLayout} layout 此容器的ContainerLayout实现。 */ 'afterlayout', /** * @event beforeadd * {@link Ext.Component}要加入或要插入到容器之前触发的事件 * @param {Ext.Container} this * @param {Ext.Component} component 要添加的组件 * @param {Number} index 组件将会加入到容器items集合中的那个索引。 */ 'beforeadd', /** * @event beforeremove * 任何从该容器身上移除{@link Ext.Component}之前触发的事件。若句柄返回false则取消移除。 * @param {Ext.Container} this * @param {Ext.Component} component 要被移除的组件 */ 'beforeremove', /** * @event add * {@link Ext.Component}加入或插入到容器成功后触发的事件 * @param {Ext.Container} this * @param {Ext.Component} component 已添加的组件 * @param {Number} index 组件加入到容器items集合中的索引。 */ 'add', /** * @event remove * 任何从该容器身上移除{@link Ext.Component}成功后触发的事件。 * @param {Ext.Container} this * @param {Ext.Component} component 被移除的组件对象 */ 'remove' ); /** * 此容器的组件集合,类型为{@link Ext.util.MixedCollection} * @type MixedCollection * @property items */ var items = this.items; if(items){ delete this.items; if(items instanceof Array){ this.add.apply(this, items); }else{ this.add(items); } } }, // private initItems : function(){ if(!this.items){ this.items = new Ext.util.MixedCollection(false, this.getComponentId); this.getLayout(); // initialize the layout } }, // private setLayout : function(layout){ if(this.layout && this.layout != layout){ this.layout.setContainer(null); } this.initItems(); this.layout = layout; layout.setContainer(this); }, // private render : function(){ Ext.Container.superclass.render.apply(this, arguments); if(this.layout){ if(typeof this.layout == 'string'){ this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig); } this.setLayout(this.layout); if(this.activeItem !== undefined){ var item = this.activeItem; delete this.activeItem; this.layout.setActiveItem(item); return; } } if(!this.ownerCt){ this.doLayout(); } if(this.monitorResize === true){ Ext.EventManager.onWindowResize(this.doLayout, this); } }, // protected - should only be called by layouts getLayoutTarget : function(){ return this.el; }, // private - used as the key lookup function for the items collection getComponentId : function(comp){ return comp.itemId || comp.id; }, /** * 把组件(omponent) 加入到此容器。在加入之前触发 beforeadd 事件和加入完毕后触发 add事件。 * 如果在容器已渲染后执行add方法(译注,如没渲染,即是属于lazy_rending状态,自由地调用add方法是无所谓的), * 你或许需要调用{@link #doLayout}的方法,刷新视图。 * 而多个子组件加入到布局,你只需执行一次这个方法。 * @param {Ext.Component/Object} component 欲加入的组件component。<br><br> * Ext采用延时渲染(lazy-rendering),加入的组件只有到了需要显示的时候才会被渲染出来。<br><br> * 你可传入一个组件的配置对象即是lazy-rendering的做法,这样做的好处是组件不会立即渲染,减低直接构建组件对象带来的开销。<br><br> * 要了解所有可用的xtyps,可参阅{@link Ext.Component}。 * 要发挥"lazy instantiation延时初始化"的特性,应对组件所属的登记类型的{@link Ext.Component#xtype}属性进行配置。 * @return {Ext.Component} component 包含容器缺省配置值的组件(或配置项对象)。 */ add : function(comp){ if(!this.items){ this.initItems(); } var a = arguments, len = a.length; if(len > 1){ for(var i = 0; i < len; i++) { this.add(a[i]); } return; } var c = this.lookupComponent(this.applyDefaults(comp)); var pos = this.items.length; if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){ this.items.add(c); c.ownerCt = this; this.fireEvent('add', this, c, pos); } return c; }, /** * 把插件(Component)插入到容器指定的位置(按索引)。 * 执行插入之前触发beforeadd事件,插入完毕触发add事件。 * @param {Number} index 组件插入到容器collection集合的索引 * @param {Ext.Component/Object} component 欲加入的组件component。<br><br> * Ext采用延时渲染(lazy-rendering),加入的组件只有到了需要显示的时候才会被渲染出来。<br><br> * 你可传入一个组件的配置对象即是lazy-rendering,这样做的好处是组件不会立即渲染 * 减低直接构建组件对象带来的开销。<br><br> * 要了解所有可用的xtyps,可参阅{@link Ext.Component}。 * 要发挥"lazy instantiation延时初始化"的特性,应对组件所属的登记类型的{@link Ext.Component#xtype}属性进行配置。 * @return {Ext.Component} component 包含容器缺省配置值的组件(或配置项对象)。 */ insert : function(index, comp){ if(!this.items){ this.initItems(); } var a = arguments, len = a.length; if(len > 2){ for(var i = len-1; i >= 1; --i) { this.insert(index, a[i]); } return; } var c = this.lookupComponent(this.applyDefaults(comp)); if(c.ownerCt == this && this.items.indexOf(c) < index){ --index; } if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){ this.items.insert(index, c); c.ownerCt = this; this.fireEvent('add', this, c, index); } return c; }, // private applyDefaults : function(c){ if(this.defaults){ if(typeof c == 'string'){ c = Ext.ComponentMgr.get(c); Ext.apply(c, this.defaults); }else if(!c.events){ Ext.applyIf(c, this.defaults); }else{ Ext.apply(c, this.defaults); } } return c; }, // private onBeforeAdd : function(item){ if(item.ownerCt){ item.ownerCt.remove(item, false); } if(this.hideBorders === true){ item.border = (item.border === true); } }, /** * 从此容器中移除某个组件。执行之前触发beforeremove事件,移除完毕后触发remove事件。 * @param {Component/String} component 组件的引用或其id * @param {Boolean} autoDestroy (可选的) True表示为自动执行组件{@link Ext.Component#destroy} 的函数。 */ remove : function(comp, autoDestroy){ var c = this.getComponent(comp); if(c && this.fireEvent('beforeremove', this, c) !== false){ this.items.remove(c); delete c.ownerCt; if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){ c.destroy(); } if(this.layout && this.layout.activeItem == c){ delete this.layout.activeItem; } this.fireEvent('remove', this, c); } return c; }, /** * 由id或索引直接返回容器的子组件。 * @param {String/Number} comp id子组件的id或index。 * @return Ext.Component */ getComponent : function(comp){ if(typeof comp == 'object'){ return comp; } return this.items.get(comp); }, // private lookupComponent : function(comp){ if(typeof comp == 'string'){ return Ext.ComponentMgr.get(comp); }else if(!comp.events){ return this.createComponent(comp); } return comp; }, // private createComponent : function(config){ return Ext.ComponentMgr.create(config, this.defaultType); }, /** * 重新计算容器的布局尺寸。当有新组件加入到已渲染容器或改变子组件的大小/位置之后,就需要执行此函数。 */ doLayout : function(){ if(this.rendered && this.layout){ this.layout.layout(); } if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++) { var c = cs[i]; if(c.doLayout){ c.doLayout(); } } } }, /** * 返回容器在使用的布局。 * 如没设置,会创建默认的{@link Ext.layout.ContainerLayout}作为容器的布局。 * @return {ContainerLayout} 容器的布局 */ getLayout : function(){ if(!this.layout){ var layout = new Ext.layout.ContainerLayout(this.layoutConfig); this.setLayout(layout); } return this.layout; }, // private onDestroy : function(){ if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++) { Ext.destroy(cs[i]); } } if(this.monitorResize){ Ext.EventManager.removeResizeListener(this.doLayout, this); } Ext.Container.superclass.onDestroy.call(this); }, /** * 逐层上报(Bubbles up)组件/容器,上报过程中对组件执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数传入或是当前组件(默认)函数的参数可经由args指定或当前组件提供, * 如果函数在某一个层次上返回false,上升将会停止。 * @param {Function} fn 调用的函数。 * @param {Object} scope (可选的) 函数的作用域(默认当前的点) * @param {Array} args (可选的) 函数将会传入的参数(默认为当前组件) */ bubble : function(fn, scope, args){ var p = this; while(p){ if(fn.apply(scope || p, args || [p]) === false){ break; } p = p.ownerCt; } }, /** * 逐层下报(Cascades down)组件/容器(从它开始),下报过程中对组件执行指定的函数。 * 函数的作用域(<i>this</i>)既可是参数传入或是当前组件(默认)函数的参数可经由args指定或当前组件提供, * 如果函数在某一个层次上返回false,下降将会停止。 * @param {Function} fn 调用的函数。 * @param {Object} scope (可选的) 函数的作用域(默认当前的点) * @param {Array} args (可选的) 函数将会传入的参数(默认为当前组件) */ cascade : function(fn, scope, args){ if(fn.apply(scope || this, args || [this]) !== false){ if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++){ if(cs[i].cascade){ cs[i].cascade(fn, scope, args); }else{ fn.apply(scope || this, args || [cs[i]]); } } } } }, /** * 在此容器之下由id查找任意层次的组件。 * @param {String} id * @return Ext.Component */ findById : function(id){ var m, ct = this; this.cascade(function(c){ if(ct != c && c.id === id){ m = c; return false; } }); return m || null; }, /** * 在此容器之下由xtype或类本身作搜索依据查找组件。 * @return {Array} Ext.Components数组 */ findByType : function(xtype){ return typeof xtype == 'function' ? this.findBy(function(c){ return c.constructor === xtype; }) : this.findBy(function(c){ return c.constructor.xtype === xtype; }); }, /** * 在此容器之下由属性作搜索依据查找组件。 * @param {String} prop * @param {String} value * @return {Array} Ext.Components数组 */ find : function(prop, value){ return this.findBy(function(c){ return c[prop] === value; }); }, /** * 在此容器之下由自定义的函数作搜索依据查找组件。 * 如函数返回true返回组件的结果。传入的函数会有(component, this container)的参数。 * @param {Function} fcn * @param {Object} scope (可选的) * @return {Array} Ext.Components数组 */ findBy : function(fn, scope){ var m = [], ct = this; this.cascade(function(c){ if(ct != c && fn.call(scope || c, c, ct) === true){ m.push(c); } }); return m; } }); Ext.Container.LAYOUTS = {}; Ext.reg('container', Ext.Container);
JavaScript
/** * @class Ext.DatePicker * @extends Ext.Component * 简单的日期选择类。 * @constructor * 创建一个 DatePicker 对象 * @param {Object} config 配置选项对象 */ Ext.DatePicker = Ext.extend(Ext.Component, { /** * @cfg {String} todayText * 显示在选择当前日期的按钮上的文本(默认为 "Today") */ todayText : "Today", /** * @cfg {String} okText * 显示在 ok 按钮上的文本 */ okText : "&#160;OK&#160;", // &#160; 用来给用户更多的点击空间 /** * @cfg {String} cancelText * 显示在 cancel 按钮上的文本 */ cancelText : "Cancel", /** * @cfg {String} todayTip * 选择当前日期的按钮的快捷提示(默认为 "{current date} (Spacebar)") */ todayTip : "{0} (Spacebar)", /** * @cfg {Date} minDate * 允许的最小日期(JavaScript 日期对象,默认为 null) */ minDate : null, /** * @cfg {Date} maxDate * 允许的最大日期(JavaScript 日期对象,默认为 null) */ maxDate : null, /** * @cfg {String} minText * minDate 效验失败时显示的错误文本(默认为 "This date is before the minimum date") */ minText : "This date is before the minimum date", /** * @cfg {String} maxText * maxDate 效验失败时显示的错误文本(默认为 "This date is after the maximum date") */ maxText : "This date is after the maximum date", /** * @cfg {String} format * 默认的日期格式化字串,可以被覆写以实现本地化支持。格式化字串必须为 {@link Date#parseDate} 中记载的有效格式(默认为 'm/d/y')。 */ format : "m/d/y", /** * @cfg {Array} disabledDays * 一个禁用星期数组,以 0 起始。例如:[0, 6] 表示禁用周日和周六(默认为 null)。 */ disabledDays : null, /** * @cfg {String} disabledDaysText * 当选中禁用星期时显示的错误文本(默认为 "") */ disabledDaysText : "", /** * @cfg {RegExp} disabledDatesRE * 一个用来表示禁用日期的 JavaScript 正则表达式(默认为 null) */ disabledDatesRE : null, /** * @cfg {String} disabledDatesText * 当选中禁用日期时显示的错误文本(默认为 "") */ disabledDatesText : "", /** * @cfg {Boolean} constrainToViewport * 值为 true 时强制日期选择器显示在 viewport 中(默认为 true) */ constrainToViewport : true, /** * @cfg {Array} monthNames * 月份名称数组,可以被覆写以实现本地化支持(默认为 Date.monthNames) */ monthNames : Date.monthNames, /** * @cfg {Array} dayNames * 星期名称数组,可以被覆写以实现本地化支持(默认为 Date.dayNames) */ dayNames : Date.dayNames, /** * @cfg {String} nextText * 下个月按钮的快捷提示(默认为 'Next Month (Control+Right)') */ nextText: 'Next Month (Control+Right)', /** * @cfg {String} prevText * 上个月按钮的快捷提示(默认为 'Previous Month (Control+Left)') */ prevText: 'Previous Month (Control+Left)', /** * @cfg {String} monthYearText * 月份选择器的快捷提示(默认为 'Choose a month (Control+Up/Down to move years)') */ monthYearText: 'Choose a month (Control+Up/Down to move years)', /** * @cfg {Number} startDay * 每周第一天的索引数,以 0 起始。(默认为 0,表示每周的第一天为周日) */ startDay : 0, initComponent : function(){ Ext.DatePicker.superclass.initComponent.call(this); this.value = this.value ? this.value.clearTime() : new Date().clearTime(); this.addEvents( /** * @event select * 选中日期时触发 * @param {DatePicker} this * @param {Date} date 选中的日期 */ 'select' ); if(this.handler){ this.on("select", this.handler, this.scope || this); } this.initDisabledDays(); }, // private initDisabledDays : function(){ if(!this.disabledDatesRE && this.disabledDates){ var dd = this.disabledDates; var re = "(?:"; for(var i = 0; i < dd.length; i++){ re += dd[i]; if(i != dd.length-1) re += "|"; } this.disabledDatesRE = new RegExp(re + ")"); } }, /** * 设置日期字段的值 * @param {Date} value 设置的日期 */ setValue : function(value){ var old = this.value; this.value = value.clearTime(true); if(this.el){ this.update(this.value); } }, /** * 获取当前日期字段中选中的值 * @return {Date} 选中的日期 */ getValue : function(){ return this.value; }, // private focus : function(){ if(this.el){ this.update(this.activeDate); } }, // private onRender : function(container, position){ var m = [ '<table cellspacing="0">', '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>', '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>']; var dn = this.dayNames; for(var i = 0; i < 7; i++){ var d = this.startDay+i; if(d > 6){ d = d-7; } m.push("<th><span>", dn[d].substr(0,1), "</span></th>"); } m[m.length] = "</tr></thead><tbody><tr>"; for(var i = 0; i < 42; i++) { if(i % 7 == 0 && i != 0){ m[m.length] = "</tr><tr>"; } m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>'; } m[m.length] = '</tr></tbody></table></td></tr><tr><td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>'; var el = document.createElement("div"); el.className = "x-date-picker"; el.innerHTML = m.join(""); container.dom.insertBefore(el, position); this.el = Ext.get(el); this.eventEl = Ext.get(el.firstChild); new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), { handler: this.showPrevMonth, scope: this, preventDefault:true, stopDefault:true }); new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), { handler: this.showNextMonth, scope: this, preventDefault:true, stopDefault:true }); this.eventEl.on("mousewheel", this.handleMouseWheel, this); this.monthPicker = this.el.down('div.x-date-mp'); this.monthPicker.enableDisplayMode('block'); var kn = new Ext.KeyNav(this.eventEl, { "left" : function(e){ e.ctrlKey ? this.showPrevMonth() : this.update(this.activeDate.add("d", -1)); }, "right" : function(e){ e.ctrlKey ? this.showNextMonth() : this.update(this.activeDate.add("d", 1)); }, "up" : function(e){ e.ctrlKey ? this.showNextYear() : this.update(this.activeDate.add("d", -7)); }, "down" : function(e){ e.ctrlKey ? this.showPrevYear() : this.update(this.activeDate.add("d", 7)); }, "pageUp" : function(e){ this.showNextMonth(); }, "pageDown" : function(e){ this.showPrevMonth(); }, "enter" : function(e){ e.stopPropagation(); return true; }, scope : this }); this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"}); this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this); this.el.unselectable(); this.cells = this.el.select("table.x-date-inner tbody td"); this.textNodes = this.el.query("table.x-date-inner tbody span"); this.mbtn = new Ext.Button({ text: "&#160;", tooltip: this.monthYearText, renderTo: this.el.child("td.x-date-middle", true) }); this.mbtn.on('click', this.showMonthPicker, this); this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu"); var today = (new Date()).dateFormat(this.format); var todayBtn = new Ext.Button({ renderTo: this.el.child("td.x-date-bottom", true), text: String.format(this.todayText, today), tooltip: String.format(this.todayTip, today), handler: this.selectToday, scope: this }); if(Ext.isIE){ this.el.repaint(); } this.update(this.value); }, createMonthPicker : function(){ if(!this.monthPicker.dom.firstChild){ var buf = ['<table border="0" cellspacing="0">']; for(var i = 0; i < 6; i++){ buf.push( '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>', '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>', i == 0 ? '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' : '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>' ); } buf.push( '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">', this.okText, '</button><button type="button" class="x-date-mp-cancel">', this.cancelText, '</button></td></tr>', '</table>' ); this.monthPicker.update(buf.join('')); this.monthPicker.on('click', this.onMonthClick, this); this.monthPicker.on('dblclick', this.onMonthDblClick, this); this.mpMonths = this.monthPicker.select('td.x-date-mp-month'); this.mpYears = this.monthPicker.select('td.x-date-mp-year'); this.mpMonths.each(function(m, a, i){ i += 1; if((i%2) == 0){ m.dom.xmonth = 5 + Math.round(i * .5); }else{ m.dom.xmonth = Math.round((i-1) * .5); } }); } }, showMonthPicker : function(){ this.createMonthPicker(); var size = this.el.getSize(); this.monthPicker.setSize(size); this.monthPicker.child('table').setSize(size); this.mpSelMonth = (this.activeDate || this.value).getMonth(); this.updateMPMonth(this.mpSelMonth); this.mpSelYear = (this.activeDate || this.value).getFullYear(); this.updateMPYear(this.mpSelYear); this.monthPicker.slideIn('t', {duration:.2}); }, updateMPYear : function(y){ this.mpyear = y; var ys = this.mpYears.elements; for(var i = 1; i <= 10; i++){ var td = ys[i-1], y2; if((i%2) == 0){ y2 = y + Math.round(i * .5); td.firstChild.innerHTML = y2; td.xyear = y2; }else{ y2 = y - (5-Math.round(i * .5)); td.firstChild.innerHTML = y2; td.xyear = y2; } this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel'); } }, updateMPMonth : function(sm){ this.mpMonths.each(function(m, a, i){ m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel'); }); }, selectMPMonth: function(m){ }, onMonthClick : function(e, t){ e.stopEvent(); var el = new Ext.Element(t), pn; if(el.is('button.x-date-mp-cancel')){ this.hideMonthPicker(); } else if(el.is('button.x-date-mp-ok')){ this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } else if(pn = el.up('td.x-date-mp-month', 2)){ this.mpMonths.removeClass('x-date-mp-sel'); pn.addClass('x-date-mp-sel'); this.mpSelMonth = pn.dom.xmonth; } else if(pn = el.up('td.x-date-mp-year', 2)){ this.mpYears.removeClass('x-date-mp-sel'); pn.addClass('x-date-mp-sel'); this.mpSelYear = pn.dom.xyear; } else if(el.is('a.x-date-mp-prev')){ this.updateMPYear(this.mpyear-10); } else if(el.is('a.x-date-mp-next')){ this.updateMPYear(this.mpyear+10); } }, onMonthDblClick : function(e, t){ e.stopEvent(); var el = new Ext.Element(t), pn; if(pn = el.up('td.x-date-mp-month', 2)){ this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } else if(pn = el.up('td.x-date-mp-year', 2)){ this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } }, hideMonthPicker : function(disableAnim){ if(this.monthPicker){ if(disableAnim === true){ this.monthPicker.hide(); }else{ this.monthPicker.slideOut('t', {duration:.2}); } } }, // private showPrevMonth : function(e){ this.update(this.activeDate.add("mo", -1)); }, // private showNextMonth : function(e){ this.update(this.activeDate.add("mo", 1)); }, // private showPrevYear : function(){ this.update(this.activeDate.add("y", -1)); }, // private showNextYear : function(){ this.update(this.activeDate.add("y", 1)); }, // private handleMouseWheel : function(e){ var delta = e.getWheelDelta(); if(delta > 0){ this.showPrevMonth(); e.stopEvent(); } else if(delta < 0){ this.showNextMonth(); e.stopEvent(); } }, // private handleDateClick : function(e, t){ e.stopEvent(); if(t.dateValue && !Ext.fly(t.parentNode).hasClass("x-date-disabled")){ this.setValue(new Date(t.dateValue)); this.fireEvent("select", this, this.value); } }, // private selectToday : function(){ this.setValue(new Date().clearTime()); this.fireEvent("select", this, this.value); }, // private update : function(date){ var vd = this.activeDate; this.activeDate = date; if(vd && this.el){ var t = date.getTime(); if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){ this.cells.removeClass("x-date-selected"); this.cells.each(function(c){ if(c.dom.firstChild.dateValue == t){ c.addClass("x-date-selected"); setTimeout(function(){ try{c.dom.firstChild.focus();}catch(e){} }, 50); return false; } }); return; } } var days = date.getDaysInMonth(); var firstOfMonth = date.getFirstDateOfMonth(); var startingPos = firstOfMonth.getDay()-this.startDay; if(startingPos <= this.startDay){ startingPos += 7; } var pm = date.add("mo", -1); var prevStart = pm.getDaysInMonth()-startingPos; var cells = this.cells.elements; var textEls = this.textNodes; days += startingPos; // convert everything to numbers so it's fast var day = 86400000; var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime(); var today = new Date().clearTime().getTime(); var sel = date.clearTime().getTime(); var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY; var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY; var ddMatch = this.disabledDatesRE; var ddText = this.disabledDatesText; var ddays = this.disabledDays ? this.disabledDays.join("") : false; var ddaysText = this.disabledDaysText; var format = this.format; var setCellClass = function(cal, cell){ cell.title = ""; var t = d.getTime(); cell.firstChild.dateValue = t; if(t == today){ cell.className += " x-date-today"; cell.title = cal.todayText; } if(t == sel){ cell.className += " x-date-selected"; setTimeout(function(){ try{cell.firstChild.focus();}catch(e){} }, 50); } // disabling if(t < min) { cell.className = " x-date-disabled"; cell.title = cal.minText; return; } if(t > max) { cell.className = " x-date-disabled"; cell.title = cal.maxText; return; } if(ddays){ if(ddays.indexOf(d.getDay()) != -1){ cell.title = ddaysText; cell.className = " x-date-disabled"; } } if(ddMatch && format){ var fvalue = d.dateFormat(format); if(ddMatch.test(fvalue)){ cell.title = ddText.replace("%0", fvalue); cell.className = " x-date-disabled"; } } }; var i = 0; for(; i < startingPos; i++) { textEls[i].innerHTML = (++prevStart); d.setDate(d.getDate()+1); cells[i].className = "x-date-prevday"; setCellClass(this, cells[i]); } for(; i < days; i++){ intDay = i - startingPos + 1; textEls[i].innerHTML = (intDay); d.setDate(d.getDate()+1); cells[i].className = "x-date-active"; setCellClass(this, cells[i]); } var extraDays = 0; for(; i < 42; i++) { textEls[i].innerHTML = (++extraDays); d.setDate(d.getDate()+1); cells[i].className = "x-date-nextday"; setCellClass(this, cells[i]); } this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear()); if(!this.internalRender){ var main = this.el.dom.firstChild; var w = main.offsetWidth; this.el.setWidth(w + this.el.getBorderWidth("lr")); Ext.fly(main).setWidth(w); this.internalRender = true; // opera does not respect the auto grow header center column // then, after it gets a width opera refuses to recalculate // without a second pass if(Ext.isOpera && !this.secondPass){ main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px"; this.secondPass = true; this.update.defer(10, this, [date]); } } } }); Ext.reg('datepicker', Ext.DatePicker);
JavaScript
/** * @class Ext.ProgressBar * @extends Ext.BoxComponent * <p> * 可更新进度条的组件。进度条支持两种不同的模式:手动的和自动的。</p> * <p>手动模式下,进度条的显示、更新(通过{@link #updateProgress})和清除这些任务便需要你代码的去完成。 * 此方法最适用于可实现预测点的操作显示进度条。</p> * <p>自动模式下,你只需要调用{@link #wait}并让进度条不停地运行下去,然后直到操作完成后停止进度条。另外一种用法是你让进度条显示一定的时间(wait方法),wait一定时间后停止显示进度。 * 自动模式最适用于已知时间的操作或不需要标识实际进度的异步操作。</p> * @cfg {Float} value 0到1区间的浮点数(例如:.5,默认为0) * @cfg {String} text 进度条提示的文本(默认为'') * @cfg {Mixed} textEl 负责进度条渲染的那个元素(默认为进度条内部文本元素) * @cfg {String} id 进度条元素的Id(默认为自动生成的id) */ Ext.ProgressBar = Ext.extend(Ext.BoxComponent, { /** * @cfg {String} baseCls * 进度条外层元素所使用的CSS样式类基类(默认为'x-progress') */ baseCls : 'x-progress', // private waitTimer : null, // private initComponent : function(){ Ext.ProgressBar.superclass.initComponent.call(this); this.addEvents( /** * @event update * 每一次更新就触发该事件 * @param {Ext.ProgressBar} this * @param {Number} value 当前进度条的值 * @param {String} text 当前进度条的提示文字 */ "update" ); }, // private onRender : function(ct, position){ Ext.ProgressBar.superclass.onRender.call(this, ct, position); var tpl = new Ext.Template( '<div class="{cls}-wrap">', '<div class="{cls}-inner">', '<div class="{cls}-bar">', '<div class="{cls}-text">', '<div>&#160;</div>', '</div>', '</div>', '<div class="{cls}-text {cls}-text-back">', '<div>&#160;</div>', '</div>', '</div>', '</div>' ); if(position){ this.el = tpl.insertBefore(position, {cls: this.baseCls}, true); }else{ this.el = tpl.append(ct, {cls: this.baseCls}, true); } if(this.id){ this.el.dom.id = this.id; } var inner = this.el.dom.firstChild; this.progressBar = Ext.get(inner.firstChild); if(this.textEl){ //use an external text el this.textEl = Ext.get(this.textEl); delete this.textTopEl; }else{ //setup our internal layered text els this.textTopEl = Ext.get(this.progressBar.dom.firstChild); var textBackEl = Ext.get(inner.childNodes[1]); this.textTopEl.setStyle("z-index", 99).addClass('x-hidden'); this.textEl = new Ext.CompositeElement([this.textTopEl.dom.firstChild, textBackEl.dom.firstChild]); this.textEl.setWidth(inner.offsetWidth); } if(this.value){ this.updateProgress(this.value, this.text); }else{ this.updateText(this.text); } this.setSize(this.width || 'auto', 'auto'); this.progressBar.setHeight(inner.offsetHeight); }, /** * 更新进度条的刻度值,也可以更新提示文本。如果文本的参数没传入,那么当前的文本将不会有变化。 * 要取消当前文本,传入''。注意即使进度条的值溢出(大于1),也不会自动复位,这样你就要确定进度是何时完成然后调用{@link #reset}停止或隐藏控件。 * @param {Float} value (可选的) 介乎0与1之间浮点数(如.5,默认为零) * @param {String} text (可选的) 显示在进度条提示文本元素的字符串(默认为'') * @return {Ext.ProgressBar} this */ updateProgress : function(value, text){ this.value = value || 0; if(text){ this.updateText(text); } var w = Math.floor(value*this.el.dom.firstChild.offsetWidth); this.progressBar.setWidth(w); if(this.textTopEl){ //textTopEl should be the same width as the bar so overflow will clip as the bar moves this.textTopEl.removeClass('x-hidden').setWidth(w); } this.fireEvent('update', this, value, text); return this; }, /** * 初始化一个自动更新的进度条。 * 如果有duration的参数传入,那么代表进度条会运行到一定的时间后停止(自动调用reset方法),并若然有指定一个回调函数,也会执行。 * 如果duration的参数不传入,那么进度条将会不停地运行下去,这样你就要调用{@link #reset}的方法停止他。wait方法可接受以下属性的配置对象: * <pre> 属性 类型 内容 ---------- ------------ ---------------------------------------------------------------------- duration Number 进度条运作时间的长度,单位是毫秒,跑完后执行自身的复位方法(默认为undefined,即不断地运行除非执行reset方法结束) interval Number 每次更新的间隔周期(默认为1000毫秒) increment Number 进度条每次更新的幅度大小(默认为10)。如果进度条达到最后,那么它会回到原点。 fn Function 当进度条完成自动更新后执行的回调函数。该函数没有参数。如不指定duration该项自动忽略,这样进度条只能写代码结束更新 scope Object 回调函数的作用域(只当duration与fn两项都传入时有效) </pre> * * 用法举例: * <pre><code> var p = new Ext.ProgressBar({ renderTo: 'my-el' }); //等待五秒,然后更新状态元素(进度条会自动复位) p.wait({ interval: 100, //非常快地移动! duration: 5000, increment: 15, scope: this, fn: function(){ Ext.fly('status').update('完成了!'); } }); //一种情况是,不停的更新直到有手工的操作控制结束。 p.wait(); myAction.on('complete', function(){ p.reset(); Ext.fly('status').update('完成了!'); }); </code></pre> * @param {Object} config (可选的)配置项对象 * @return {Ext.ProgressBar} this */ wait : function(o){ if(!this.waitTimer){ var scope = this; o = o || {}; this.waitTimer = Ext.TaskMgr.start({ run: function(i){ var inc = o.increment || 10; this.updateProgress(((((i+inc)%inc)+1)*(100/inc))*.01); }, interval: o.interval || 1000, duration: o.duration, onStop: function(){ if(o.fn){ o.fn.apply(o.scope || this); } this.reset(); }, scope: scope }); } return this; }, /** * 返回进度条当前是否在{@link #wait}的操作中。 * @return {Boolean} True表示在等待,false反之 */ isWaiting : function(){ return this.waitTimer != null; }, /** * 更新进度条的提示文本。 如传入text参数,textEl会更新其内容,否则进度条本身会显示已更新的文本。 * @param {String} text (可选的)显示的字符串(默认为'') * @return {Ext.ProgressBar} this */ updateText : function(text){ this.text = text || '&#160;'; this.textEl.update(this.text); return this; }, /** * 设置进度条的尺寸大小。 * @param {Number} width 新宽度(像素) * @param {Number} height 新高度(像素) * @return {Ext.ProgressBar} this */ setSize : function(w, h){ Ext.ProgressBar.superclass.setSize.call(this, w, h); if(this.textTopEl){ var inner = this.el.dom.firstChild; this.textEl.setSize(inner.offsetWidth, inner.offsetHeight); } return this; }, /** * 将进度条的刻度复位为零并将提示文本设置为空白字符串。如果hide=true,那么进度条会被隐藏(根据在内部的{@link #hideMode}属性)。 * @param {Boolean} hide (可选的)True表示隐藏进度条(默认为false) * @return {Ext.ProgressBar} this */ reset : function(hide){ this.updateProgress(0); if(this.textTopEl){ this.textTopEl.addClass('x-hidden'); } if(this.waitTimer){ this.waitTimer.onStop = null; //prevent recursion Ext.TaskMgr.stop(this.waitTimer); this.waitTimer = null; } if(hide === true){ this.hide(); } return this; } }); Ext.reg('progress', Ext.ProgressBar);
JavaScript
/** * @class Ext.ComponentMgr * <p>为页面上全体的组件(特指 {@link Ext.Component} 的子类) 以便能够可通过 * 组件的id方便地访问 (see {@link Ext.getCmp}).</p> * <p>此对象对组件的类 <i>classes</i> 提供索引的功能,这个索引应是如 {@link Ext.Component#xtype}. * 般的易记标识码。对于大量复合配置对象 Ext构成的页面。 * <tt>xtype</tt> 避免不必要子组件实例化。只要xtype正确声明好,就可利用 <i>配置项对象config object</i> * 表示一个子组件,这样,如遇到组件真是需要显示的时候,与之适合的类型(xtype)就会匹配对应的组件类,达到 * 延时实例化 lazy instantiation.</p> * <p>For a list of all available xtypes, see {@link Ext.Component}.</p> * @singleton */ Ext.ComponentMgr = function(){ var all = new Ext.util.MixedCollection(); var types = {}; return { /** * 注册一个组件 * @param {Ext.Component} c 组件对象 */ register : function(c){ all.add(c); }, /** * 撤消登记一个组件 * @param {Ext.Component} c 组件对象 */ unregister : function(c){ all.remove(c); }, /** * 由id返回组件 * @param {String} id 组件的id * @return Ext.Component */ get : function(id){ return all.get(id); }, /** * 当指定组件被加入到ComponentMgr时调用的函数。 * @param {String} id 组件Id * @param {Function} fn 回调函数 * @param {Object} scope 回调的作用域 */ onAvailable : function(id, fn, scope){ all.on("add", function(index, o){ if(o.id == id){ fn.call(scope || o, o); all.un("add", fn, scope); } }); }, /** * 为组件缓存所使用的MixedCollection。 * 可在这个MixedCollection中加入相应的事件,监视增加或移除的情况。只读的 * @type {MixedCollection} */ all : all, /** * 输入新的{@link Ext.Component#xtype},登记一个新组件的构造器。<br><br> * 使用该方法登记{@link Ext.Component}的子类以便当指定子组件的xtype时即可延时加载(lazy instantiation) * 参阅{@link Ext.Container#items} * @param {String} xtype 组件类的标识字符串 * @param {Constructor} cls 新的组件类 */ registerType : function(xtype, cls){ types[xtype] = cls; cls.xtype = xtype; }, // private create : function(config, defaultType){ return new types[config.xtype || defaultType](config); } }; }(); // this will be called a lot internally, // shorthand to keep the bytes down Ext.reg = Ext.ComponentMgr.registerType;
JavaScript
/** * @class Ext.Button * @extends Ext.Component * 简单的按钮类 * @cfg {String} text 按钮文本 * @cfg {String} 背景图片路径 (默认是采用css的background-image来设置图片,所以如果你需要混合了图片和文字的图片按钮请使用cls类"x-btn-text-icon") * @cfg {Function} 按钮单击事件触发函数 (可取代单击的事件) * @cfg {Object} scope 按钮单击事件触发函数的作用域 * @cfg {Number} minWidth 按钮最小宽度(常用于定义一组按钮的标准宽度) * @cfg {String/Object} tooltip 按钮鼠标划过时的提示语类似title - 可以是字符串QuickTips配置项对象 * @cfg {Boolean} hidden 是否隐藏 默认否 (默认为false) * @cfg {Boolean} disabled True 是否失效 默认否 (默认为false) * @cfg {Boolean} pressed 是否为按下状态 (仅当enableToggle = true时) * @cfg {String} toggleGroup 是否属于按钮组 (组里只有一个按钮可以为按下状态,仅当enableToggle = true时) * @cfg {Boolean/Object} repeat 触发函数是否可以重复触发while the mouse is down. 默认为false,也可以为{@link Ext.util.ClickRepeater}的参数对象. * @constructor 构造函数 * @param {Object} config 参数对象 */ Ext.Button = Ext.extend(Ext.Component, { /** * Read-only. True 如果按钮是隐藏的 * @type Boolean */ hidden : false, /** * Read-only. True 如果按钮是失效的 * @type Boolean */ disabled : false, /** * Read-only. True 如果按钮是按下状态 (仅当enableToggle = true时) * @type Boolean */ pressed : false, /** * @cfg {Number} tabIndex 按钮的DOM焦点序号即tab键时候得到焦点的序号 (默认为undefined) */ /** * @cfg {Boolean} enableToggle * True 是否在 pressed/not pressed 这两个状态间切换 (默认为false) */ enableToggle: false, /** * @cfg {Mixed} menu * 标准menu属性 可设置为menu的引用 或者menu的id 或者menu的参数对象 (默认为undefined). */ /** * @cfg {String} menuAlign * 菜单的对齐方式(参阅{@link Ext.Element#alignTo}以了解个中细节,默认为'tl-bl?')。 */ menuAlign : "tl-bl?", /** * @cfg {String} iconCls * A css class 用来指定背景图片 */ /** * @cfg {String} type * submit, reset or button - 按钮的三种类型 默认为'button' */ type : 'button', // private menuClassTarget: 'tr', /** * @cfg {String} clickEvent * handler 句柄触发事件 默认是单击 (defaults to 'click') */ clickEvent : 'click', /** * @cfg {Boolean} handleMouseEvents * 是否启用mouseover, mouseout and mousedown鼠标事件 (默认为true) */ handleMouseEvents : true, /** * @cfg {String} tooltipType * tooltip 的显示方式 既可是'qtip'(默认),也可是设置title属性的“标题”。 */ tooltipType : 'qtip', buttonSelector : "button:first", /** * @cfg {String} cls * 作用在按钮主元素的CSS样式类。 */ /** * @cfg {Ext.Template} template (Optional) * An {@link Ext.Template}可选配置 如果设置了可用来生成按钮的主要元素. 第一个占位符为按钮文本.修改这个属性要主意相关参数不能缺失. */ initComponent : function(){ Ext.Button.superclass.initComponent.call(this); this.addEvents( /** * @event click *单击触发事件 * @param {Button} this * @param {EventObject} e 单击的事件对象 */ "click", /** * @event toggle * 按钮按下状态切换触发事件(仅当enableToggle = true时) * @param {Button} this * @param {Boolean} pressed */ "toggle", /** * @event mouseover * 鼠标居上触发事件 * @param {Button} this * @param {Event} e The 事件对象 */ 'mouseover', /** * @event mouseout * 鼠标离开事件 * @param {Button} this * @param {Event} e 事件对象 */ 'mouseout', /** * @event menushow * 有menu的时候 menu显示触发事件 * @param {Button} this * @param {Menu} menu */ 'menushow', /** * @event menuhide * 有menu的时候 menu隐藏触发事件 * @param {Button} this * @param {Menu} menu */ 'menuhide', /** * @event menutriggerover * 有menu的时候 menu焦点转移到菜单项时触发事件 * @param {Button} this * @param {Menu} menu * @param {EventObject} e 事件对象 */ 'menutriggerover', /** * @event menutriggerout * 有menu的时候 menu焦点离开菜单项时触发事件 * @param {Button} this * @param {Menu} menu * @param {EventObject} e 事件对象 */ 'menutriggerout' ); if(this.menu){ this.menu = Ext.menu.MenuMgr.get(this.menu); } if(typeof this.toggleGroup === 'string'){ this.enableToggle = true; } }, // private onRender : function(ct, position){ if(!this.template){ if(!Ext.Button.buttonTemplate){ // hideous table template Ext.Button.buttonTemplate = new Ext.Template( '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>', '<td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i>&#160;</i></td>', "</tr></tbody></table>"); } this.template = Ext.Button.buttonTemplate; } var btn, targs = [this.text || '&#160;', this.type]; if(position){ btn = this.template.insertBefore(position, targs, true); }else{ btn = this.template.append(ct, targs, true); } var btnEl = btn.child(this.buttonSelector); btnEl.on('focus', this.onFocus, this); btnEl.on('blur', this.onBlur, this); this.initButtonEl(btn, btnEl); if(this.menu){ this.el.child(this.menuClassTarget).addClass("x-btn-with-menu"); } Ext.ButtonToggleMgr.register(this); }, // private initButtonEl : function(btn, btnEl){ this.el = btn; btn.addClass("x-btn"); if(this.icon){ btnEl.setStyle('background-image', 'url(' +this.icon +')'); } if(this.iconCls){ btnEl.addClass(this.iconCls); if(!this.cls){ btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon'); } } if(this.tabIndex !== undefined){ btnEl.dom.tabIndex = this.tabIndex; } if(this.tooltip){ if(typeof this.tooltip == 'object'){ Ext.QuickTips.register(Ext.apply({ target: btnEl.id }, this.tooltip)); } else { btnEl.dom[this.tooltipType] = this.tooltip; } } if(this.pressed){ this.el.addClass("x-btn-pressed"); } if(this.handleMouseEvents){ btn.on("mouseover", this.onMouseOver, this); // new functionality for monitoring on the document level //btn.on("mouseout", this.onMouseOut, this); btn.on("mousedown", this.onMouseDown, this); } if(this.menu){ this.menu.on("show", this.onMenuShow, this); this.menu.on("hide", this.onMenuHide, this); } if(this.id){ this.el.dom.id = this.el.id = this.id; } if(this.repeat){ var repeater = new Ext.util.ClickRepeater(btn, typeof this.repeat == "object" ? this.repeat : {} ); repeater.on("click", this.onClick, this); } btn.on(this.clickEvent, this.onClick, this); }, // private afterRender : function(){ Ext.Button.superclass.afterRender.call(this); if(Ext.isIE6){ this.autoWidth.defer(1, this); }else{ this.autoWidth(); } }, /** * 替换按钮针对背景图片的css类 连动替换按钮参数对象中的该属性 * @param {String} cls 图标的CSS样式类 */ setIconClass : function(cls){ if(this.el){ this.el.child(this.buttonSelector).replaceClass(this.iconCls, cls); } this.iconCls = cls; }, // private beforeDestroy: function(){ if(this.rendered){ var btn = this.el.child(this.buttonSelector); if(btn){ btn.removeAllListeners(); } } if(this.menu){ Ext.destroy(this.menu); } }, // private onDestroy : function(){ if(this.rendered){ Ext.ButtonToggleMgr.unregister(this); } }, // private autoWidth : function(){ if(this.el){ this.el.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child(this.buttonSelector); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if(this.el.getWidth() < this.minWidth){ this.el.setWidth(this.minWidth); } } } }, /** * 增加按钮事件句柄触发函数的方法 * @param {Function} handler 当按钮按下执行的函数 * @param {Object} scope (optional) 传入参数的作用域 */ setHandler : function(handler, scope){ this.handler = handler; this.scope = scope; }, /** * 设置按钮文本 * @param {String} text 按钮的文字 */ setText : function(text){ this.text = text; if(this.el){ this.el.child("td.x-btn-center " + this.buttonSelector).update(text); } this.autoWidth(); }, /** * 获取按钮的文字 * @return {String} 按钮的文字 */ getText : function(){ return this.text; }, /** * 如果有传入state的参数,就按照state的参数设置否则当前的state就会轮换。 * @param {Boolean} state (可选的)指定特定的状态 */ toggle : function(state){ state = state === undefined ? !this.pressed : state; if(state != this.pressed){ if(state){ this.el.addClass("x-btn-pressed"); this.pressed = true; this.fireEvent("toggle", this, true); }else{ this.el.removeClass("x-btn-pressed"); this.pressed = false; this.fireEvent("toggle", this, false); } if(this.toggleHandler){ this.toggleHandler.call(this.scope || this, this, state); } } }, /** * 使按钮获取焦点 */ focus : function(){ this.el.child(this.buttonSelector).focus(); }, // private onDisable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.addClass("x-item-disabled"); } this.el.dom.disabled = true; } this.disabled = true; }, // private onEnable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.removeClass("x-item-disabled"); } this.el.dom.disabled = false; } this.disabled = false; }, /** * 显示按钮附带的菜单(如果有的话) */ showMenu : function(){ if(this.menu){ this.menu.show(this.el, this.menuAlign); } return this; }, /** * 隐藏按钮附带的菜单(如果有的话) */ hideMenu : function(){ if(this.menu){ this.menu.hide(); } return this; }, /** * 若按钮附有菜单并且是显示着的就返回true * @return {Boolean} */ hasVisibleMenu : function(){ return this.menu && this.menu.isVisible(); }, // private onClick : function(e){ if(e){ e.preventDefault(); } if(e.button != 0){ return; } if(!this.disabled){ if(this.enableToggle && (this.allowDepress !== false || !this.pressed)){ this.toggle(); } if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){ this.showMenu(); } this.fireEvent("click", this, e); if(this.handler){ //this.el.removeClass("x-btn-over"); this.handler.call(this.scope || this, this, e); } } }, // private isMenuTriggerOver : function(e, internal){ return this.menu && !internal; }, // private isMenuTriggerOut : function(e, internal){ return this.menu && !internal; }, // private onMouseOver : function(e){ if(!this.disabled){ var internal = e.within(this.el, true); if(!internal){ this.el.addClass("x-btn-over"); Ext.getDoc().on('mouseover', this.monitorMouseOver, this); this.fireEvent('mouseover', this, e); } if(this.isMenuTriggerOver(e, internal)){ this.fireEvent('menutriggerover', this, this.menu, e); } } }, // private monitorMouseOver : function(e){ if(e.target != this.el.dom && !e.within(this.el)){ Ext.getDoc().un('mouseover', this.monitorMouseOver, this); this.onMouseOut(e); } }, // private onMouseOut : function(e){ var internal = e.within(this.el) && e.target != this.el.dom; this.el.removeClass("x-btn-over"); this.fireEvent('mouseout', this, e); if(this.isMenuTriggerOut(e, internal)){ this.fireEvent('menutriggerout', this, this.menu, e); } }, // private onFocus : function(e){ if(!this.disabled){ this.el.addClass("x-btn-focus"); } }, // private onBlur : function(e){ this.el.removeClass("x-btn-focus"); }, // private getClickEl : function(e, isUp){ return this.el; }, // private onMouseDown : function(e){ if(!this.disabled && e.button == 0){ this.getClickEl(e).addClass("x-btn-click"); Ext.getDoc().on('mouseup', this.onMouseUp, this); } }, // private onMouseUp : function(e){ if(e.button == 0){ this.getClickEl(e, true).removeClass("x-btn-click"); Ext.getDoc().un('mouseup', this.onMouseUp, this); } }, // private onMenuShow : function(e){ this.ignoreNextClick = 0; this.el.addClass("x-btn-menu-active"); this.fireEvent('menushow', this, this.menu); }, // private onMenuHide : function(e){ this.el.removeClass("x-btn-menu-active"); this.ignoreNextClick = this.restoreClick.defer(250, this); this.fireEvent('menuhide', this, this.menu); }, // private restoreClick : function(){ this.ignoreNextClick = 0; } }); Ext.reg('button', Ext.Button); // Private utility class used by Button Ext.ButtonToggleMgr = function(){ var groups = {}; function toggleGroup(btn, state){ if(state){ var g = groups[btn.toggleGroup]; for(var i = 0, l = g.length; i < l; i++){ if(g[i] != btn){ g[i].toggle(false); } } } } return { register : function(btn){ if(!btn.toggleGroup){ return; } var g = groups[btn.toggleGroup]; if(!g){ g = groups[btn.toggleGroup] = []; } g.push(btn); btn.on("toggle", toggleGroup); }, unregister : function(btn){ if(!btn.toggleGroup){ return; } var g = groups[btn.toggleGroup]; if(g){ g.remove(btn); btn.un("toggle", toggleGroup); } } }; }();
JavaScript
/** * @class Ext.BoxComponent * @extends Ext.Component * 任何使用矩形容器的作可视化组件{@link Ext.Component}的基类。 * 所有的容器类都应从BoxComponent继承,从而每个嵌套的Ext布局容器都会紧密地协调工作。 * @constructor * @param {Ext.Element/String/Object} config 配置选项 */ Ext.BoxComponent = Ext.extend(Ext.Component, { /** * @cfg {Number} height * 此组件的高度(单位象素)(缺省为auto)。 */ /** * @cfg {Number} width * 此组件的宽度(单位象素)(缺省为auto)。 */ /** * @cfg {Boolean} autoHeight * True表示为使用height:'auto',false表示为使用固定高度(缺省为false)。 */ /** * @cfg {Boolean} autoWidth * True表示为使用width:'auto',false表示为使用固定宽度(缺省为false)。 */ /** * @cfg {Boolean} deferHeight * True表示为根据外置的组件延时计算高度,false表示允许该组件自行设置高度(缺省为false)。 */ initComponent : function(){ Ext.BoxComponent.superclass.initComponent.call(this); this.addEvents( /** * @event resize * 当组件调节过大小后触发。 * @param {Ext.Component} this * @param {Number} adjWidth 矩形调整过后的宽度 * @param {Number} adjHeight 矩形调整过后的高度 * @param {Number} rawWidth 原来设定的宽度 * @param {Number} rawHeight 原来设定的高度 */ 'resize', /** * @event move * 当组件被移动过之后触发。 * @param {Ext.Component} this * @param {Number} x 新x位置 * @param {Number} y 新y位置 */ 'move' ); }, // private, set in afterRender to signify that the component has been rendered boxReady : false, // private, used to defer height settings to subclasses deferHeight: false, /** * 设置组件的宽度和高度。 * 此方法会触发resize事件。 * 此方法既可接受单独的数字类型的参数,也可以传入一个size的对象,如 {width:10, height:20}。 * @param {Number/Object} width 要设置的宽度,或一个size对象,格式是{width, height} * @param {Number} height 要设置的高度(如第一参数是size对象的那第二个参数经不需要了) * @return {Ext.BoxComponent} this */ setSize : function(w, h){ // support for standard size objects if(typeof w == 'object'){ h = w.height; w = w.width; } // not rendered if(!this.boxReady){ this.width = w; this.height = h; return this; } // prevent recalcs when not needed if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){ return this; } this.lastSize = {width: w, height: h}; var adj = this.adjustSize(w, h); var aw = adj.width, ah = adj.height; if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters var rz = this.getResizeEl(); if(!this.deferHeight && aw !== undefined && ah !== undefined){ rz.setSize(aw, ah); }else if(!this.deferHeight && ah !== undefined){ rz.setHeight(ah); }else if(aw !== undefined){ rz.setWidth(aw); } this.onResize(aw, ah, w, h); this.fireEvent('resize', this, aw, ah, w, h); } return this; }, /** * 设置组件的宽度。此方法会触发resize事件。 * @param {Number} height 要设置的新宽度 * @return {Ext.BoxComponent} this */ setWidth : function(width){ return this.setSize(width); }, /** * 设置组件的高度。此方法会触发resize事件。 * @param {Number} height 要设置的新高度 * @return {Ext.BoxComponent} this */ setHeight : function(height){ return this.setSize(undefined, height); }, /** * 返回当前组件所属元素的大小。 * @return {Object} 包含元素大小的对象,格式为{width: (元素宽度), height:(元素高度)} */ getSize : function(){ return this.el.getSize(); }, /** * 对组件所在元素当前的XY位置 * @param {Boolean} local (可选的)如为真返回的是元素的left和top而非XY(默认为false) * @return {Array} 元素的XY位置(如[100, 200]) */ getPosition : function(local){ if(local === true){ return [this.el.getLeft(true), this.el.getTop(true)]; } return this.xy || this.el.getXY(); }, /** * 返回对组件所在元素的测量矩形大小。 * @param {Boolean} local (可选的) 如为真返回的是元素的left和top而非XY(默认为false) * @return {Object} 格式为{x, y, width, height}的对象(矩形) */ getBox : function(local){ var s = this.el.getSize(); if(local === true){ s.x = this.el.getLeft(true); s.y = this.el.getTop(true); }else{ var xy = this.xy || this.el.getXY(); s.x = xy[0]; s.y = xy[1]; } return s; }, /** * 对组件所在元素的测量矩形大小,然后根据此值设置组件的大小。 * @param {Object} box 格式为{x, y, width, height}的对象 * @return {Ext.BoxComponent} this */ updateBox : function(box){ this.setSize(box.width, box.height); this.setPagePosition(box.x, box.y); return this; }, // protected getResizeEl : function(){ return this.resizeEl || this.el; }, // protected getPositionEl : function(){ return this.positionEl || this.el; }, /** * 设置组件的left和top值。要设置基于页面的XY位置,可使用{@link #setPagePosition}。 * 此方法触发move事件。 * @param {Number} left 新left * @param {Number} top 新top * @return {Ext.BoxComponent} this */ setPosition : function(x, y){ if(x && typeof x[1] == 'number'){ y = x[1]; x = x[0]; } this.x = x; this.y = y; if(!this.boxReady){ return this; } var adj = this.adjustPosition(x, y); var ax = adj.x, ay = adj.y; var el = this.getPositionEl(); if(ax !== undefined || ay !== undefined){ if(ax !== undefined && ay !== undefined){ el.setLeftTop(ax, ay); }else if(ax !== undefined){ el.setLeft(ax); }else if(ay !== undefined){ el.setTop(ay); } this.onPosition(ax, ay); this.fireEvent('move', this, ax, ay); } return this; }, /** * 设置组件页面上的left和top值。 * 要设置left、top的位置,可使用{@link #setPosition}。 * 此方法触发move事件。 * @param {Number} x 新x位置 * @param {Number} y 新y位置 * @return {Ext.BoxComponent} this */ setPagePosition : function(x, y){ if(x && typeof x[1] == 'number'){ y = x[1]; x = x[0]; } this.pageX = x; this.pageY = y; if(!this.boxReady){ return; } if(x === undefined || y === undefined){ // cannot translate undefined points return; } var p = this.el.translatePoints(x, y); this.setPosition(p.left, p.top); return this; }, // private onRender : function(ct, position){ Ext.BoxComponent.superclass.onRender.call(this, ct, position); if(this.resizeEl){ this.resizeEl = Ext.get(this.resizeEl); } if(this.positionEl){ this.positionEl = Ext.get(this.positionEl); } }, // private afterRender : function(){ Ext.BoxComponent.superclass.afterRender.call(this); this.boxReady = true; this.setSize(this.width, this.height); if(this.x || this.y){ this.setPosition(this.x, this.y); }else if(this.pageX || this.pageY){ this.setPagePosition(this.pageX, this.pageY); } }, /** * 强制重新计算组件的大小尺寸,这个尺寸是基于所属元素当前的高度和宽度。 * @return {Ext.BoxComponent} this */ syncSize : function(){ delete this.lastSize; this.setSize(this.autoWidth ? undefined : this.el.getWidth(), this.autoHeight ? undefined : this.el.getHeight()); return this; }, /* // protected * 组件大小调节过后调用的函数,这是个空函数,可由一个子类来实现,执行一些调节大小过后的自定义逻辑。 * @param {Number} x 新X值 * @param {Number} y 新y值 * @param {Number} adjWidth 矩形调整过后的宽度 * @param {Number} adjHeight 矩形调整过后的高度 * @param {Number} rawWidth 原本设定的宽度 * @param {Number} rawHeight 原本设定的高度 */ onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){ }, /* // protected * 组件移动过后调用的函数,这是个空函数,可由一个子类来实现,执行一些移动过后的自定义逻辑。 * @param {Number} x 新X值 * @param {Number} y 新y值 */ onPosition : function(x, y){ }, // private adjustSize : function(w, h){ if(this.autoWidth){ w = 'auto'; } if(this.autoHeight){ h = 'auto'; } return {width : w, height: h}; }, // private adjustPosition : function(x, y){ return {x : x, y: y}; } }); Ext.reg('box', Ext.BoxComponent);
JavaScript
/** * @class Ext.WindowGroup * 此对象代表一组{@link Ext.Window}的实例并提供z-order的管理和window激活的行为。 * @constructor */ Ext.WindowGroup = function(){ var list = {}; var accessList = []; var front = null; // private var sortWindows = function(d1, d2){ return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1; }; // private var orderWindows = function(){ var a = accessList, len = a.length; if(len > 0){ a.sort(sortWindows); var seed = a[0].manager.zseed; for(var i = 0; i < len; i++){ var win = a[i]; if(win && !win.hidden){ win.setZIndex(seed + (i*10)); } } } activateLast(); }; // private var setActiveWin = function(win){ if(win != front){ if(front){ front.setActive(false); } front = win; if(win){ win.setActive(true); } } }; // private var activateLast = function(){ for(var i = accessList.length-1; i >=0; --i) { if(!accessList[i].hidden){ setActiveWin(accessList[i]); return; } } // none to activate setActiveWin(null); }; return { /** * windows的初始z-idnex(缺省为9000) * @type Number z-index的值 */ zseed : 9000, // private register : function(win){ list[win.id] = win; accessList.push(win); win.on('hide', activateLast); }, // private unregister : function(win){ delete list[win.id]; win.un('hide', activateLast); accessList.remove(win); }, /** * 返回指定id的window。 * @param {String/Object} id window的id或{@link Ext.Window}实例。 * @return {Ext.Window} */ get : function(id){ return typeof id == "object" ? id : list[id]; }, /** * 将指定的window居于其它活动的window前面。 * @param {String/Object} win window的id或{@link Ext.Window}实例。 * @return {Boolean} True表示为对话框成功居前,else则本身已是在前面。 */ bringToFront : function(win){ win = this.get(win); if(win != front){ win._lastAccess = new Date().getTime(); orderWindows(); return true; } return false; }, /** * 将指定的window居于其它活动的window后面。 * @param {String/Object} win window的id或{@link Ext.Window}实例。 * @return {Ext.Window} The window */ sendToBack : function(win){ win = this.get(win); win._lastAccess = -(new Date().getTime()); orderWindows(); return win; }, /** * 隐藏组内的所有的window */ hideAll : function(){ for(var id in list){ if(list[id] && typeof list[id] != "function" && list[id].isVisible()){ list[id].hide(); } } }, /** * 返回组内的当前活动的window * @return {Ext.Window} 活动的window */ getActive : function(){ return front; }, /** * 传入一个制定的搜索函数到该方法内,返回组内的零个或多个windows。 * 函数一般会接收{@link Ext.Window}的引用作为其唯一的函数,若window符合搜索的标准及返回true, * 否则应返回false. * @param {Function} fn 搜索函数 * @param {Object} scope (可选的)执行函数的作用域(若不指定便是window会传入) * @return {Array} 零个或多个匹配的window */ getBy : function(fn, scope){ var r = []; for(var i = accessList.length-1; i >=0; --i) { var win = accessList[i]; if(fn.call(scope||win, win) !== false){ r.push(win); } } return r; }, /** * 在组内的每一个window上执行指定的函数,传入window自身作为唯一的参数。若函数返回false即停止迭代。 * @param {Function} fn 每一项都会执行的函数 * @param {Object} scope (可选的)执行函数的作用域 */ each : function(fn, scope){ for(var id in list){ if(list[id] && typeof list[id] != "function"){ if(fn.call(scope || list[id], list[id]) === false){ return; } } } } }; };
JavaScript
/** * @class Ext.Editor * @extends Ext.Component * 一个基础性的字段编辑器,内建按需的显示、隐藏控制和一些内建的调节大小及事件句柄逻辑。 * @constructor * 建立一个新的编辑器 * @param {Ext.form.Field} field 字段对象(或后代descendant) * @param {Object} config 配置项对象 */ Ext.Editor = function(field, config){ this.field = field; Ext.Editor.superclass.constructor.call(this, config); }; Ext.extend(Ext.Editor, Ext.Component, { /** * @cfg {Boolean/String} autosize * True表示为编辑器的大小尺寸自适应到所属的字段,设置“width”表示单单适应宽度, * 设置“height”表示单单适应高度(默认为fasle) */ /** * @cfg {Boolean} revertInvalid * True表示为当用户完成编辑但字段验证失败后,自动恢复原始值,然后取消这次编辑(默认为true) */ /** * @cfg {Boolean} ignoreNoChange * True表示为如果用户完成一次编辑但值没有改变时,中止这次编辑的操作(不保存,不触发事件)(默认为false)。 * 只对字符类型的值有效,其它编辑的数据类型将会被忽略。 */ /** * @cfg {Boolean} hideEl * False表示为当编辑器显示时,保持绑定的元素可见(默认为true)。 */ /** * @cfg {Mixed} value * 所属字段的日期值(默认为"") */ value : "", /** * @cfg {String} alignment * 对齐的位置(参见{@link Ext.Element#alignTo}了解详细,默认为"c-c?")。 */ alignment: "c-c?", /** * @cfg {Boolean/String} shadow属性为"sides"是四边都是向上阴影, "frame"表示四边外发光, "drop"表示 * 从右下角开始投影(默认为"frame") */ shadow : "frame", /** * @cfg {Boolean} constrain 表示为约束编辑器到视图 */ constrain : false, /** * @cfg {Boolean} swallowKeys 处理keydown/keypress事件使得不会上报(propagate),(默认为true) */ swallowKeys : true, /** * @cfg {Boolean} completeOnEnter True表示为回车按下之后就完成编辑(默认为false) */ completeOnEnter : false, /** * @cfg {Boolean} cancelOnEsc True表示为escape键按下之后便取消编辑(默认为false) */ cancelOnEsc : false, /** * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false) * @cfg {Boolean} updateEl True表示为当更新完成之后同时更新绑定元素的innerHTML(默认为false) */ updateEl : false, initComponent : function(){ Ext.Editor.superclass.initComponent.call(this); this.addEvents( /** * @event beforestartedit * 编辑器开始初始化,但在修改值之前触发。若事件句柄返回false则取消整个编辑事件。 * @param {Editor} this * @param {Ext.Element} boundEl 编辑器绑定的所属元素 * @param {Mixed} value 正被设置的值 */ "beforestartedit", /** * 当编辑器显示时触发 * @param {Ext.Element} boundEl 编辑器绑定的所属元素 * @param {Mixed} value 原始字段值 */ "startedit", /** * @event beforecomplete * 修改已提交到字段,但修改未真正反映在所属的字段上之前触发。 * 若事件句柄返回false则取消整个编辑事件。 * 注意如果值没有变动的话并且ignoreNoChange = true的情况下, * 编辑依然会结束但因为没有真正的编辑所以不会触发事件。 * @param {Editor} this * @param {Mixed} value 当前字段的值 * @param {Mixed} startValue 原始字段的值 */ "beforecomplete", /** * @event complete * 当编辑完成过后,任何的改变写入到所属字段时触发。 * @param {Editor} this * @param {Mixed} value 当前字段的值 * @param {Mixed} startValue 原始字段的值 */ "complete", /** * @event specialkey * 用于导航的任意键被按下触发(arrows、 tab、 enter、esc等等) * 你可检查{@link Ext.EventObject#getKey}以确定哪个键被按了。 * @param {Ext.form.Field} this * @param {Ext.EventObject} e 事件对象 */ "specialkey" ); }, // private onRender : function(ct, position){ this.el = new Ext.Layer({ shadow: this.shadow, cls: "x-editor", parentEl : ct, shim : this.shim, shadowOffset:4, id: this.id, constrain: this.constrain }); this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden"); if(this.field.msgTarget != 'title'){ this.field.msgTarget = 'qtip'; } this.field.render(this.el); if(Ext.isGecko){ this.field.el.dom.setAttribute('autocomplete', 'off'); } this.field.on("specialkey", this.onSpecialKey, this); if(this.swallowKeys){ this.field.el.swallowEvent(['keydown','keypress']); } this.field.show(); this.field.on("blur", this.onBlur, this); if(this.field.grow){ this.field.on("autosize", this.el.sync, this.el, {delay:1}); } }, onSpecialKey : function(field, e){ if(this.completeOnEnter && e.getKey() == e.ENTER){ e.stopEvent(); this.completeEdit(); }else if(this.cancelOnEsc && e.getKey() == e.ESC){ this.cancelEdit(); }else{ this.fireEvent('specialkey', field, e); } }, /** * 进入编辑状态并显示编辑器 * @param {String/HTMLElement/Element} el 要编辑的元素 * @param {String} value (optional) 编辑器初始化的值,如不设置该值便是元素的innerHTML */ startEdit : function(el, value){ if(this.editing){ this.completeEdit(); } this.boundEl = Ext.get(el); var v = value !== undefined ? value : this.boundEl.dom.innerHTML; if(!this.rendered){ this.render(this.parentEl || document.body); } if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){ return; } this.startValue = v; this.field.setValue(v); if(this.autoSize){ var sz = this.boundEl.getSize(); switch(this.autoSize){ case "width": this.setSize(sz.width, ""); break; case "height": this.setSize("", sz.height); break; default: this.setSize(sz.width, sz.height); } } this.el.alignTo(this.boundEl, this.alignment); this.editing = true; this.show(); }, /** * 设置编辑器高、宽 * @param {Number} width 新宽度 * @param {Number} height 新高度 */ setSize : function(w, h){ this.field.setSize(w, h); if(this.el){ this.el.sync(); } }, /** * 按照当前的最齐设置,把编辑器重新对齐到所绑定的字段。 */ realign : function(){ this.el.alignTo(this.boundEl, this.alignment); }, /** * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false) * 结束编辑状态,提交变化的内容到所属的字段,并隐藏编辑器。 * @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false) */ completeEdit : function(remainVisible){ if(!this.editing){ return; } var v = this.getValue(); if(this.revertInvalid !== false && !this.field.isValid()){ v = this.startValue; this.cancelEdit(true); } if(String(v) === String(this.startValue) && this.ignoreNoChange){ this.editing = false; this.hide(); return; } if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){ this.editing = false; if(this.updateEl && this.boundEl){ this.boundEl.update(v); } if(remainVisible !== true){ this.hide(); } this.fireEvent("complete", this, v, this.startValue); } }, // private onShow : function(){ this.el.show(); if(this.hideEl !== false){ this.boundEl.hide(); } this.field.show(); if(Ext.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time this.fixIEFocus = true; this.deferredFocus.defer(50, this); }else{ this.field.focus(); } this.fireEvent("startedit", this.boundEl, this.startValue); }, deferredFocus : function(){ if(this.editing){ this.field.focus(); } }, /** * 取消编辑状态并返回到原始值,不作任何的修改, * @param {Boolean} remainVisible 让编辑过后仍然显示编辑器,这是重写默认的动作(默认为false) */ cancelEdit : function(remainVisible){ if(this.editing){ this.setValue(this.startValue); if(remainVisible !== true){ this.hide(); } } }, // private onBlur : function(){ if(this.allowBlur !== true && this.editing){ this.completeEdit(); } }, // private onHide : function(){ if(this.editing){ this.completeEdit(); return; } this.field.blur(); if(this.field.collapse){ this.field.collapse(); } this.el.hide(); if(this.hideEl !== false){ this.boundEl.show(); } }, /** * 设置编辑器的数据。 * @param {Mixed} value 所属field可支持的任意值 */ setValue : function(v){ this.field.setValue(v); }, /** * 获取编辑器的数据。 * @return {Mixed} 数据值 */ getValue : function(){ return this.field.getValue(); }, beforeDestroy : function(){ this.field.destroy(); this.field = null; } }); Ext.reg('editor', Ext.Editor);
JavaScript
/** * @class Ext.Layer * @extends Ext.Element * 一个由{@link Ext.Element}扩展的对象,支持阴影和shim,受视图限制和自动修复阴影/shim位置。 * @cfg {Boolean} shim False表示为禁用iframe的shim,在某些浏览器里需用到(默认为true) * @cfg {String/Boolean} shadow True表示为创建元素的阴影,采用样式类"x-layer-shadow",或者你可以传入一个字符串指定一个CSS样式类,False表示为关闭阴影。 * @cfg {Object} dh DomHelper配置格式的对象,来创建元素(默认为{tag: "div", cls: "x-layer"}) * @cfg {Boolean} constrain False表示为不受视图的限制(默认为true) * @cfg {String} cls 元素要添加的CSS样式类 * @cfg {Number} zindex 开始的z-index(默认为1100) * @cfg {Number} shadowOffset 阴影偏移的像素值(默认为3) * @constructor * @param {Object} config 配置项对象 * @param {String/HTMLElement} existingEl (可选的)使用现有的DOM的元素。 如找不到就创建一个。 */ (function(){ Ext.Layer = function(config, existingEl){ config = config || {}; var dh = Ext.DomHelper; var cp = config.parentEl, pel = cp ? Ext.getDom(cp) : document.body; if(existingEl){ this.dom = Ext.getDom(existingEl); } if(!this.dom){ var o = config.dh || {tag: "div", cls: "x-layer"}; this.dom = dh.append(pel, o); } if(config.cls){ this.addClass(config.cls); } this.constrain = config.constrain !== false; this.visibilityMode = Ext.Element.VISIBILITY; if(config.id){ this.id = this.dom.id = config.id; }else{ this.id = Ext.id(this.dom); } this.zindex = config.zindex || this.getZIndex(); this.position("absolute", this.zindex); if(config.shadow){ this.shadowOffset = config.shadowOffset || 4; this.shadow = new Ext.Shadow({ offset : this.shadowOffset, mode : config.shadow }); }else{ this.shadowOffset = 0; } this.useShim = config.shim !== false && Ext.useShims; this.useDisplay = config.useDisplay; this.hide(); }; var supr = Ext.Element.prototype; // shims are shared among layer to keep from having 100 iframes var shims = []; Ext.extend(Ext.Layer, Ext.Element, { getZIndex : function(){ return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000; }, getShim : function(){ if(!this.useShim){ return null; } if(this.shim){ return this.shim; } var shim = shims.shift(); if(!shim){ shim = this.createShim(); shim.enableDisplayMode('block'); shim.dom.style.display = 'none'; shim.dom.style.visibility = 'visible'; } var pn = this.dom.parentNode; if(shim.dom.parentNode != pn){ pn.insertBefore(shim.dom, this.dom); } shim.setStyle('z-index', this.getZIndex()-2); this.shim = shim; return shim; }, hideShim : function(){ if(this.shim){ this.shim.setDisplayed(false); shims.push(this.shim); delete this.shim; } }, disableShadow : function(){ if(this.shadow){ this.shadowDisabled = true; this.shadow.hide(); this.lastShadowOffset = this.shadowOffset; this.shadowOffset = 0; } }, enableShadow : function(show){ if(this.shadow){ this.shadowDisabled = false; this.shadowOffset = this.lastShadowOffset; delete this.lastShadowOffset; if(show){ this.sync(true); } } }, // private // this code can execute repeatedly in milliseconds (i.e. during a drag) so // code size was sacrificed for effeciency (e.g. no getBox/setBox, no XY calls) sync : function(doShow){ var sw = this.shadow; if(!this.updating && this.isVisible() && (sw || this.useShim)){ var sh = this.getShim(); var w = this.getWidth(), h = this.getHeight(); var l = this.getLeft(true), t = this.getTop(true); if(sw && !this.shadowDisabled){ if(doShow && !sw.isVisible()){ sw.show(this); }else{ sw.realign(l, t, w, h); } if(sh){ if(doShow){ sh.show(); } // fit the shim behind the shadow, so it is shimmed too var a = sw.adjusts, s = sh.dom.style; s.left = (Math.min(l, l+a.l))+"px"; s.top = (Math.min(t, t+a.t))+"px"; s.width = (w+a.w)+"px"; s.height = (h+a.h)+"px"; } }else if(sh){ if(doShow){ sh.show(); } sh.setSize(w, h); sh.setLeftTop(l, t); } } }, // private destroy : function(){ this.hideShim(); if(this.shadow){ this.shadow.hide(); } this.removeAllListeners(); Ext.removeNode(this.dom); Ext.Element.uncache(this.id); }, remove : function(){ this.destroy(); }, // private beginUpdate : function(){ this.updating = true; }, // private endUpdate : function(){ this.updating = false; this.sync(true); }, // private hideUnders : function(negOffset){ if(this.shadow){ this.shadow.hide(); } this.hideShim(); }, // private constrainXY : function(){ if(this.constrain){ var vw = Ext.lib.Dom.getViewWidth(), vh = Ext.lib.Dom.getViewHeight(); var s = Ext.getDoc().getScroll(); var xy = this.getXY(); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset; // only move it if it needs it var moved = false; // first validate right/bottom if((x + w) > vw+s.left){ x = vw - w - this.shadowOffset; moved = true; } if((y + h) > vh+s.top){ y = vh - h - this.shadowOffset; moved = true; } // then make sure top/left isn't negative if(x < s.left){ x = s.left; moved = true; } if(y < s.top){ y = s.top; moved = true; } if(moved){ if(this.avoidY){ var ay = this.avoidY; if(y <= ay && (y+h) >= ay){ y = ay-h-5; } } xy = [x, y]; this.storeXY(xy); supr.setXY.call(this, xy); this.sync(); } } }, isVisible : function(){ return this.visible; }, // private showAction : function(){ this.visible = true; // track visibility to prevent getStyle calls if(this.useDisplay === true){ this.setDisplayed(""); }else if(this.lastXY){ supr.setXY.call(this, this.lastXY); }else if(this.lastLT){ supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]); } }, // private hideAction : function(){ this.visible = false; if(this.useDisplay === true){ this.setDisplayed(false); }else{ this.setLeftTop(-10000,-10000); } }, // overridden Element method setVisible : function(v, a, d, c, e){ if(v){ this.showAction(); } if(a && v){ var cb = function(){ this.sync(true); if(c){ c(); } }.createDelegate(this); supr.setVisible.call(this, true, true, d, cb, e); }else{ if(!v){ this.hideUnders(true); } var cb = c; if(a){ cb = function(){ this.hideAction(); if(c){ c(); } }.createDelegate(this); } supr.setVisible.call(this, v, a, d, cb, e); if(v){ this.sync(true); }else if(!a){ this.hideAction(); } } }, storeXY : function(xy){ delete this.lastLT; this.lastXY = xy; }, storeLeftTop : function(left, top){ delete this.lastXY; this.lastLT = [left, top]; }, // private beforeFx : function(){ this.beforeAction(); return Ext.Layer.superclass.beforeFx.apply(this, arguments); }, // private afterFx : function(){ Ext.Layer.superclass.afterFx.apply(this, arguments); this.sync(this.isVisible()); }, // private beforeAction : function(){ if(!this.updating && this.shadow){ this.shadow.hide(); } }, // overridden Element method setLeft : function(left){ this.storeLeftTop(left, this.getTop(true)); supr.setLeft.apply(this, arguments); this.sync(); }, setTop : function(top){ this.storeLeftTop(this.getLeft(true), top); supr.setTop.apply(this, arguments); this.sync(); }, setLeftTop : function(left, top){ this.storeLeftTop(left, top); supr.setLeftTop.apply(this, arguments); this.sync(); }, setXY : function(xy, a, d, c, e){ this.fixDisplay(); this.beforeAction(); this.storeXY(xy); var cb = this.createCB(c); supr.setXY.call(this, xy, a, d, cb, e); if(!a){ cb(); } }, // private createCB : function(c){ var el = this; return function(){ el.constrainXY(); el.sync(true); if(c){ c(); } }; }, // overridden Element method setX : function(x, a, d, c, e){ this.setXY([x, this.getY()], a, d, c, e); }, // overridden Element method setY : function(y, a, d, c, e){ this.setXY([this.getX(), y], a, d, c, e); }, // overridden Element method setSize : function(w, h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setSize.call(this, w, h, a, d, cb, e); if(!a){ cb(); } }, // overridden Element method setWidth : function(w, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setWidth.call(this, w, a, d, cb, e); if(!a){ cb(); } }, // overridden Element method setHeight : function(h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setHeight.call(this, h, a, d, cb, e); if(!a){ cb(); } }, // overridden Element method setBounds : function(x, y, w, h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); if(!a){ this.storeXY([x, y]); supr.setXY.call(this, [x, y]); supr.setSize.call(this, w, h, a, d, cb, e); cb(); }else{ supr.setBounds.call(this, x, y, w, h, a, d, cb, e); } return this; }, /** * 设置层的z-index和调整全部的阴影和垫片(shim) z-indexes。 * 层本身的z-index是会自动+2,所以它总会是在其他阴影和垫片上面(这时阴影元素会分配z-index+1,垫片的就是原本传入的z-index)。 * @param {Number} zindex 要设置的新z-index * @return {this} The Layer */ setZIndex : function(zindex){ this.zindex = zindex; this.setStyle("z-index", zindex + 2); if(this.shadow){ this.shadow.setZIndex(zindex + 1); } if(this.shim){ this.shim.setStyle("z-index", zindex); } } }); })();
JavaScript
/** * @class Ext.MessageBox * <p>用来生成不同样式的消息框的实用类。还可以使用它的别名 Ext.Msg。<p/> * <p>需要注意的是 MessageBox 对象是异步的。不同于 JavaScript 中原生的 <code>alert</code>(它会暂停浏览器的执行),显示 MessageBox 不会中断代码的运行。 * 由于这个原因,如果你的代码需要在用户对 MessageBox 做出反馈<em>之后</em>执行,则必须用到回调函数(详情可见 {@link #show} 方法中的 <code>function</code> 参数)。 * <p>用法示例:</p> *<pre><code> // 基本的通知: Ext.Msg.alert('Status', 'Changes saved successfully.'); // 提示用户输入数据并使用回调方法进得处理: Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){ if (btn == 'ok'){ // process text value and close... } }); // 显示一个使用配置选项的对话框: Ext.Msg.show({ title:'Save Changes?', msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?', buttons: Ext.Msg.YESNOCANCEL, fn: processResult, animEl: 'elId', icon: Ext.MessageBox.QUESTION }); </code></pre> * @singleton */ Ext.MessageBox = function(){ var dlg, opt, mask, waitTimer; var bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl; var buttons, activeTextEl, bwidth, iconCls = ''; // private var handleButton = function(button){ dlg.hide(); Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1); }; // private var handleHide = function(){ if(opt && opt.cls){ dlg.el.removeClass(opt.cls); } progressBar.reset(); }; // private var handleEsc = function(d, k, e){ if(opt && opt.closable !== false){ dlg.hide(); } if(e){ e.stopEvent(); } }; // private var updateButtons = function(b){ var width = 0; if(!b){ buttons["ok"].hide(); buttons["cancel"].hide(); buttons["yes"].hide(); buttons["no"].hide(); return width; } dlg.footer.dom.style.display = ''; for(var k in buttons){ if(typeof buttons[k] != "function"){ if(b[k]){ buttons[k].show(); buttons[k].setText(typeof b[k] == "string" ? b[k] : Ext.MessageBox.buttonText[k]); width += buttons[k].el.getWidth()+15; }else{ buttons[k].hide(); } } } return width; }; return { /** * 返回 {@link Ext.Window} 对象的元素的引用 * @return {Ext.Window} window 对象 */ getDialog : function(titleText){ if(!dlg){ dlg = new Ext.Window({ autoCreate : true, title:titleText, resizable:false, constrain:true, constrainHeader:true, minimizable : false, maximizable : false, stateful: false, modal: true, shim:true, buttonAlign:"center", width:400, height:100, minHeight: 80, plain:true, footer:true, closable:true, close : function(){ if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){ handleButton("no"); }else{ handleButton("cancel"); } } }); buttons = {}; var bt = this.buttonText; //TODO: refactor this block into a buttons config to pass into the Window constructor buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok")); buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes")); buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no")); buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel")); buttons["ok"].hideMode = buttons["yes"].hideMode = buttons["no"].hideMode = buttons["cancel"].hideMode = 'offsets'; dlg.render(document.body); dlg.getEl().addClass('x-window-dlg'); mask = dlg.mask; bodyEl = dlg.body.createChild({ html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div>' }); iconEl = Ext.get(bodyEl.dom.firstChild); var contentEl = bodyEl.dom.childNodes[1]; msgEl = Ext.get(contentEl.firstChild); textboxEl = Ext.get(contentEl.childNodes[2]); textboxEl.enableDisplayMode(); textboxEl.addKeyListener([10,13], function(){ if(dlg.isVisible() && opt && opt.buttons){ if(opt.buttons.ok){ handleButton("ok"); }else if(opt.buttons.yes){ handleButton("yes"); } } }); textareaEl = Ext.get(contentEl.childNodes[3]); textareaEl.enableDisplayMode(); progressBar = new Ext.ProgressBar({ renderTo:bodyEl }); bodyEl.createChild({cls:'x-clear'}); } return dlg; }, /** * 更新消息框中 body 元素的文本 * @param {String} text (可选)使用指定的文本替换消息框中元素的 innerHTML (默认为XHTML兼容的非换行空格字符 '&amp;#160;') * @return {Ext.MessageBox} this */ updateText : function(text){ if(!dlg.isVisible() && !opt.width){ dlg.setSize(this.maxWidth, 100); // resize first so content is never clipped from previous shows } msgEl.update(text || '&#160;'); var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0; var mw = msgEl.getWidth() + msgEl.getMargins('lr'); var fw = dlg.getFrameWidth('lr'); var bw = dlg.body.getFrameWidth('lr'); if (Ext.isIE && iw > 0){ //3 pixels get subtracted in the icon CSS for an IE margin issue, //so we have to add it back here for the overall width to be consistent iw += 3; } var w = Math.max(Math.min(opt.width || iw+mw+fw+bw, this.maxWidth), Math.max(opt.minWidth || this.minWidth, bwidth || 0)); if(opt.prompt === true){ activeTextEl.setWidth(w-iw-fw-bw); } if(opt.progress === true || opt.wait === true){ progressBar.setSize(w-iw-fw-bw); } dlg.setSize(w, 'auto').center(); return this; }, /** * 更新带有进度条的消息框中的文本和进度条。 * 仅仅是由通过 {@link Ext.MessageBox#progress} 方法或者是在调用 {@link Ext.MessageBox#show} 方法时使用参数 progress: true 显示的消息框中可用。 * @param {Number} value 0 到 1 之间的任意数字(例如: .5,默认为 0) * @param {String} progressText 进度条中显示的文本(默认为 '') * @param {String} msg 用于替换消息框中 body 元素内容的文本(默认为 undefined,因此如果没有指定该参数则 body 中任何现存的文本将不会被覆写) * @return {Ext.MessageBox} this */ updateProgress : function(value, progressText, msg){ progressBar.updateProgress(value, progressText); if(msg){ this.updateText(msg); } return this; }, /** * 如果消息框当前可见则返回 true * @return {Boolean} 如果消息框当前可见则返回 true,否则返回 false */ isVisible : function(){ return dlg && dlg.isVisible(); }, /** * 如果消息框当前可见则将其隐藏 * @return {Ext.MessageBox} this */ hide : function(){ if(this.isVisible()){ dlg.hide(); handleHide(); } return this; }, /** * 基于给定的配置选项显示一个消息框,或者重新初始一个现存的消息框。 * MessageBox 对象的所有显示函数(例如:prompt、alert、等等)均为内部调用此函数, * 虽然这些调用均为此方法的简单的快捷方式并且不提供所有的下列配置选项。 * <pre> 属性 类型 说明 ---------------- --------------- ----------------------------------------------------------------------------- animEl String/Element 消息框显示和关闭时动画展现的目标元素,或它的 ID(默认为 undefined) buttons Object/Boolean Button 配置对象(例如:Ext.MessageBox.OKCANCEL 或者 {ok:'Foo', cancel:'Bar'}),或者 false 表示不显示任何按钮(默认为 false) closable Boolean 值为 false 则隐藏右上角的关闭按钮(默认为 true)。注意由于 progress 和 wait 对话框只能 通过程序关闭,因此它们将忽略此参数并总是隐藏关闭按钮。 cls String 应用到消息框的元素中的自定义 CSS 类 defaultTextHeight Number 以像素为单位表示的默认消息框的文本域高度,如果有的话(默认为 75) fn Function 当对话框关闭后执行的回调函数。参数包括按钮(被点击的按钮的名字,如果可用,如:"ok"), 文本(活动的文本框的值,如果可用)。Progress 和 wait 对话框将忽略此选项,因为它们不会回应使用者的动作, 并且只能在程序中被关闭,所以任何必须的函数都可以放在关闭对话框的代码中调用。 icon String 一个指定了背景图片地址的 CSS 类名用于对话框显示图标(例如:Ext.MessageBox.WARNING 或者 'custom-class',默认这 '') maxWidth Number 以像素为单位表示的消息框的最大宽度(默认为 600) minWidth Number 以像素为单位表示的消息框的最小宽度(默认为 100) modal Boolean 值为 false 时允许用户在消息框在显示时交互(默认为 true) msg String 使用指定的文本替换消息框中元素的 innerHTML (默认为XHTML兼容的非换行空格字符 '&amp;#160;') multiline Boolean 值为 true 时显示一个提示用户输入多行文本的对话框(默认为 false) progress Boolean 值为 true 时显示一个进度条(默认为 false) progressText String 当 progress = true 时进度条内显示的文本(默认为 '') prompt Boolean 值为 true 时显示一个提示用户输入单行文本的对话框(默认为 false) proxyDrag Boolean 值为 true 则在拖拽的时候显示一个轻量级的代理(默认为 false) title String 标题文本 value String 设置到活动文本框中的文本 wait Boolean 值为 true 时显示一个进度条(默认为 false) waitConfig Object {@link Ext.ProgressBar#waitConfig} 对象(仅在 wait = true 时可用) width Number 以像素为单位表示的对话框的宽度 </pre> * * 用法示例: * <pre><code> Ext.Msg.show({ title: 'Address', msg: 'Please enter your address:', width: 300, buttons: Ext.MessageBox.OKCANCEL, multiline: true, fn: saveAddress, animEl: 'addAddressBtn', icon: Ext.MessagBox.INFO }); </code></pre> * @param {Object} config 配置选项 * @return {Ext.MessageBox} this */ show : function(options){ if(this.isVisible()){ this.hide(); } opt = options; var d = this.getDialog(opt.title || "&#160;"); d.setTitle(opt.title || "&#160;"); var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true); d.tools.close.setDisplayed(allowClose); activeTextEl = textboxEl; opt.prompt = opt.prompt || (opt.multiline ? true : false); if(opt.prompt){ if(opt.multiline){ textboxEl.hide(); textareaEl.show(); textareaEl.setHeight(typeof opt.multiline == "number" ? opt.multiline : this.defaultTextHeight); activeTextEl = textareaEl; }else{ textboxEl.show(); textareaEl.hide(); } }else{ textboxEl.hide(); textareaEl.hide(); } activeTextEl.dom.value = opt.value || ""; if(opt.prompt){ d.focusEl = activeTextEl; }else{ var bs = opt.buttons; var db = null; if(bs && bs.ok){ db = buttons["ok"]; }else if(bs && bs.yes){ db = buttons["yes"]; } if (db){ d.focusEl = db; } } this.setIcon(opt.icon); bwidth = updateButtons(opt.buttons); progressBar.setVisible(opt.progress === true || opt.wait === true); this.updateProgress(0, opt.progressText); this.updateText(opt.msg); if(opt.cls){ d.el.addClass(opt.cls); } d.proxyDrag = opt.proxyDrag === true; d.modal = opt.modal !== false; d.mask = opt.modal !== false ? mask : false; if(!d.isVisible()){ // force it to the end of the z-index stack so it gets a cursor in FF document.body.appendChild(dlg.el.dom); d.setAnimateTarget(opt.animEl); d.show(opt.animEl); } //workaround for window internally enabling keymap in afterShow d.on('show', function(){ if(allowClose === true){ d.keyMap.enable(); }else{ d.keyMap.disable(); } }); if(opt.wait === true){ progressBar.wait(opt.waitConfig); } return this; }, /** * 添加指定的图标到对话框中。默认情况下,'ext-mb-icon' 被应用于默认的样式,给定的样式类需要指定背景图片地址。 * 如果要清除图标则给定一个空字串('')。下面是提供的内建图标样式类,当然你也可以给定一个自定义的类: * <pre> Ext.MessageBox.INFO Ext.MessageBox.WARNING Ext.MessageBox.QUESTION Ext.MessageBox.ERROR *</pre> * @param {String} icon 一个指定了背景图片地址的 CSS 类名,或者一个空字串表示清除图标 * @return {Ext.MessageBox} this */ setIcon : function(icon){ if(icon && icon != ''){ iconEl.removeClass('x-hidden'); iconEl.replaceClass(iconCls, icon); iconCls = icon; }else{ iconEl.replaceClass(iconCls, 'x-hidden'); iconCls = ''; } return this; }, /** * 显示一个带有进度条的消息框。此消息框没有按钮并且无法被用户关闭。 * 你必须通过 {@link Ext.MessageBox#updateProgress} 方法更新进度条,并当进度完成时关闭消息框。 * @param {String} title 标题文本 * @param {String} msg 消息框 body 文本 * @param {String} progressText 进度条显示的文本(默认为 '') * @return {Ext.MessageBox} this */ progress : function(title, msg, progressText){ this.show({ title : title, msg : msg, buttons: false, progress:true, closable:false, minWidth: this.minProgressWidth, progressText: progressText }); return this; }, /** * 显示一个带有不断自动更新的进度条的消息框。这个可以被用在一个长时间运行的进程中防止用户交互。你需要在进程完成的时候关闭消息框。 * @param {String} msg 消息框 body 文本 * @param {String} title (可选) 标题文本 * @param {Object} config (可选) {@link Ext.ProgressBar#waitConfig} 对象 * @return {Ext.MessageBox} this */ wait : function(msg, title, config){ this.show({ title : title, msg : msg, buttons: false, closable:false, wait:true, modal:true, minWidth: this.minProgressWidth, waitConfig: config }); return this; }, /** * 显示一个标准的带有确认按钮的只读消息框(类似于 JavaScript 原生的 alert、prompt)。 * 如果给定了回调函数,则会在用户点击按钮后执行,并且被点击的按钮的 ID 会当做唯一的参数传入到回调函数中(也有可能是右上角的关闭按钮)。 * @param {String} title 标题文本 * @param {String} msg 消息框 body 文本 * @param {Function} fn (可选)消息框被关闭后调用的回调函数 * @param {Object} scope (可选)回调函数的作用域 * @return {Ext.MessageBox} this */ alert : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.OK, fn: fn, scope : scope }); return this; }, /** * 显示一个带有是和否按钮的确认消息框(等同与 JavaScript 原生的 confirm)。 * 如果给定了回调函数,则会在用户点击按钮后执行,并且被点击的按钮的 ID 会当做唯一的参数传入到回调函数中(也有可能是右上角的关闭按钮)。 * @param {String} title 标题文本 * @param {String} msg 消息框 body 文本 * @param {Function} fn (可选) 消息框被关闭后调用的回调函数 * @param {Object} scope (可选) 回调函数的作用域 * @return {Ext.MessageBox} this */ confirm : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.YESNO, fn: fn, scope : scope, icon: this.QUESTION }); return this; }, /** * 显示一个带有确认和取消按钮的提示框,并接受用户输入文本(等同与 JavaScript 原生的 prompt)。 * 提示框可以是一个单行或多行文本框。如果给定了回调函数,则在用户点击任意一个按钮后执行回调函数, * 并且被点击的按钮的 ID(有可能是右上角的关闭按钮)和用户输入的文本都将被当做参数传给回调函数。 * @param {String} title 标题文本 * @param {String} msg 消息框 body 文本 * @param {Function} fn (可选)消息框被关闭后调用的回调函数 * @param {Object} scope (可选)回调函数的作用域 * @param {Boolean/Number} multiline (可选)值为 true 时则创建一个 defaultTextHeight * 值指定行数的文本域,或者一个以像素为单位表示的高度(默认为 false,表示单行) * @return {Ext.MessageBox} this */ prompt : function(title, msg, fn, scope, multiline){ this.show({ title : title, msg : msg, buttons: this.OKCANCEL, fn: fn, minWidth:250, scope : scope, prompt:true, multiline: multiline }); return this; }, /** * 只显示一个确认按钮的 Button 配置项 * @type Object */ OK : {ok:true}, /** * 只显示一个取消按钮的 Button 配置项 * @type Object */ CANCEL : {cancel:true}, /** * 显示确认和取消按钮的 Button 配置项 * @type Object */ OKCANCEL : {ok:true, cancel:true}, /** * 显示是和否按钮的 Button 配置项 * @type Object */ YESNO : {yes:true, no:true}, /** * 显示是、否和取消按钮的 Button 配置项 * @type Object */ YESNOCANCEL : {yes:true, no:true, cancel:true}, /** * 显示 INFO 图标的 CSS 类 * @type String */ INFO : 'ext-mb-info', /** * 显示 WARNING 图标的 CSS 类 * @type String */ WARNING : 'ext-mb-warning', /** * 显示 QUESTION 图标的 CSS 类 * @type String */ QUESTION : 'ext-mb-question', /** * 显示 ERROR 图标的 CSS 类 * @type String */ ERROR : 'ext-mb-error', /** * 以像素为单位表示的消息框中文本域的默认高度(默认为 75) * @type Number */ defaultTextHeight : 75, /** * 以像素为单位表示的消息框的最大宽度(默认为 600) * @type Number */ maxWidth : 600, /** * 以像素为单位表示的消息框的最小宽度(默认为 100) * @type Number */ minWidth : 100, /** * 带有进度条的对话框的以像素为单位表示的最小宽度。在与纯文本对话框设置不同的最小宽度时会用到(默认为 250) * @type Number */ minProgressWidth : 250, /** * 一个包含默认的按钮文本字串的对象,为本地化支持时可以被覆写。 * 可用的属性有:ok、cancel、yes 和 no。通常情况下你可以通过包含一个本地资源文件来实现整个框架的本地化。 * 像这样就可以定制默认的文本:Ext.MessageBox.buttonText.yes = "是"; //中文 * @type Object */ buttonText : { ok : "OK", cancel : "Cancel", yes : "Yes", no : "No" } }; }(); /** * {@link Ext.MessageBox} 的缩写 */ Ext.Msg = Ext.MessageBox;
JavaScript
/** * @class Ext.TabPanel * <p>基础性的tab容器。Tab面板(Tab Panels)可用于如标准{@link Ext.Panel}的布局目的, * 亦可将多个面板归纳为一组tabs的特殊用途。</p> * <p>这里没有实际tab类,每一张tab便是一个{@link Ext.Panel}。然而,当Panel放在TabPanel * 里面作子面板渲染时会额外增加若干事件,而这些事件一般的Panel是没有的,如下列:</p> * <ul> * <li><b>activate</b>: 当面板变成为活动时触发。 * <div class="mdetail-params"> * <strong style="font-weight: normal;">侦听器(Listeners)调用时会有下列的参数:</strong> * <ul><li><code>tab</code> : Panel<div class="sub-desc">被激活的tab对象/div></li></ul> * </div></li> * <li><b>deactivate</b>: 当活动的面板变成为不活动的状态触发。 * <div class="mdetail-params"> * <strong style="font-weight: normal;">侦听器(Listeners)调用时会有下列的参数:</strong> * <ul><li><code>tab</code> : Panel<div class="sub-desc">取消活动状态的tab对象</div></li></ul> * </div></li> * </ul> * <p>有几种途径可生成Tab面板本身,下面演示的是纯粹通过代码来创建和渲染tabs.</p> * <pre><code> var tabs = new Ext.TabPanel({ renderTo: Ext.getBody(), activeTab: 0, items: [{ title: 'Tab 1', html: 'A simple tab' },{ title: 'Tab 2', html: 'Another one' }] }); </pre></code> * <p>TabPanels can also be rendered from markup in a couple of ways. See the {@link #autoTabs} example for * rendering entirely from markup that is already structured correctly as a TabPanel (a container div with * one or more nested tab divs with class 'x-tab'). You can also render from markup that is not strictly * structured by simply specifying by id which elements should be the container and the tabs. Using this method, * tab content can be pulled from different elements within the page by id regardless of page structure. Note * that the tab divs in this example contain the class 'x-hide-display' so that they can be rendered deferred * without displaying outside the tabs. You could alternately set {@link #deferredRender} to false to render all * content tabs on page load. For example: * <pre><code> * 整个TabPanel对象也可以由标签,分别几个途径来创建。参阅{@link #autoTabs}的例子了解由标签创建的全部过程。这些标签必须是符合TabPanel的要求的 * (div作为容器,然后内含一个或多个'x-tab'样式类的div表示每个标签页)。同时你也可以通过指定id方式来选择哪个是容器的div、哪个是标签页的div, * 该方式下,标签页的内容会从页面上不同元素中提取,而不需要考虑页面的分配结构,自由度较高。注意该例中class属性为'x-hide-display'的DIV表示 * 延时渲染标签页,不会导致标签页在TabPanel外部的区域渲染显示出来。你可选择设置{@link #deferredRender}为false表示所有的内容在页面加载时就渲染出来。例如: var tabs = new Ext.TabPanel({ renderTo: 'my-tabs', activeTab: 0, items:[ {contentEl:'tab1', title:'Tab 1'}, {contentEl:'tab2', title:'Tab 2'} ] }); // Note that the tabs do not have to be nested within the container (although they can be) // 注意tab没有被容器套着(尽管也是可以套着的) &lt;div id="my-tabs">&lt;/div> &lt;div id="tab1" class="x-hide-display">A simple tab&lt;/div> &lt;div id="tab2" class="x-hide-display">Another one&lt;/div> </pre></code> * @extends Ext.Panel * @constructor * @param {Object} config 配置项对象 */ Ext.TabPanel = Ext.extend(Ext.Panel, { /** * @cfg {Boolean} layoutOnTabChange True表示为每当Tab切换时就绘制一次布局. */ /** * @cfg {Boolean} monitorResize True表示为自动随着window的大小变化,按照浏览器的大小渲染布局.(默认为 true). */ monitorResize : true, /** * @cfg {Boolean} deferredRender 内置地, Tab面板是采用 {@link Ext.layout.CardLayout} 的方法管理tabs. * 此属性的值将会传递到布局的 {@link Ext.layout.CardLayout#deferredRender} 配置值中,以决定是否只有tab面板 * 第一次访问时才渲染 (缺省为 true). */ deferredRender : true, /** * @cfg {Number} tabWidth 每一张新tab的初始宽度,单位为象素 (缺省为 120). */ tabWidth: 120, /** * @cfg {Number} minTabWidth 每张tab宽度的最小值,仅当 {@link #resizeTabs} = true有效 (缺省为 30). */ minTabWidth: 30, /** * @cfg {Boolean} resizeTabs True to automatically resize each tab so that the tabs will completely fill the * tab strip (defaults to false). * Setting this to true may cause specific widths that might be set per tab to * be overridden in order to fit them all into view (although {@link #minTabWidth} will always be honored). * * True表示为自动调整各个标签页的宽度,以便适应当前TabPanel的候选栏的宽度(默认为false)。 * 这样设置的话,那么每个标签页都可能会一个规定的宽度,原先标签页的宽度将不会保留以便适应显示(尽管{@link #minTabWidth}依然作用)。 */ resizeTabs:false, /** * @cfg {Number} enableTabScroll * True to enable scrolling to tabs that may be invisible due to overflowing the * overall TabPanel width. Only available with tabs on top. (defaults to false). * * 『有时标签页会超出TabPanel的整体宽度。为防止此情况下溢出的标签页不可见,就需要将此项设为true以出现标签页可滚动的功能。 * 只当标签页位于上方的位置时有效(默认为false)。』 */ enableTabScroll: false, /** * @cfg {Number} scrollIncrement * The number of pixels to scroll each time a tab scroll button is pressed (defaults * to 100, or if {@link #resizeTabs} = true, the calculated tab width). * Only applies when {@link #enableTabScroll} = true. * * 『每次滚动按钮按下时,被滚动的标签页所移动的距离(单位是像素,默认为100,若{@link #resizeTabs}=true,那么默认值将是计算好的标签页宽度)。 * 只当{@link #enableTabScroll} = true时有效。』 */ scrollIncrement : 0, /** * @cfg {Number} scrollRepeatInterval Number of milliseconds between each scroll while a tab scroll button is * continuously pressed (defaults to 400). * * 『当标签页滚动按钮不停地被按下时,两次执行滚动的间隔的毫秒数(默认为400)。』 */ scrollRepeatInterval : 400, /** * @cfg {Float} scrollDuration 每次滚动所产生动画会持续多久(单位毫秒,默认为0.35)。只当{@link #animScroll} = true时有效。 */ scrollDuration : .35, /** * @cfg {Boolean} animScroll True 表示为tab滚动时出现动画效果以使tab在视图中消失得更平滑 (缺省为true). * 只当 {@link #enableTabScroll} = true时有效. */ animScroll : true, /** * @cfg {String} tabPosition Tab候选栏渲染的位置 (默认为 'top'). 其它可支持值是'bottom'. * 注意tab滚动 (tab scrolling) 只支持'top'的位置. */ tabPosition: 'top', /** * @cfg {String} baseCls 作用在面板上CSS样式类 (默认为 'x-tab-panel'). */ baseCls: 'x-tab-panel', /** * @cfg {Boolean} autoTabs * <p>True 表示为查询DOM中任何带 "x-tab' 样式类的div元素,转化为tab加入到此面板中 * (默认为 false)。注意查询的执行范围仅限于容器元素内 * (so that multiple tab panels from markup can be supported via this method) </p> * <p>此时要求markup(装饰元素)结构(即在容器内嵌有'x-tab'类的div元素)才有效. * 要突破这种限制,或从页面上其它元素的内容拉到tab中,可参阅由markup生成tab的第一个示例.</p> * <p>采用这种方法须注意下列几个问题:<ul> * <li>当使用autoTabs的时候(与不同的tab配置传入到tabPanel * {@link #items} 集合的方法相反), 你同时必须使用 {@link #applyTo} * 正确地指明tab容器的id. * AutoTabs 方法把现有的内容替换为TabPanel组件.</li> * <li>确保已设 {@link #deferredRender} 为false,使得每个tab中的内容元素能在页面加载之后立即渲染到 * TabPanel,否则的话激活tab也不能成功渲染.</li> * </ul>用法举例:</p> * <pre><code> var tabs = new Ext.TabPanel({ applyTo: 'my-tabs', activeTab: 0, deferredRender: false, autoTabs: true }); //这些装饰元素会按照以上的代码转换为TabPanel对象 &lt;div id="my-tabs"> &lt;div class="x-tab" title="Tab 1">A simple tab&lt;/div> &lt;div class="x-tab" title="Tab 2">Another one&lt;/div> &lt;/div> </code></pre> */ autoTabs : false, /** * @cfg {String} autoTabSelector 用于搜索tab的那个CSS选择符,当 {@link #autoTabs} * 时有效. (默认为 'div.x-tab'). 此值可是 {@link Ext.DomQuery#select}的任意有效值. * 注意 the query will be executed within the scope of this tab panel only (so that multiple tab panels from * markup can be supported on a page). */ autoTabSelector:'div.x-tab', // private itemCls : 'x-tab-item', /** * @cfg {String/Number} activeTab 一个字符串或数字(索引)表示,渲染后就活动的那个tab (默认为没有). */ activeTab : null, /** * @cfg {Number} tabMargin 此象素值参与大小调整和卷动时的运算,以计算空隙的象素值。如果你在CSS中改变了margin(外补丁),那么这个值也要随着更改,才能正确地计算值(默认为2) */ tabMargin : 2, /** * @cfg {Boolean} plain True表示为不渲染tab候选栏上背景容器图片(默认为false)。 */ plain: false, /** * @cfg {Number} wheelIncrement 对于可滚动的tabs,鼠标滚轮翻页一下的步长值,单位为象素(缺省为20)。 */ wheelIncrement : 20, // private config overrides elements: 'body', headerAsText: false, frame: false, hideBorders:true, // private initComponent : function(){ this.frame = false; Ext.TabPanel.superclass.initComponent.call(this); this.addEvents( /** * @event beforetabchange * 当活动tab改变时触发。若句柄返回false则取消tab的切换。 * @param {TabPanel} this * @param {Panel} newTab 活动着的tab对象 * @param {Panel} currentTab 当前活动tab对象 */ 'beforetabchange', /** * @event tabchange * 当活动tab改变后触发。 * @param {TabPanel} this * @param {Panel} tab 新的活动tab对象 */ 'tabchange', /** * @event contextmenu * 当原始浏览器的右键事件在tab元素上触发时,连动到此事件。 * @param {TabPanel} this * @param {Panel} tab 目标tab对象 * @param {EventObject} e */ 'contextmenu' ); this.setLayout(new Ext.layout.CardLayout({ deferredRender: this.deferredRender })); if(this.tabPosition == 'top'){ this.elements += ',header'; this.stripTarget = 'header'; }else { this.elements += ',footer'; this.stripTarget = 'footer'; } if(!this.stack){ this.stack = Ext.TabPanel.AccessStack(); } this.initItems(); }, // private render : function(){ Ext.TabPanel.superclass.render.apply(this, arguments); if(this.activeTab !== undefined){ var item = this.activeTab; delete this.activeTab; this.setActiveTab(item); } }, // private onRender : function(ct, position){ Ext.TabPanel.superclass.onRender.call(this, ct, position); if(this.plain){ var pos = this.tabPosition == 'top' ? 'header' : 'footer'; this[pos].addClass('x-tab-panel-'+pos+'-plain'); } var st = this[this.stripTarget]; this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{ tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}}); this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'}); this.strip = new Ext.Element(this.stripWrap.dom.firstChild); this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'}); this.strip.createChild({cls:'x-clear'}); this.body.addClass('x-tab-panel-body-'+this.tabPosition); if(!this.itemTpl){ var tt = new Ext.Template( '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>', '<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">', '<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>', '</em></a></li>' ); tt.disableFormats = true; tt.compile(); Ext.TabPanel.prototype.itemTpl = tt; } this.items.each(this.initTab, this); }, // private afterRender : function(){ Ext.TabPanel.superclass.afterRender.call(this); if(this.autoTabs){ this.readTabs(false); } }, // private initEvents : function(){ Ext.TabPanel.superclass.initEvents.call(this); this.on('add', this.onAdd, this); this.on('remove', this.onRemove, this); this.strip.on('mousedown', this.onStripMouseDown, this); this.strip.on('click', this.onStripClick, this); this.strip.on('contextmenu', this.onStripContextMenu, this); if(this.enableTabScroll){ this.strip.on('mousewheel', this.onWheel, this); } }, // private findTargets : function(e){ var item = null; var itemEl = e.getTarget('li', this.strip); if(itemEl){ item = this.getComponent(itemEl.id.split('__')[1]); if(item.disabled){ return { close : null, item : null, el : null }; } } return { close : e.getTarget('.x-tab-strip-close', this.strip), item : item, el : itemEl }; }, // private onStripMouseDown : function(e){ e.preventDefault(); if(e.button != 0){ return; } var t = this.findTargets(e); if(t.close){ this.remove(t.item); return; } if(t.item && t.item != this.activeTab){ this.setActiveTab(t.item); } }, // private onStripClick : function(e){ var t = this.findTargets(e); if(!t.close && t.item && t.item != this.activeTab){ this.setActiveTab(t.item); } }, // private onStripContextMenu : function(e){ e.preventDefault(); var t = this.findTargets(e); if(t.item){ this.fireEvent('contextmenu', this, t.item, e); } }, /** * True表示为使用autoTabSelector选择符来扫描此tab面板内的markup,以准备autoTabs的特性。 * @param {Boolean} removeExisting True表示为移除现有的tabs */ readTabs : function(removeExisting){ if(removeExisting === true){ this.items.each(function(item){ this.remove(item); }, this); } var tabs = this.el.query(this.autoTabSelector); for(var i = 0, len = tabs.length; i < len; i++){ var tab = tabs[i]; var title = tab.getAttribute('title'); tab.removeAttribute('title'); this.add({ title: title, el: tab }); } }, // private initTab : function(item, index){ var before = this.strip.dom.childNodes[index]; var cls = item.closable ? 'x-tab-strip-closable' : ''; if(item.disabled){ cls += ' x-item-disabled'; } if(item.iconCls){ cls += ' x-tab-with-icon'; } var p = { id: this.id + '__' + item.getItemId(), text: item.title, cls: cls, iconCls: item.iconCls || '' }; var el = before ? this.itemTpl.insertBefore(before, p) : this.itemTpl.append(this.strip, p); Ext.fly(el).addClassOnOver('x-tab-strip-over'); if(item.tabTip){ Ext.fly(el).child('span.x-tab-strip-text', true).qtip = item.tabTip; } item.on('disable', this.onItemDisabled, this); item.on('enable', this.onItemEnabled, this); item.on('titlechange', this.onItemTitleChanged, this); item.on('beforeshow', this.onBeforeShowItem, this); }, // private onAdd : function(tp, item, index){ this.initTab(item, index); if(this.items.getCount() == 1){ this.syncSize(); } this.delegateUpdates(); }, // private onBeforeAdd : function(item){ var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item); if(existing){ this.setActiveTab(item); return false; } Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments); var es = item.elements; item.elements = es ? es.replace(',header', '') : es; item.border = (item.border === true); }, // private onRemove : function(tp, item){ Ext.removeNode(this.getTabEl(item)); this.stack.remove(item); if(item == this.activeTab){ var next = this.stack.next(); if(next){ this.setActiveTab(next); }else{ this.setActiveTab(0); } } this.delegateUpdates(); }, // private onBeforeShowItem : function(item){ if(item != this.activeTab){ this.setActiveTab(item); return false; } }, // private onItemDisabled : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).addClass('x-item-disabled'); } this.stack.remove(item); }, // private onItemEnabled : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).removeClass('x-item-disabled'); } }, // private onItemTitleChanged : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).child('span.x-tab-strip-text', true).innerHTML = item.title; } }, /** * 指定一个子面板,返回此面板在tab候选栏上的DOM元素。访问DOM元素可以修改一些可视化效果,例如更改CSS样式类的名称。 * @param {Panel} tab tab对象 * @return {HTMLElement} DOM节点 */ getTabEl : function(item){ return document.getElementById(this.id+'__'+item.getItemId()); }, // private onResize : function(){ Ext.TabPanel.superclass.onResize.apply(this, arguments); this.delegateUpdates(); }, /** * 暂停一切内置的运算或卷动好让扩充操作(bulk operation)进行。参阅{@link #endUpdate}。 */ beginUpdate : function(){ this.suspendUpdates = true; }, /** * 结束扩充操作(bulk operation)后,重新开始一切内置的运算或滚动效果。参阅{@link #beginUpdate}。 */ endUpdate : function(){ this.suspendUpdates = false; this.delegateUpdates(); }, /** * 隐藏Tab候选栏以传入tab。 * @param {Number/String/Panel} item tab索引、id或item对象 */ hideTabStripItem : function(item){ item = this.getComponent(item); var el = this.getTabEl(item); if(el){ el.style.display = 'none'; this.delegateUpdates(); } }, /** * 取消Tab候选栏隐藏的状态以传入tab。 * @param {Number/String/Panel} item tab索引、id或item对象 */ unhideTabStripItem : function(item){ item = this.getComponent(item); var el = this.getTabEl(item); if(el){ el.style.display = ''; this.delegateUpdates(); } }, // private delegateUpdates : function(){ if(this.suspendUpdates){ return; } if(this.resizeTabs && this.rendered){ this.autoSizeTabs(); } if(this.enableTabScroll && this.rendered){ this.autoScrollTabs(); } }, // private autoSizeTabs : function(){ var count = this.items.length; var ce = this.tabPosition != 'bottom' ? 'header' : 'footer'; var ow = this[ce].dom.offsetWidth; var aw = this[ce].dom.clientWidth; if(!this.resizeTabs || count < 1 || !aw){ // !aw for display:none return; } var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.tabMargin, this.tabWidth), this.minTabWidth); // -4 for float errors in IE this.lastTabWidth = each; var lis = this.stripWrap.dom.getElementsByTagName('li'); for(var i = 0, len = lis.length-1; i < len; i++) { // -1 for the "edge" li var li = lis[i]; var inner = li.childNodes[1].firstChild.firstChild; var tw = li.offsetWidth; var iw = inner.offsetWidth; inner.style.width = (each - (tw-iw)) + 'px'; } }, // private adjustBodyWidth : function(w){ if(this.header){ this.header.setWidth(w); } if(this.footer){ this.footer.setWidth(w); } return w; }, /** * 设置特定的tab为活动面板。 * 此方法触发{@link #beforetabchange}事件,若处理函数返回false则取消tab切换。 * @param {String/Panel} tab 活动面板或其id */ setActiveTab : function(item){ item = this.getComponent(item); if(!item || this.fireEvent('beforetabchange', this, item, this.activeTab) === false){ return; } if(!this.rendered){ this.activeTab = item; return; } if(this.activeTab != item){ if(this.activeTab){ var oldEl = this.getTabEl(this.activeTab); if(oldEl){ Ext.fly(oldEl).removeClass('x-tab-strip-active'); } this.activeTab.fireEvent('deactivate', this.activeTab); } var el = this.getTabEl(item); Ext.fly(el).addClass('x-tab-strip-active'); this.activeTab = item; this.stack.add(item); this.layout.setActiveItem(item); if(this.layoutOnTabChange && item.doLayout){ item.doLayout(); } if(this.scrolling){ this.scrollToTab(item, this.animScroll); } item.fireEvent('activate', item); this.fireEvent('tabchange', this, item); } }, /** * 返回当前活动的Tab。 * @return {Panel} 活动的Tab */ getActiveTab : function(){ return this.activeTab || null; }, /** * 根据id获取指定tab * @param {String} id Tab的ID * @return {Panel} tab */ getItem : function(item){ return this.getComponent(item); }, // private autoScrollTabs : function(){ var count = this.items.length; var ow = this.header.dom.offsetWidth; var tw = this.header.dom.clientWidth; var wrap = this.stripWrap; var cw = wrap.dom.offsetWidth; var pos = this.getScrollPos(); var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos; if(!this.enableTabScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues return; } if(l <= tw){ wrap.dom.scrollLeft = 0; wrap.setWidth(tw); if(this.scrolling){ this.scrolling = false; this.header.removeClass('x-tab-scrolling'); this.scrollLeft.hide(); this.scrollRight.hide(); } }else{ if(!this.scrolling){ this.header.addClass('x-tab-scrolling'); } tw -= wrap.getMargins('lr'); wrap.setWidth(tw > 20 ? tw : 20); if(!this.scrolling){ if(!this.scrollLeft){ this.createScrollers(); }else{ this.scrollLeft.show(); this.scrollRight.show(); } } this.scrolling = true; if(pos > (l-tw)){ // ensure it stays within bounds wrap.dom.scrollLeft = l-tw; }else{ // otherwise, make sure the active tab is still visible this.scrollToTab(this.activeTab, false); } this.updateScrollButtons(); } }, // private createScrollers : function(){ var h = this.stripWrap.dom.offsetHeight; // left var sl = this.header.insertFirst({ cls:'x-tab-scroller-left' }); sl.setHeight(h); sl.addClassOnOver('x-tab-scroller-left-over'); this.leftRepeater = new Ext.util.ClickRepeater(sl, { interval : this.scrollRepeatInterval, handler: this.onScrollLeft, scope: this }); this.scrollLeft = sl; // right var sr = this.header.insertFirst({ cls:'x-tab-scroller-right' }); sr.setHeight(h); sr.addClassOnOver('x-tab-scroller-right-over'); this.rightRepeater = new Ext.util.ClickRepeater(sr, { interval : this.scrollRepeatInterval, handler: this.onScrollRight, scope: this }); this.scrollRight = sr; }, // private getScrollWidth : function(){ return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos(); }, // private getScrollPos : function(){ return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0; }, // private getScrollArea : function(){ return parseInt(this.stripWrap.dom.clientWidth, 10) || 0; }, // private getScrollAnim : function(){ return {duration:this.scrollDuration, callback: this.updateScrollButtons, scope: this}; }, // private getScrollIncrement : function(){ return this.scrollIncrement || (this.resizeTabs ? this.lastTabWidth+2 : 100); }, /** * 滚动到指定的TAB * @param {Panel} item 要滚动到项 * @param {Boolean} animate True表示有动画效果 */ scrollToTab : function(item, animate){ if(!item){ return; } var el = this.getTabEl(item); var pos = this.getScrollPos(), area = this.getScrollArea(); var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos; var right = left + el.offsetWidth; if(left < pos){ this.scrollTo(left, animate); }else if(right > (pos + area)){ this.scrollTo(right - area, animate); } }, // private scrollTo : function(pos, animate){ this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false); if(!animate){ this.updateScrollButtons(); } }, onWheel : function(e){ var d = e.getWheelDelta()*this.wheelIncrement*-1; e.stopEvent(); var pos = this.getScrollPos(); var newpos = pos + d; var sw = this.getScrollWidth()-this.getScrollArea(); var s = Math.max(0, Math.min(sw, newpos)); if(s != pos){ this.scrollTo(s, false); } }, // private onScrollRight : function(){ var sw = this.getScrollWidth()-this.getScrollArea(); var pos = this.getScrollPos(); var s = Math.min(sw, pos + this.getScrollIncrement()); if(s != pos){ this.scrollTo(s, this.animScroll); } }, // private onScrollLeft : function(){ var pos = this.getScrollPos(); var s = Math.max(0, pos - this.getScrollIncrement()); if(s != pos){ this.scrollTo(s, this.animScroll); } }, // private updateScrollButtons : function(){ var pos = this.getScrollPos(); this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('x-tab-scroller-left-disabled'); this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('x-tab-scroller-right-disabled'); } /** * @cfg {Boolean} collapsible * @hide */ /** * @cfg {String} header * @hide */ /** * @cfg {Boolean} headerAsText * @hide */ /** * @property header * @hide */ }); Ext.reg('tabpanel', Ext.TabPanel); /** * 设置特定的tab为活动面板。 * 此方法触发{@link #beforetabchange}事件若返回false则取消tab切换。 * @param {String/Panel} tab 活动面板或其id * @method activate */ Ext.TabPanel.prototype.activate = Ext.TabPanel.prototype.setActiveTab; // private utility class used by TabPanel Ext.TabPanel.AccessStack = function(){ var items = []; return { add : function(item){ items.push(item); if(items.length > 10){ items.shift(); } }, remove : function(item){ var s = []; for(var i = 0, len = items.length; i < len; i++) { if(items[i] != item){ s.push(items[i]); } } items = s; }, next : function(){ return items.pop(); } }; };
JavaScript
/* * Ext JS Library 2.1 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** * @class Ext.Slider * @extends Ext.BoxComponent * Slider which supports vertical or horizontal orientation, keyboard adjustments, * configurable snapping, axis clicking and animation. Can be added as an item to * any container. Example usage: <pre><code> new Ext.Slider({ renderTo: Ext.getBody(), width: 200, value: 50, increment: 10, minValue: 0, maxValue: 100 }); </code></pre> */ Ext.Slider = Ext.extend(Ext.BoxComponent, { /** * @cfg {Number} value The value to initialize the slider with. Defaults to minValue. */ /** * @cfg {Boolean} vertical Orient the Slider vertically rather than horizontally, defaults to false. */ vertical: false, /** * @cfg {Number} minValue The minimum value for the Slider. Defaults to 0. */ minValue: 0, /** * @cfg {Number} maxValue The maximum value for the Slider. Defaults to 100. */ maxValue: 100, /** * @cfg {Number} keyIncrement How many units to change the Slider when adjusting with keyboard navigation. Defaults to 1. If the increment config is larger, it will be used instead. */ keyIncrement: 1, /** * @cfg {Number} increment How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'. */ increment: 0, // private clickRange: [5,15], /** * @cfg {Boolean} clickToChange Determines whether or not clicking on the Slider axis will change the slider. Defaults to true */ clickToChange : true, /** * @cfg {Boolean} animate Turn on or off animation. Defaults to true */ animate: true, // private override initComponent : function(){ if(this.value === undefined){ this.value = this.minValue; } Ext.Slider.superclass.initComponent.call(this); this.keyIncrement = Math.max(this.increment, this.keyIncrement); this.addEvents( /** * @event beforechange * Fires before the slider value is changed. By returning false from an event handler, * you can cancel the event and prevent the slider from changing. * @param {Ext.Slider} slider The slider * @param {Number} newValue The new value which the slider is being changed to. * @param {Number} oldValue The old value which the slider was previously. */ 'beforechange', /** * @event change * Fires when the slider value is changed. * @param {Ext.Slider} slider The slider * @param {Number} newValue The new value which the slider has been changed to. */ 'change', /** * @event dragstart * Fires after a drag operation has started. * @param {Ext.Slider} slider The slider * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker */ 'dragstart', /** * @event drag * Fires continuously during the drag operation while the mouse is moving. * @param {Ext.Slider} slider The slider * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker */ 'drag', /** * @event dragend * Fires after the drag operation has completed. * @param {Ext.Slider} slider The slider * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker */ 'dragend' ); if(this.vertical){ Ext.apply(this, Ext.Slider.Vertical); } }, // private override onRender : function(){ this.autoEl = { cls: 'x-slider ' + (this.vertical ? 'x-slider-vert' : 'x-slider-horz'), cn:{cls:'x-slider-end',cn:{cls:'x-slider-inner',cn:[{cls:'x-slider-thumb'},{tag:'a', cls:'x-slider-focus', href:"#", tabIndex: '-1', hidefocus:'on'}]}} }; Ext.Slider.superclass.onRender.apply(this, arguments); this.endEl = this.el.first(); this.innerEl = this.endEl.first(); this.thumb = this.innerEl.first(); this.halfThumb = (this.vertical ? this.thumb.getHeight() : this.thumb.getWidth())/2; this.focusEl = this.thumb.next(); this.initEvents(); }, // private override initEvents : function(){ this.thumb.addClassOnOver('x-slider-thumb-over'); this.mon(this.el, 'mousedown', this.onMouseDown, this); this.mon(this.el, 'keydown', this.onKeyDown, this); this.tracker = new Ext.dd.DragTracker({ onBeforeStart: this.onBeforeDragStart.createDelegate(this), onStart: this.onDragStart.createDelegate(this), onDrag: this.onDrag.createDelegate(this), onEnd: this.onDragEnd.createDelegate(this), tolerance: 3, autoStart: 300 }); this.tracker.initEl(this.thumb); this.on('beforedestroy', this.tracker.destroy, this.tracker); }, // private override onMouseDown : function(e){ if(this.disabled) {return;} if(this.clickToChange && e.target != this.thumb.dom){ var local = this.innerEl.translatePoints(e.getXY()); this.onClickChange(local); } this.focus(); }, // private onClickChange : function(local){ if(local.top > this.clickRange[0] && local.top < this.clickRange[1]){ this.setValue(Math.round(local.left/this.getRatio())); } }, // private onKeyDown : function(e){ if(this.disabled){e.preventDefault();return;} var k = e.getKey(); switch(k){ case e.UP: case e.RIGHT: e.stopEvent(); if(e.ctrlKey){ this.setValue(this.maxValue); }else{ this.setValue(this.value+this.keyIncrement); } break; case e.DOWN: case e.LEFT: e.stopEvent(); if(e.ctrlKey){ this.setValue(this.minValue); }else{ this.setValue(this.value-this.keyIncrement); } break; default: e.preventDefault(); } }, // private doSnap : function(value){ if(!this.increment || this.increment == 1 || !value) { return value; } var newValue = value, inc = this.increment; var m = value % inc; if(m > 0){ if(m > (inc/2)){ newValue = value + (inc-m); }else{ newValue = value - m; } } return newValue.constrain(this.minValue, this.maxValue); }, // private afterRender : function(){ Ext.Slider.superclass.afterRender.apply(this, arguments); if(this.value !== undefined){ var v = this.normalizeValue(this.value); if(v !== this.value){ delete this.value; this.setValue(v, false); }else{ this.moveThumb(this.translateValue(v), false); } } }, // private getRatio : function(){ var w = this.innerEl.getWidth(); var v = this.maxValue - this.minValue; return w/v; }, // private normalizeValue : function(v){ if(typeof v != 'number'){ v = parseInt(v); } v = Math.round(v); v = this.doSnap(v); v = v.constrain(this.minValue, this.maxValue); return v; }, /** * Programmatically sets the value of the Slider. Ensures that the value is constrained within * the minValue and maxValue. * @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue) * @param {Boolean} animate Turn on or off animation, defaults to true */ setValue : function(v, animate){ v = this.normalizeValue(v); if(v !== this.value && this.fireEvent('beforechange', this, v, this.value) !== false){ this.value = v; this.moveThumb(this.translateValue(v), animate !== false); this.fireEvent('change', this, v); } }, // private translateValue : function(v){ return (v * this.getRatio())-this.halfThumb; }, // private moveThumb: function(v, animate){ if(!animate || this.animate === false){ this.thumb.setLeft(v); }else{ this.thumb.shift({left: v, stopFx: true, duration:.35}); } }, // private focus : function(){ this.focusEl.focus(10); }, // private onBeforeDragStart : function(e){ return !this.disabled; }, // private onDragStart: function(e){ this.thumb.addClass('x-slider-thumb-drag'); this.fireEvent('dragstart', this, e); }, // private onDrag: function(e){ var pos = this.innerEl.translatePoints(this.tracker.getXY()); this.setValue(Math.round(pos.left/this.getRatio()), false); this.fireEvent('drag', this, e); }, // private onDragEnd: function(e){ this.thumb.removeClass('x-slider-thumb-drag'); this.fireEvent('dragend', this, e); }, // private onResize : function(w, h){ this.innerEl.setWidth(w - (this.el.getPadding('l') + this.endEl.getPadding('r'))); }, /** * Returns the current value of the slider * @return {Number} The current value of the slider */ getValue : function(){ return this.value; } }); Ext.reg('slider', Ext.Slider); // private class to support vertical sliders Ext.Slider.Vertical = { onResize : function(w, h){ this.innerEl.setHeight(h - (this.el.getPadding('t') + this.endEl.getPadding('b'))); }, getRatio : function(){ var h = this.innerEl.getHeight(); var v = this.maxValue - this.minValue; return h/v; }, moveThumb: function(v, animate){ if(!animate || this.animate === false){ this.thumb.setBottom(v); }else{ this.thumb.shift({bottom: v, stopFx: true, duration:.35}); } }, onDrag: function(e){ var pos = this.innerEl.translatePoints(this.tracker.getXY()); var bottom = this.innerEl.getHeight()-pos.top; this.setValue(Math.round(bottom/this.getRatio()), false); this.fireEvent('drag', this, e); }, onClickChange : function(local){ if(local.left > this.clickRange[0] && local.left < this.clickRange[1]){ var bottom = this.innerEl.getHeight()-local.top; this.setValue(Math.round(bottom/this.getRatio())); } } };
JavaScript
/** * @class Ext.Action * <p>Action 是可复用性中可以抽象出来,被任意特定组件所继承的特性之一。 * Action 使你可以通过所有实现了 Actions 接口的组件共享处理函数、配置选项对象以及 UI 的更新(比如 {@link Ext.Toolbar}、{@link Ext.Button} 和 {@link Ext.menu.Menu} 组件)。</p> * <p>除了提供的配置选项对象接口之外,任何想要使用 Action 的组件必需提供下列方法以便在 Action 所需时调用:setText(string)、setIconCls(string)、setDisabled(boolean)、setVisible(boolean)和setHandler(function)。</p> * 使用示例:<br> * <pre><code> // Define the shared action. Each component below will have the same // display text and icon, and will display the same message on click. var action = new Ext.Action({ text: 'Do something', handler: function(){ Ext.Msg.alert('Click', 'You did something.'); }, iconCls: 'do-something' }); var panel = new Ext.Panel({ title: 'Actions', width:500, height:300, tbar: [ // Add the action directly to a toolbar as a menu button action, { text: 'Action Menu', // Add the action to a menu as a text item menu: [action] } ], items: [ // Add the action to the panel body as a standard button new Ext.Button(action) ], renderTo: Ext.getBody() }); // Change the text for all components using the action action.setText('Something else'); </code></pre> * @constructor * @param {Object} config 配置选项对象 */ Ext.Action = function(config){ this.initialConfig = config; this.items = []; } Ext.Action.prototype = { /** * @cfg {String} text 使用 action 对象的所有组件的文本(默认为 '')。 */ /** * @cfg {String} iconCls 使用 action 对象的组件的图标样式表(默认为 '')。 * 该样式类应该提供一个显示为图标的背景图片。 */ /** * @cfg {Boolean} disabled true 则禁用组件,false 则启用组件(默认为 false)。 */ /** * @cfg {Boolean} hidden true 则隐藏组件,false 则显示组件(默认为 false)。 */ /** * @cfg {Function} handler 每个使用 action 对象的组件的主要事件触发时调用的处理函数(默认为 undefined)。 */ /** * @cfg {Object} scope {@link #handler} 函数执行的作用域。 */ // private isAction : true, /** * 设置使用 action 对象的所有组件的文本。 * @param {String} text 显示的文本 */ setText : function(text){ this.initialConfig.text = text; this.callEach('setText', [text]); }, /** * 获取使用 action 对象的组件当前显示的文本。 */ getText : function(){ return this.initialConfig.text; }, /** * 设置使用 action 对象的组件的图标样式表。该样式类应该提供一个显示为图标的背景图片。 * @param {String} cls 提供图标图片的 CSS 样式类 */ setIconClass : function(cls){ this.initialConfig.iconCls = cls; this.callEach('setIconClass', [cls]); }, /** * 获取使用 action 对象的组件的图标样式表。 */ getIconClass : function(){ return this.initialConfig.iconCls; }, /** * 设置所有使用 action 对象的组件的 disabled 状态。{@link #enable} 和 {@link #disable} 方法的快捷方式。 * @param {Boolean} disabled true 则禁用组件,false 则启用组件 */ setDisabled : function(v){ this.initialConfig.disabled = v; this.callEach('setDisabled', [v]); }, /** * 启用所有使用 action 对象的组件。 */ enable : function(){ this.setDisabled(false); }, /** * 禁用所有使用 action 对象的组件。 */ disable : function(){ this.setDisabled(true); }, /** * 如果组件当前使用的 action 对象是禁用的,则返回 true,否则返回 false。只读。 * @property */ isDisabled : function(){ return this.initialConfig.disabled; }, /** * 设置所有使用 action 对象的组件的 hidden 状态。{@link #hide} 和 {@link #show} 方法的快捷方式。 * @param {Boolean} hidden true 则隐藏组件,false 则显示组件 */ setHidden : function(v){ this.initialConfig.hidden = v; this.callEach('setVisible', [!v]); }, /** * 显示所有使用 action 对象的组件。 */ show : function(){ this.setHidden(false); }, /** * 隐藏所有使用 action 对象的组件。 */ hide : function(){ this.setHidden(true); }, /** * 如果组件当前使用的 action 对象是隐藏的,则返回 true,否则返回 false。只读。 * @property */ isHidden : function(){ return this.initialConfig.hidden; }, /** * 为每个使用 action 对象的组件设置主要事件触发时调用的处理函数。 * @param {Function} fn action 对象的组件调用的函数。调用该函数时没有参数。 * @param {Object} scope 函数运行的作用域 */ setHandler : function(fn, scope){ this.initialConfig.handler = fn; this.initialConfig.scope = scope; this.callEach('setHandler', [fn, scope]); }, /** * 绑定到当前 action 对象上的所有组件都执行一次指定的函数。传入的函数将接受一个由 action 对象所支持的配置选项对象组成的参数。 * @param {Function} fn 每个组件执行的函数 * @param {Object} scope 函数运行的作用域 */ each : function(fn, scope){ Ext.each(this.items, fn, scope); }, // private callEach : function(fnName, args){ var cs = this.items; for(var i = 0, len = cs.length; i < len; i++){ cs[i][fnName].apply(cs[i], args); } }, // private addComponent : function(comp){ this.items.push(comp); comp.on('destroy', this.removeComponent, this); }, // private removeComponent : function(comp){ this.items.remove(comp); } };
JavaScript
/** * @class Ext.DataView * @extends Ext.BoxComponent * 能够为自己设计模板和特定格式而提供的一种数据显示机制。 * DataView采用{@link Ext.XTemplate}为其模板处理的机制,并依靠{@link Ext.data.Store}来绑定数据,这样的话store中数据发生变化时便会自动更新前台。DataView亦提供许多针对对象项(item)的内建事件,如单击、双击、mouseover、mouseout等等,还包括一个内建的选区模型(selection model)。<b>要实现以上这些功能,必须要为DataView对象设置一个itemSelector协同工作。</b> * <p>下面给出的例子是已将DataView绑定到一个{@link Ext.data.Store}对象并在一个上{@link Ext.Panel}渲染。</p> * <pre><code> var store = new Ext.data.JsonStore({ url: 'get-images.php', root: 'images', fields: [ 'name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date', dateFormat:'timestamp'} ] }); store.load(); var tpl = new Ext.XTemplate( '&lt;tpl for="."&gt;', '&lt;div class="thumb-wrap" id="{name}"&gt;', '&lt;div class="thumb"&gt;&lt;img src="{url}" title="{name}"&gt;&lt;/div&gt;', '&lt;span class="x-editable"&gt;{shortName}&lt;/span&gt;&lt;/div&gt;', '&lt;/tpl&gt;', '&lt;div class="x-clear"&gt;&lt;/div&gt;' ); var panel = new Ext.Panel({ id:'images-view', frame:true, width:535, autoHeight:true, collapsible:true, layout:'fit', title:'Simple DataView', items: new Ext.DataView({ store: store, tpl: tpl, autoHeight:true, multiSelect: true, overClass:'x-view-over', itemSelector:'div.thumb-wrap', emptyText: 'No images to display' }) }); panel.render(document.body); </code></pre> * @constructor * 创建一个新的DataView对象 * @param {Object} config 配置对象 */ Ext.DataView = Ext.extend(Ext.BoxComponent, { /** * @cfg {String/Array} tpl * 构成这个DataView的HTML片断,或片断的数组,其格式应正如{@link Ext.XTemplate}构造器的一样。 */ /** * @cfg {Ext.data.Store} store * 此DataView所绑定的{@link Ext.data.Store} */ /** * @cfg {String} itemSelector * <b>此项是必须的设置</b>。任何符号{@link Ext.DomQuery}格式的CSS选择符,以确定DataView所使用的节点是哪一种元素 */ /** * @cfg {Boolean} multiSelect * True表示为允许同时可以选取多个对象项,false表示只能同时选择单个对象项 * 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 ,false表示没有选区也是可以的(默认为false)。 * 注意当{@link #multiSelect} = true时,该项会被忽略。 */ /** * @cfg {Boolean} simpleSelect * True表示为不需要用户按下Shift或Ctrl键就可以实现多选,false表示用户一定要用户按下Shift或Ctrl键才可以多选对象项(默认为false)。 */ /** * @cfg {String} overClass * 视图中每一项mouseover事件触发时所应用到的CSS样式类(默认为undefined) */ /** * @cfg {String} loadingText * 当数据加载进行时显示的字符串(默认为undefined)。 If specified, this text will be * displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's * contents will continue to display normally until the new data is loaded and the contents are replaced. */ /** * @cfg {String} selectedClass * 视图中每个选中项所应用到的CSS样式类(默认为'x-view-selected') */ selectedClass : "x-view-selected", /** * @cfg {String} emptyText * 没有数据显示时,向用户提示的信息(默认为'') */ emptyText : "", //private last: false, // private initComponent : function(){ Ext.DataView.superclass.initComponent.call(this); if(typeof this.tpl == "string"){ this.tpl = new Ext.XTemplate(this.tpl); } this.addEvents( /** * @event beforeclick * 单击执行之前触发,返回 false 则取消默认的动作。 * @param {Ext.DataView} this DataView * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "beforeclick", /** * @event click * 当模板节点单击时触发事件,如返回 false 则取消默认的动作。 * @param {Ext.DataView} this DataView * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "click", /** * @event containerclick * 当点击发生时但又不在模板节点上发生时触发 * @param {Ext.DataView} this * @param {Ext.EventObject} e 原始事件对象 */ "containerclick", /** * @event dblclick * 当模板节点双击时触发事件 * @param {Ext.DataView} this DataView * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "dblclick", /** * @event contextmenu * 当模板节右击时触发事件 * @param {Ext.DataView} this DataView * @param {Number} index 目标节点的索引 * @param {HTMLElement} node 目标节点 * @param {Ext.EventObject} e 原始事件对象 */ "contextmenu", /** * @event selectionchange * 当选取改变时触发. * @param {Ext.DataView} this DataView * @param {Array} selections 已选取节点所组成的数组 */ "selectionchange", /** * @event beforeselect * 选取生成之前触发,如返回false,则选区不会生成。 * @param {Ext.DataView} this DataView * @param {HTMLElement} node 要选取的节点 * @param {Array} selections 当前已选取节点所组成的数组 */ "beforeselect" ); this.all = new Ext.CompositeElementLite(); this.selected = new Ext.CompositeElementLite(); }, // private onRender : function(){ if(!this.el){ this.el = document.createElement('div'); } Ext.DataView.superclass.onRender.apply(this, arguments); }, // private afterRender : function(){ Ext.DataView.superclass.afterRender.call(this); this.el.on({ "click": this.onClick, "dblclick": this.onDblClick, "contextmenu": this.onContextMenu, scope:this }); if(this.overClass){ this.el.on({ "mouseover": this.onMouseOver, "mouseout": this.onMouseOut, scope:this }); } if(this.store){ this.setStore(this.store, true); } }, /** * 刷新视图。重新加载store的数据并重新渲染模板 */ refresh : function(){ this.clearSelections(false, true); this.el.update(""); var html = []; var records = this.store.getRange(); if(records.length < 1){ this.el.update(this.emptyText); this.all.clear(); return; } this.tpl.overwrite(this.el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, this.el.dom)); this.updateIndexes(0); }, /** * 重写该函数,可对每个节点的数据进行格式化,再交给模板进一步处理. * @param {Array/Object} data 原始数据,是Data Model所绑定的视图的colData数组,或Updater数据对象绑定的JSON对象 */ prepareData : function(data){ return data; }, // private collectData : function(records, startIndex){ var r = []; for(var i = 0, len = records.length; i < len; i++){ r[r.length] = this.prepareData(records[i].data, startIndex+i, records[i]); } return r; }, // private bufferRender : function(records){ var div = document.createElement('div'); this.tpl.overwrite(div, this.collectData(records)); return Ext.query(this.itemSelector, div); }, // private onUpdate : function(ds, record){ var index = this.store.indexOf(record); var sel = this.isSelected(index); var original = this.all.elements[index]; var node = this.bufferRender([record], index)[0]; this.all.replaceElement(index, node, true); if(sel){ this.selected.replaceElement(original, node); this.all.item(index).addClass(this.selectedClass); } this.updateIndexes(index, index); }, // private onAdd : function(ds, records, index){ if(this.all.getCount() == 0){ this.refresh(); return; } var nodes = this.bufferRender(records, index), n; if(index < this.all.getCount()){ n = this.all.item(index).insertSibling(nodes, 'before', true); this.all.elements.splice(index, 0, n); }else{ n = this.all.last().insertSibling(nodes, 'after', true); this.all.elements.push(n); } this.updateIndexes(index); }, // private onRemove : function(ds, record, index){ this.deselect(index); this.all.removeElement(index, true); this.updateIndexes(index); }, /** * 刷新不同的节点的数据(来自store)。 * @param {Number} index 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; } }, /** * 改变在使用的Data Store并刷新 view。 * @param {Store} store 绑定这个view的store对象 */ setStore : function(store, initial){ if(!initial && this.store){ this.store.un("beforeload", this.onBeforeLoad, this); this.store.un("datachanged", this.refresh, this); this.store.un("add", this.onAdd, this); this.store.un("remove", this.onRemove, this); this.store.un("update", this.onUpdate, this); this.store.un("clear", this.refresh, this); } if(store){ store = Ext.StoreMgr.lookup(store); store.on("beforeload", this.onBeforeLoad, this); store.on("datachanged", this.refresh, this); store.on("add", this.onAdd, this); store.on("remove", this.onRemove, this); store.on("update", this.onUpdate, this); store.on("clear", this.refresh, this); } this.store = store; if(store){ this.refresh(); } }, /** * 传入一个节点(node)的参数,返回该属于模板的节点,返回null则代表它不属于模板的任何一个节点。 * @param {HTMLElement} node * @return {HTMLElement} 模板节点 */ findItemFromChild : function(node){ return Ext.fly(node).findParent(this.itemSelector, this.el); }, // private onClick : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ var index = this.indexOf(item); if(this.onItemClick(item, index, e) !== false){ this.fireEvent("click", this, index, item, e); } }else{ if(this.fireEvent("containerclick", this, e) !== false){ this.clearSelections(); } } }, // private onContextMenu : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ this.fireEvent("contextmenu", this, this.indexOf(item), item, e); } }, // private onDblClick : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ this.fireEvent("dblclick", this, this.indexOf(item), item, e); } }, // private onMouseOver : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item && item !== this.lastItem){ this.lastItem = item; Ext.fly(item).addClass(this.overClass); } }, // private onMouseOut : function(e){ if(this.lastItem){ if(!e.within(this.lastItem, true)){ Ext.fly(this.lastItem).removeClass(this.overClass); delete this.lastItem; } } }, // private onItemClick : function(item, index, e){ if(this.fireEvent("beforeclick", this, index, item, e) === false){ return false; } if(this.multiSelect){ this.doMultiSelection(item, index, e); e.preventDefault(); }else if(this.singleSelect){ this.doSingleSelection(item, index, e); e.preventDefault(); } return true; }, // private doSingleSelection : function(item, index, e){ if(e.ctrlKey && this.isSelected(index)){ this.deselect(index); }else{ this.select(index, false); } }, // private doMultiSelection : function(item, index, e){ if(e.shiftKey && this.last !== false){ var last = this.last; this.selectRange(last, index, e.ctrlKey); this.last = last; // reset the last }else{ if((e.ctrlKey||this.simpleSelect) && this.isSelected(index)){ this.deselect(index); }else{ this.select(index, e.ctrlKey || e.shiftKey || this.simpleSelect); } } }, /** * 返回选中节点的数量 * @return {Number} 节点数量 */ getSelectionCount : function(){ return this.selected.getCount() }, /** * 返回当前选中的节点 * @return {Array} HTMLElements数组 */ getSelectedNodes : function(){ return this.selected.elements; }, /** * 返回选中的节点的索引 * @return {Array} 数字索引的数组 */ getSelectedIndexes : function(){ var indexes = [], s = this.selected.elements; for(var i = 0, len = s.length; i < len; i++){ indexes.push(s[i].viewIndex); } return indexes; }, /** * 返回所选记录组成的数组 * @return {Array} {@link Ext.data.Record}对象数组 */ getSelectedRecords : function(){ var r = [], s = this.selected.elements; for(var i = 0, len = s.length; i < len; i++){ r[r.length] = this.store.getAt(s[i].viewIndex); } return r; }, /** * 从一个节点数组中返回记录节点 * @param {Array} nodes 参与运算的节点 * @return {Array} {@link Ext.data.Record}记录对象的数组 */ getRecords : function(nodes){ var r = [], s = nodes; for(var i = 0, len = s.length; i < len; i++){ r[r.length] = this.store.getAt(s[i].viewIndex); } return r; }, /** * 返回节点的记录 * @param {HTMLElement} node 涉及的节点 * @return {Record} {@link Ext.data.Record}对象 */ getRecord : function(node){ return this.store.getAt(node.viewIndex); }, /** * 清除所有选区 * @param {Boolean} suppressEvent (可选的)True跃过触发selectionchange的事件 */ clearSelections : function(suppressEvent, skipUpdate){ if(this.multiSelect || this.singleSelect){ if(!skipUpdate){ this.selected.removeClass(this.selectedClass); } this.selected.clear(); this.last = false; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selected.elements); } } }, /** * 传入一个节点的参数,如果是属于已选取的话便返回true否则返回false。 * @param {HTMLElement/Number} node 节点或节点索引 * @return {Boolean} true表示选中否则返回false */ isSelected : function(node){ return this.selected.contains(this.getNode(node)); }, /** * 反选节点 * @param {HTMLElement/Number} node 反选的节点 */ deselect : function(node){ if(this.isSelected(node)){ var node = this.getNode(node); this.selected.removeElement(node); if(this.last == node.viewIndex){ this.last = false; } Ext.fly(node).removeClass(this.selectedClass); this.fireEvent("selectionchange", this, this.selected.elements); } }, /** * 选取节点 * @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID * @param {Boolean} keepExisting (可选项) true 代表保留当前选区 * @param {Boolean} suppressEvent (可选项) true表示为跳过所有selectionchange事件 */ select : function(nodeInfo, keepExisting, suppressEvent){ if(nodeInfo instanceof Array){ if(!keepExisting){ this.clearSelections(true); } for(var i = 0, len = nodeInfo.length; i < len; i++){ this.select(nodeInfo[i], true, true); } } else{ var node = this.getNode(nodeInfo); if(!keepExisting){ this.clearSelections(true); } if(node && !this.isSelected(node)){ if(this.fireEvent("beforeselect", this, node, this.selected.elements) !== false){ Ext.fly(node).addClass(this.selectedClass); this.selected.add(node); this.last = node.viewIndex; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selected.elements); } } } } }, /** * 选中某个范围内的节点。所有的节点都是被选中。 * @param {Number} start 索引头 在范围中第一个节点的索引 * @param {Number} end 索引尾 在范围中最后一个节点的索引 * @param {Boolean} keepExisting (可选项) true 代表保留当前选区 */ selectRange : function(start, end, keepExisting){ if(!keepExisting){ this.clearSelections(true); } this.select(this.getNodes(start, end), true); }, /** * 获取多个模板节点 * @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID * @return {HTMLElement} 若找不到返回null */ getNode : function(nodeInfo){ if(typeof nodeInfo == "string"){ return document.getElementById(nodeInfo); }else if(typeof nodeInfo == "number"){ return this.all.elements[nodeInfo]; } return nodeInfo; }, /** * 获取某个范围的模板节点。 * @param {Number} start 索引头 在范围中第一个节点的索引 * @param {Number} end 索引尾 在范围中最后一个节点的索引 * @return {Array} 节点数组 */ getNodes : function(start, end){ var ns = this.all.elements; start = start || 0; end = typeof end == "undefined" ? ns.length - 1 : end; var nodes = [], i; if(start <= end){ for(i = start; i <= end; i++){ nodes.push(ns[i]); } } else{ for(i = start; i >= end; i--){ nodes.push(ns[i]); } } return nodes; }, /** * 传入一个node作为参数,找到它的索引 * @param {HTMLElement/String/Number} nodeInfo HTMLElement类型的模板节点,模板节点的索引或是模板节点的ID * @return {Number} 节点索引或-1 * */ indexOf : function(node){ node = this.getNode(node); if(typeof node.viewIndex == "number"){ return node.viewIndex; } return this.all.indexOf(node); }, // private onBeforeLoad : function(){ if(this.loadingText){ this.clearSelections(false, true); this.el.update('<div class="loading-indicator">'+this.loadingText+'</div>'); this.all.clear(); } } }); Ext.reg('dataview', Ext.DataView);
JavaScript
/** * @class Ext.Shadow * 为所有元素提供投影效果的一个简易类。 注意元素必须为绝对定位,而且投影并没有填充的效果(shimming)。 * 这只是适用简单的场合- 如想提供更高阶的投影效果,请参阅{@link Ext.Layer}类。 * @constructor * Create a new Shadow * @param {Object} config 配置项对象 */ Ext.Shadow = function(config){ Ext.apply(this, config); if(typeof this.mode != "string"){ this.mode = this.defaultMode; } var o = this.offset, a = {h: 0}; var rad = Math.floor(this.offset/2); switch(this.mode.toLowerCase()){ // all this hideous nonsense calculates the various offsets for shadows case "drop": a.w = 0; a.l = a.t = o; a.t -= 1; if(Ext.isIE){ a.l -= this.offset + rad; a.t -= this.offset + rad; a.w -= rad; a.h -= rad; a.t += 1; } break; case "sides": a.w = (o*2); a.l = -o; a.t = o-1; if(Ext.isIE){ a.l -= (this.offset - rad); a.t -= this.offset + rad; a.l += 1; a.w -= (this.offset - rad)*2; a.w -= rad + 1; a.h -= 1; } break; case "frame": a.w = a.h = (o*2); a.l = a.t = -o; a.t += 1; a.h -= 2; if(Ext.isIE){ a.l -= (this.offset - rad); a.t -= (this.offset - rad); a.l += 1; a.w -= (this.offset + rad + 1); a.h -= (this.offset + rad); a.h += 1; } break; }; this.adjusts = a; }; Ext.Shadow.prototype = { /** * @cfg {String} mode * 投影显示的模式。有下列选项:<br /> * sides: 投影限显示在两边和底部<br /> * frame: 投影在四边均匀出现<br /> * drop: 传统的物理效果的,底部和右边。这是默认值。 */ /** * @cfg {String} offset * 元素和投影之间的偏移象素值(默认为4) */ offset: 4, // private defaultMode: "drop", /** * 在目标元素上显示投影, * @param {String/HTMLElement/Element} targetEl 指定要显示投影的那个元素 */ show : function(target){ target = Ext.get(target); if(!this.el){ this.el = Ext.Shadow.Pool.pull(); if(this.el.dom.nextSibling != target.dom){ this.el.insertBefore(target); } } this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1); if(Ext.isIE){ this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")"; } this.realign( target.getLeft(true), target.getTop(true), target.getWidth(), target.getHeight() ); this.el.dom.style.display = "block"; }, /** * 返回投影是否在显示 */ isVisible : function(){ return this.el ? true : false; }, /** * 当值可用时直接对称位置。 * Show方法必须至少在调用realign方法之前调用一次,以保证能够初始化。 * @param {Number} left 目标元素left位置 * @param {Number} top 目标元素top位置 * @param {Number} width 目标元素宽度 * @param {Number} height 目标元素高度 */ realign : function(l, t, w, h){ if(!this.el){ return; } var a = this.adjusts, d = this.el.dom, s = d.style; var iea = 0; s.left = (l+a.l)+"px"; s.top = (t+a.t)+"px"; var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px"; if(s.width != sws || s.height != shs){ s.width = sws; s.height = shs; if(!Ext.isIE){ var cn = d.childNodes; var sww = Math.max(0, (sw-12))+"px"; cn[0].childNodes[1].style.width = sww; cn[1].childNodes[1].style.width = sww; cn[2].childNodes[1].style.width = sww; cn[1].style.height = Math.max(0, (sh-12))+"px"; } } }, /** * 隐藏投影 */ hide : function(){ if(this.el){ this.el.dom.style.display = "none"; Ext.Shadow.Pool.push(this.el); delete this.el; } }, /** * 调整该投影的z-index * @param {Number} zindex 新z-index */ setZIndex : function(z){ this.zIndex = z; if(this.el){ this.el.setStyle("z-index", z); } } }; // Private utility class that manages the internal Shadow cache Ext.Shadow.Pool = function(){ var p = []; var markup = Ext.isIE ? '<div class="x-ie-shadow"></div>' : '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>'; return { pull : function(){ var sh = p.shift(); if(!sh){ sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup)); sh.autoBoxAdjust = false; } return sh; }, push : function(sh){ p.push(sh); } }; }();
JavaScript
/** * @class Ext.PagingToolbar * @extends Ext.Toolbar * 一个要和{@link Ext.data.Store}绑定并且自动提供翻页控制的工具栏. * @constructor * 创建一个新的翻页工具栏 * @param {Object} config 配置对象 */ Ext.PagingToolbar = Ext.extend(Ext.Toolbar, { /** * @cfg {Ext.data.Store} store 翻页工具栏应该使用{@link Ext.data.Store}作为它的数据源 (在需要的时候). */ /** * @cfg {Boolean} displayInfo * 为true时展示展现信息 (默认为false) */ /** * @cfg {Number} pageSize * 每页要展现的记录数 (默认为 20) */ pageSize: 20, /** * @cfg {String} displayMsg * 用来显示翻页的情况信息 (默认为"Displaying {0} - {1} of {2}"). * 注意这个字符串里大括号中的数字是一种标记,其中的数字分别代表起始值,结束值和总数.当重写这个字符串的时候如果这些值是要显示的,那么这些标识应该被保留下来 */ displayMsg : 'Displaying {0} - {1} of {2}', /** * @cfg {String} emptyMsg * 没有数据记录的时候所展示的信息 (默认为"No data to display") */ emptyMsg : 'No data to display', /** * 可定制的默认翻页文本 (默认为 to "Page") * @type String */ beforePageText : "Page", /** * 可定制的默认翻页文本 (默认为 to "of %0") * @type String */ afterPageText : "of {0}", /** * 可定制的默认翻页文本 (默认为 "First Page") * @type String */ firstText : "First Page", /** * 可定制的默认翻页文本 (defaults to "Previous Page") * @type String */ prevText : "Previous Page", /** * 可定制的默认翻页文本 (defaults to "Next Page") * @type String */ nextText : "Next Page", /** * 可定制的默认翻页文本 (defaults to "Last Page") * @type String */ lastText : "Last Page", /** * 可定制的默认翻页文本 (defaults to "Refresh") * @type String */ refreshText : "Refresh", /** * 加载调用时的参数名对象映射(默认为 {start: 'start', limit: 'limit'}) */ paramNames : {start: 'start', limit: 'limit'}, initComponent : function(){ Ext.PagingToolbar.superclass.initComponent.call(this); this.cursor = 0; this.bind(this.store); }, // private onRender : function(ct, position){ Ext.PagingToolbar.superclass.onRender.call(this, ct, position); this.first = this.addButton({ tooltip: this.firstText, iconCls: "x-tbar-page-first", disabled: true, handler: this.onClick.createDelegate(this, ["first"]) }); this.prev = this.addButton({ tooltip: this.prevText, iconCls: "x-tbar-page-prev", disabled: true, handler: this.onClick.createDelegate(this, ["prev"]) }); this.addSeparator(); this.add(this.beforePageText); this.field = Ext.get(this.addDom({ tag: "input", type: "text", size: "3", value: "1", cls: "x-tbar-page-number" }).el); this.field.on("keydown", this.onPagingKeydown, this); this.field.on("focus", function(){this.dom.select();}); this.afterTextEl = this.addText(String.format(this.afterPageText, 1)); this.field.setHeight(18); this.addSeparator(); this.next = this.addButton({ tooltip: this.nextText, iconCls: "x-tbar-page-next", disabled: true, handler: this.onClick.createDelegate(this, ["next"]) }); this.last = this.addButton({ tooltip: this.lastText, iconCls: "x-tbar-page-last", disabled: true, handler: this.onClick.createDelegate(this, ["last"]) }); this.addSeparator(); this.loading = this.addButton({ tooltip: this.refreshText, iconCls: "x-tbar-loading", handler: this.onClick.createDelegate(this, ["refresh"]) }); if(this.displayInfo){ this.displayEl = Ext.fly(this.el.dom).createChild({cls:'x-paging-info'}); } if(this.dsLoaded){ this.onLoad.apply(this, this.dsLoaded); } }, // private updateInfo : function(){ if(this.displayEl){ var count = this.store.getCount(); var msg = count == 0 ? this.emptyMsg : String.format( this.displayMsg, this.cursor+1, this.cursor+count, this.store.getTotalCount() ); this.displayEl.update(msg); } }, // private onLoad : function(store, r, o){ if(!this.rendered){ this.dsLoaded = [store, r, o]; return; } this.cursor = o.params ? o.params[this.paramNames.start] : 0; var d = this.getPageData(), ap = d.activePage, ps = d.pages; this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages); this.field.dom.value = ap; this.first.setDisabled(ap == 1); this.prev.setDisabled(ap == 1); this.next.setDisabled(ap == ps); this.last.setDisabled(ap == ps); this.loading.enable(); this.updateInfo(); }, // private getPageData : function(){ var total = this.store.getTotalCount(); return { total : total, activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize), pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize) }; }, // private onLoadError : function(){ if(!this.rendered){ return; } this.loading.enable(); }, readPage : function(d){ var v = this.field.dom.value, pageNum; if (!v || isNaN(pageNum = parseInt(v, 10))) { this.field.dom.value = d.activePage; return false; } return pageNum; }, // private onPagingKeydown : function(e){ var k = e.getKey(), d = this.getPageData(), pageNum; if (k == e.RETURN) { e.stopEvent(); if(pageNum = this.readPage(d)){ pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1; this.doLoad(pageNum * this.pageSize); } }else if (k == e.HOME || k == e.END){ e.stopEvent(); pageNum = k == e.HOME ? 1 : d.pages; this.field.dom.value = pageNum; }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){ e.stopEvent(); if(pageNum = this.readPage(d)){ var increment = e.shiftKey ? 10 : 1; if(k == e.DOWN || k == e.PAGEDOWN){ increment *= -1; } pageNum += increment; if(pageNum >= 1 & pageNum <= d.pages){ this.field.dom.value = pageNum; } } } }, // private beforeLoad : function(){ if(this.rendered && this.loading){ this.loading.disable(); } }, doLoad : function(start){ var o = {}, pn = this.paramNames; o[pn.start] = start; o[pn.limit] = this.pageSize; this.store.load({params:o}); }, // private onClick : function(which){ var store = this.store; switch(which){ case "first": this.doLoad(0); break; case "prev": this.doLoad(Math.max(0, this.cursor-this.pageSize)); break; case "next": this.doLoad(this.cursor+this.pageSize); break; case "last": var total = store.getTotalCount(); var extra = total % this.pageSize; var lastStart = extra ? (total - extra) : total-this.pageSize; this.doLoad(lastStart); break; case "refresh": this.doLoad(this.cursor); break; } }, /** * 从指定的 {@link Ext.data.Store}数据源解除翻页工具栏绑定 * @param {Ext.data.Store} store 要解除绑定的数据源 */ unbind : function(store){ store = Ext.StoreMgr.lookup(store); store.un("beforeload", this.beforeLoad, this); store.un("load", this.onLoad, this); store.un("loadexception", this.onLoadError, this); this.store = undefined; }, /** * 在数据源 {@link Ext.data.Store} 上绑定指定翻页工具栏 * @param {Ext.data.Store} store 要绑定的数据源 */ bind : function(store){ store = Ext.StoreMgr.lookup(store); store.on("beforeload", this.beforeLoad, this); store.on("load", this.onLoad, this); store.on("loadexception", this.onLoadError, this); this.store = store; } }); Ext.reg('paging', Ext.PagingToolbar);
JavaScript
/* // Internal developer documentation -- will not show up in API docs * @class Ext.dd.PanelProxy * 为 {@link Ext.Panel} 对象定制的拖拽代理的实现。该主要被 Panel 对象在内部调用以实现拖拽,因此不需要直接创建。 * @constructor * @param panel 要代理的 {@link Ext.Panel} 对象 * @param config 配置选项对象 */ Ext.dd.PanelProxy = function(panel, config){ this.panel = panel; this.id = this.panel.id +'-ddproxy'; Ext.apply(this, config); }; Ext.dd.PanelProxy.prototype = { /** * @cfg {Boolean} insertProxy 如果值为 true 则在拖拽 Panel 时插入一个代理占位元素,值为 false 则在拖拽时没有代理(默认为 true)。 */ insertProxy : true, // private overrides setStatus : Ext.emptyFn, reset : Ext.emptyFn, update : Ext.emptyFn, stop : Ext.emptyFn, sync: Ext.emptyFn, /** * 获取代理元素 * @return {Element} 代理元素 */ getEl : function(){ return this.ghost; }, /** * 获取代理的影子元素 * @return {Element} 代理的影子元素 */ getGhost : function(){ return this.ghost; }, /** * 获取代理元素 * @return {Element} 代理元素 */ getProxy : function(){ return this.proxy; }, /** * 隐藏代理 */ hide : function(){ if(this.ghost){ if(this.proxy){ this.proxy.remove(); delete this.proxy; } this.panel.el.dom.style.display = ''; this.ghost.remove(); delete this.ghost; } }, /** * 显示代理 */ show : function(){ if(!this.ghost){ this.ghost = this.panel.createGhost(undefined, undefined, Ext.getBody()); this.ghost.setXY(this.panel.el.getXY()) if(this.insertProxy){ this.proxy = this.panel.el.insertSibling({cls:'x-panel-dd-spacer'}); this.proxy.setSize(this.panel.getSize()); } this.panel.el.dom.style.display = 'none'; } }, // private repair : function(xy, callback, scope){ this.hide(); if(typeof callback == "function"){ callback.call(scope || this); } }, /** * 将代理元素移动到 DOM 中不同的位置。通常该方法被用来当拖拽 Panel 对象时保持两者位置的同步。 * @param {HTMLElement} parentNode 代理元素的父级 DOM 节点 * @param {HTMLElement} before (可选)代理被插入的位置的前一个侧边节点(如果不指定则默认为父节点的最后一个子节点) */ moveProxy : function(parentNode, before){ if(this.proxy){ parentNode.insertBefore(this.proxy.dom, before); } } }; // private - DD implementation for Panels Ext.Panel.DD = function(panel, cfg){ this.panel = panel; this.dragData = {panel: panel}; this.proxy = new Ext.dd.PanelProxy(panel, cfg); Ext.Panel.DD.superclass.constructor.call(this, panel.el, cfg); this.setHandleElId(panel.header.id); panel.header.setStyle('cursor', 'move'); this.scroll = false; }; Ext.extend(Ext.Panel.DD, Ext.dd.DragSource, { showFrame: Ext.emptyFn, startDrag: Ext.emptyFn, b4StartDrag: function(x, y) { this.proxy.show(); }, b4MouseDown: function(e) { var x = e.getPageX(); var y = e.getPageY(); this.autoOffset(x, y); }, onInitDrag : function(x, y){ this.onStartDrag(x, y); return true; }, createFrame : Ext.emptyFn, getDragEl : function(e){ return this.proxy.ghost.dom; }, endDrag : function(e){ this.proxy.hide(); this.panel.saveState(); }, autoOffset : function(x, y) { x -= this.startPageX; y -= this.startPageY; this.setDelta(x, y); } });
JavaScript
/** * @class Ext.SplitButton * @extends Ext.Button * 一个提供了内建下拉箭头的分割按钮,该箭头还可以触发按钮默认的 click 之外的事件。 * 典型的应用场景是,用来显示一个为主按钮提供附加选项的下拉菜单,并且可以为 arrowclick 事件设置单独的处理函数。 * @cfg {Function} arrowHandler 点击箭头时调用的函数(可以用来代替的 click 事件) * @cfg {String} arrowTooltip 箭头的 title 属性 * @constructor * 创建一个菜单按钮 * @param {Object} config 配置选项对象 */ Ext.SplitButton = Ext.extend(Ext.Button, { arrowSelector : 'button:last', initComponent : function(){ Ext.SplitButton.superclass.initComponent.call(this); /** * @event arrowclick * 当点击按钮的箭头时触发 * @param {MenuButton} this * @param {EventObject} e click 事件对象 */ this.addEvents("arrowclick"); }, onRender : function(ct, position){ // this is one sweet looking template! var tpl = new Ext.Template( '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>', '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>', '<tr><td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>', "</tbody></table></td><td>", '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>', '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button">&#160;</button></td><td class="x-btn-right"><i>&#160;</i></td></tr>', "</tbody></table></td></tr></table>" ); var btn, targs = [this.text || '&#160;', this.type]; if(position){ btn = tpl.insertBefore(position, targs, true); }else{ btn = tpl.append(ct, targs, true); } var btnEl = btn.child(this.buttonSelector); this.initButtonEl(btn, btnEl); this.arrowBtnTable = btn.child("table:last"); if(this.arrowTooltip){ btn.child(this.arrowSelector).dom[this.tooltipType] = this.arrowTooltip; } }, // private autoWidth : function(){ if(this.el){ var tbl = this.el.child("table:first"); var tbl2 = this.el.child("table:last"); this.el.setWidth("auto"); tbl.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child(this.buttonSelector); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){ tbl.setWidth(this.minWidth-tbl2.getWidth()); } } this.el.setWidth(tbl.getWidth()+tbl2.getWidth()); } }, /** * 设置按钮的箭头点击处理函数 * @param {Function} handler 点击箭头时调用的函数 * @param {Object} scope (可选)处理函数的作用域 */ setArrowHandler : function(handler, scope){ this.arrowHandler = handler; this.scope = scope; }, // private onClick : function(e){ e.preventDefault(); if(!this.disabled){ if(e.getTarget(".x-btn-menu-arrow-wrap")){ if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){ this.showMenu(); } this.fireEvent("arrowclick", this, e); if(this.arrowHandler){ this.arrowHandler.call(this.scope || this, this, e); } }else{ if(this.enableToggle){ this.toggle(); } this.fireEvent("click", this, e); if(this.handler){ this.handler.call(this.scope || this, this, e); } } } }, getClickEl : function(e, isUp){ if(!isUp){ return (this.lastClickEl = e.getTarget("table", 10, true)); } return this.lastClickEl; }, onDisable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.addClass("x-item-disabled"); } this.el.child(this.buttonSelector).dom.disabled = true; this.el.child(this.arrowSelector).dom.disabled = true; } this.disabled = true; }, onEnable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.removeClass("x-item-disabled"); } this.el.child(this.buttonSelector).dom.disabled = false; this.el.child(this.arrowSelector).dom.disabled = false; } this.disabled = false; }, isMenuTriggerOver : function(e){ return this.menu && e.within(this.arrowBtnTable) && !e.within(this.arrowBtnTable, true); }, isMenuTriggerOut : function(e, internal){ return this.menu && !e.within(this.arrowBtnTable); }, onDestroy : function(){ Ext.destroy(this.arrowBtnTable); Ext.SplitButton.superclass.onDestroy.call(this); } }); // backwards compat Ext.MenuButton = Ext.SplitButton; Ext.reg('splitbutton', Ext.SplitButton);
JavaScript
/* * Ext JS Library 2.0.2 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ /** *@class Ext.Toolbar *@extends Ext.BoxComponent *基本工具栏类.工具栏元素可以通过它们的构造函数明确地被创建,或者通过它们的xtype类型来实现。一些项也有创建的简单字符串。 *@constructor *创建一个新的工具栏 *@param {Object/Array} config 要添加的一个配置对象或者一个要按钮数组 */ Ext.Toolbar = function(config){ if(Ext.isArray(config)){ config = {buttons:config}; } Ext.Toolbar.superclass.constructor.call(this, config); }; (function(){ var T = Ext.Toolbar; Ext.extend(T, Ext.BoxComponent, { trackMenus : true, // private initComponent : function(){ T.superclass.initComponent.call(this); if(this.items){ this.buttons = this.items; } /** * 工具栏项的集合类 * @property items * @type Ext.util.MixedCollection */ this.items = new Ext.util.MixedCollection(false, function(o){ return o.itemId || o.id || Ext.id(); }); }, // private autoCreate: { cls:'x-toolbar x-small-editor', html:'<table cellspacing="0"><tr></tr></table>' }, // private onRender : function(ct, position){ this.el = ct.createChild(Ext.apply({ id: this.id },this.autoCreate), position); this.tr = this.el.child("tr", true); }, // private afterRender : function(){ T.superclass.afterRender.call(this); if(this.buttons){ this.add.apply(this, this.buttons); delete this.buttons; } }, /** * 增加一个元素到工具栏上 -- 这个函数可以把许多混合类型的参数添加到工具栏上. * @param {Mixed} arg1 下面的所有参数都是有效的:<br /> * <ul> * <li>{@link Ext.Toolbar.Button} config: 一个有效的按钮配置对象 (等价于{@link #addButton})</li> * <li>HtmlElement: 任何一个标准的HTML元素 (等价于 {@link #addElement})</li> * <li>Field: 任何一个form域 (等价于 {@link #addField})</li> * <li>Item: 任何一个{@link Ext.Toolbar.Item}的子类 (等价于{@link #addItem})</li> * <li>String: 任何一种类型的字符串 (在{@link Ext.Toolbar.TextItem}里被封装, 等价于 {@link #addText}). * 注意:下面这些特殊的字符串被特殊处理</li> * <li>'separator' 或 '-': 创建一个分隔符元素 (等价于 {@link #addSeparator})</li> * <li>' ': 创建一个空白分隔元素 (等价于 {@link #addSpacer})</li> * <li>'->': 创建一个填充元素 (等价于 {@link #addFill})</li> * </ul> * @param {Mixed} arg2 * @param {Mixed} etc. */ add : function(){ var a = arguments, l = a.length; for(var i = 0; i < l; i++){ var el = a[i]; if(el.isFormField){ // some kind of form field this.addField(el); }else if(el.render){ // some kind of Toolbar.Item this.addItem(el); }else if(typeof el == "string"){ // string if(el == "separator" || el == "-"){ this.addSeparator(); }else if(el == " "){ this.addSpacer(); }else if(el == "->"){ this.addFill(); }else{ this.addText(el); } }else if(el.tagName){ // element this.addElement(el); }else if(typeof el == "object"){ // must be button config? if(el.xtype){ this.addField(Ext.ComponentMgr.create(el, 'button')); }else{ this.addButton(el); } } } }, /** * 添加一个分隔符 * @return {Ext.Toolbar.Item} 分隔符项 */ addSeparator : function(){ return this.addItem(new T.Separator()); }, /** * 添加一个空白分隔符 * @return {Ext.Toolbar.Spacer} 空白项 */ addSpacer : function(){ return this.addItem(new T.Spacer()); }, /** * 添加一个填充元素,把后面的元素全都放到工具栏的右侧 * @return {Ext.Toolbar.Fill} The fill item */ addFill : function(){ return this.addItem(new T.Fill()); }, /** * 在工具栏上添加任何一个标准的HTML元素 * @param {Mixed} el 要加入的元素本身或元素其id * @return {Ext.Toolbar.Item} 元素项 */ addElement : function(el){ return this.addItem(new T.Item(el)); }, /** * 添加任何一个 Toolbar.Item 或者其子类 * @param {Ext.Toolbar.Item} item 元素项 * @return {Ext.Toolbar.Item} 元素项 */ addItem : function(item){ var td = this.nextBlock(); this.initMenuTracking(item); item.render(td); this.items.add(item); return item; }, /** * 添加一个按钮(或者一组按钮). 可以查看 {@link Ext.Toolbar.Button} 获取更多的配置信息. * @param {Object/Array} config 按钮的配置项或配置项的数组 * @return {Ext.Toolbar.Button/Array} */ addButton : function(config){ if(Ext.isArray(config)){ var buttons = []; for(var i = 0, len = config.length; i < len; i++) { buttons.push(this.addButton(config[i])); } return buttons; } var b = config; if(!(config instanceof T.Button)){ b = config.split ? new T.SplitButton(config) : new T.Button(config); } var td = this.nextBlock(); this.initMenuTracking(b); b.render(td); this.items.add(b); return b; }, // private initMenuTracking : function(item){ if(this.trackMenus && item.menu){ item.on({ 'menutriggerover' : this.onButtonTriggerOver, 'menushow' : this.onButtonMenuShow, 'menuhide' : this.onButtonMenuHide, scope: this }) } }, /** * 在工具栏上添加文本 * @param {String} text 添加的文本 * @return {Ext.Toolbar.Item} item元素 */ addText : function(text){ return this.addItem(new T.TextItem(text)); }, /** * 在指定的索引位置插入任何一个{@link Ext.Toolbar.Item}/{@link Ext.Toolbar.Button}项. * @param {Number} index item插入的地方(索引值) * @param {Object/Ext.Toolbar.Item/Ext.Toolbar.Button/Array} item 要插入的按钮本身或按钮其配置项,或配置项的数组 * @return {Ext.Toolbar.Button/Item} */ insertButton : function(index, item){ if(Ext.isArray(item)){ var buttons = []; for(var i = 0, len = item.length; i < len; i++) { buttons.push(this.insertButton(index + i, item[i])); } return buttons; } if (!(item instanceof T.Button)){ item = new T.Button(item); } var td = document.createElement("td"); this.tr.insertBefore(td, this.tr.childNodes[index]); this.initMenuTracking(item); item.render(td); this.items.insert(index, item); return item; }, /** * 在工具栏上添加一个从 {@link Ext.DomHelper}配置传递过来的元素 * @param {Object} config * @return {Ext.Toolbar.Item} item元素 */ addDom : function(config, returnEl){ var td = this.nextBlock(); Ext.DomHelper.overwrite(td, config); var ti = new T.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, /** * 添加一个动态的可展现的 Ext.form field (TextField, ComboBox, 等等). * 注意: 这个域应该还没有被展现.对于一个已经被展现了的域,使用{@link #addElement}. * @param {Ext.form.Field} field * @return {Ext.ToolbarItem} */ addField : function(field){ var td = this.nextBlock(); field.render(td); var ti = new T.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, // private nextBlock : function(){ var td = document.createElement("td"); this.tr.appendChild(td); return td; }, // private onDestroy : function(){ Ext.Toolbar.superclass.onDestroy.call(this); if(this.rendered){ if(this.items){ // rendered? Ext.destroy.apply(Ext, this.items.items); } Ext.Element.uncache(this.tr); } }, // private onDisable : function(){ this.items.each(function(item){ if(item.disable){ item.disable(); } }); }, // private onEnable : function(){ this.items.each(function(item){ if(item.enable){ item.enable(); } }); }, // private onButtonTriggerOver : function(btn){ if(this.activeMenuBtn && this.activeMenuBtn != btn){ this.activeMenuBtn.hideMenu(); btn.showMenu(); this.activeMenuBtn = btn; } }, // private onButtonMenuShow : function(btn){ this.activeMenuBtn = btn; }, // private onButtonMenuHide : function(btn){ delete this.activeMenuBtn; } /** * @cfg {String} autoEl @hide */ }); Ext.reg('toolbar', Ext.Toolbar); /** * @class Ext.Toolbar.Item * 被其他类所继承的基类,以获取一些基本的工具栏项功能 * @constructor * 创建一个新的项 * @param {HTMLElement} el */ T.Item = function(el){ this.el = Ext.getDom(el); this.id = Ext.id(this.el); this.hidden = false; }; T.Item.prototype = { /** * 得到此项的HTML元素 * @return {HTMLElement} */ getEl : function(){ return this.el; }, // private render : function(td){ this.td = td; td.appendChild(this.el); }, /** * 移除并且销毁此项. */ destroy : function(){ if(this.td && this.td.parentNode){ this.td.parentNode.removeChild(this.td); } }, /** * 显示此项. */ show: function(){ this.hidden = false; this.td.style.display = ""; }, /** * 隐藏此项. */ hide: function(){ this.hidden = true; this.td.style.display = "none"; }, /** * 用于控制显示/隐藏的简便函数. * @param {Boolean} visible true就隐藏 */ setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } }, /** * 在该项上获得焦点 */ focus : function(){ Ext.fly(this.el).focus(); }, /** * 禁用该项 */ disable : function(){ Ext.fly(this.td).addClass("x-item-disabled"); this.disabled = true; this.el.disabled = true; }, /** * 激活该项 */ enable : function(){ Ext.fly(this.td).removeClass("x-item-disabled"); this.disabled = false; this.el.disabled = false; } }; Ext.reg('tbitem', T.Item); /** * @class Ext.Toolbar.Separator * @extends Ext.Toolbar.Item * 一个简单的类,在工具栏项之间添加垂直竖线分隔符. 实例使用: * <pre><code> new Ext.Panel({ tbar : [ 'Item 1', {xtype: 'tbseparator'}, // 或 '-' 'Item 2' ] }); </code></pre> * @constructor * 创建一个新的分隔符 */ T.Separator = function(){ var s = document.createElement("span"); s.className = "ytb-sep"; T.Separator.superclass.constructor.call(this, s); }; Ext.extend(T.Separator, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbseparator', T.Separator); /** * @class Ext.Toolbar.Spacer * @extends Ext.Toolbar.Item * 一个在工具栏各项间添加水平方向空间的简单元素. * <pre><code> new Ext.Panel({ tbar : [ 'Item 1', {xtype: 'tbspacer'}, // or ' ' 'Item 2' ] }); </code></pre> * @constructor * 创建一个新空白间位符(spacer) */ T.Spacer = function(){ var s = document.createElement("div"); s.className = "ytb-spacer"; T.Spacer.superclass.constructor.call(this, s); }; Ext.extend(T.Spacer, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbspacer', T.Spacer); /** * @class Ext.Toolbar.Fill * @extends Ext.Toolbar.Spacer * 一个在工具栏各项间尽最大可能宽度 (100% width) 添加水平方向空间的简单元素. * <pre><code> new Ext.Panel({ tbar : [ 'Item 1', {xtype: 'tbfill'}, // or '->' 'Item 2' ] }); </code></pre> * @constructor * 创建一个新空白间位符(spacer) */ T.Fill = Ext.extend(T.Spacer, { // private render : function(td){ td.style.width = '100%'; T.Fill.superclass.render.call(this, td); } }); Ext.reg('tbfill', T.Fill); /** * @class Ext.Toolbar.TextItem * @extends Ext.Toolbar.Item * 一个在工具栏直接展现文本的简单类. * <pre><code> new Ext.Panel({ tbar : [ {xtype: 'tbtext', text: 'Item 1'} // 或'Item 1'即可 ] }); </code></pre> * @constructor * 创建一个新的文本项 * @param {String/Object} text 文本字符串,或带有<tt>text</tt>属性的配置项对象 */ T.TextItem = function(t){ var s = document.createElement("span"); s.className = "ytb-text"; s.innerHTML = t.text ? t.text : t; T.TextItem.superclass.constructor.call(this, s); }; Ext.extend(T.TextItem, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbtext', T.TextItem); /** * @class Ext.Toolbar.Button * @extends Ext.Button * 展现在工具栏中的一个按钮. 使用 <tt>handler</tt> 配置来指定一个回调函数去触发按钮点击的事件 * <pre><code> new Ext.Panel({ tbar : [ {text: 'OK', handler: okHandler} // 如不指定缺省类型是tbbutton ] }); </code></pre> * @constructor * 创建一个新的按钮 * @param {Object} config 一个标准{@link Ext.Button}配置项对象 */ T.Button = Ext.extend(Ext.Button, { hideParent : true, onDestroy : function(){ T.Button.superclass.onDestroy.call(this); if(this.container){ this.container.remove(); } } }); Ext.reg('tbbutton', T.Button); /** * @class Ext.Toolbar.SplitButton * @extends Ext.SplitButton * 工具栏中一个有分隔符标志的菜单按钮 * <pre><code> new Ext.Panel({ tbar : [ { xtype: 'tbsplit', text: 'Options', handler: optionsHandler, // handle a click on the button itself menu: new Ext.menu.Menu({ items: [ // These items will display in a dropdown menu when the split arrow is clicked {text: 'Item 1', handler: item1Handler}, {text: 'Item 2', handler: item2Handler}, ] }) } ] }); </code></pre> * @constructor * 创建一个有分隔符标志的菜单按钮 * @param {Object} config 一个标准的 {@link Ext.SplitButton} 配置对象 */ T.SplitButton = Ext.extend(Ext.SplitButton, { hideParent : true, onDestroy : function(){ T.SplitButton.superclass.onDestroy.call(this); if(this.container){ this.container.remove(); } } }); Ext.reg('tbsplit', T.SplitButton); // backwards compat T.MenuButton = T.SplitButton; })();
JavaScript
/** * @class Ext.tree.TreeNodeUI * 为实现Ext树节点UI而提供的类。TreeNode的UI是与tree的实现相分离,以方便自定义tree节点的外观。 * <br> * <p> * 不应该直接实例化该类,要制定Tree的用户界面,你应该继承这个类。 * </p> * <p> * 可通过{@link Ext.tree.TreeNode#getUI}方法访问Ext TreeNode的用户界面组件。</p> */ Ext.tree.TreeNodeUI = function(node){ this.node = node; this.rendered = false; this.animating = false; this.wasLeaf = true; this.ecc = 'x-tree-ec-icon x-tree-elbow'; this.emptyIcon = Ext.BLANK_IMAGE_URL; }; Ext.tree.TreeNodeUI.prototype = { // private removeChild : function(node){ if(this.rendered){ this.ctNode.removeChild(node.ui.getEl()); } }, // private beforeLoad : function(){ this.addClass("x-tree-node-loading"); }, // private afterLoad : function(){ this.removeClass("x-tree-node-loading"); }, // private onTextChange : function(node, text, oldText){ if(this.rendered){ this.textNode.innerHTML = text; } }, // private onDisableChange : function(node, state){ this.disabled = state; if (this.checkbox) { this.checkbox.disabled = state; } if(state){ this.addClass("x-tree-node-disabled"); }else{ this.removeClass("x-tree-node-disabled"); } }, // private onSelectedChange : function(state){ if(state){ this.focus(); this.addClass("x-tree-selected"); }else{ //this.blur(); this.removeClass("x-tree-selected"); } }, // private onMove : function(tree, node, oldParent, newParent, index, refNode){ this.childIndent = null; if(this.rendered){ var targetNode = newParent.ui.getContainer(); if(!targetNode){//target not rendered this.holder = document.createElement("div"); this.holder.appendChild(this.wrap); return; } var insertBefore = refNode ? refNode.ui.getEl() : null; if(insertBefore){ targetNode.insertBefore(this.wrap, insertBefore); }else{ targetNode.appendChild(this.wrap); } this.node.renderIndent(true); } }, /** * 为节点的UI元素添加一到多个CSS样式类。重复的样式类会省略。 * @param {String/Array} className 添加的样式类或数组。 */ addClass : function(cls){ if(this.elNode){ Ext.fly(this.elNode).addClass(cls); } }, /** * 移除节点的一到多个CSS样式类。 * @param {String/Array} className 待删除的样式类或数组。 */ removeClass : function(cls){ if(this.elNode){ Ext.fly(this.elNode).removeClass(cls); } }, // private remove : function(){ if(this.rendered){ this.holder = document.createElement("div"); this.holder.appendChild(this.wrap); } }, // private fireEvent : function(){ return this.node.fireEvent.apply(this.node, arguments); }, // private initEvents : function(){ this.node.on("move", this.onMove, this); if(this.node.disabled){ this.addClass("x-tree-node-disabled"); if (this.checkbox) { this.checkbox.disabled = true; } } if(this.node.hidden){ this.hide(); } var ot = this.node.getOwnerTree(); var dd = ot.enableDD || ot.enableDrag || ot.enableDrop; if(dd && (!this.node.isRoot || ot.rootVisible)){ Ext.dd.Registry.register(this.elNode, { node: this.node, handles: this.getDDHandles(), isHandle: false }); } }, // private getDDHandles : function(){ return [this.iconNode, this.textNode, this.elNode]; }, /** * 隐藏本节点。 */ hide : function(){ this.node.hidden = true; if(this.wrap){ this.wrap.style.display = "none"; } }, /** * 显示本节点。 */ show : function(){ this.node.hidden = false; if(this.wrap){ this.wrap.style.display = ""; } }, // private onContextMenu : function(e){ if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) { e.preventDefault(); this.focus(); this.fireEvent("contextmenu", this.node, e); } }, // private onClick : function(e){ if(this.dropping){ e.stopEvent(); return; } if(this.fireEvent("beforeclick", this.node, e) !== false){ var a = e.getTarget('a'); if(!this.disabled && this.node.attributes.href && a){ this.fireEvent("click", this.node, e); return; }else if(a && e.ctrlKey){ e.stopEvent(); } e.preventDefault(); if(this.disabled){ return; } if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){ this.node.toggle(); } this.fireEvent("click", this.node, e); }else{ e.stopEvent(); } }, // private onDblClick : function(e){ e.preventDefault(); if(this.disabled){ return; } if(this.checkbox){ this.toggleCheck(); } if(!this.animating && this.node.hasChildNodes()){ this.node.toggle(); } this.fireEvent("dblclick", this.node, e); }, onOver : function(e){ this.addClass('x-tree-node-over'); }, onOut : function(e){ this.removeClass('x-tree-node-over'); }, // private onCheckChange : function(){ var checked = this.checkbox.checked; // fix for IE6 this.checkbox.defaultChecked = checked; this.node.attributes.checked = checked; this.fireEvent('checkchange', this.node, checked); }, // private ecClick : function(e){ if(!this.animating && (this.node.hasChildNodes() || this.node.attributes.expandable)){ this.node.toggle(); } }, // private startDrop : function(){ this.dropping = true; }, // delayed drop so the click event doesn't get fired on a drop endDrop : function(){ setTimeout(function(){ this.dropping = false; }.createDelegate(this), 50); }, // private expand : function(){ this.updateExpandIcon(); this.ctNode.style.display = ""; }, // private focus : function(){ if(!this.node.preventHScroll){ try{this.anchor.focus(); }catch(e){} }else if(!Ext.isIE){ try{ var noscroll = this.node.getOwnerTree().getTreeEl().dom; var l = noscroll.scrollLeft; this.anchor.focus(); noscroll.scrollLeft = l; }catch(e){} } }, /** * 设置树节点的checked状态值到传入的值,或,如果没有传入值,就轮回选中的状态 * 如果节点没有checkbox,这将不会有效果 * @param {Boolean} (可选的)新的选中状态 */ toggleCheck : function(value){ var cb = this.checkbox; if(cb){ cb.checked = (value === undefined ? !cb.checked : value); this.onCheckChange(); } }, // private blur : function(){ try{ this.anchor.blur(); }catch(e){} }, // private animExpand : function(callback){ var ct = Ext.get(this.ctNode); ct.stopFx(); if(!this.node.hasChildNodes()){ this.updateExpandIcon(); this.ctNode.style.display = ""; Ext.callback(callback); return; } this.animating = true; this.updateExpandIcon(); ct.slideIn('t', { callback : function(){ this.animating = false; Ext.callback(callback); }, scope: this, duration: this.node.ownerTree.duration || .25 }); }, // private highlight : function(){ var tree = this.node.getOwnerTree(); Ext.fly(this.wrap).highlight( tree.hlColor || "C3DAF9", {endColor: tree.hlBaseColor} ); }, // private collapse : function(){ this.updateExpandIcon(); this.ctNode.style.display = "none"; }, // private animCollapse : function(callback){ var ct = Ext.get(this.ctNode); ct.enableDisplayMode('block'); ct.stopFx(); this.animating = true; this.updateExpandIcon(); ct.slideOut('t', { callback : function(){ this.animating = false; Ext.callback(callback); }, scope: this, duration: this.node.ownerTree.duration || .25 }); }, // private getContainer : function(){ return this.ctNode; }, // private getEl : function(){ return this.wrap; }, // private appendDDGhost : function(ghostNode){ ghostNode.appendChild(this.elNode.cloneNode(true)); }, // private getDDRepairXY : function(){ return Ext.lib.Dom.getXY(this.iconNode); }, // private onRender : function(){ this.render(); }, // private render : function(bulkRender){ var n = this.node, a = n.attributes; var targetNode = n.parentNode ? n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom; if(!this.rendered){ this.rendered = true; this.renderElements(n, a, targetNode, bulkRender); if(a.qtip){ if(this.textNode.setAttributeNS){ this.textNode.setAttributeNS("ext", "qtip", a.qtip); if(a.qtipTitle){ this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle); } }else{ this.textNode.setAttribute("ext:qtip", a.qtip); if(a.qtipTitle){ this.textNode.setAttribute("ext:qtitle", a.qtipTitle); } } }else if(a.qtipCfg){ a.qtipCfg.target = Ext.id(this.textNode); Ext.QuickTips.register(a.qtipCfg); } this.initEvents(); if(!this.node.expanded){ this.updateExpandIcon(true); } }else{ if(bulkRender === true) { targetNode.appendChild(this.wrap); } } }, // private renderElements : function(n, a, targetNode, bulkRender){ // add some indent caching, this helps performance when rendering a large tree this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : ''; var cb = typeof a.checked == 'boolean'; var href = a.href ? a.href : Ext.isGecko ? "" : "#"; var buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">', '<span class="x-tree-node-indent">',this.indentMarkup,"</span>", '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />', '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />', cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '', '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ', a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,"</span></a></div>", '<ul class="x-tree-node-ct" style="display:none;"></ul>', "</li>"].join(''); var nel; if(bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())){ this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf); }else{ this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf); } this.elNode = this.wrap.childNodes[0]; this.ctNode = this.wrap.childNodes[1]; var cs = this.elNode.childNodes; this.indentNode = cs[0]; this.ecNode = cs[1]; this.iconNode = cs[2]; var index = 3; if(cb){ this.checkbox = cs[3]; // fix for IE6 this.checkbox.defaultChecked = this.checkbox.checked; index++; } this.anchor = cs[index]; this.textNode = cs[index].firstChild; }, /** * 返回焦点所在的节点UI的&lt;a> 元素。 * @return {HtmlElement} DOM anchor元素。 */ getAnchor : function(){ return this.anchor; }, /** * 返回文本节点 * @return {HtmlNode} DOM格式的文本文字 */ getTextEl : function(){ return this.textNode; }, /** * 返回图标&lt;img>元素 * @return {HtmlElement} DOM格式的图片元素 */ getIconEl : function(){ return this.iconNode; }, /** * 返回节点的checked status。如果节点没有渲染checkbox,返回false。 * @return {Boolean} The checked flag. */ isChecked : function(){ return this.checkbox ? this.checkbox.checked : false; }, // private updateExpandIcon : function(){ if(this.rendered){ var n = this.node, c1, c2; var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow"; var hasChild = n.hasChildNodes(); if(hasChild || n.attributes.expandable){ if(n.expanded){ cls += "-minus"; c1 = "x-tree-node-collapsed"; c2 = "x-tree-node-expanded"; }else{ cls += "-plus"; c1 = "x-tree-node-expanded"; c2 = "x-tree-node-collapsed"; } if(this.wasLeaf){ this.removeClass("x-tree-node-leaf"); this.wasLeaf = false; } if(this.c1 != c1 || this.c2 != c2){ Ext.fly(this.elNode).replaceClass(c1, c2); this.c1 = c1; this.c2 = c2; } }else{ if(!this.wasLeaf){ Ext.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf"); delete this.c1; delete this.c2; this.wasLeaf = true; } } var ecc = "x-tree-ec-icon "+cls; if(this.ecc != ecc){ this.ecNode.className = ecc; this.ecc = ecc; } } }, // private getChildIndent : function(){ if(!this.childIndent){ var buf = []; var p = this.node; while(p){ if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){ if(!p.isLast()) { buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />'); } else { buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />'); } } p = p.parentNode; } this.childIndent = buf.join(""); } return this.childIndent; }, // private renderIndent : function(){ if(this.rendered){ var indent = ""; var p = this.node.parentNode; if(p){ indent = p.ui.getChildIndent(); } if(this.indentMarkup != indent){ // don't rerender if not required this.indentNode.innerHTML = indent; this.indentMarkup = indent; } this.updateExpandIcon(); } }, destroy : function(){ if(this.elNode){ Ext.dd.Registry.unregister(this.elNode.id); } delete this.elNode; delete this.ctNode; delete this.indentNode; delete this.ecNode; delete this.iconNode; delete this.checkbox; delete this.anchor; delete this.textNode; Ext.removeNode(this.ctNode); } };
JavaScript