package app { import mx.collections.ArrayCollection; import mx.rpc.remoting.RemoteObject; import mx.messaging.ChannelSet; import mx.messaging.channels.AMFChannel; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; import mx.collections.ListCollectionView; import mx.controls.Alert; import app.vo.Entity; import flash.utils.Dictionary; public class RemotingUtils { public static function defaultItemInflator(state:Object, type:Class=null):Object { return new type(state); } public static function inflate(items:Array, type:Class, itemInflator:Function=null):Array { if (itemInflator == null) { itemInflator = defaultItemInflator; } for (var i:int = 0; i < items.length; i++) { items[i] = itemInflator(items[i], type); } return items; } public static function repopulate(ac:ArrayCollection, s:*, reinitialize:Boolean=true):void { if (ac == null) { throw new Error("You can't repopulate a null ArrayCollection"); } var na:Array; if (s is ListCollectionView) { na = s.toArray(); } else if (s is Array) { na = s as Array; } else { throw new Error("Invalid argument: only Arrays and ListCollectionView may be used to repopulate an ArrayCollection"); } if (reinitialize && na.length > 0 && na[0] is Entity) { /** * This block of code reinitializes the existing object with * the new state from the server, so as not to break * existing client-side references where possible. */ var oo:Dictionary = new Dictionary(true); var no:Dictionary = new Dictionary(true); var i:int; for (i = 0; i < ac.length; i++) { oo[Entity(ac[i]).id] = ac[i]; } for (i = 0; i < na.length; i++) { no[Entity(na[i]).id] = na[i]; } ac.removeAll(); var id:String; var o:Entity; for (id in no) { if (oo.hasOwnProperty(id)) { o = oo[id]; o.initialize(no[id]); } else { o = no[id]; } ac.addItem(o); } } else { ac.source = na; } ac.sort = null ac.filterFunction = null; ac.refresh(); } } }