<mx:Button label="추가" click="addComponent()" />
 <mx:Button label="삭제" click="removeComponent()" />
 
// 추가 버튼을 누르면 VBOX에 버튼을 생성하여 추가한다.
 <mx:VBox id="vb" width="100%" height="100%" />


1. 우선 추가 버튼을 눌렀을 때 버튼이 생성되게 해보자.

   private var cnt:int;
   private function addComponent():void{
    if(vb.getChildren().length < 5){
     cnt++;
     
     /**
      * 사용자가 추가 버튼을 클릭하면 실행되는 함수.
      * 버튼 객체를 하나 생성하여 속성값을 지정한 다음
      * 이벤트 리스너를 등록하여 준다.
      * vBox에 버튼 객체를 추가한다.
      *
      */
     var btn:Button = new Button();
     btn.label = "동적버튼" + cnt;
     
     /**
      *
      *  flex 이벤트란..? 플렉스 컴포넌트에서 호출되는 이벤트..??
      *  ADD이벤트와 REMOVE이벤트를 등록하여 버튼이 추가되거나 삭제될때
      *  메시지를 보여주기 위해 eventHandler라는 함수를 하나 만든다.
     */
     btn.addEventListener(MouseEvent.CLICK, onClick);
     
     
     btn.addEventListener(FlexEvent.ADD, eventHandler);
     btn.addEventListener(FlexEvent.REMOVE, eventHandler);
     
    // 버튼 생성
     vb.addChild(btn);    
    }else{
     mx.controls.Alert.show("5개 이상은 만드실 수 없습니다!!!!!!!");
    }
   
   }


// 컴포넌트에서 실행된(?) 이벤트를 받아와서 어떤 타입의 이벤트인지 Console창에 출력.
   private function eventHandler(e:FlexEvent):void{
    var btn:Button = e.currentTarget as Button;
    trace(e.type + ":" + btn.label);
   }

private function onClick(e:MouseEvent):void{
    // as 키워드를 이용하여 형변환을 할 수 있다.
    // 아래 소스는 e.currentTarget이라는 객체를 DisplayObject형으로 형변환을 한 것이다.
    // 사용자가 클릭한 currentTarget을 삭제 하는 소스이다.
    var btn:Button = e.currentTarget as Button;
   
    // 이벤트 리스너가 포함된 객체를 remove 하였기 때문에 이벤트 리스너가 더 이상 존재할 필요가 없으므로
    // 해당 이벤트 리스너를 삭제 해 주는 작업이 필요하다
    // 아래 코드는 그런 작업을 해주는 녀석이다-0-
   
    btn.removeEventListener(MouseEvent.CLICK, onClick);
   
    vb.removeChild(e.currentTarget as DisplayObject);
   }
   
   // 부모 노드를 죽일때 자식노드를 모두 없애고 죽이는게 좋다
   // removeAllChildren(); 을 이용하면 된다.
   private function removeComponent():void{
   
    if(vb.getChildren().length <= 0){
     mx.controls.Alert.show("지울 버튼이 없어요!!!!!!");
    }else{
     vb.removeAllChildren();
    }
   }
Posted by NemoLuNa
l

Component 만드는법

Flex 3.0 2009. 8. 18. 18:06
우선 컴포넌트 mxml을 만든다.



컴포넌트를 만든 다음에.

<mx:VBox horizontalAlign="center">  
   <mx:Label id="lb2ndDayCondition" text="{ '('+ forecastCondition[1].day_of_week.data +')'} />
   <mx:Image source="http://www.google.co.kr{forecastCondition[1].icon.data}" />
   <mx:Label text="{forecastCondition[1].low.data + '/' + forecastCondition[1].high.data}" />  
</mx:VBox>

위와 같이 각각의 날짜별로 만들었던 날씨 정보 출력을 반복을 피하기 위해 컴포넌트로 만들기로 한다.



위에서 만든 컴포넌트 mxml파일에
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" horizontalAlign="center">
 <mx:Script>
  <![CDATA[
   [Bindable] public var item:Object;
   
  ]]>
 </mx:Script>
 <mx:Label text="{ '('+ item.day_of_week.data +')'} "/>
 <mx:Image source="http://www.google.co.kr{item.icon.data}" />
 <mx:Label text="{item.low.data + '/' + item.high.data}" />
</mx:VBox>

이런 코드를 작성하여 item이라는 변수로 접근이 가능하게 한다.

만들어진 컴포넌트를 아래와 같이 컴포넌트 사이에 추가한다.


그럼 기존 소스에
<ns1:WeatherInfo item="{forecastCondition[0]}" /> 요런 소스가 생긴다.
WeatherInfo는 파일명이고 item은 컴포넌트에 미리 작성했던 변수명이다.
거기에 google API 에서 return한 forecastCondition 배열에 접근하여 컴포넌트를 동적으로 생성할 수 있다.

같은 방법으로 4개의 배열을

<ns1:WeatherInfo item="{forecastCondition[1]}" />
  <ns1:WeatherInfo item="{forecastCondition[2]}" />
  <ns1:WeatherInfo item="{forecastCondition[3]}" />

요렇게 생성하면 총 4개의 컴포넌트가 동적으로 생성이 된다.

기존 클릭 이벤트 코드도 조금 변경하여

<mx:Button label="날씨보기" click="requestHandler()"   labelPlacement="bottom"/> 에서

<mx:Button label="서울" click="requestHandler('seoul')"   labelPlacement="bottom"/>
위와같이 변경하여 날씨를 지역별로 가져오게끔 button을 생성한다.



이와같이 누르면 지역명에 따라 해당 지역의 정보가 return 되는 것을 확인 할 수 있다.

Posted by NemoLuNa
l

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
 <mx:Script>
  <![CDATA[
   import mx.binding.utils.BindingUtils;
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   import mx.rpc.events.ResultEvent;
   

   // 서버에 요청을 하는 핸들러
   private function requestHandler():void
   {
    // api로 전송할 parameter를 정의한다.
    var params:Object = new Object();

    // seoul의 날씨를 얻기 위한 parameter 정의
    params.weather = "seoul";
    srv.send(params);
   }

   [Bindable] private var currentCondition:Object;
   [Bindable] private var forecastCondition:ArrayCollection;
   
   // 서버의 응답을 처리하는 핸들러
   private function resultHandler(event:ResultEvent):void
   {
    // 현재 날씨 정
    
    currentCondition = event.result.xml_api_reply.weather.current_conditions;
    
    // 첫째날 날씨 정보
    forecastCondition = event.result.xml_api_reply.weather.forecast_conditions;
        
// 바인딩을 했기 때문에 아래 정보는 주석 처리 한다.
//    lb1stDayCondition.text = forecastCondition[0].day_of_week.data;
//    lb1stDayCondition.text += forecastCondition[0].low.data;
//    lb1stDayCondition.text += forecastCondition[0].high.data;
//    lb1stDayCondition.text += forecastCondition[0].condition;
   }
  ]]>
 </mx:Script>
 <mx:Button label="서버요청" click="requestHandler()"  />
 
  // google API 에 접속하기 위한 주소를 정의
  // url 로의 요청을 HTTPService를 이용해 접근하고 그 결과를 받는 정보를 result에 받는다. 
  // 결과는 xml로 return 된다. 직접 브라우저에 주소를 입력해 보면 xml형태의 결과물을 확인할 수 있다.
  // 마치 ajax의 callback 함수와 같은 역할을 한다고 생각된다.
 <mx:HTTPService id="srv" url="http://www.google.co.kr/ig/api"
  result="resultHandler(event)" />  
  
 <mx:Panel title="날씨 정보"  fontSize="20"  horizontalAlign="center" textAlign="center">
  <mx:Label text="현재날씨 : {currentCondition.condition.data + '( ' +
  currentCondition.temp_c.data+ ' ) '
  }" />
 
 <mx:HBox horizontalAlign="center" verticalAlign="middle">
  <mx:VBox horizontalAlign="center">   
   <mx:Label id="lb1stDayCondition" text="{ '('+ forecastCondition[0].day_of_week.data +')'} "/>
   // 아래와 같이 이미지의 경로를 배열로 접근하여 해당 날씨 정보의 이미지를 가져올 수도 있다.
   <mx:Image source="http://www.google.co.kr{forecastCondition[0].icon.data}" />
   <mx:Label text="{forecastCondition[0].low.data + '/' + forecastCondition[0].high.data}" />   
  </mx:VBox>
  
  <mx:VBox horizontalAlign="center">   
   <mx:Label id="lb2ndDayCondition" text="{ '('+ forecastCondition[1].day_of_week.data +')'} "/>
   <mx:Image source="http://www.google.co.kr{forecastCondition[1].icon.data}" />
   <mx:Label text="{forecastCondition[1].low.data + '/' + forecastCondition[1].high.data}" />   
  </mx:VBox>
  
  <mx:VBox horizontalAlign="center">   
   <mx:Label id="lb3rdDayCondition" text="{ '('+ forecastCondition[2].day_of_week.data +')'} "/>
   <mx:Image source="http://www.google.co.kr{forecastCondition[2].icon.data}" />
   <mx:Label text="{forecastCondition[2].low.data + '/' + forecastCondition[2].high.data}" />   
  </mx:VBox>
  
  <mx:VBox horizontalAlign="center">   
   <mx:Label id="lb4thDayCondition" text="{ '('+ forecastCondition[3].day_of_week.data +')'} "/>
   <mx:Image source="http://www.google.co.kr{forecastCondition[3].icon.data}" />
   <mx:Label text="{forecastCondition[3].low.data + '/' + forecastCondition[3].high.data}" />   
  </mx:VBox>
 </mx:HBox> 
  
 </mx:Panel>
 
 
</mx:Application>



실행 화면




바인딩 : text={parent.childe.data} 같이 xml에 정의된 값을 바인딩을 통해 가져올 수 있다.
            EL태그와 비슷한 양식을 보인다.





 

Posted by NemoLuNa
l