/*

원본 URL :http://livedocs.macromedia.com/flex/2/docs/00000970.html

자원을 내장시키는 방법은 3가지가 있다는 것을 기억하자..


 

*/

Syntax for embedding assets

The syntax that you use for embedding assets depends on where in your application you embed the asset. Flex supports the following syntaxes:

  • The [Embed(parameter1, paramater2, ...)] metadata tag

    You use this syntax to embed an asset in an ActionScript file, or within an <mx:Script> block in an MXML file. For more information, see Using the [Embed] metadata tag.

  • The @Embed(parameter1, paramater2, ...) directive

    You use this syntax in an MXML tag definition to embed an asset. For more information, see Using the @Embed() directive in MXML.

  • The Embed(parameter1, paramater2, ...) directive

    You use this syntax within an <mx:Style> block in an MXML file to embed an asset. For more information, see Embedding assets in style sheets.

All three varieties of the embed syntax let you access the same assets; the only difference is where you use them in your application.

Subtopics

Escaping the @ character
Embed parameters
About the source parameter
About the MIME type
Using the [Embed] metadata tag
Using the @Embed() directive in MXML
Embedding assets in style sheets

Escaping the @ character

You can use the slash character ( \ ) to escape the at sign character (@) when you want to use a literal @ character. For example, the string "\@Embed(foo)" means the literal string "@Embed(foo)"). You use two slash characters (\\) to escape a single backslash character. For example, use the character string "\\@" to specify the literal strings "\@".

Embed parameters

Each form of the embed syntax takes one or more optional parameters. The exact syntax that you use to embed assets depends on where they are embedded. Some of these parameters are available regardless of what type of asset you are embedding, and others are specific to a particular type of media. For example, you can use the source and mimeType parameters with any type of media, but the scaleGridRight parameter applies only to images.

The following table describes the parameters available for any type of embedded asset. For more information, see About the source parameter and About the MIME type.

Parameter

Description

source

Specifies the name and path of the asset to embed; either an absolute path or a path relative to the file containing the embed statement. The embedded asset must be a locally stored asset. Therefore, you cannot specify a URL for an asset to embed.

For more information on setting the path, see About setting the path to the embedded asset.

mimeType

Specifies the mime type of the asset.

The following table describes the parameters specific for images and Sprite objects. For more information, see Using scale-9 formatting with embedded images.

Parameter

Description

scaleGridTop

Specifies the distance, in pixels, of the upper dividing line from the top of the image in a scale-9 formatting system. The distance is relative to the original, unscaled size of the image.

scaleGridBottom

Specifies the distance in pixels of the lower dividing line from the top of the image in a scale-9 formatting system. The distance is relative to the original, unscaled size of the image.

scaleGridLeft

Specifies the distance in pixels of the left dividing line from the left side of the image in a scale-9 formatting system. The distance is relative to the original, unscaled size of the image.

scaleGridRight

Specifies the distance in pixels of the right dividing line from the left side of the image in a scale-9 formatting system. The distance is relative to the original, unscaled size of the image.

The following table describes the parameter that is specific to SWF files. For more information, see Embedding SWF files.

Parameter

Description

symbol

Specifies the symbol in a SWF file to embed, for use with Adobe's Macromedia Flash Player 8 and earlier.

About the source parameter

In almost all cases, you must specify the source parameter or nothing is embedded.

The source parameter is the default parameter of the [Embed] metadata tag; therefore, if you are not specifying any other parameters, you can just supply its value without explicitly including the parameter name or assigning it the desired value, as the following example shows:

<mx:Style>    
    .myCustomButton {
        overIcon:Embed("overIconImage.gif");
        upIcon:Embed(source="upIconImage.gif");
        downIcon:Embed(source="downIconImage.gif");
    }
</mx:Style>

About setting the path to the embedded asset

You can specify a fully qualified path to the image or a URL, as the following examples show:

<mx:Button label="Icon Button" 
    icon="@Embed(source='c:/myapp/assets/logo.gif')"/>
<mx:Button label="Icon Button"
    icon="@Embed(source='http://host.com/myapp/assets/logo.gif')"/>

NOTE


Do not use the backslash character, \, as a separator in the path.

If the path does not start with a slash character, Flex first searches for the file relative to the file containing the [Embed] metadata tag. For example, the MXML file testEmbed.mxml file includes the following code:

<mx:Button label="Icon Button" icon="@Embed(source='assets/logo.gif')"/> 

In this example, Flex searches the subdirectory named assets in the directory containing the testEmbed.mxml file. If the image is not found, Flex then searches for the image in the SWC files associated with the application.

If the path starts with a slash character, Flex first searches the directory of the MXML file for the asset, and then it searches the source path. You specify the source path to the Flex compiler by using the source-path compiler option. For example, you set the source-path option as the following code shows:

-source-path=a1,a2,a3 

The MXML file a1/testEmbed.mxml then uses the following code:

<mx:Button label="Icon Button" icon="@Embed(source='/assets/logo.gif')"/> 

Flex first searches for the file in a1/assets, then a2/assets, and then a3/assets. If the image is not found, Flex searches for the image in the SWC files associated with the application.

If the MXML file is in the a2 directory, as in a2/testEmbed.mxml, Flex first searches the a2 directory, and then the directories specified by the source-path option.

About the MIME type

You can optionally specify a MIME type for the imported asset by using the mimeType parameter. If you do not specify a mimeType parameter, Flex makes a best guess about the type of the imported file based on the file extension. If you do specify it, the mimeType parameter overrides the default guess of the asset type.

Flex supports the following MIME types:

  • application/octet-stream
  • application/x-font
  • application/x-font-truetype
  • application/x-shockwave-flash
  • audio/mpeg
  • image/gif
  • image/jpeg
  • image/png
  • image/svg
  • image/svg-xml

Using the [Embed] metadata tag

You can use the [Embed] metadata tag to import JPEG, GIF, PNG, SVG, SWF, TTF, and MP3 files.

You must use the [Embed] metadata tag before a variable definition, where the variable is of type Class. The following example loads an image file, assigns it to the imgCls variable, and then uses that variable to set the value of the source property of an Image control:


[Embed] 메타태그를 사용하기 위해서는 반드시 Class변수 앞에서 사용해야 된다.

그러면 Class 변수에 Embed 자원이 할당된다.

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" width="100" height="80" borderStyle="solid">
    <mx:Script>
        <![CDATA[
            [Embed(source="logo.gif")]
            [Bindable]
            public var imgCls:Class;
        ]]>
    </mx:Script>
    <mx:Image source="{imgCls}"/>
</mx:Application>

Notice that Flex uses data binding to tie the imgCls variable to the source property. If you omit the [Bindable] metadata tag preceding the imgCls variable definition, Flex can only perform the data binding operation once, at application startup. When you include the [Bindable] metadata tag, Flex recognizes any changes to the imgCls variable, and updates any components that use that variable when a change to it occurs.

Generally, this method of embedding assets provides more flexibility than other methods because you can import an asset once, and then use it in multiple places in your application, and because you can update the asset and have the data binding mechanism propagate that update throughout your application.

Using the @Embed() directive in MXML

Many Flex components, such as Button and TabNavigator, take an icon property or other property that lets you specify an image to the control. You can embed the image asset by specifying the property value by using the @Embed() directive in MXML. You can use any supported graphic file with the @Embed() directive, including SWF files and assets inside SWF files.

You can use the @Embed() directive to set an MXML tag property, or to set a property value by using a child tag. The @Embed() directive returns a value of type Class or String. If the component's property is of type String, the @Embed() directive returns a String. If the component's property is of type Class, the @Embed() directive returns a Class. Using the @Embed() directive with a property that requires value of any other data type results in an error.

The following example creates a Button control, and sets its icon property by using the @Embed() directive:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Button label="Icon Button" id="b2" icon="@Embed(source='logo.gif')"/>
</mx:Application>

Embedding assets in style sheets

Many style properties of Flex components support imported assets. Most frequently, you use these style properties to set the skins for a component. Skinning is the process of changing the appearance of a component by modifying or replacing its visual elements. These elements can be made up of images, SWF files, or class files that contain drawing API methods.

For more information on skinning, and embedding asset using style sheets, see Using Skins.


Flex 2



sparky1962 said on Aug 26, 2006 at 2:04 PM :
The sentence "The embedded asset must be a locally stored asset" is ambiguous. Local to what? the compiler, the running swf?
mpeterson said on Aug 30, 2006 at 9:29 AM :
Locally stored means that the asset must be local to the location of the compiler.

- Mike Peterson
Flex doc team

Posted by 나비:D
:

출처 : http://islet4you.tistory.com/27

포토뷰어라는 예제에 있는 것을 추출해 왔습니다
항상 모듈화라는 숙제를 가지고 보니 이런 좋은 예제가 아닌가 합니다.

package samples.photoviewer
{
 import flash.events.*;

 import mx.collections.ArrayCollection;
 import mx.collections.IViewCursor;
 import mx.core.Application;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.http.HTTPService;
 import mx.utils.ArrayUtil;

 public class PhotoService
 {
  private var service:HTTPService;

        [Bindable]
  public var galleries:ArrayCollection;

  public function PhotoService(url:String)
  {
   service = new HTTPService();
   service.url = url;
   service.addEventListener(ResultEvent.RESULT, resultHandler);
   service.send();
  } // httpservice를 이용한 호출

  private function resultHandler(event:ResultEvent):void
  {
      var result:ArrayCollection = event.result.galleries.gallery is ArrayCollection
          ? event.result.galleries.gallery as ArrayCollection
          : new ArrayCollection(ArrayUtil.toArray(event.result.galleries.gallery));
      var temp:ArrayCollection = new ArrayCollection();
      var cursor:IViewCursor = result.createCursor();
      while (!cursor.afterLast)
      {
          temp.addItem(new Gallery(cursor.current));
          cursor.moveNext();
      }
      galleries = temp;
  }
 }
} // 결과를 arraycollection으로 적용

이 actionscript를 적용해서 구현을 한 예제를 보면
<?xml version="1.0" encoding="utf-8"?>
<!--
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2003-2006 Adobe Macromedia Software LLC and its licensors.
// All Rights Reserved.
// The following is Sample Code and is subject to all restrictions on such code
// as contained in the End User License Agreement accompanying this product.
// If you have received this file from a source other than Adobe,
// then your use, modification, or distribution of it requires
// the prior written permission of Adobe.
//
////////////////////////////////////////////////////////////////////////////////
-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
 paddingBottom="0" paddingTop="0"
 paddingLeft="0" paddingRight="0"
    layout="vertical"
    pageTitle="Photo Viewer"
 creationComplete="init()">

 <mx:Script>
  <![CDATA[
   import mx.collections.ArrayCollection;
   import mx.rpc.events.*;
   
   import samples.photoviewer.Gallery;
   import samples.photoviewer.PhotoService;  //위의 소스를 import
   
   [Bindable]
   private var gallery:Gallery;
   
   [Bindable]
   private var service:PhotoService;
   
   private function init():void
   {
    service = new PhotoService("data/galleries.xml"); //httpservice를 호출
   }
  ]]>
 </mx:Script>
 
 <mx:Style source="main.css" />
 
 <mx:Binding source="service.galleries.getItemAt(0)" destination="gallery" />
 
 <mx:ViewStack id="views" width="100%" height="100%">
 
  <ThumbnailView id="thumbnailView" gallery="{gallery}"
   slideshowView="views.selectedChild = slideshowView"
   carouselView="views.selectedChild = carouselView"/>
 
  <CarouselView id="carouselView" gallery="{gallery}"
   slideshowView="views.selectedChild = slideshowView"
   thumbnailView="views.selectedChild = thumbnailView"/>
 
  <SlideShowView id="slideshowView" gallery="{gallery}"
   thumbnailView="views.selectedChild = thumbnailView"
   carouselView="views.selectedChild = carouselView"/>
   
 </mx:ViewStack>
   
</mx:Application>

Viewstack을 가지고 처리를 해주는 것이다.
아울러 여기서 보여주는 콤포넌트에 대해서는 다음시간에 따로 설명을 하도록 하겠습니다.
조금씩 업무별로 가는 프레임웍에 대한 레퍼런스가 만들어지면 올리도록 하겠슴당 ㅋ

Posted by 나비:D
:

출처 : http://blog.naver.com/mash9/20046392694

Flex를 어느 정도 하신 분들이라면 HTTPService 사용과 데이터 바인딩(binding)에 익숙해지셨겠지만, 제가 만난 분들 중에도

종종 실수를 하시는 분들이 계십니다. 그 분들이 누군지 밝히고자 하는건 아니고..  HTTPService 에서 데이터를 읽어와

DataGrid까지 바인딩(binding)시키는 부분에서 실수하기 쉬운 부분에 대해 설명하려 합니다.


먼저 아래처럼 웹서비스(web service)를 선언해줍니다.

<mx:HTTPService id="service" resultFormat="e4x" result="resultHandler(event)" />

여기서 result="resultHandler(event)" 는 이벤트 내부적으로 event 라는 이벤트 인스턴스(instance)가 생성되는데 이것을

콜백함수(callback function)에 넣겠다는 뜻입니다. resultFormat 은 대부분 웹서비스는 XML 기반으로 데이터를 연동시킬 목적으로

구현할것이라면 e4x 라고 선언해주어야 나중에 뒷탈(?)이 없습니다. 종종 원치않은 바이너리가 들어가는 경우가 생깁니다.

import mx.collections.XMLListCollection;

import mx.rpc.events.ResultEvent;


[Bindable] private var dataset:XMLListCollection = new XMLListCollection();
   

private function resultHandler(e:ResultEvent):void
{
    dataset = new XMLListCollection(new XMLList(e.result.node));
}



많은 분들이 이 부분에서 실수를 하는데 '예제로 배우는 Adobe 플렉스 2' 에 (저를 포함한 많은 분들이 이 책으로 시작하셨죠)

DataGrid 에 데이터를 바인딩 시키기는 부분이 나오는데 책에서는 HTTPService.lastResult 를 바로 DataGrid에 바인딩 시킵니다.


HTTPService.lastResult 을 바로 DataGrid에 바인딩 시켰을경우 데이터가 1개의 노드가 존재할때 문제가 null 객체에 접근 에러가

뜨고 말지요. XML이 한개 였을경우 데이터가 어레이(array) 형태가 아닌 오브젝트(object) 형태라고 인식하기 때문입니다. 때문에

번거롭지만 위 처럼 XMLList를 통해 어레이(array) 형태란것을 인식시키고 이것을 바인딩된 변수 dataset에 넣어주는것입니다.


저 함수에서 DataGrid.dataProvider 에 넣어줄수도 있지만 그렇게 했을경우 정상적인 바인딩이 이루어지지 않을뿐더러 버그를

유발할수도 있습니다. 외부로 들어온 데이터는 저렇게 모두 바인딩 변수에 넣어주시는 편이 좋습니다.


바인딩을 설명하기위해 dataProvider 에 ArrayCollection 을 넣어서 설명하는 부분 때문에 ArrayCollection 에 담는 분도

계시더구요. 전에도 잠깐 언급했듯이 HTTPService 는 기본 XMLListCollection 을 사용하는것이 정석입니다.

XMLListCollection를 사용해야지만 또 나중에 필터링에 대해 깊이 들어갈때 도움이 됩니다.

 


<mx:DataGrid dataProvider="{maAC}" /> 



마무리는 다음과 같이 선언해주면 끝입니다. 간단하지만 의외로 실수하기 쉬운 부분이죠.


Posted by 나비:D
:

Cairngorm Framework

1.
Cairngorm Framework 정의
cairngorm은 사전적인 의미로는 연수정이란 뜻입니다.
발음을 하면 컨검? 주위에서는 그냥 캔곰이라고 부르더군요. 이하 강좌는 캔곰이라는 용어를 사용하여 진행하도록 하겠습니다. 알아서 이해해 주시면 감사…^^
캔곰 프레임워크는 Flex를 위한 작은 규모의 프레임워크입니다. 기존에 사용하던 프레임워크와는 차이가 많이 나죠. 저도 처음엔 뭐 이런게 프레임워크인가 생각했던 적이 있습니다. 하지만 그래도 몇가지 사항에서 중요합니다.
캔곰은 Flex Application을 사용하여 Enterprise Software를 개발하기 위한 디자인패턴들로 구현되어 있습니다. 또한 캔곰 사용의 장점은 동일한 패턴으로 서비스를 정의하고 관리함으로서 간결한 코드를 작성할 수 있습니다. 단점은 파일 개수가 많아 진다는 것이 아닐까 싶네요.

2.
캔곰 프레임워크 설치하기
캔곰 프레임워크는 Flex에서 사용하는 라이브러리 포맷인 swc 형태로 배포됩니다. 또한 소스코드까지 포함되어 있으므로 좀 더 구체적인 내용을 알고 싶은 분들은 소스코드를 분석하셔도 됩니다.

2.1
캔곰 프레임웍2.1을 다운로드 합니다.
URL : http://labs.adobe.com/wiki/index.php/Cairngorm

<그림 1>

2.2
다운로드 받은 파일의 압축을 풉니다.
압축을 풀면 bin 폴더에서 Cairngorm.swc 파일을 확인할 수 있습니다.

<그림 2>


2.3
프로젝트의 library path로 이동한 다음 ‘Add SWC’버튼을 클릭 한 후 bin폴더에 있는 Cairngorm.swc파일을 추가합니다.

<그림 3>


3. Cairngorm Framework 구조
3.1
캔곰은 MVC구조 형태로 패턴화 되어 있습니다. 프리젠테이션과 비즈니스 로직을 분리 할 수 있는 형태의 템플릿을 제공합니다.
3.2 캔곰 architecture

<그림 4>

- View : End User의 View화면을 지칭합니다. View는 사용자의 이벤트를 받아 CairngormEventDispatcher를 사용하여 Controller에 등록되어 있는 커맨드를 호출하는 역할을 담당합니다.
- Model : Controller와 View를 중계하는 역할을 담당합니다. 최종적으로 처리된 결과를 ModelLocator를 통해 View에 전달됩니다.
-
Controller : Command를 실행하여 서비스를 요청하는 역할을 담당합니다. 처리된 결과는 ModelLocator를 통해 View에 전달됩니다.

3.3
캔곰 패키지 구조
각각의 기능 그룹별로 패키지 폴더를 구성합니다. 뭐 반드시 지켜야 하는 구조는 아니지만 되도록이면 동일한 형태의 Naming Rule을 사용하기를 권장합니다.

- Business : Delegate 클래스를 모아 놓은 폴더입니다. 그리고 데이터 서비스를 정의하는 Services.mxml도 이곳이 포함됩니다.
-
Commands : Delegate를 호출하고 리턴된 결과 값을 View에 전달하는 역할을 담당하는 command 클래스를 모아 놓은 폴더입니다. Command 클래스는 캔곰에서 제공하는 Command,Responder 인터페이스를 상속받아 구현합니다.
-
Control : command를 관리하는 controller 클래스를 모아 놓은 폴더입니다. CairngormEventDispatcher를 통해 Control에 등록된 Command를 실행합니다. Controller 클래스는 캔곰에서 제공하는 FrontController를 상속받아 구현합니다.
-
Model : View들을 관리하는 역할을 담당하는 ModelLocator를 모아 놓은 폴더입니다. ModelLocator 클래스는 캔곰에서 제공하는 ModelLocator클래스를 상속받아 구현합니다(개인적으로는 사용 안 함).
-
Vo : RemoteObject서비스를 사용할때만 해당되는 클래스일 듯 합니다. Value Object의 약어로서 View에서 표시될 속성들을 모아놓은 클래스입니다. Vo는 ValueObject를 상속받아 구현합니다. Vo사용의 장점은 타입 체크를 통해 좀 더 명확하게 무슨 정보 인지를 판단 할 수 있습니다.

4.
캔곰 사용하기
예제로 게시판 리스트와 게시글 읽기 기능 두 가지를 가지고 캔곰을 적용해 서비스 데이터를 연동해 보도록 하겠습니다. 단 RemoteObject를 정의하여 자바 클래스를 호출하는 부분은 “RemoteObject 사용하기” 강좌에서 계속 진행 할 예정입니다.

4.1 프로젝트의 패키지를 아래와 같이 business,command,control,event,model,view.vo를 정의합니다.

<그림 5>

4.2
이벤트 정의

-
ViewEvent.as : CairngormEvent를 상속받은 클래스로서 리턴 페이지 객체를 저장하기 위한 view 속성을 포함하고 있습니다. 추후 커맨드를 호출하기 위해서는 반드시 ViewEvent를 생성하여 사용해야 합니다

package sample.event
{
        import com.adobe.cairngorm.control.CairngormEvent;
        import mx.core.UIComponent;
        public class ViewEvent extends CairngormEvent
        {
                //view객체를 저장하기 위한 속성
               public var view:UIComponent;
               public function ViewEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
               {
                       super(type, bubbles, cancelable);
               }
         }
}

- ServiceResultEvent.as : 서비스 결과를 전달하기 위한 이벤트 입니다. 결과 값을 저장하기 위한 result속성을 포함하고 있습니다.
package sample.event
{
 import flash.events.Event;
 public class ServiceResultEvent extends Event
 {
  public var result:*;
                //이벤트 이름
  public static const EVENT_SERVICE_RESULT:String = "serviceResult";
 
  public function ServiceResultEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
  {
   super(type, bubbles, cancelable);
  }
 }
}

4.3 Delegate 정의
-
BBSServiceDelegate.as : ServiceLocator를 사용하여 RemoteObject 서비스를 호출하고 리턴된 결과값을 command에 전달합니다. 서비스 호출은 AsyncToken을 사용하여 비동기 형태로 호출됩니다. RemoteObject를 이용한 코드는 다음 강좌에 진행하기 때문에 임시로 주석처리 하였습니다.
package sample.business
{
 import sample.event.ViewEvent;
 import com.adobe.cairngorm.business.Responder;
 import com.adobe.cairngorm.business.ServiceLocator;
 import mx.rpc.AsyncToken;
 import mx.collections.ArrayCollection;
 import flash.utils.setTimeout;
 import sample.vo.BBSData;
 
 public class BBSServiceDelegate
 {
  private var responder:Responder;
  private var serivce:Object;
 
  public function BBSServiceDelegate(responder:Responder)
  {
   //정의된 RemoteObject의 id값으로 서비스 객체를 얻어 옵니다.
   //this.serivce = ServiceLocator.getInstance().getService("BBSService");
   this.responder = responder;
  }
  public function getBBSList(event:ViewEvent):void
  {
   var dataArr:ArrayCollection = new ArrayCollection();
   var obj:BBSData = new BBSData();
   obj.num = 1;
   obj.subject = "aaaa";
   obj.writer = "lee";
           
   dataArr.addItem(obj);
           
   var resultObj:Object = new Object();
   resultObj.result = dataArr;
           
   setTimeout( responder.onResult, 100, resultObj );
   //var token:AsyncToken = service.getBBSList();
   //token.resultHandler = responder.onResult;
   //token.faultHandler = responder.onFault;
  }
  public function getBBSRead(event:ViewEvent):void
  {
   var obj:BBSData = new BBSData();
   obj.num = 1;
   obj.subject = "aaaa";
   obj.writer = "lee";
           
   var resultObj:Object = new Object();
   resultObj.result = obj;
           
   setTimeout( responder.onResult, 100, resultObj );
   //var token:AsyncToken = service.getBBSRead(event.data.rowNum);
   //token.resultHandler = responder.onResult;
   //token.faultHandler = responder.onFault;
  }
 }
}

4.4 Command 정의

-
BBSListCommand.as : 게시판 리스트 command입니다. BBSServiceDelegate function을 호출한후 결과 값을 view 속성을 사용하여 ServiceResultEvent 이벤트를 발생시킵니다.
package sample.command
{
 import com.adobe.cairngorm.control.CairngormEvent;
 import com.adobe.cairngorm.commands.Command;
 import com.adobe.cairngorm.business.Responder;
 import sample.event.ViewEvent;
 import sample.event.ServiceResultEvent;
 import mx.core.UIComponent;
 import sample.business.BBSServiceDelegate;
 import mx.collections.ArrayCollection;
 import sample.vo.BBSData;
 public class BBSListCommand implements Command, Responder
 {
  private var view:UIComponent;
  public function execute(event:CairngormEvent):void
  {
   var viewEvt:ViewEvent = ViewEvent(event);
   //호출한 View. 결과를 리턴할때 사용함.
   view = viewEvt.view;
  
    //Delegate 클래스 호출
    var delegate : BBSServiceDelegate = new BBSServiceDelegate( this );  
    delegate.getBBSList(viewEvt);
  }
 
  public function onResult(event:*=null):void
  {
   var res:ServiceResultEvent = new ServiceResultEvent(ServiceResultEvent.EVENT_SERVICE_RESULT);
   res.result = event.result;
   //호출한 view의 "serviceResult" 이벤트를 발생시킴
   view.dispatchEvent(res);
  }
 
  public function onFault(event:*=null):void
  {
  }
 
 }
}

4.5 Controller 정의

-
BBSController.as : 게시판 관련 이벤트를 관리하는 역할을 담당합니다. 등록된 이벤트 들은 CairngormEventDispatcher를 사용하여 실행됩니다.

package sample.control
{
 import com.adobe.cairngorm.control.FrontController;
 import sample.command.BBSListCommand;
 import sample.command.BBSReadCommand;

 public class BBSController extends FrontController
 {
  public static const EVENT_BBS_LIST : String = "bbs_list";
  public static const EVENT_BBS_READ : String = "bbs_read";
  public function BBSController()
  {
   addCommand( BBSController.EVENT_BBS_LIST, BBSListCommand );
   addCommand( BBSController.EVENT_BBS_READ, BBSReadCommand);
  }
 
 }
}


4.6 Vo 정의

-
BBSData.as : 게시판에서 사용되는 데이터 속성 값을 정의 한 클래스입니다.
package sample.vo
{
 import com.adobe.cairngorm.vo.ValueObject;
 [Bindable]
 public class BBSData implements ValueObject
 {
  public var num:int; //번호
  public var subject:String; //제목
  public var content:String; //내용
  public var writer:String; //작성자
 }
}

4.7 View 정의

-
이제부터 모든 사용자 View들에 대한 컴포넌트들은 view 패키지 아래에서 정의한 다음 네임스페이스 정의를 통해 접근하는 형태로 사용합니다. 그리고 서비스를 호출하는 페이지들은 아래와 같이 이벤트를 정의하고 initialize 시점에 이벤트를 등록하여 처리하는 형태로 작성됩니다.

  *사용자 이벤트 정의

<그림 6>

  *
initialize 이벤트

<그림 7>

  *
serviceResult” 이벤트 처리

<그림 8>

-
BBSListView.mxml : 게시판 리스트를 구현한 MXML 컴포넌트 입니다. CairngormEventDispatcher를 사용하여 command를 호출하고 “serviceResult”를 등록하여 결과 리턴 이벤트를 전달받아 DataGrid에 Binding을 합니다.
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" initialize="initView()">
 <mx:Metadata>
  [event(type="serviceResult","sample.event.ServiceResultEvent")]
 </mx:Metadata>
 <mx:Script>
  <![CDATA[
   import mx.managers.PopUpManager;
   import mx.collections.ArrayCollection;
   import sample.event.ServiceResultEvent;
   import sample.event.ViewEvent;
   import com.adobe.cairngorm.control.CairngormEventDispatcher;
   import sample.control.BBSController;
   import com.adobe.cairngorm.control.CairngormEvent;
   
   [Bindable]
   private var listdata:ArrayCollection;
   private function initView():void
   {
    this.addEventListener("serviceResult",resultEvt);
   
    //BBS 리스트를 요청하는 이벤트를 생성합니다.
    var event:ViewEvent = new ViewEvent(BBSController.EVENT_BBS_LIST);
    //결과값을 받기위해 현재 페이지 객체를 파라미터로 전달 합니다.
    event.view = this;
    //Controller에 등록된 Command를 실행 합니다.
    CairngormEventDispatcher.getInstance().dispatchEvent( event );
   }
   private function resultEvt(event:ServiceResultEvent):void
   {
    //리턴받은 결과값을 데이터 그리드에 Binding 합니다.
    this.listdata = event.result;
   }
   private function changeEvt():void
   {
    //상세보기 화면을 띄어줍니다.
    var readView:BBSReadView = PopUpManager.createPopUp(this,BBSReadView,true) as BBSReadView;
    readView.rowNum = 1;
    PopUpManager.centerPopUp(readView);
   }
  ]]>
 </mx:Script>
 <mx:DataGrid width="100%" height="100%" dataProvider="{listdata}" change="changeEvt()">
  <mx:columns>
   <mx:DataGridColumn headerText="번호" dataField="num">
   </mx:DataGridColumn>
   <mx:DataGridColumn headerText="제목" dataField="subject">
   </mx:DataGridColumn>
   <mx:DataGridColumn headerText="작성자" dataField="writer">
   </mx:DataGridColumn>
  </mx:columns>
 </mx:DataGrid>
</mx:HBox>

4.8 완성된 전체 게시판 구조는 아래 그림 형태로 실행됩니다

<그림 9>


처음 시작하시는 분들은 여러 개의 파일을 생성하여 서비스를 구현하는 형태가 번거롭다고 생각할지도 모르나 추후 프로젝트를 진행하면서 새로운 기능들이 추가되고 이전 기능들이 수정될 경우 동일한 패턴을 사용하므로 서비스 변경이 용이합니다. 그리고 캔곰에 대해 어느정도 익숙해지면 나름대로 프로젝트 성격에 맞는 형태로 수정하여 재사용할 수도 있습니다. 나름대로 고민해 보길 바랍니다.

다음은 RemoteObject에 대해
지금까지 각각의 캔곰 클래스들이 담당하는 역할과 이를 활용하여 게시판 리스트를 구현하는 방법에 대해 알아 보았습니다. 다음 시간에는 RemoteObject에 대해 알아보도록 합니다.

Posted by 나비:D
:
Posted by 나비:D
:

   import mx.controls.Alert;
   import mx.events.CloseEvent;

   // show alert
   private function clickButton():void {
     Alert.yesLabel = "예", Alert.noLabel = "아니오";
     Alert.show("예 아니오 냐는?", "", Alert.YES|Alert.NO, this, buttonAlertListener, null);
   }
  
   // alert listener
   private function buttonAlertListener(evt:CloseEvent):void {
    if ( evt.detail == Alert.YES ) {
        Alert.okLabel = "예";
        Alert.show("예 선택했다는");
    } else if ( evt.detail == Alert.NO ) {
        Alert.okLabel = "아니오 선택했소";
        Alert.buttonWidth = 200;
        Alert.show("아니오 선택했다는");
    }
   }


간단 예제 입니다
Alert.yesLabe  Alert.noLabel   Alert.okLabel 등으로 버튼 이름을 한글로 세팅해줄수 있숩니다.


만약 버튼에 할당한 이름이 길다면  Alert.buttonWidth = 200 으로 버튼 길이를 조정하여 글자가 짤리는걸 방지할수 있습니다.


선택에 따라 맞는 행위?를 실행시키려면 Alert.show에 각종 인자를 줍니다


...buttonAlertListener ... 부분이 선택에 따라 실행할 함수 지정 부분


그럼 private function buttonAlertListener(evt:CloseEvent):void 식으로 함수 만들어서
조건에 따라 맞는 행위를 기술해 주시면 된다는.. :)

Posted by 나비:D
:

BLOG main image
by 나비:D

공지사항

카테고리

분류 전체보기 (278)
Programming? (0)
---------------------------.. (0)
나비의삽질 (5)
Application (177)
C# (28)
JAVA (22)
ASP.NET (3)
C++ (19)
C (18)
.NET (0)
Visual Basic (12)
Flex (16)
Eclipse (8)
Delphi (16)
Visual Studio 2005 (5)
Embed (6)
Linux (2)
Mobile (1)
XML (1)
안드로이드 (2)
SQL (51)
Web (27)
etc. (14)
Omnia (0)
---------------------------.. (0)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Total :
Today : Yesterday :