3 This file is part of Ext JS 4
5 Copyright (c) 2011 Sencha Inc
7 Contact: http://www.sencha.com/contact
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
16 * Base class that provides a common interface for publishing events. Subclasses are expected to to have a property
17 * "events" with all the events defined, and, optionally, a property "listeners" with configured listeners defined.
21 * Ext.define('Employee', {
22 * extend: 'Ext.util.Observable',
23 * constructor: function(config){
24 * this.name = config.name;
30 * // Copy configured listeners into *this* object so that the base class's
31 * // constructor will add them.
32 * this.listeners = config.listeners;
34 * // Call our superclass constructor to complete construction process.
35 * Employee.superclass.constructor.call(this, config)
39 * This could then be used like this:
41 * var newEmployee = new Employee({
45 * // By default, "this" will be the object that fired the event.
46 * alert(this.name + " has quit!");
51 Ext.define('Ext.util.Observable', {
53 /* Begin Definitions */
55 requires: ['Ext.util.Event'],
59 * Removes **all** added captures from the Observable.
61 * @param {Observable} o The Observable to release
64 releaseCapture: function(o) {
65 o.fireEvent = this.prototype.fireEvent;
69 * Starts capture on the specified Observable. All events will be passed to the supplied function with the event
70 * name + standard signature of the event **before** the event is fired. If the supplied function returns false,
71 * the event will not fire.
73 * @param {Observable} o The Observable to capture events from.
74 * @param {Function} fn The function to call when an event is fired.
75 * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. Defaults to
76 * the Observable firing the event.
79 capture: function(o, fn, scope) {
80 o.fireEvent = Ext.Function.createInterceptor(o.fireEvent, fn, scope);
84 * Sets observability on the passed class constructor.
86 * This makes any event fired on any instance of the passed class also fire a single event through
87 * the **class** allowing for central handling of events on many instances at once.
91 * Ext.util.Observable.observe(Ext.data.Connection);
92 * Ext.data.Connection.on('beforerequest', function(con, options) {
93 * console.log('Ajax request made to ' + options.url);
96 * @param {Function} c The class constructor to make observable.
97 * @param {Object} listeners An object containing a series of listeners to add. See {@link #addListener}.
100 observe: function(cls, listeners) {
102 if (!cls.isObservable) {
103 Ext.applyIf(cls, new this());
104 this.capture(cls.prototype, cls.fireEvent, cls);
106 if (Ext.isObject(listeners)) {
114 /* End Definitions */
117 * @cfg {Object} listeners
119 * A config object containing one or more event handlers to be added to this object during initialization. This
120 * should be a valid listeners config object as specified in the {@link #addListener} example for attaching multiple
123 * **DOM events from ExtJS {@link Ext.Component Components}**
125 * While _some_ ExtJs Component classes export selected DOM events (e.g. "click", "mouseover" etc), this is usually
126 * only done when extra value can be added. For example the {@link Ext.view.View DataView}'s **`{@link
127 * Ext.view.View#itemclick itemclick}`** event passing the node clicked on. To access DOM events directly from a
128 * child element of a Component, we need to specify the `element` option to identify the Component property to add a
131 * new Ext.panel.Panel({
139 * element: 'el', //bind to the underlying el property on the panel
140 * fn: function(){ console.log('click el'); }
143 * element: 'body', //bind to the underlying body property on the panel
144 * fn: function(){ console.log('dblclick body'); }
152 constructor: function(config) {
155 Ext.apply(me, config);
160 me.events = me.events || {};
162 if (me.bubbleEvents) {
163 me.enableBubble(me.bubbleEvents);
168 eventOptionsRe : /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate|element|vertical|horizontal)$/,
171 * Adds listeners to any Observable object (or Element) which are automatically removed when this Component is
174 * @param {Observable/Element} item The item to which to add a listener/listeners.
175 * @param {Object/String} ename The event name, or an object containing event name properties.
176 * @param {Function} fn (optional) If the `ename` parameter was an event name, this is the handler function.
177 * @param {Object} scope (optional) If the `ename` parameter was an event name, this is the scope (`this` reference)
178 * in which the handler function is executed.
179 * @param {Object} opt (optional) If the `ename` parameter was an event name, this is the
180 * {@link Ext.util.Observable#addListener addListener} options.
182 addManagedListener : function(item, ename, fn, scope, options) {
184 managedListeners = me.managedListeners = me.managedListeners || [],
187 if (typeof ename !== 'string') {
189 for (ename in options) {
190 if (options.hasOwnProperty(ename)) {
191 config = options[ename];
192 if (!me.eventOptionsRe.test(ename)) {
193 me.addManagedListener(item, ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
199 managedListeners.push({
207 item.on(ename, fn, scope, options);
212 * Removes listeners that were added by the {@link #mon} method.
214 * @param {Observable|Element} item The item from which to remove a listener/listeners.
215 * @param {Object|String} ename The event name, or an object containing event name properties.
216 * @param {Function} fn Optional. If the `ename` parameter was an event name, this is the handler function.
217 * @param {Object} scope Optional. If the `ename` parameter was an event name, this is the scope (`this` reference)
218 * in which the handler function is executed.
220 removeManagedListener : function(item, ename, fn, scope) {
228 if (typeof ename !== 'string') {
230 for (ename in options) {
231 if (options.hasOwnProperty(ename)) {
232 config = options[ename];
233 if (!me.eventOptionsRe.test(ename)) {
234 me.removeManagedListener(item, ename, config.fn || config, config.scope || options.scope);
240 managedListeners = me.managedListeners ? me.managedListeners.slice() : [];
242 for (i = 0, length = managedListeners.length; i < length; i++) {
243 me.removeManagedListenerItem(false, managedListeners[i], item, ename, fn, scope);
248 * Fires the specified event with the passed parameters (minus the event name, plus the `options` object passed
249 * to {@link #addListener}).
251 * An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) by
252 * calling {@link #enableBubble}.
254 * @param {String} eventName The name of the event to fire.
255 * @param {Object...} args Variable number of parameters are passed to handlers.
256 * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
258 fireEvent: function() {
260 args = Ext.Array.toArray(arguments),
261 ename = args[0].toLowerCase(),
263 event = me.events[ename],
264 queue = me.eventQueue,
267 if (me.eventsSuspended === true) {
271 } else if (event && event !== true) {
273 if (event.fire.apply(event, args.slice(1)) === false) {
276 parent = me.getBubbleTarget && me.getBubbleTarget();
277 if (parent && parent.isObservable) {
278 if (!parent.events[ename] || parent.events[ename] === true || !parent.events[ename].bubble) {
279 parent.enableBubble(ename);
281 return parent.fireEvent.apply(parent, args);
286 ret = event.fire.apply(event, args);
293 * Appends an event handler to this object.
295 * @param {String} eventName The name of the event to listen for. May also be an object who's property names are
297 * @param {Function} handler The method the event invokes. Will be called with arguments given to
298 * {@link #fireEvent} plus the `options` parameter described below.
299 * @param {Object} scope (optional) The scope (`this` reference) in which the handler function is executed. **If
300 * omitted, defaults to the object which fired the event.**
301 * @param {Object} options (optional) An object containing handler configuration.
303 * **Note:** Unlike in ExtJS 3.x, the options object will also be passed as the last argument to every event handler.
305 * This object may contain any of the following properties:
307 * - **scope** : Object
309 * The scope (`this` reference) in which the handler function is executed. **If omitted, defaults to the object
310 * which fired the event.**
312 * - **delay** : Number
314 * The number of milliseconds to delay the invocation of the handler after the event fires.
316 * - **single** : Boolean
318 * True to add a handler to handle just the next firing of the event, and then remove itself.
320 * - **buffer** : Number
322 * Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed by the specified number of
323 * milliseconds. If the event fires again within that time, the original handler is _not_ invoked, but the new
324 * handler is scheduled in its place.
326 * - **target** : Observable
328 * Only call the handler if the event was fired on the target Observable, _not_ if the event was bubbled up from a
331 * - **element** : String
333 * **This option is only valid for listeners bound to {@link Ext.Component Components}.** The name of a Component
334 * property which references an element to add a listener to.
336 * This option is useful during Component construction to add DOM event listeners to elements of
337 * {@link Ext.Component Components} which will exist only after the Component is rendered.
338 * For example, to add a click listener to a Panel's body:
340 * new Ext.panel.Panel({
341 * title: 'The title',
343 * click: this.handlePanelClick,
348 * **Combining Options**
350 * Using the options argument, it is possible to combine different types of listeners:
352 * A delayed, one-time listener.
354 * myPanel.on('hide', this.handleClick, this, {
359 * **Attaching multiple handlers in 1 call**
361 * The method also allows for a single argument to be passed which is a config object containing properties which
362 * specify multiple events. For example:
365 * cellClick: this.onCellClick,
366 * mouseover: this.onMouseOver,
367 * mouseout: this.onMouseOut,
368 * scope: this // Important. Ensure "this" is correct during handler execution
371 * One can also specify options for each event handler separately:
374 * cellClick: {fn: this.onCellClick, scope: this, single: true},
375 * mouseover: {fn: panel.onMouseOver, scope: panel}
379 addListener: function(ename, fn, scope, options) {
384 if (typeof ename !== 'string') {
386 for (ename in options) {
387 if (options.hasOwnProperty(ename)) {
388 config = options[ename];
389 if (!me.eventOptionsRe.test(ename)) {
390 me.addListener(ename, config.fn || config, config.scope || options.scope, config.fn ? config : options);
396 ename = ename.toLowerCase();
397 me.events[ename] = me.events[ename] || true;
398 event = me.events[ename] || true;
399 if (Ext.isBoolean(event)) {
400 me.events[ename] = event = new Ext.util.Event(me, ename);
402 event.addListener(fn, scope, Ext.isObject(options) ? options : {});
407 * Removes an event handler.
409 * @param {String} eventName The type of event the handler was associated with.
410 * @param {Function} handler The handler to remove. **This must be a reference to the function passed into the
411 * {@link #addListener} call.**
412 * @param {Object} scope (optional) The scope originally specified for the handler.
414 removeListener: function(ename, fn, scope) {
420 if (typeof ename !== 'string') {
422 for (ename in options) {
423 if (options.hasOwnProperty(ename)) {
424 config = options[ename];
425 if (!me.eventOptionsRe.test(ename)) {
426 me.removeListener(ename, config.fn || config, config.scope || options.scope);
431 ename = ename.toLowerCase();
432 event = me.events[ename];
433 if (event && event.isEvent) {
434 event.removeListener(fn, scope);
440 * Removes all listeners for this object including the managed listeners
442 clearListeners: function() {
443 var events = this.events,
447 for (key in events) {
448 if (events.hasOwnProperty(key)) {
451 event.clearListeners();
456 this.clearManagedListeners();
460 purgeListeners : function() {
461 if (Ext.global.console) {
462 Ext.global.console.warn('Observable: purgeListeners has been deprecated. Please use clearListeners.');
464 return this.clearListeners.apply(this, arguments);
469 * Removes all managed listeners for this object.
471 clearManagedListeners : function() {
472 var managedListeners = this.managedListeners || [],
474 len = managedListeners.length;
476 for (; i < len; i++) {
477 this.removeManagedListenerItem(true, managedListeners[i]);
480 this.managedListeners = [];
484 * Remove a single managed listener item
486 * @param {Boolean} isClear True if this is being called during a clear
487 * @param {Object} managedListener The managed listener item
488 * See removeManagedListener for other args
490 removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){
491 if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) {
492 managedListener.item.un(managedListener.ename, managedListener.fn, managedListener.scope);
494 Ext.Array.remove(this.managedListeners, managedListener);
500 purgeManagedListeners : function() {
501 if (Ext.global.console) {
502 Ext.global.console.warn('Observable: purgeManagedListeners has been deprecated. Please use clearManagedListeners.');
504 return this.clearManagedListeners.apply(this, arguments);
509 * Adds the specified events to the list of events which this Observable may fire.
511 * @param {Object/String} o Either an object with event names as properties with a value of `true` or the first
512 * event name string if multiple event names are being passed as separate parameters. Usage:
519 * @param {String...} more Optional additional event names if multiple event names are being passed as separate
522 * this.addEvents('storeloaded', 'storecleared');
525 addEvents: function(o) {
531 me.events = me.events || {};
532 if (Ext.isString(o)) {
537 me.events[args[i]] = me.events[args[i]] || true;
540 Ext.applyIf(me.events, o);
545 * Checks to see if this object has any listeners for a specified event
547 * @param {String} eventName The name of the event to check for
548 * @return {Boolean} True if the event is being listened for, else false
550 hasListener: function(ename) {
551 var event = this.events[ename.toLowerCase()];
552 return event && event.isEvent === true && event.listeners.length > 0;
556 * Suspends the firing of all events. (see {@link #resumeEvents})
558 * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
559 * after the {@link #resumeEvents} call instead of discarding all suspended events.
561 suspendEvents: function(queueSuspended) {
562 this.eventsSuspended = true;
563 if (queueSuspended && !this.eventQueue) {
564 this.eventQueue = [];
569 * Resumes firing events (see {@link #suspendEvents}).
571 * If events were suspended using the `**queueSuspended**` parameter, then all events fired
572 * during event suspension will be sent to any listeners now.
574 resumeEvents: function() {
576 queued = me.eventQueue || [];
578 me.eventsSuspended = false;
579 delete me.eventQueue;
583 me.fireEvent.apply(me, e);
588 * Relays selected events from the specified Observable as if the events were fired by `this`.
590 * @param {Object} origin The Observable whose events this object is to relay.
591 * @param {[String]} events Array of event names to relay.
592 * @param {Object} prefix
594 relayEvents : function(origin, events, prefix) {
595 prefix = prefix || '';
602 for (; i < len; i++) {
603 oldName = events[i].substr(prefix.length);
604 newName = prefix + oldName;
605 me.events[newName] = me.events[newName] || true;
606 origin.on(oldName, me.createRelayer(newName));
612 * Creates an event handling function which refires the event from this object as the passed event name.
614 * @returns {Function}
616 createRelayer: function(newName){
619 return me.fireEvent.apply(me, [newName].concat(Array.prototype.slice.call(arguments, 0, -1)));
624 * Enables events fired by this Observable to bubble up an owner hierarchy by calling `this.getBubbleTarget()` if
625 * present. There is no implementation in the Observable base class.
627 * This is commonly used by Ext.Components to bubble events to owner Containers.
628 * See {@link Ext.Component#getBubbleTarget}. The default implementation in Ext.Component returns the
629 * Component's immediate owner. But if a known target is required, this can be overridden to access the
630 * required target more quickly.
634 * Ext.override(Ext.form.field.Base, {
635 * // Add functionality to Field's initComponent to enable the change event to bubble
636 * initComponent : Ext.Function.createSequence(Ext.form.field.Base.prototype.initComponent, function() {
637 * this.enableBubble('change');
640 * // We know that we want Field's events to bubble directly to the FormPanel.
641 * getBubbleTarget : function() {
642 * if (!this.formPanel) {
643 * this.formPanel = this.findParentByType('form');
645 * return this.formPanel;
649 * var myForm = new Ext.formPanel({
650 * title: 'User Details',
655 * change: function() {
656 * // Title goes red if form has been modified.
657 * myForm.header.setStyle('color', 'red');
662 * @param {String/[String]} events The event name to bubble, or an Array of event names.
664 enableBubble: function(events) {
666 if (!Ext.isEmpty(events)) {
667 events = Ext.isArray(events) ? events: Ext.Array.toArray(arguments);
670 ename = ename.toLowerCase();
671 var ce = me.events[ename] || true;
672 if (Ext.isBoolean(ce)) {
673 ce = new Ext.util.Event(me, ename);
674 me.events[ename] = ce;
685 * Shorthand for {@link #addListener}.
686 * @alias Ext.util.Observable#addListener
691 * Shorthand for {@link #removeListener}.
692 * @alias Ext.util.Observable#removeListener
694 un: 'removeListener',
697 * Shorthand for {@link #addManagedListener}.
698 * @alias Ext.util.Observable#addManagedListener
700 mon: 'addManagedListener',
703 * Shorthand for {@link #removeManagedListener}.
704 * @alias Ext.util.Observable#removeManagedListener
706 mun: 'removeManagedListener'
709 //deprecated, will be removed in 5.0
710 this.observeClass = this.observe;
712 Ext.apply(Ext.util.Observable.prototype, function(){
713 // this is considered experimental (along with beforeMethod, afterMethod, removeMethodListener?)
714 // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
716 function getMethodEvent(method){
717 var e = (this.methodEvents = this.methodEvents || {})[method],
724 this.methodEvents[method] = e = {};
725 e.originalFn = this[method];
726 e.methodName = method;
730 var makeCall = function(fn, scope, args){
731 if((v = fn.apply(scope || obj, args)) !== undefined){
732 if (typeof v == 'object') {
733 if(v.returnValue !== undefined){
734 returnValue = v.returnValue;
750 this[method] = function(){
751 var args = Array.prototype.slice.call(arguments, 0),
753 returnValue = v = undefined;
756 for(i = 0, len = e.before.length; i < len; i++){
758 makeCall(b.fn, b.scope, args);
764 if((v = e.originalFn.apply(obj, args)) !== undefined){
768 for(i = 0, len = e.after.length; i < len; i++){
770 makeCall(b.fn, b.scope, args);
782 // these are considered experimental
783 // allows for easier interceptor and sequences, including cancelling and overwriting the return value of the call
784 // adds an 'interceptor' called before the original method
785 beforeMethod : function(method, fn, scope){
786 getMethodEvent.call(this, method).before.push({
792 // adds a 'sequence' called after the original method
793 afterMethod : function(method, fn, scope){
794 getMethodEvent.call(this, method).after.push({
800 removeMethodListener: function(method, fn, scope){
801 var e = this.getMethodEvent(method),
803 for(i = 0, len = e.before.length; i < len; i++){
804 if(e.before[i].fn == fn && e.before[i].scope == scope){
805 Ext.Array.erase(e.before, i, 1);
809 for(i = 0, len = e.after.length; i < len; i++){
810 if(e.after[i].fn == fn && e.after[i].scope == scope){
811 Ext.Array.erase(e.after, i, 1);
817 toggleEventLogging: function(toggle) {
818 Ext.util.Observable[toggle ? 'capture' : 'releaseCapture'](this, function(en) {
819 if (Ext.isDefined(Ext.global.console)) {
820 Ext.global.console.log(en, arguments);