Flex中的mxml類實現(繼承)接口的方法

可以把mxml文件看作一個類,這個類可以實現某一接口,可以繼承某一類

示例1,mxml實現接口。在這裏示例中,A包含在B中,A是B的一個控件,同時,在設計的時候,讓A保存B的一個引用,這樣的話,就可在A中調用B的方法等操作

接口文件:

/*
  Modularity - A PureMVC AS3 MultiCore Flex Demo
  Copyright(c) 2008 Cliff Hall <[email protected]>
  Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package org.puremvc.as3.multicore.demos.flex.modularity.interfaces
{
	/**
	 * Interface for a Widget.
	 * <P>
	 * This is the API that must be implemented by a
	 * Widget. What we are calling 'widgets' 
	 * in this demo application are Flex Modules, but they 
	 * could also be Flash based apps using the PureMVC 
	 * AS3 MultiCore framework.</P>
	 */
	public interface IWidget
	{
		/**
		 * Get the Widget's key. 
		 * <P> 
		 * This will be a unique string. Generally created
		 * by adding a unique URI for the widget to the 
		 * id property of the IWidget instance.</P>
		 */
		function getWidgetKey( ):String;
		
		/**
		 * Set the Widget's reference to the WidgetShell.
		 * <P>
		 * The Widget communicates with the rest of the
		 * application via the API exposed by the 
		 * WidgetShell.  
		 */
		function setWidgetShell( shell:IWidgetShell ):void;
	}
}
/*
  Modularity - A PureMVC AS3 MultiCore Flex Demo
  Copyright(c) 2008 Cliff Hall <[email protected]>
  Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package org.puremvc.as3.multicore.demos.flex.modularity.interfaces
{
	import flash.display.DisplayObject;
	
	/**
	 * Interface for the WidgetShell
	 * <P>
	 * This is the API that the WidgetShell
	 * exposes to Widgets for communication.
	 * Through this interface alone the IWidget
	 * is able to communicate its wishes to the
	 * application into which it is loaded.</P>
	 * <P>
	 * Since third-parties may develop widgets
	 * to run inside the app, we want to limit
	 * their access to the application and its
	 * resources.</P>
	 * 
	 */
	public interface IWidgetShell
	{
		
		/**
		 * A widget may add a view component to the canvas.
		 * <P>
		 * Though the display object reference is added to
		 * the view hierarchy of the app, it is still managed
		 * by a mediator running inside the widget itself.</P>
		 * 
		 * @param displayObject to add to the canvas
		 */
		function addComponent( component:DisplayObject ):void;
		
		/**
		 * A widget may remove a view component it added to the canvas.
		 * <P>
		 * 
		 * @param displayObject to add to the canvas
		 */
		function removeComponent( component:DisplayObject ):void;
		
		/**
		 * Allow the Widget to write to the status line
		 */
		function setStatusMessage( message:String ):void;
		
		
	}
}

mxml實現接口

<?xml version="1.0" encoding="utf-8"?>
<!-- 
  Modularity - A PureMVC AS3 MultiCore Flex Demo
  Copyright(c) 2008 Cliff Hall <[email protected]>
  Your reuse is governed by the Creative Commons Attribution 3.0 License
 -->
<mx:ApplicationControlBar 
	xmlns:mx="http://www.adobe.com/2006/mxml"
	implements="org.puremvc.as3.multicore.demos.flex.modularity.interfaces.IWidgetShell" //實現接口
	xmlns:widgetmakers="com.widgetmakers.coolwidget.view.components.*" 
	xmlns:widgetworks="com.widgetworks.superwidget.view.components.*"
	verticalAlign="middle" 
	creationComplete="initializeShell()"
	dock="true">
	
	<mx:Metadata>
		[Event('addComponent', org.puremvc.as3.multicore.demos.flex.modularity.view.events.AddComponentEvent)]	
		[Event('removeComponent', org.puremvc.as3.multicore.demos.flex.modularity.view.events.RemoveComponentEvent)]	
	</mx:Metadata>
	
	<mx:Script>
		<![CDATA[
			import org.puremvc.as3.multicore.demos.flex.modularity.view.events.AddComponentEvent;
			import org.puremvc.as3.multicore.demos.flex.modularity.view.events.RemoveComponentEvent;
			
			protected function initializeShell():void
			{
				w1.setWidgetShell( this );//面向接口的編程,實現了方法,並且方法的參數也是一個接口類型的參數
				w2.setWidgetShell( this );
			}
			
			// Add a component to the widget canvas
			public function addComponent( component:DisplayObject ):void
			{
				var event:AddComponentEvent = new AddComponentEvent( component );
				event.component = component;
				this.dispatchEvent( event );
			}
			
			// Remove a component from the widget canvas
			public function removeComponent( component:DisplayObject ):void
			{
				var event:RemoveComponentEvent = new RemoveComponentEvent( component );
				event.component = component;
				this.dispatchEvent( event );
			}
			
			// Set the status message
			public function setStatusMessage( message:String ):void
			{
				statusLine.text = message;	
			}
			
		]]>
	</mx:Script>
	
	<!-- The Widgets -->
	<mx:HBox horizontalAlign="left" verticalAlign="middle" width="50%" height="100%">
		<mx:Text text="Modularity" fontFamily="Verdana" fontSize="22" fontStyle="normal" color="#0559CC"/>
		<widgetmakers:CoolWidget id="w1" />
		<widgetworks:SuperWidget id="w2" />
	</mx:HBox>
	
	<!-- Status Line -->
	<mx:HBox horizontalAlign="right" verticalAlign="middle" width="50%" height="100%">
		<mx:Label id="statusLine" fontWeight="bold" text="PureMVC AS3 MultiCore Demo"/>
	</mx:HBox>
	
</mx:ApplicationControlBar>	


<?xml version="1.0" encoding="utf-8"?>
<!-- 
  Modularity - A PureMVC AS3 MultiCore Flex Demo
  Copyright(c) 2008 Cliff Hall <[email protected]>
  Your reuse is governed by the Creative Commons Attribution 3.0 License
 -->
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" 
	implements="org.puremvc.as3.multicore.demos.flex.modularity.interfaces.IWidget"
	creationComplete="initializeWidget()"
	layout="absolute">

	<mx:Metadata>
		[Event('prod')]	
	</mx:Metadata>
	
	<mx:Script>
		<![CDATA[
			import org.puremvc.as3.multicore.demos.flex.modularity.interfaces.IWidgetShell;
			import com.widgetmakers.coolwidget.ApplicationFacade;
			
			// URI for this widget. Must be unique
			protected static const WIDGET_URI:String = "http://widgetmakers.com/CoolWidget/";
			
			// Constants for the events this component dispatches.  
			public static const PROD:String='prod';
			
			// This Widget's reference to the WidgetShell  
			public var widgetShell:IWidgetShell;
			
			// Set the Widget Shell,實現了接口中的方法
			public function setWidgetShell( shell:IWidgetShell ):void 
			{
				widgetShell=shell;
			}
			
			// The unique key for this widget instance
			public function getWidgetKey():String
			{
				return WIDGET_URI+this.id
			}
			
			// Initialize the widget using the multiton key passed in.
			public function initializeWidget( ):void
			{
				ApplicationFacade.getInstance( this.getWidgetKey() ).startup( this );
			}
			
		]]>
	</mx:Script>
	
	<mx:Button label="CoolWidget" click="dispatchEvent(new Event(PROD,true));"/>
	
</mx:Module>



第一種,實現某個接口,如下mxml類實現了IDataRenderer接口,推薦使用。在Flex中,DataRenderer和IDataRenderer很方面使用。

<?xml version="1.0" encoding="utf-8"?>
<s:VGroup xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx"
          clipAndEnableScrolling="true"
          creationComplete="creationCompleteHandler()"
          implements="mx.core.IDataRenderer">
   <--
     在mxml中繼承mx.core.IDataRenderer,實現IdataRenderer中的方法
    -->
     <!--
       This is used by the InfoSymbolWithStates sample.
    -->

    <fx:Script>
        <![CDATA[
            private var _data:Object;

            [Bindable]
            // implement IDataRenderer。這裏可以學習怎麼樣進行實現繼承的接口
            public function get data():Object
            {
                return _data;
            }

            public function set data(value:Object):void
            {
                _data = value;
            }

            private function creationCompleteHandler():void
            {
                addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
                addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
            }

            private function rollOverHandler(event:MouseEvent):void
            {
                if (currentState == "normal")
                {
                    currentState = "titleState";
                }
            }

            private function rollOutHandler(event:MouseEvent):void
            {
                if (currentState == "titleState")
                {
                    currentState = "normal";
                }
            }

            private function expandButton_clickHandler():void
            {
                currentState = "detailState";
            }

            private function closeButton_clickHandler():void
            {
                currentState = "normal";
            }

            private function effectStartHandler():void
            {
                removeEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
            }

            private function effectEndHandler():void
            {
                addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
            }
        ]]>
    </fx:Script>

    <s:states>
        <s:State name="normal"/>
        <s:State name="titleState"/>
        <s:State name="detailState"/>
    </s:states>

    <s:transitions>
        <s:Transition fromState="*" toState="*">
            <s:Resize duration="250"
                      effectEnd="effectEndHandler()"
                      effectStart="effectStartHandler()"
                      target="{this}"/>
        </s:Transition>
    </s:transitions>

    <s:HGroup id="titleBar"
              width="100%"
              verticalAlign="middle">
        <s:Image width="18" height="18"
                 source="@Embed(source='/assets/skins.swf', symbol='Icon_airport')"/>
        <s:Label id="titleLabel"
                 fontWeight="bold"
                 includeIn="titleState,detailState"
                 rollOut="{Label(event.currentTarget).setStyle('textDecoration', 'none');}"
                 rollOver="{Label(event.currentTarget).setStyle('textDecoration', 'underline');}"
                 text="{data.theName}"/>

        <s:Button id="expandButton"
                  width="18" height="18"
                  click="expandButton_clickHandler()"
                  includeIn="titleState"
                  skinClass="com.esri.ags.samples.skins.InfoExpandButtonSkin"/>
        <s:Button id="closeButton"
                  width="18" height="18"
                  click="closeButton_clickHandler()"
                  includeIn="detailState"
                  skinClass="com.esri.ags.samples.skins.InfoCloseButtonSkin"/>
    </s:HGroup>
    <s:Label id="line1Label"
             includeIn="detailState"
             text="{data.thePlaceName}"/>
</s:VGroup>

第二種,在mxml中實現子類

<?xml version="1.0" encoding="utf-8"?>
<s:DataRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
				xmlns:s="library://ns.adobe.com/flex/spark" implements="mx.core.IFactory"
				xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:supportClasses="com.esri.ags.skins.supportClasses.*"
				creationComplete="datarenderer1_creationCompleteHandler(event)" styleName="InfoSymbolstyle">
	<fx:Declarations>
		<!-- 將非可視元素(例如服務、值對象)放在此處 -->
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import com.depth.viewer.facade.IocAppFacade;
			import com.esri.ags.Graphic;
			import com.esri.ags.layers.FeatureLayer;
			import com.xcsw.flex.facade.ConstFacade;
			
			import flashx.textLayout.formats.Float;
			
			import mx.events.FlexEvent;
			protected function linkbutton2_clickHandler(event:MouseEvent):void
			{
				if(!data)//由渲染器使用者提供
					return;
				var feature:Graphic = data.feature as Graphic;//注意此處的data.feature在什麼地方賦值的???
				var fl:FeatureLayer = feature.graphicsLayer as FeatureLayer;
				//var fId:String = feature.attributes[fl.layerDetails.objectIdField];
				var fId:String = feature.attributes["ID"];
				IocAppFacade.sendNotification(ConstFacade.STAT_MONITOR_DATA,{station:data.station,fId:fId,lId:fl.layerDetails.name});
				//在MonitorManagerWidgetMediator響應消息,彈出統計框
			}
			public function newInstance():*{
				return new MonitorInfoSymbolRenderer();
			}

			protected function linkbutton3_clickHandler(event:MouseEvent):void
			{
				
				if(!data)//由渲染器使用者提供
					return;
				//雨量信息警戒水位參數設置
				IocAppFacade.getInstance().sendNotification(IocAppFacade.LOAD_WIDGET,{id:"TriggerlevelWidget",runingParams:data});
			}
			
			protected function btnExpandButton_clickHandler(event:MouseEvent):void
			{
				if (currentState == "minState")
				{
					currentState = "normal";
				}
			}
			
			protected function btnCloseButton_clickHandler(event:MouseEvent):void
			{
				if (currentState != "minState")
				{
					currentState = "minState";
				} 
			}


			protected function datarenderer1_creationCompleteHandler(event:FlexEvent):void
			{
				for each (var name:String in data.fieldNames){
					switch (name){
						case "RainFall":
						if (data[name] && data[name].Time){
							if (data[name].offset < 0){
								rainExceedWarn.visible = false;
								rainExceedWarn.includeInLayout =false;
							}
						}else{
							RainFall.visible=false;
							RainFall.includeInLayout=false;
						}
						break;
						case "WaterLevel":
						if (data.WaterLevel && data.WaterLevel.Time){
							if (data[name].offset < 0){
								waterExceedWarn.visible = false;
								waterExceedWarn.includeInLayout = false;
							}
						}else{
							WaterLevel.visible=false;
							WaterLevel.includeInLayout=false;
						}
						break;
						case "FloodgateHeight":
						if ( data.FloodgateHeight && data.FloodgateHeight.Time){
							if (data[name].offset < 0){
								floodExceedWarn.visible=false;
								floodExceedWarn.includeInLayout =false;
							}
						}else{
							FloodgateHeight.visible=false;
							FloodgateHeight.includeInLayout=false;
						}
						break;
					}
				}
		   }
		]]>
	</fx:Script>
	
	<s:states>
		<s:State name="normal"/>
		<s:State name="minState"/>
	</s:states>
	
	<fx:Style>
		@namespace s "library://ns.adobe.com/flex/spark";
		@namespace mx "library://ns.adobe.com/flex/mx";
		.InfoExpandButton {
			disabledSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_expandButtonDisabledSkin");
			downSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_expandButtonDownSkin");
			overSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_expandButtonOverSkin");
			upSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_expandButtonUpSkin");
		}
		
		.InfoCloseButton {
			disabledSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_closeButtonDisabledSkin");
			downSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_closeButtonDownSkin");
			overSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_closeButtonOverSkin");
			upSkin: Embed(source="/assets/swf/skins.swf", symbol="Callout_closeButtonUpSkin");
		}
		.InfoSymbolstyle
		{
		   /*  backgroundAlpha: 0.9;  */
			backgroundColor: #FCFCFC;
			borderColor: #6E7C9C;
			borderThickness: 3;
			/* color: #0000ff; */
			/* chrome-color: #0000ff;
			back-color: #0000ff;
			color: #ff0000; */
		}
	</fx:Style>
	
	<s:VGroup width="100%" gap="5"  paddingLeft="3">
		<s:HGroup verticalAlign="middle">
			<s:Label text="站名:{data.station}   " color="#4D4D4D" fontSize="15" fontWeight="bold"/>
			<mx:Button id="btnExpandButton"
					   width="18" height="18"
					   click="btnExpandButton_clickHandler(event)"
					   includeIn="minState"
					   styleName="InfoExpandButton"/>
			<mx:Button id="btnCloseButton" 
					   width="18" height="18"
					   includeIn="normal"
					   click="btnCloseButton_clickHandler(event)" 
					   styleName="InfoCloseButton" toolTip="關閉"/>
		</s:HGroup>
		<s:Line width="100%" height="1" includeIn="normal">   
			<s:stroke>   
				<s:SolidColorStroke color="#C7C7C7" weight="2"/>   
			</s:stroke>   
		</s:Line>
		<s:VGroup id="RainFall" gap="5" includeIn="normal">
			<s:Label id="rainValue" color="#0673E2" fontSize="15" fontWeight="bold"
					 text="雨量: {data.RainFall.RainFall} 毫米" />
			<s:Label id="rainExceedWarn"  color="0xff0000" fontSize="15" fontWeight="bold"
					 text="狀態: 己超過警戒雨量:  {data.RainFall.offset} 毫米" />
		</s:VGroup>
		
		<s:VGroup id="WaterLevel" includeIn="normal" >
			<s:Label id="waterValue" color="#0673E2" fontSize="15" fontWeight="bold"
					 text="水位: {data.WaterLevel.value} 米" />
			<s:Label id="waterExceedWarn"   color="0xff0000" fontSize="15" fontWeight="bold"			 
					 text="狀態: 己超過警戒水位:  {data.WaterLevel.offset} 米" />
		</s:VGroup>

		<s:VGroup id="FloodgateHeight" includeIn="normal">
			<s:Label id="gateValue" color="#0673E2" fontSize="15" fontWeight="bold"
					 text="閘門高: {data.FloodgateHeight.value} 米"/>
			<s:Label id="floodExceedWarn"  color="0xff0000" fontSize="15" fontWeight="bold"				 
					 text="狀態: 己超過警戒閘門高:  {data.FloodgateHeight.offset} 米" />
		</s:VGroup>
		
		<s:HGroup includeIn="normal" width="100%" horizontalAlign="right" gap="3">
			<mx:LinkButton label="詳細信息" color="#0673E2" click="linkbutton2_clickHandler(event)"/>
			<mx:LinkButton label="參數設置" color="#0673E2" click="linkbutton3_clickHandler(event)"/>
		</s:HGroup>
	</s:VGroup>
</s:DataRenderer>

===============================

DataRenderer的使用舉例。

    <!--
         Basic example of an infosymbol containing a vbox with an image and a label.
         The image url is read from the attributes of the graphic.
    -->
    <fx:Declarations>
        <esri:InfoSymbol id="infoSymbol1">
            <esri:infoRenderer>
                <fx:Component>
                    <s:DataRenderer>
                        <s:layout>
                            <s:VerticalLayout/>
                        </s:layout>
                        <mx:Image source="{data.myImageURL}"/>
                        <s:Label text="{data.myTitle}"/>
                    </s:DataRenderer>
                </fx:Component>
            </esri:infoRenderer>
        </esri:InfoSymbol>
    </fx:Declarations>
在DataRenderer的data屬性是數據源,重要,需注意。在這裏,只要給Graphic賦值attributes 即可將屬性信息給data


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章