Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Action Script / Flex Konstruktur (MXML)

// Konstruktur AS > f. Flex

   1  
   2  <mx:Script>
   3  	<![CDATA[
   4  	import mx.controls.Alert; // or any other controls
   5  
   6  	private function myname():void {
   7  		myComponent.field="something";
   8  	}
   9  	]]>
  10  </mx:Script>

DeclarativeDescriptor an example of writing a custom DataDescriptor


Sometimes it becomes necessary to write a custom DataDescriptor for certain Flex controls (i.e. Tree, TreeMap, etc). This is a generic data descriptor that allows you to declare a single field name to be used for the children of the given node. This makes it easy to simple tell Flex to use any field instead of the default "children" field.

   1  
   2  package {
   3  	
   4  	import mx.collections.ArrayCollection;
   5  	import mx.collections.CursorBookmark;
   6  	import mx.collections.ICollectionView;
   7  	import mx.collections.IViewCursor;
   8  	import mx.controls.treeClasses.ITreeDataDescriptor;
   9  	import mx.events.CollectionEvent;
  10  	import mx.events.CollectionEventKind;
  11  	
  12  	public class DeclarativeDescriptor implements ITreeDataDescriptor {
  13  		
  14  		private var _fieldname : String;
  15  		
  16  		public function DeclarativeDescriptor( fieldname : String ) {
  17  			_fieldname = fieldname;
  18  		}
  19  
  20  		public function getChildren(node:Object, model:Object=null) : ICollectionView {
  21  			if( node.hasOwnProperty( _fieldname ) ) {
  22  				return node[_fieldname] is ICollectionView ? node[_fieldname] as ICollectionView : new ArrayCollection( node[_fieldname] );
  23  			} else {
  24  				return null;
  25  			}
  26  		}
  27  		
  28  		public function hasChildren(node:Object, model:Object=null) : Boolean {
  29  			if( isBranch( node, model ) ) {
  30  				var children : ICollectionView = getChildren( node, model );
  31  				return children.length > 0;
  32  			} else {
  33  				return false;
  34  			}
  35  		}
  36  		
  37  		public function isBranch(node:Object, model:Object=null) : Boolean {
  38  			return node.hasOwnProperty(_fieldname);
  39  		}
  40  		
  41  		public function getData(node:Object, model:Object=null) : Object {
  42  			return node;
  43  		}
  44  		
  45  		public function addChildAt(parent:Object, child:Object, index:int, model:Object=null) : Boolean {
  46  	        var event:CollectionEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
  47  	        event.kind = CollectionEventKind.ADD;
  48  	        event.items = [child];
  49  	        event.location = index;
  50  	        if (!parent) {
  51  	            var iterator:IViewCursor = model.createCursor();
  52  	            iterator.seek(CursorBookmark.FIRST, index);
  53  	            iterator.insert(child);
  54  	        } else if (parent is Object) {
  55  	            if (isBranch(parent) ) {
  56  	            	var children : Object = parent[_fieldname];
  57  	                if( children is ArrayCollection) {
  58  	                    children.addItemAt(child, index);
  59  	                    if (model) {
  60  	                        model.dispatchEvent(event);
  61  	                        model.itemUpdated(parent);
  62  	                    }
  63  	                    return true;
  64  	                } else {
  65  	                    children.splice(index, 0, child);
  66  	                    if (model)
  67  	                        model.dispatchEvent(event);
  68  	                    return true;
  69  	                }
  70  	            }
  71  	        }
  72  	        return false;
  73  		}
  74  		
  75  		public function removeChildAt(parent:Object, child:Object, index:int, model:Object=null) : Boolean {
  76  	        var event:CollectionEvent = new CollectionEvent(CollectionEvent.COLLECTION_CHANGE);
  77  	        event.kind = CollectionEventKind.REMOVE;
  78  		    event.items = [child];
  79  		    event.location = index;
  80  		
  81  		    //handle top level where there is no parent
  82  		    if (!parent) {
  83  		        var iterator:IViewCursor = model.createCursor();
  84  		        iterator.seek(CursorBookmark.FIRST, index);
  85  		        iterator.remove();
  86  		        if (model)
  87  		            model.dispatchEvent(event);
  88  		        return true;
  89  		    } else if (parent is Object) {
  90  		    	var children : Object = parent[_fieldname];
  91  		        if (children) {
  92  		            children.splice(index, 1);
  93  		            if (model) 
  94  		                model.dispatchEvent(event);
  95  		            return true;
  96  		        }
  97  		    }
  98  		    return false;
  99  		}
 100  	}
 101  }

Example of a TreeMap using Objects Instead of XML


This is an example of how to use Flex2TreeMap with plain old ActionScript (POASO) objects instead of XML. You have to declare a dataDescriptor of the TreeMap so you can map companies field to the children of the sector node.

This class depends on DeclarativeDescriptor in order to compile.

   1  
   2  <?xml version="1.0" encoding="utf-8"?>
   3  <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:toolbox="http://www.flextoolbox.com/2006/mxml">
   4  
   5  	<mx:Script>
   6  		<![CDATA[
   7  		
   8  			private const MIN_COLOR:uint = 0xcc0000;
   9  			private const ZERO_COLOR:uint = 0;
  10  			private const MAX_COLOR:uint = 0x00cc00;
  11  			
  12  			private var _maxAbsoluteChange:Number;
  13  			private var __descriptor : DeclarativeDescriptor = new DeclarativeDescriptor("companies");
  14  			
  15  			[Bindable]
  16  			private var marketData : Array = [
  17  				{ name: "Technology",
  18  				  companies: [
  19  					{ name: "WidgetCorp", marketCap: "4200000000", value: 42.01, change: -2.03 },
  20  					{ name: "Sprocket Systems", marketCap: "2100000000", value: 24.87, change: 4.45 },
  21  					{ name: "Gizmodyne", marketCap: "10500000000", value: 106.52, change: 1.01 },
  22  					{ name: "GadgetSoft", marketCap: "1200000000", value: 12.98, change: -0.82 }
  23  				  ]
  24  				},
  25  				{ name: "Financial",
  26  				  companies: [
  27  					{ name: "Parker-Hayes", marketCap: "4550000000", value: 36.74, change: 3.56},
  28  					{ name: "G.A. Harvard", marketCap: "12800000000", value: 21.61, change: -1.71},
  29  					{ name: "P. Royal Trust", marketCap: "8700000000", value: 25.22, change: 2.09},
  30  					{ name: "Houndsworth Bank", marketCap: "1900000000", value: 33.71, change: 0.2}
  31  				  ]
  32  			 	},
  33  				{ name: "Communication",
  34  				  companies: [
  35  				     { name: "Richtel Networks", marketCap: "2400000000", value: 34.93, change: -1.94},
  36  				     { name: "TCI", marketCap: "9600000000", value: 45.82, change: 0.22},
  37  				     { name: "Norizon", marketCap: "1400000000", value: 27.46, change: 1.68}
  38  				  ]
  39  			 	},
  40  			 	{ name: "Energy",
  41  			 	  companies: [
  42  				     { name: "Axxom Monopocorp", marketCap: "3200000000", value: 36.18, change: 5.46},
  43  				     { name: "RP Petrol", marketCap: "7500000000", value: 26.74, change: -3.25},
  44  				     { name: "Lexaco", marketCap: "3900000000", value: 15.96, change: -2.08}
  45  			 	  ]
  46  			 	}
  47  			];
  48  			
  49  			/**
  50  			 * For each item, determines the tooltip text.
  51  			 */
  52  			private function itemToToolTip(item:Object):String
  53  			{
  54  				//one tooltip for branches and one for leaves
  55  				if(this.treeMap.dataDescriptor.isBranch(item))
  56  				{
  57  					return null;
  58  				}
  59  				var capInBillions:Number = Number(item.marketCap) / 1000000000;
  60  				return "Value: " + this.formatter.format(item.value) + "\n" +
  61  					"Change: " + item.change + "%\n" +
  62  					"Market Cap: $" + capInBillions + "B";
  63  			}
  64  
  65  			/**
  66  			 * Takes the absolute value of each change value and determines the maximum.
  67  			 */
  68  			private function calculateMaxAbsoluteChange():void
  69  			{
  70  				var companies:Array = this.marketData.companies;
  71  				this._maxAbsoluteChange = 0;
  72  				for each(var company:Object in companies)
  73  				{
  74  					var change:Number = Number(company.change);
  75  					this._maxAbsoluteChange = Math.max(this._maxAbsoluteChange, Math.abs(change));
  76  				}
  77  			}
  78  			
  79  			/**
  80  			 * For each item, determines the background color.
  81  			 */
  82  			private function itemToColor(item:Object):uint
  83  			{
  84  				var change:Number = Number(item.change);
  85  				if(change < 0)
  86  				{
  87  					return this.blendColors(MIN_COLOR, ZERO_COLOR, Math.abs(change) / this._maxAbsoluteChange);
  88  				}
  89  				else if(change > 0)
  90  				{
  91  					return this.blendColors(ZERO_COLOR, MAX_COLOR, 1 - (Math.abs(change) / this._maxAbsoluteChange));
  92  				}
  93  				return ZERO_COLOR;
  94  			}
  95  			
  96  			/**
  97  			 * Determines the blended color between two separate colors using a range from 0 to 1.
  98  			 */
  99  			private function blendColors(color1:uint, color2:uint, percent:Number = 0.5):uint
 100  			{
 101  				var remaining:Number = 1 - percent;
 102  				
 103  				var red1:uint = (color1 >> 16) & 0xff;
 104  				var green1:uint = (color1 >> 8) & 0xff;
 105  				var blue1:uint = color1 & 0xff;
 106  				
 107  				var red2:uint = (color2 >> 16) & 0xff;
 108  				var green2:uint = (color2 >> 8) & 0xff;
 109  				var blue2:uint = color2 & 0xff;
 110  				 
 111  				color1 = ((red1 * percent) << 16) + ((green1 * percent) << 8) + blue1 * percent;
 112  				color2 = ((red2 * remaining) << 16) + ((green2 * remaining) << 8) + blue2 * remaining;
 113  	
 114  				return color1 + color2;
 115  	
 116  			}
 117  			
 118  		]]>
 119  	</mx:Script>
 120  
 121  	<toolbox:TreeMap id="treeMap" width="400" height="300"
 122  		dataProvider="{marketData}" labelField="name" weightField="marketCap"
 123  		colorFunction="{itemToColor}" dataTipFunction="{itemToToolTip}" dataDescriptor="{__descriptor}"/>
 124  	
 125  	<mx:CurrencyFormatter id="formatter"/>
 126  	
 127  	
 128  </mx:Application>

Some Flex Code

// A login box component in mxml. This is buggy, I'll adjust this to the clean stuff when I get it figured out.
   1  
   2  <?xml version="1.0" encoding="UTF-8"?>
   3  <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" label="Login">
   4    <mx:Form labelWidth="150">
   5    <mx:Metadata> 
   6        [Event(name="login", type="com.pomodo.events.LoginEvent")] 
   7    </mx:Metadata> 
   8    <mx:Script> 
   9    <![CDATA[ 
  10      import mx.controls.Alert; 
  11      import mx.rpc.events.ResultEvent;
  12      import com.pomodo.events.LoginEvent; 
  13        private function login():void { 
  14            svcAccountLogin.send({login: loginTI.text, password: passwordTI.text}); 
  15        } 
  16        private function handleAccountLoginResult(event:ResultEvent):void { 
  17            var result:Object = event.result; 
  18            if (result == "badlogin") { 
  19                Alert.show("The username or password is wrong.", "Login Error"); 
  20            } else { 
  21                dispatchEvent(new LoginEvent(XML(result))); 
  22            } 
  23        } 
  24    ]]> 
  25    </mx:Script> 
  26    <mx:HTTPService 
  27        id="svcAccountLogin" 
  28        url="/sessions/create_xml" 
  29        resultFormat="e4x" 
  30        method="POST" 
  31        result="handleAccountLoginResult(event)"/>
  32  
  33      <mx:FormItem label="Username" required="true">
  34        <mx:TextInput id="loginTI"/>
  35      </mx:FormItem>
  36      <mx:FormItem label="Password" required="true">
  37        <mx:TextInput id="passwordTI"/>
  38      </mx:FormItem>
  39      <mx:FormItem>
  40        <mx:Button id="loginButton" label="Login" click="login()"/> 
  41      </mx:FormItem>
  42    </mx:Form>
  43  </mx:VBox>
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS