Depois de ter aqui falado de como um componente é apresentado no stage, bem como todos os passos da sua criação, falo agora, em continuação com a documentação da adobe, de como se deve proceder à implementação de um componente, bem com os passos a executar na sua implementação. After having spoken of here as a component is shown in the stage and all steps of its creation, I speak now, in continuation with the documentation of adobe, of how to proceed with the implementation of a component, along with the steps run in its implementation.
Estes procedimentos não são todos obrigatórios, mas deve-se ter em conta as suas dependências. These procedures are not all mandatory, but you must take into account their dependencies. Passo então a citar a fonte original, mas em português e com um exemplo não testado. I then cite the original source, but in Portuguese and an example untested.
Passos para criar um componente Steps to create a component
Quando se implementa um componente, regra geral, fazemos o override (re-escrita) de determinado métodos do componente, definimos novas propriedades, disparamos/criaamos eventos e efectuamos quaisquer outras alterações/personalizações tendo em conta o objectivo do nosso componente na aplicação. When component implements a general rule, do the override (re-written) from certain methods of the component, we set new properties, disparamos / criaamos events and perform any other changes / customizations taking into account the objective of our component in the application.
Para implementar um componente, devemos seguir a seguinte ordem: To implement a component, we must follow the following order:
1. 1. Se necessário, criamos skins para o nosso componente; If necessary, create skins for our component;
2. 2. Criamos um ficheiro "Action Script Class file" tendo a estrutura: We created a "Class Action Script file" having the structure:
1: package meuComponente 1: package meuComponente
2: { 2: (
3: //importar o que iremos usar no nosso componente. 3: / / import what we use in our component.
4: import mx.core.UIComponent; 4: Import mx.core.UIComponent;
5: import mx.controls.Button; 5: Import mx.controls.Button;
6: import mx.controls.TextArea; 6: Import mx.controls.TextArea;
7: import flash.events.Event; 7: Import flash.events.Event;
8: 8:
9: // definimos o nosso evento pessoal que usaremos em baixo 9: / / define our event staff who use below
10: [Event(name= "change" , type= "flash.events.Event" )] 10: [Event (name = "change", type = "flash.events.Event")]
a) Extendemos uma das classes base, todos os componentes são baseados na class UI, se desejarmos criar um componente de raiz, mais complexo, devemos extender esta class, caso contrario se só desejarmos implementar/extender um componente simples como um botão, extendemos apenas esse componente. a) Extendemos one of the basic classes, all components are based on class IU, if we want to create a component from scratch, more complex, we must extend this class, if only wish Otherwise implement / extend a component simple as a button, only extendemos that component.
1: //extender a class que desejamos 1: / / we want to extend the class
2: public class Exemplo extends UIComponent { 2: public class Example (extends UIComponent
3: 3:
8: } 8:)
b) Especificamos as propriedades/variáveis que o utilizador pode definir usando as propriedades ou a tag MXML; b) We specify the properties / variables that you can set using the properties or the tag MXML;
1: private var textObj:TextArea; 1: private var textObj: TextArea;
2: private var modeObj:Button; 2: private var modeObj: Button;
3: private var _textLabel:String; 3: private var _textLabel: String;
c) Incluir (embed) qualquer gráfico ou skin. c) include (embed) any plot or skin.
1: //usando skins de um swf. 1: / / skins using a swf.
2: [Embed(source= "Modal2.swf" , symbol= "blueCircle" )] 2: [Embed (source = "Modal2.swf", symbol = "blueCircle")]
3: public var modeUpSkinName:Class; 3: public var modeUpSkinName: Class;
4: 4:
5: //importando/incluido uma imagem 5: / / importing / included an image
6: [Embed(source= "img/img1.png" )] 7: public var imagem1:Class; 6: [Embed (source = "img/img1.png")] 7: public var imagem1: Class;
d) Implementar o construtor da class. d) Implement the manufacturer of class.
1: public function Exemplo() { 1: Example public function () (
2: super(); 2: super ();
3: } 3:)
Chamada na inicialização do componente, util para adicionar-mos um novo child, por exemplo os nossos componentes TextArea e Button declarados em cima: Call in the boot of the component, useful to add a new child-tion, for example our components TextArea and Button declared upon:
1: override protected function createChildren(): void { 1: override protected function createChildren (): void (
2: super.createChildren(); 2: super.createChildren ();
3: 3:
4: // Criar e inicializar a nossa TextArea. 4: / / Create and start our TextArea.
5: if (!textObj) 5: if (! TextObj)
6: { 6: (
7: textObj = new TextArea(); 7: textObj = new TextArea ();
8: textObj.explicitWidth = 80; 8: textObj.explicitWidth = 80;
9: //podemos adicionar um evento: 9: / / can add an event:
10: textObj.addEventListener( "change" , handleChangeEvent); 10: textObj.addEventListener ( "change", handleChangeEvent);
11: addChild(textObj); 11: addChild (textObj);
12: } 12:)
13: 13:
14: // Criar e inicializar o nosso Botão 14: / / Create and start our Button
15: if (!modeObj) 15: if (! ModeObj)
16: { modeObj = new Button(); 16: (modeObj = new Button ();
17: modeObj.label = "Exemplo de Btn" ; 17: modeObj.label = "Sample Btn";
18: addChild(modeObj); 18: addChild (modeObj);
19: } 19:)
20: } 20:)
Chamado pelo método invalidateProperties(); que actualiza quaisquer as propriedades do nosso componente: Called by the method invalidateProperties (), which updates all the properties of our component:
1: override protected function commitProperties(): void { 1: override protected function commitProperties (): void (
2: super.commitProperties(); 2: super.commitProperties ();
3: 3:
4: if (modObj && _textLabel.lenght>0) { 4: if (modObj & & _textLabel.lenght> 0) (
5: //usando o label, se existir, da nossa variavel _textLabel 5: / / using the label, if any, of our variable _textLabel
6: modObj.label=_textLabel; 6: modObj.label = _textLabel;
7: invalidateDisplayList(); 7: invalidateDisplayList ();
8: } 8:)
9: } 9:)
Chamado para recalcular (ao ser alterado) o tamanho do nosso componente, bem como definirmos as posições dos nosso childs. Called to recalculate (to be changed) the size of the component, and define the positions of our childs.
1: override protected function measure(): void { 1: override protected function measure (): void (
2: super.measure(); 2: super.measure ();
3: 3:
4: //o tamanho do nosso UIComponent vai depender do tamanho dos 4: / / the size of our UIComponent vai depend on the size of
5: //childs, por isso temos que calcular o tamanho deles pra poder 5: / / childs, so we have to calculate the size of them get power
6: //definir correctamente o layout do nosso componente. 6: / / correctly define the layout of our component.
7: 7:
8: var buttonWidth:Number = modeObj.measuredWidth; 8: var buttonWidth: Number = modeObj.measuredWidth;
9: var buttonHeight:Number = modeObj.measuredHeight; 9: var buttonHeight: Number = modeObj.measuredHeight;
10: 10:
11: // O valor do comprimento, por defeito e minimo são igauis 11: / / The value of length, default and minimum are igauis
12: // á measeuredWidth da nossa TextArea mais o measuredWidth 12: / / will measeuredWidth of our most TextArea the measuredWidth
13: // do nosso botão 13: / / of our button
14: measuredWidth = measuredMinWidth = 14: measuredWidth = = measuredMinWidth
15: textObj.measuredWidth buttonWidth; 15: textObj.measuredWidth buttonWidth;
16: 16:
17: // O mesmo se passa com a altura do nosso componente que será 17: / / The same goes for the height of our component that will be
18: // igual à measuredHeight da nossa textArea measuredHeight do 18: / / equal to the measuredHeight of our textArea measuredHeight of
19: // nosso botão. 19: / / our button.
20: measuredHeight = measuredMinHeight = 20: measuredHeight = = measuredMinHeight
21: modeObj.measuredHeight, buttonHeight; 21: modeObj.measuredHeight, buttonHeight;
22: } 22:)
Podemos definir mais algumas propriedades do nosso layout: We can define a few more properties of our layout:
1: protected override function layoutChrome(unscaledWidth:Number, unscaledHeight:Number): void { 1: protected override function layoutChrome (unscaledWidth: Number, unscaledHeight: Number): void (
2: super.layoutChrome(unscaledWidth, unscaledHeight); 2: super.layoutChrome (unscaledWidth, unscaledHeight);
3: 3:
4: this .textObj.disabled = true ; 4: this. TextObj.disabled = true;
5: } 5:)
Chamado pelo método invalidateDisplayList(); para redefinir a nossa DisplayList (caso sejam alterados os tamanhos do nosso componente) : Called by the method invalidateDisplayList (); to redefine our DisplayList (if changed the sizes of our component):
1: override protected function updateDisplayList(unscaledWidth:Number, 1: override protected function updateDisplayList (unscaledWidth: Number,
2: unscaledHeight:Number): void { 2: unscaledHeight: Number): void (
3: super.updateDisplayList(unscaledWidth, unscaledHeight); 3: super.updateDisplayList (unscaledWidth, unscaledHeight);
4: 4:
5: // subtraimos um pixel dos bordos e usamos uma 5: / / subtraimos a pixel from the edges and use a
6: // margem de 3 pixeis à esquerda e direita 6: / / margin of 3 pixels left and right
7: // 1 1 3 3 = 8; 7: / / 1 1 3 3 = 8;
8: var usableWidth:Number = unscaledWidth - 8; 8: var usableWidth: Number = unscaledWidth - 8;
9: 9:
10: // Fazemos o mesmo para o topo e fundo 10: / / We do it to the top and bottom
11: var usableHeight:Number = unscaledHeight - 8; 11: var usableHeight: Number = unscaledHeight - 8;
12: 12:
13: //tamanhos da textArea e botão 13: / / sizes of textArea button and
14: //a textArea terá o tamanho máximo do nosso compoenente 14: / / textArea to have the maximum size of our compoenente
15: var textWidth:Number = usableWidth; 15: var textWidth: Number = usableWidth;
16: //a altura, definimos a altura maxima, subtraindo apenas a 16: / /'s time, we set the height maximum, subtracting just
17: // altura do nosso botão, para este fique logo em baixo da nossa 17: / / height of our button, so this is just below of our
18: // textArea. 18: / / textArea.
19: var textHeight:Number = usableHeight-modeObj.height; 19: var textHeight: Number = usableHeight-modeObj.height;
20: textObj.setActualSize(textWidth, textHeight); 20: textObj.setActualSize (textWidth, textHeight);
21: 21:
22: //o nosso botão terá todo o comprimento no nosso componente 22: / / button will take our entire length in our component
23: modeObj.setActualSize(usableWidth, modeObj.height); 23: modeObj.setActualSize (usableWidth, modeObj.height);
24: 24:
25: // Redefinirmos as posições dos nosso childs 25: / / Redefinirmos the positions of our childs
26: textObj.move(4,4); //x=y=(margem=3 bordo=1)= 4 26: textObj.move (4.4); / / x = y = (margin = 3 board = 1) = 4
27: //x=margem bordo=4, y=height espaço de 5px entre eles 27: / / x = margin board = 4, y = height of space between them 5px
28: modeObj.move(4,textObj.height 5); 28: modeObj.move (4, textObj.height 5);
29: 29:
30: // Desenhamos uma linha à volta do nosso componente a negro pra 30: / / Desenhamos a line around the black component to our pra
31: //servir de bordo. 31: / / serve as a board.
32: graphics.lineStyle(1, 0×000000, 1.0); 32: graphics.lineStyle (1, 0 × 000000, 1.0);
33: graphics.drawRect(0, 0, unscaledWidth, unscaledHeight); 33: graphics.drawRect (0, 0, unscaledWidth, unscaledHeight);
34: } 34:)
j) Adicionar propriedades, métodos, styles, eventos e metadata. j) Add properties, methods, styles, events and metadata.
adicionamos o resto das propriedades do nosso componente: add the rest of the properties of our component:
1: //funções para definir e retornar a variavel textLabel (getters/setters) 2: //função set/define 1: / / functions to define and return to variable textLabel (getters / setters) 2: / / function in September / set
3: public function set textLabel(texto:String): void { 3: public function set textLabel (text: String): void (
4: //mudamos o texto 4: / / change the text
5: _textLabel = text; 5: _textLabel = text;
6: //temos que forçar a actualização do texto no componente 6: / / we have to force update the text in component
7: invalidateProperties(); 7: invalidateProperties ();
8: } 8:)
9: 9:
10: //função para devolver o nosso texto do botão. 10: / / function to return our text of the button.
11: public function get textLabel():String { 11: public function get textLabel (): String (
12: return modeObj.text; 12: Return modeObj.text;
13: } 13:)
14: 14:
15: // Função para lidar com o evento disparado por nós no child. 15: / / staff to handle the event triggered by us in the child.
16: private function handleChangeEvent(eventObj:Event): void { 16: private function handleChangeEvent (eventObj: Event): void (
17: dispatchEvent( new Event( "change" )); 17: dispatchEvent (new Event ( "change"));
18: } 18:)
Não esquecer no final de fechar o nosso componente, iciniado pelo package meuComponente { : Do not forget to close at the end of our component, iciniado by meuComponente (package:
3. 3. Salve o ficheiro ActionScript ou distribua como biblioteca .swc. Save the file as ActionScript or distribute library. Swc.
Para usar este componente, usaríamos no caso de actionScript: To use this component, usaríamos in the case of actionScript:
1: import meuComponente.Exemplo; 1: Import meuComponente.Exemplo;
2: //Declarando o componente 2: / / Expressing the component
3: var tempComp:Exemplo = new Exemplo(); 3: var tempComp: Example = new Example ();
4: //Adicionando ao um panel, por exemplo: 4: / / Adding to a panel, for example:
5: meuPainel.addChild(tempComp); 5: meuPainel.addChild (tempComp);
6: //definindo o lanel do nosso botão no componente: 6: / / defining the lanel of our button in component:
7: tempComp.textLabel= "BOTAO" ; 7: tempComp.textLabel = "BUTTON";
Este exemplo, não foi testado e devem ser tomados em conta alguns erros que possam acontecer a testar, mas em principio funcionará bem. This example has not been tested and should be taken into account some errors that could happen to be tested, but as a rule do well. Este exemplo é dos mais completos, já que implementa directamente um UIComponent, ou seja, cria um componente de raiz. This example is the most complete, since implementing a UIComponent directly, or create a piece of root.
Caso seja distribuído num swc, o "Exemplo" estará disponível tanto no action script, como na janela "Components" em "Custom". If distributed in a swc, the "Example" will be available both in action script, as in the window "Components" under "Custom".
Este exemplo e artigo foi baseado na documentação disponíveis aqui , aqui e aqui (EN) This example and article was based on documentation available here, here and here (EN) Espero que seja verdadeiramente util! I hope that is truly useful!
Um Abraço! A Abraço!
Este artigo está disponivel em pdf para download. This article is available in pdf format for download.
2 Comments
Truly useful? An explanation step-by-step, how to work with OO in AS3! Extremely useful, my dear! Parabens and link on my blog for this post!
Abração of Ved
Not yet had time to test: p But in principle work direitinho
So now anyone can create a component to add to any application or as swc
Abraço!