XObject.js
[gitlive] / XObject.js
1 //<script type="text/javascript">
2
3 /**
4  * XObject
5  * Yet another attempt to create a usable object construction library for seed..
6  *
7  * Extend this.. to use it's wonderful features..
8  * 
9  * 
10  * 
11  * 
12  * 
13  * @arg xtype {String|Function} constructor or string.
14  * @arg xid {String}  (optional) id for registry
15  * @arg xns {String|Object}   (optional) namespace eg. Gtk or 'Gtk' - used with xtype.
16  * @arg items {Array}   (optional) list of child elements which will be constructed.. using XObject
17  * @arg listeners {Object}   (optional) map Gobject signals to functions
18  * @arg pack {Function|String|Array}   (optional) how this object gets added to it's parent
19  * @arg el {Object}   (optional) premade GObject
20  * 
21  *  --- needs a xdebug option!
22  */
23
24 function XObject (cfg) {
25     // first apply cfg if set.
26     this.config = cfg;
27     
28     
29 }
30
31
32
33 XObject.prototype = {
34     /**
35      * @property el {GObject} the Gtk / etc. element.
36      */
37     el : false, 
38     /*
39      * @property items {Array} list of sub elements
40      */
41     /**
42      * @property parent {XObject} parent Element
43      */
44      
45      /**
46      * @property config {Object} the construction configuration.
47      */
48      /**
49       * @method init
50       * Initializes the Element (el) hooks up all the listeners
51       * and packs the children.
52       */ 
53     init : function()
54     {
55         var cfg = this.config;
56     
57         print("new xobj?"  + XObject.keys(cfg).join(','));
58         //print(cfg);
59         o =  {};
60         
61         cfg.items = cfg.items || [];
62         
63         XObject.extend(o, cfg); // copy everything into o.
64         
65         o.pack = typeof(o.pack) == 'undefined' ? 'add' : o.pack;
66         
67         XObject.extend(this, o);
68
69         // remove items.
70         
71         this.listeners = this.listeners || {}; 
72         this.items = [];
73         
74         // remove objects/functions from o, so they can be sent to the contructor.
75         for (var i in o) {
76             if ((typeof(o[i]) == 'object') || 
77                 (typeof(o[i]) == 'function') || 
78                 i == 'pack' ||
79                 i == 'xid' ||
80                 i == 'xtype' ||
81                 i == 'xdebug' ||
82                 i == 'xns'
83             ) {
84                 delete o[i];
85             }
86         }
87         
88         // do we need to call 'beforeInit here?'
89          
90         // handle include?
91         //if ((this.xtype == 'Include')) {
92         //    o = this.pre_registry[cls];
93         //}
94         var isSeed = typeof(Seed) != 'undefined';
95          
96         // xtype= Gtk.Menu ?? what about c_new stuff?
97         print(this.xtype);
98         if (typeof(this.xtype) == 'function') {
99             print("func?"  + XObject.keys(o).join(','));
100             this.el = this.el ||   this.xtype(o);
101         }
102         if (typeof(this.xtype) == 'object') {
103             print("obj?"  + XObject.keys(o).join(','));
104             this.el = this.el ||  new this.xtype(o);
105         }
106         //print(this.el);
107         if (!this.el && o.xns) {
108             
109             var NS = imports.gi[o.xns];
110             if (!NS) {
111                 Seed.print('Invalid xns: ' + o.xns);
112             }
113             constructor = NS[o.xtype];
114             if (!constructor) {
115                 Seed.print('Invalid xtype: ' + o.xns + '.' + o.xtype);
116             }
117             this.el  =   isSeed ? new constructor(o) : new constructor();
118             
119         }
120         // always overlay props..
121         for (var i in o) {
122             this.el[i] = o[i];
123         }
124         // register it!
125         //if (o.xnsid  && o.xid) {
126          //   XObject.registry = XObject.registry || { };
127          //   XObject.registry[o.xnsid] = XObject.registry[o.xnsid] || {}; 
128          //   XObject.registry[o.xnsid][o.xid] = this;
129         //}
130         
131         cfg.items.forEach(this.addItem, this);
132         
133         for (var i in this.listeners) {
134             this.addListener(i, this.listeners[i]);
135         }
136         // delete this.listeners ?
137         
138         
139         // do we need to call 'init here?'
140     },
141       
142      
143      /**
144       * @method addItem
145       * Adds an item to the object using a new XObject
146       * uses pack property to determine how to add it.
147       * @arg cfg {Object} same as XObject constructor.
148       */
149     addItem : function(o) {
150         
151          
152         var item = (o.constructor == XObject) ? o : new XObject(o);
153         item.parent = this;
154         this.items.push(item);
155         
156         if (item.pack===false) {  // no 
157             return;
158         }
159         if (typeof(item.pack) == 'function') {
160             // parent, child
161             item.pack.apply(o, [ o , o.items[i] ]);
162             item.parent = this;
163             return;
164         }
165         var args = [];
166         var pack_m  = false;
167         if (typeof(item.pack) == 'string') {
168             pack_m = item.pack;
169         } else {
170             pack_m = item.pack.shift();
171             args = item.pack;
172         }
173         
174         // handle error.
175         if (pack_m && typeof(this.el[pack_m]) == 'undefined') {
176             Seed.print('pack method not available : ' + this.xtype + '.' +  pack_m);
177             return;
178         }
179         
180         
181         //Seed.print('Pack ' + this.el + '.'+ pack_m + '(' + item.el + ')');
182
183         args.unshift(item.el);
184         print('[' + args.join(',') +']');
185         //Seed.print('args: ' + args.length);
186         if (pack_m) {
187             this.el[pack_m].apply(this.el, args);
188         }
189         
190        
191         
192     },
193     /**
194       * @method addListener
195       * Connects a method to a signal. (gjs/Seed aware)
196       * 
197       * @arg sig  {String} name of signal
198       * @arg fn  {Function} handler.
199       */
200     addListener  : function(sig, fn) 
201     {
202  
203         Seed.print("Add signal " + sig);
204  
205         var _li = XObject.createDelegate(fn,this);
206         // private listeners that are not copied to GTk.
207         
208         if (typeof(Seed) != 'undefined') {
209           //   Seed.print(typeof(_li));
210             this.el.signal[sig].connect(_li);
211         } else {
212             this.el.connect( sig, _li);
213         }
214              
215         
216     },
217      /**
218       * @method get
219       * Finds an object in the child elements using xid of object.
220       * prefix with '.' to look up the tree.. multiple '..' to look further up..
221       * 
222       * @arg name  {String} name of signal
223       * @return   {XObject|false} the object if found.
224       */
225     get : function(xid)
226     {
227         var ret=  false;
228         if (xid[0] == '.') {
229             return this.parent.get(xid.substring(1));
230         }
231         
232         
233         this.items.forEach(function(ch) {
234             if (ch.xid == xid) {
235                 ret = ch;
236                 return true;
237             }
238         })
239         if (ret) {
240             return ret;
241         }
242         // iterate children.
243         this.items.forEach(function(ch) {
244             ret = ch.get(xid);
245             if (ret) {
246                 return true;
247             }
248         })
249         return ret;
250     }
251       
252       
253
254          
255         
256 /**
257  * Copies all the properties of config to obj.
258  *
259  * Pretty much the same as JQuery/Prototype..
260  * @param {Object} obj The receiver of the properties
261  * @param {Object} config The source of the properties
262  * @param {Object} defaults A different object that will also be applied for default values
263  * @return {Object} returns obj
264  * @member XObject extend
265  */
266
267
268 XObject.extend = function(o, c, defaults){
269     if(defaults){
270         // no "this" reference for friendly out of scope calls
271         XObject.extend(o, defaults);
272     }
273     if(o && c && typeof c == 'object'){
274         for(var p in c){
275             o[p] = c[p];
276         }
277     }
278     return o;
279 };
280
281 XObject.extend(XObject,
282 {
283     /**
284      * Copies all the properties of config to obj, if the do not exist.
285      * @param {Object} obj The receiver of the properties
286      * @param {Object} config The source of the properties
287      * @return {Object} returns obj
288      * @member Object extendIf
289      */
290
291
292     extendIf : function(o, c){
293
294         if(!o || !c || typeof c != 'object'){
295             return o;
296         }
297         for(var p in c){
298             if (typeof(o[p]) != 'undefined') {
299                 continue;
300             }
301             o[p] = c[p];
302         }
303         return o;
304     },
305
306  
307
308     /**
309      * Extends one class with another class and optionally overrides members with the passed literal. This class
310      * also adds the function "override()" to the class that can be used to override
311      * members on an instance.
312      *
313      * usage:
314      * MyObject = Object.define(
315      *     function(...) {
316      *          ....
317      *     },
318      *     parentClass, // or Object
319      *     {
320      *        ... methods and properties.
321      *     }
322      * });
323      * @param {Function} constructor The class inheriting the functionality
324      * @param {Object} superclass The class being extended
325      * @param {Object} overrides (optional) A literal with members
326      * @return {Function} constructor (eg. class
327      * @method define
328      */
329     define : function(){
330         // inline overrides
331         var io = function(o){
332             for(var m in o){
333                 this[m] = o[m];
334             }
335         };
336         return function(sb, sp, overrides) {
337             if (typeof(sp) == 'undefined') {
338                 // error condition - try and dump..
339                 throw "Missing superclass: when applying: " + sb
340             }
341
342             var F = function(){}, sbp, spp = sp.prototype;
343             F.prototype = spp;
344             sbp = sb.prototype = new F();
345             sbp.constructor=sb;
346             sb.superclass=spp;
347
348             // extends Object.
349             if(spp.constructor == Object.prototype.constructor){
350                 spp.constructor=sp;
351             }
352             
353             sb.override = function(o){
354                 Object.extend(sb.prototype, o);
355             };
356             sbp.override = io;
357             Object.extend(sb.prototype, overrides);
358             return sb;
359         };
360     }(),
361
362          
363     /**
364      * returns a list of keys of the object.
365      * @param {Object} obj object to inspect
366      * @return {Array} returns list of kyes
367      * @member XObject keys
368      */
369     keys : function(o)
370     {
371         var ret = [];
372         for(var i in o) {
373             ret.push(i);
374         }
375         return ret;
376     },
377       
378     /**
379      * @member XObject createDelegate
380      * creates a delage metdhod
381      * @param {Function} method to wrap
382      * @param {Object} scope 
383      * @param {Array} args to add
384      * @param {Boolean|Number} append arguments or replace after N arguments.
385      * @return {Function} returns the delegate
386      */
387
388     createDelegate : function(method, obj, args, appendArgs){
389         
390         return function() {
391             var callArgs = args || arguments;
392             if(appendArgs === true){
393                 callArgs = Array.prototype.slice.call(arguments, 0);
394                 callArgs = callArgs.concat(args);
395             }else if(typeof appendArgs == "number"){
396                 callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
397                     var applyArgs = [appendArgs, 0].concat(args); // create method call params
398                     Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
399                 }
400                 return method.apply(obj || window, callArgs);
401             };
402     }
403     
404 });