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 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             XObject.extendIf(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  
252
253 var createSingle = function(h, e, fn, scope){
254     return function(){
255         e.removeListener(fn, scope);
256         return h.apply(scope, arguments);
257     };
258 };
259
260 // NOT SUPPORTED YET>
261 //var createBuffered = function(h, o, scope){
262 //    var task = new Roo.DelayedTask();
263 //    return function(){
264 //        task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0));
265 //    };
266 //};
267
268
269 //var createDelayed = function(h, o, scope){
270 //    return function(){
271 //        var args = Array.prototype.slice.call(arguments, 0);
272 //        setTimeout(function(){
273 //            h.apply(scope, args);
274 //        }, o.delay || 10);
275 //    };
276 //};
277
278
279
280
281
282
283 Event = XObject.define({
284     function(obj, name){
285         this.name = name;
286         this.obj = obj;
287         this.listeners = [];
288     },
289     Object, 
290     {
291         addListener : function(fn, scope, options){
292             var o = options || {};
293             scope = scope || this.obj;
294             if(!this.isListening(fn, scope)){
295                 var l = {fn: fn, scope: scope, options: o};
296                 var h = fn;
297                // if(o.delay){
298                 //       h = createDelayed(h, o, scope);
299                // }
300                 if(o.single){
301                     h = createSingle(h, this, fn, scope);
302                 }
303                 //if(o.buffer){
304                //     h = createBuffered(h, o, scope);
305                 //}
306                 l.fireFn = h;
307                 if(!this.firing){ // if we are currently firing this event, don't disturb the listener loop
308                     this.listeners.push(l);
309                 }else{
310                     this.listeners = this.listeners.slice(0);
311                     this.listeners.push(l);
312                 }
313             }
314         },
315
316         findListener : function(fn, scope){
317             scope = scope || this.obj;
318             var ls = this.listeners;
319             for(var i = 0, len = ls.length; i < len; i++){
320                 var l = ls[i];
321                 if(l.fn == fn && l.scope == scope){
322                     return i;
323                 }
324             }
325             return -1;
326         },
327
328         isListening : function(fn, scope){
329             return this.findListener(fn, scope) != -1;
330         },
331
332         removeListener : function(fn, scope){
333             var index;
334             if((index = this.findListener(fn, scope)) != -1){
335                 if(!this.firing){
336                     this.listeners.splice(index, 1);
337                 }else{
338                     this.listeners = this.listeners.slice(0);
339                     this.listeners.splice(index, 1);
340                 }
341                 return true;
342             }
343             return false;
344         },
345
346         clearListeners : function(){
347             this.listeners = [];
348         },
349
350         fire : function(){
351             var ls = this.listeners, scope, len = ls.length;
352             if(len > 0){
353                 this.firing = true;
354                 var args = Array.prototype.slice.call(arguments, 0);
355                 for(var i = 0; i < len; i++){
356                     var l = ls[i];
357                     if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){
358                         this.firing = false;
359                         return false;
360                     }
361                 }
362                 this.firing = false;
363             }
364             return true;
365         }
366     }
367 );