PDA

View Full Version : Extending MixedColllection



tryanDLS
14 Nov 2006, 10:11 AM
I'm migrating one of my custom collection objects to take advantage of MixedCollection. The following works, but isn't the most elegant solution:

1) output has to be defined at the object level, rather than being passed as an arg or returned from each/eachKey.
2) requires 2 methods to accomplish a function (e.g. toString/_toString). I tried to inline the _toString as the 1st arg to eachKey, but couldn't get it to work.

Any thoughts on making this cleaner?




SoapArgs = function() {
SoapArgs.superclass.constructor.call(this, true);
}
YAHOO.extendX(SoapArgs, YAHOO.ext.util.MixedCollection, {
output: '',

toXml: function() {
this.output = '';
this.eachKey(this._serialize, this);
return this.output;
},

toString: function() {
this.output = '';
this.eachKey(this._toString, this);
return this.output;
},

/* @private */
_toString: function(key, item) {
this.output += (this.output.length > 0) ? ',' : '';
this.output += key + ':' + item;

},

/* @private */
_serialize: function(key, item) {
// util.serialize recursively processes item to dump its data
this.output += '<' + key + '>' + util.serialize(item) + '</' + key + '>';
}
});

// test
var args = new SoapArgs();
args.add('ntid', 'jdoe');
args.add('domain', 'yahoo.com');
args.add('complexObj', {a:0, b:'1', c:true, d:null});

var xml = args.toXml();
// returns "<ntid>jdoe</ntid><domain>yahoo.com</domain><complexObj><a>0</a>1<c>true</c><d></d></complexObj>"

var txt = args.toString();
// returns "ntid:jdoe,domain:yahoo.com,complexObj:[object Object]"