PDA

View Full Version : Extending MixedColllection



tryanDLS
14 Nov 2006, 10:13 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]"

jack.slocum
14 Nov 2006, 11:27 PM
You could just use a closure:



toXml: function() {
var output = '';
this.eachKey(function(key, value){
output += '<' + key + '>' + util.serialize(value) + '</' + key + '>';
});
return output;
}

tryanDLS
15 Nov 2006, 7:53 AM
Yeah, that was my thought too. I couldn't get it to work - it just disappeared off into neverland in the debugger. I gave up and went with the 2 step solution. Just retried your way and it worked - must of been a typo - too much time spent looking at the code I guess :(

jbowman
15 Nov 2006, 11:08 AM
I've found that using try and catch when you're deep into javascript running javascript helps a lot. I just use YAHOO.log and shoot error messages to that, you could also just alert.