Observable.js
[app.Builder.js] / Observable.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11 XObject = imports.XObject.XObject;
12 /**
13  * @class Observable
14  * Base class that provides a common interface for publishing events. Subclasses are expected to
15  * to have a property "events" with all the events defined.<br>
16  * For example:
17  * <pre><code>
18  Employee = XObject.define(
19       function(name){
20         this.name = name;
21         this.addEvents({
22             "fired" : true,
23             "quit" : true
24         });
25      },
26      Observable, {});
27      
28 </code></pre>
29  * @param {Object} config properties to use (incuding events / listeners)
30  */
31  
32  
33 Observable = XObject.define(
34     function(cfg){
35         
36         cfg = cfg|| {};
37         this.addEvents(cfg.events || {});
38         if (cfg.events) {
39             delete cfg.events; // make sure
40         }
41          
42         XObject.extend(this, cfg);
43         
44         if(this.listeners){
45             this.on(this.listeners);
46             delete this.listeners;
47         }
48     },
49     Object,  
50     {
51         /** 
52          * @cfg {Object} listeners  list of events and functions to call for this object, 
53          * For example :
54          * <pre><code>
55             listeners :  { 
56                'click' : function(e) {
57                    ..... 
58                 } ,
59                 .... 
60             } 
61           </code></pre>
62          */
63             
64         
65         /**
66          * Fires the specified event with the passed parameters (minus the event name).
67          * @param {String} eventName
68          * @param {Object...} args Variable number of parameters are passed to handlers
69          * @return {Boolean} returns false if any of the handlers return false otherwise it returns true
70          */
71         fireEvent : function(){
72             var ce = this.events[arguments[0].toLowerCase()];
73             if(typeof ce == "object"){
74                 return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1));
75             }else{
76                 return true;
77             }
78         },
79
80         // private - blcoks these types of signals?
81         filterOptRe : /^(?:scope|delay|buffer|single)$/,
82
83         /**
84          * Appends an event handler to this component
85          * @param {String}   eventName The type of event to listen for
86          * @param {Function} handler The method the event invokes
87          * @param {Object}   scope (optional) The scope in which to execute the handler
88          * function. The handler function's "this" context.
89          * @param {Object}   options (optional) An object containing handler configuration
90          * properties. This may contain any of the following properties:<ul>
91          * <li>scope {Object} The scope in which to execute the handler function. The handler function's "this" context.</li>
92          * <li>delay {Number} The number of milliseconds to delay the invocation of the handler after te event fires.</li>
93          * <li>single {Boolean} True to add a handler to handle just the next firing of the event, and then remove itself.</li>
94          * <li>buffer {Number} Causes the handler to be scheduled to run in an {@link Roo.DelayedTask} delayed
95          * by the specified number of milliseconds. If the event fires again within that time, the original
96          * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</li>
97          * </ul><br>
98          * <p>
99          * <b>Combining Options</b><br>
100          * Using the options argument, it is possible to combine different types of listeners:<br>
101          * <br>
102          * A normalized, delayed, one-time listener that auto stops the event and passes a custom argument (forumId)
103             <pre><code>
104             el.on('click', this.onClick, this, {
105                 single: true,
106                 delay: 100,
107                 forumId: 4
108             });
109             </code></pre>
110          * <p>
111          * <b>Attaching multiple handlers in 1 call</b><br>
112          * The method also allows for a single argument to be passed which is a config object containing properties
113          * which specify multiple handlers.
114          * <pre><code>
115             el.on({
116                 'click': {
117                     fn: this.onClick,
118                     scope: this,
119                     delay: 100
120                 }, 
121                 'mouseover': {
122                     fn: this.onMouseOver,
123                     scope: this
124                 },
125                 'mouseout': {
126                     fn: this.onMouseOut,
127                     scope: this
128                 }
129             });
130             </code></pre>
131          * <p>
132          * Or a shorthand syntax which passes the same scope object to all handlers:
133             <pre><code>
134             el.on({
135                 'click': this.onClick,
136                 'mouseover': this.onMouseOver,
137                 'mouseout': this.onMouseOut,
138                 scope: this
139             });
140             </code></pre>
141          */
142         on : function(eventName, fn, scope, o){
143             if(typeof eventName == "object"){
144                 o = eventName;
145                 for(var e in o){
146                     if(this.filterOptRe.test(e)){
147                         continue;
148                     }
149                     if(typeof o[e] == "function"){
150                         // shared options
151                         this.on(e, o[e], o.scope,  o);
152                     }else{
153                         // individual options
154                         this.on(e, o[e].fn, o[e].scope, o[e]);
155                     }
156                 }
157                 return;
158             }
159             o = (!o || typeof o == "boolean") ? {} : o;
160             eventName = eventName.toLowerCase();
161             var ce = this.events[eventName] || true;
162             if(typeof ce == "boolean"){
163                 ce = new Roo.Event(this, eventName);
164                 this.events[eventName] = ce;
165             }
166             ce.addListener(fn, scope, o);
167         },
168
169         /**
170          * Removes a listener
171          * @param {String}   eventName     The type of event to listen for
172          * @param {Function} handler        The handler to remove
173          * @param {Object}   scope  (optional) The scope (this object) for the handler
174          */
175         un : function(eventName, fn, scope){
176             var ce = this.events[eventName.toLowerCase()];
177             if(typeof ce == "object"){
178                 ce.removeListener(fn, scope);
179             }
180         },
181
182         /**
183          * Removes all listeners for this object
184          */
185         purgeListeners : function(){
186             for(var evt in this.events){
187                 if(typeof this.events[evt] == "object"){
188                      this.events[evt].clearListeners();
189                 }
190             }
191         },
192
193         relayEvents : function(o, events){
194             var createHandler = function(ename){
195                 return function(){
196                     return this.fireEvent.apply(this, Roo.combine(ename, Array.prototype.slice.call(arguments, 0)));
197                 };
198             };
199             for(var i = 0, len = events.length; i < len; i++){
200                 var ename = events[i];
201                 if(!this.events[ename]){ this.events[ename] = true; };
202                 o.on(ename, createHandler(ename), this);
203             }
204         },
205
206         /**
207          * Used to define events on this Observable
208          * @param {Object} object The object with the events defined
209          */
210         addEvents : function(o){
211             if(!this.events){
212                 this.events = {};
213             }
214             Roo.applyIf(this.events, o);
215         },
216
217         /**
218          * Checks to see if this object has any listeners for a specified event
219          * @param {String} eventName The name of the event to check for
220          * @return {Boolean} True if the event is being listened for, else false
221          */
222         hasListener : function(eventName){
223             var e = this.events[eventName];
224             return typeof e == "object" && e.listeners.length > 0;
225         }
226 };
227  
228 /**
229  * Starts capture on the specified Observable. All events will be passed
230  * to the supplied function with the event name + standard signature of the event
231  * <b>before</b> the event is fired. If the supplied function returns false,
232  * the event will not fire.
233  * @param {Observable} o The Observable to capture
234  * @param {Function} fn The function to call
235  * @param {Object} scope (optional) The scope (this object) for the fn
236  * @static
237  */
238 Observable.capture = function(o, fn, scope){
239     o.fireEvent = o.fireEvent.createInterceptor(fn, scope);
240 };
241
242 /**
243  * Removes <b>all</b> added captures from the Observable.
244  * @param {Observable} o The Observable to release
245  * @static
246  */
247 Observable.releaseCapture = function(o){
248     o.fireEvent = Observable.prototype.fireEvent;
249 };
250
251 (function(){
252
253     var createBuffered = function(h, o, scope){
254         var task = new Roo.DelayedTask();
255         return function(){
256             task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
257         };
258     };
259
260     var createSingle = function(h, e, fn, scope){
261         return function(){
262             e.removeListener(fn, scope);
263             return h.apply(scope, arguments);
264         };
265     };
266
267     var createDelayed = function(h, o, scope){
268         return function(){
269             var args = Array.prototype.slice.call(arguments, 0);
270             setTimeout(function(){
271                 h.apply(scope, args);
272             }, o.delay || 10);
273         };
274     };
275
276     Roo.Event = function(obj, name){
277         this.name = name;
278         this.obj = obj;
279         this.listeners = [];
280     };
281
282     Roo.Event.prototype = {
283         addListener : function(fn, scope, options){
284             var o = options || {};
285             scope = scope || this.obj;
286             if(!this.isListening(fn, scope)){
287                 var l = {fn: fn, scope: scope, options: o};
288                 var h = fn;
289                 if(o.delay){
290                     h = createDelayed(h, o, scope);
291                 }
292                 if(o.single){
293                     h = createSingle(h, this, fn, scope);
294                 }
295                 if(o.buffer){
296                     h = createBuffered(h, o, scope);
297                 }
298                 l.fireFn = h;
299                 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
300                     this.listeners.push(l);
301                 }else{
302                     this.listeners = this.listeners.slice(0);
303                     this.listeners.push(l);
304                 }
305             }
306         },
307
308         findListener : function(fn, scope){
309             scope = scope || this.obj;
310             var ls = this.listeners;
311             for(var i = 0, len = ls.length; i < len; i++){
312                 var l = ls[i];
313                 if(l.fn == fn && l.scope == scope){
314                     return i;
315                 }
316             }
317             return -1;
318         },
319
320         isListening : function(fn, scope){
321             return this.findListener(fn, scope) != -1;
322         },
323
324         removeListener : function(fn, scope){
325             var index;
326             if((index = this.findListener(fn, scope)) != -1){
327                 if(!this.firing){
328                     this.listeners.splice(index, 1);
329                 }else{
330                     this.listeners = this.listeners.slice(0);
331                     this.listeners.splice(index, 1);
332                 }
333                 return true;
334             }
335             return false;
336         },
337
338         clearListeners : function(){
339             this.listeners = [];
340         },
341
342         fire : function(){
343             var ls = this.listeners, scope, len = ls.length;
344             if(len > 0){
345                 this.firing = true;
346                 var args = Array.prototype.slice.call(arguments, 0);
347                 for(var i = 0; i < len; i++){
348                     var l = ls[i];
349                     if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
350                         this.firing = false;
351                         return false;
352                     }
353                 }
354                 this.firing = false;
355             }
356             return true;
357         }
358     };
359 })();