Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / util / core / Observable.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 (function(){
8
9 var EXTUTIL = Ext.util,
10     TOARRAY = Ext.toArray,
11     EACH = Ext.each,
12     ISOBJECT = Ext.isObject,
13     TRUE = true,
14     FALSE = false;
15 /**
16  * @class Ext.util.Observable
17  * Base class that provides a common interface for publishing events. Subclasses are expected to
18  * to have a property "events" with all the events defined, and, optionally, a property "listeners"
19  * with configured listeners defined.<br>
20  * For example:
21  * <pre><code>
22 Employee = Ext.extend(Ext.util.Observable, {
23     constructor: function(config){
24         this.name = config.name;
25         this.addEvents({
26             "fired" : true,
27             "quit" : true
28         });
29
30         // Copy configured listeners into *this* object so that the base class&#39;s
31         // constructor will add them.
32         this.listeners = config.listeners;
33
34         // Call our superclass constructor to complete construction process.
35         Employee.superclass.constructor.call(config)
36     }
37 });
38 </code></pre>
39  * This could then be used like this:<pre><code>
40 var newEmployee = new Employee({
41     name: employeeName,
42     listeners: {
43         quit: function() {
44             // By default, "this" will be the object that fired the event.
45             alert(this.name + " has quit!");
46         }
47     }
48 });
49 </code></pre>
50  */
51 EXTUTIL.Observable = function(){
52     /**
53      * @cfg {Object} listeners (optional) <p>A config object containing one or more event handlers to be added to this
54      * object during initialization.  This should be a valid listeners config object as specified in the
55      * {@link #addListener} example for attaching multiple handlers at once.</p>
56      * <br><p><b><u>DOM events from ExtJs {@link Ext.Component Components}</u></b></p>
57      * <br><p>While <i>some</i> ExtJs Component classes export selected DOM events (e.g. "click", "mouseover" etc), this
58      * is usually only done when extra value can be added. For example the {@link Ext.DataView DataView}'s
59      * <b><code>{@link Ext.DataView#click click}</code></b> event passing the node clicked on. To access DOM
60      * events directly from a Component's HTMLElement, listeners must be added to the <i>{@link Ext.Component#getEl Element}</i> after the Component
61      * has been rendered. A plugin can simplify this step:<pre><code>
62 // Plugin is configured with a listeners config object.
63 // The Component is appended to the argument list of all handler functions.
64 Ext.DomObserver = Ext.extend(Object, {
65     constructor: function(config) {
66         this.listeners = config.listeners ? config.listeners : config;
67     },
68
69     // Component passes itself into plugin&#39;s init method
70     init: function(c) {
71         var p, l = this.listeners;
72         for (p in l) {
73             if (Ext.isFunction(l[p])) {
74                 l[p] = this.createHandler(l[p], c);
75             } else {
76                 l[p].fn = this.createHandler(l[p].fn, c);
77             }
78         }
79
80         // Add the listeners to the Element immediately following the render call
81         c.render = c.render.{@link Function#createSequence createSequence}(function() {
82             var e = c.getEl();
83             if (e) {
84                 e.on(l);
85             }
86         });
87     },
88
89     createHandler: function(fn, c) {
90         return function(e) {
91             fn.call(this, e, c);
92         };
93     }
94 });
95
96 var combo = new Ext.form.ComboBox({
97
98     // Collapse combo when its element is clicked on
99     plugins: [ new Ext.DomObserver({
100         click: function(evt, comp) {
101             comp.collapse();
102         }
103     })],
104     store: myStore,
105     typeAhead: true,
106     mode: 'local',
107     triggerAction: 'all'
108 });
109      * </code></pre></p>
110      */
111     var me = this, e = me.events;
112     if(me.listeners){
113         me.on(me.listeners);
114         delete me.listeners;
115     }
116     me.events = e || {};
117 };
118
119 EXTUTIL.Observable.prototype = {
120     // private
121     filterOptRe : /^(?:scope|delay|buffer|single)$/,
122
123     /**
124      * <p>Fires the specified event with the passed parameters (minus the event name).</p>
125      * <p>An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget})
126      * by calling {@link #enableBubble}.</p>
127      * @param {String} eventName The name of the event to fire.
128      * @param {Object...} args Variable number of parameters are passed to handlers.
129      * @return {Boolean} returns false if any of the handlers return false otherwise it returns true.
130      */
131     fireEvent : function(){
132         var a = TOARRAY(arguments),
133             ename = a[0].toLowerCase(),
134             me = this,
135             ret = TRUE,
136             ce = me.events[ename],
137             q,
138             c;
139         if (me.eventsSuspended === TRUE) {
140             if (q = me.eventQueue) {
141                 q.push(a);
142             }
143         }
144         else if(ISOBJECT(ce) && ce.bubble){
145             if(ce.fire.apply(ce, a.slice(1)) === FALSE) {
146                 return FALSE;
147             }
148             c = me.getBubbleTarget && me.getBubbleTarget();
149             if(c && c.enableBubble) {
150                 if(!c.events[ename] || !Ext.isObject(c.events[ename]) || !c.events[ename].bubble) {
151                     c.enableBubble(ename);
152                 }
153                 return c.fireEvent.apply(c, a);
154             }
155         }
156         else {
157             if (ISOBJECT(ce)) {
158                 a.shift();
159                 ret = ce.fire.apply(ce, a);
160             }
161         }
162         return ret;
163     },
164
165     /**
166      * Appends an event handler to this object.
167      * @param {String}   eventName The name of the event to listen for.
168      * @param {Function} handler The method the event invokes.
169      * @param {Object}   scope (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
170      * <b>If omitted, defaults to the object which fired the event.</b>
171      * @param {Object}   options (optional) An object containing handler configuration.
172      * properties. This may contain any of the following properties:<ul>
173      * <li><b>scope</b> : Object<div class="sub-desc">The scope (<code><b>this</b></code> reference) in which the handler function is executed.
174      * <b>If omitted, defaults to the object which fired the event.</b></div></li>
175      * <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>
176      * <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>
177      * <li><b>buffer</b> : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
178      * by the specified number of milliseconds. If the event fires again within that time, the original
179      * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
180      * <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>
181      * if the event was bubbled up from a child Observable.</div></li>
182      * </ul><br>
183      * <p>
184      * <b>Combining Options</b><br>
185      * Using the options argument, it is possible to combine different types of listeners:<br>
186      * <br>
187      * A delayed, one-time listener.
188      * <pre><code>
189 myDataView.on('click', this.onClick, this, {
190 single: true,
191 delay: 100
192 });</code></pre>
193      * <p>
194      * <b>Attaching multiple handlers in 1 call</b><br>
195      * The method also allows for a single argument to be passed which is a config object containing properties
196      * which specify multiple handlers.
197      * <p>
198      * <pre><code>
199 myGridPanel.on({
200 'click' : {
201     fn: this.onClick,
202     scope: this,
203     delay: 100
204 },
205 'mouseover' : {
206     fn: this.onMouseOver,
207     scope: this
208 },
209 'mouseout' : {
210     fn: this.onMouseOut,
211     scope: this
212 }
213 });</code></pre>
214  * <p>
215  * Or a shorthand syntax:<br>
216  * <pre><code>
217 myGridPanel.on({
218 'click' : this.onClick,
219 'mouseover' : this.onMouseOver,
220 'mouseout' : this.onMouseOut,
221  scope: this
222 });</code></pre>
223      */
224     addListener : function(eventName, fn, scope, o){
225         var me = this,
226             e,
227             oe,
228             isF,
229         ce;
230         if (ISOBJECT(eventName)) {
231             o = eventName;
232             for (e in o){
233                 oe = o[e];
234                 if (!me.filterOptRe.test(e)) {
235                     me.addListener(e, oe.fn || oe, oe.scope || o.scope, oe.fn ? oe : o);
236                 }
237             }
238         } else {
239             eventName = eventName.toLowerCase();
240             ce = me.events[eventName] || TRUE;
241             if (Ext.isBoolean(ce)) {
242                 me.events[eventName] = ce = new EXTUTIL.Event(me, eventName);
243             }
244             ce.addListener(fn, scope, ISOBJECT(o) ? o : {});
245         }
246     },
247
248     /**
249      * Removes an event handler.
250      * @param {String}   eventName The type of event the handler was associated with.
251      * @param {Function} handler   The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
252      * @param {Object}   scope     (optional) The scope originally specified for the handler.
253      */
254     removeListener : function(eventName, fn, scope){
255         var ce = this.events[eventName.toLowerCase()];
256         if (ISOBJECT(ce)) {
257             ce.removeListener(fn, scope);
258         }
259     },
260
261     /**
262      * Removes all listeners for this object
263      */
264     purgeListeners : function(){
265         var events = this.events,
266             evt,
267             key;
268         for(key in events){
269             evt = events[key];
270             if(ISOBJECT(evt)){
271                 evt.clearListeners();
272             }
273         }
274     },
275
276     /**
277      * Adds the specified events to the list of events which this Observable may fire.
278      * @param {Object|String} o Either an object with event names as properties with a value of <code>true</code>
279      * or the first event name string if multiple event names are being passed as separate parameters.
280      * @param {string} Optional. Event name if multiple event names are being passed as separate parameters.
281      * Usage:<pre><code>
282 this.addEvents('storeloaded', 'storecleared');
283 </code></pre>
284      */
285     addEvents : function(o){
286         var me = this;
287         me.events = me.events || {};
288         if (Ext.isString(o)) {
289             EACH(arguments, function(a) {
290                 me.events[a] = me.events[a] || TRUE;
291             });
292         } else {
293             Ext.applyIf(me.events, o);
294         }
295     },
296
297     /**
298      * Checks to see if this object has any listeners for a specified event
299      * @param {String} eventName The name of the event to check for
300      * @return {Boolean} True if the event is being listened for, else false
301      */
302     hasListener : function(eventName){
303         var e = this.events[eventName];
304         return ISOBJECT(e) && e.listeners.length > 0;
305     },
306
307     /**
308      * Suspend the firing of all events. (see {@link #resumeEvents})
309      * @param {Boolean} queueSuspended Pass as true to queue up suspended events to be fired
310      * after the {@link #resumeEvents} call instead of discarding all suspended events;
311      */
312     suspendEvents : function(queueSuspended){
313         this.eventsSuspended = TRUE;
314         if(queueSuspended && !this.eventQueue){
315             this.eventQueue = [];
316         }
317     },
318
319     /**
320      * Resume firing events. (see {@link #suspendEvents})
321      * If events were suspended using the <tt><b>queueSuspended</b></tt> parameter, then all
322      * events fired during event suspension will be sent to any listeners now.
323      */
324     resumeEvents : function(){
325         var me = this,
326             queued = me.eventQueue || [];
327         me.eventsSuspended = FALSE;
328         delete me.eventQueue;
329         EACH(queued, function(e) {
330             me.fireEvent.apply(me, e);
331         });
332     }
333 };
334
335 var OBSERVABLE = EXTUTIL.Observable.prototype;
336 /**
337  * Appends an event handler to this object (shorthand for {@link #addListener}.)
338  * @param {String}   eventName     The type of event to listen for
339  * @param {Function} handler       The method the event invokes
340  * @param {Object}   scope         (optional) The scope (<code><b>this</b></code> reference) in which the handler function is executed.
341  * <b>If omitted, defaults to the object which fired the event.</b>
342  * @param {Object}   options       (optional) An object containing handler configuration.
343  * @method
344  */
345 OBSERVABLE.on = OBSERVABLE.addListener;
346 /**
347  * Removes an event handler (shorthand for {@link #removeListener}.)
348  * @param {String}   eventName     The type of event the handler was associated with.
349  * @param {Function} handler       The handler to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
350  * @param {Object}   scope         (optional) The scope originally specified for the handler.
351  * @method
352  */
353 OBSERVABLE.un = OBSERVABLE.removeListener;
354
355 /**
356  * Removes <b>all</b> added captures from the Observable.
357  * @param {Observable} o The Observable to release
358  * @static
359  */
360 EXTUTIL.Observable.releaseCapture = function(o){
361     o.fireEvent = OBSERVABLE.fireEvent;
362 };
363
364 function createTargeted(h, o, scope){
365     return function(){
366         if(o.target == arguments[0]){
367             h.apply(scope, TOARRAY(arguments));
368         }
369     };
370 };
371
372 function createBuffered(h, o, scope){
373     var task = new EXTUTIL.DelayedTask();
374     return function(){
375         task.delay(o.buffer, h, scope, TOARRAY(arguments));
376     };
377 }
378
379 function createSingle(h, e, fn, scope){
380     return function(){
381         e.removeListener(fn, scope);
382         return h.apply(scope, arguments);
383     };
384 }
385
386 function createDelayed(h, o, scope){
387     return function(){
388         var args = TOARRAY(arguments);
389         (function(){
390             h.apply(scope, args);
391         }).defer(o.delay || 10);
392     };
393 };
394
395 EXTUTIL.Event = function(obj, name){
396     this.name = name;
397     this.obj = obj;
398     this.listeners = [];
399 };
400
401 EXTUTIL.Event.prototype = {
402     addListener : function(fn, scope, options){
403         var me = this,
404             l;
405         scope = scope || me.obj;
406         if(!me.isListening(fn, scope)){
407             l = me.createListener(fn, scope, options);
408             if(me.firing){ // if we are currently firing this event, don't disturb the listener loop
409                 me.listeners = me.listeners.slice(0);
410             }
411             me.listeners.push(l);
412         }
413     },
414
415     createListener: function(fn, scope, o){
416         o = o || {}, scope = scope || this.obj;
417         var l = {
418             fn: fn,
419             scope: scope,
420             options: o
421         }, h = fn;
422         if(o.target){
423             h = createTargeted(h, o, scope);
424         }
425         if(o.delay){
426             h = createDelayed(h, o, scope);
427         }
428         if(o.single){
429             h = createSingle(h, this, fn, scope);
430         }
431         if(o.buffer){
432             h = createBuffered(h, o, scope);
433         }
434         l.fireFn = h;
435         return l;
436     },
437
438     findListener : function(fn, scope){
439         var s, ret = -1;
440         EACH(this.listeners, function(l, i) {
441             s = l.scope;
442             if(l.fn == fn && (s == scope || s == this.obj)){
443                 ret = i;
444                 return FALSE;
445             }
446         },
447         this);
448         return ret;
449     },
450
451     isListening : function(fn, scope){
452         return this.findListener(fn, scope) != -1;
453     },
454
455     removeListener : function(fn, scope){
456         var index,
457             me = this,
458             ret = FALSE;
459         if((index = me.findListener(fn, scope)) != -1){
460             if (me.firing) {
461                 me.listeners = me.listeners.slice(0);
462             }
463             me.listeners.splice(index, 1);
464             ret = TRUE;
465         }
466         return ret;
467     },
468
469     clearListeners : function(){
470         this.listeners = [];
471     },
472
473     fire : function(){
474         var me = this,
475             args = TOARRAY(arguments),
476             ret = TRUE;
477
478         EACH(me.listeners, function(l) {
479             me.firing = TRUE;
480             if (l.fireFn.apply(l.scope || me.obj || window, args) === FALSE) {
481                 return ret = me.firing = FALSE;
482             }
483         });
484         me.firing = FALSE;
485         return ret;
486     }
487 };
488 })();