This vs e.currentTarget ?

I have several movie clips on the stage. They are draggable. I want to be able to drag the movie clip, then when it is dropped, a copy of that movie clip will appear where the first one had been, and the first one will just stay where it is on the screen.
However, I'm running into problems with the syntax. I don't have a good  grasp on the difference between "this" and "e.currentTarget".
Here is my current code:
public function letterStop(e:MouseEvent): void {
            if (this.dropTarget.parent is BlankSquare) { //check to see if the movie clip is being dropped over a drop spot
                e.currentTarget.x = this.dropTarget.parent.x + 10; //lock movie clip to the drop spot
                e.currentTarget.y = this.dropTarget.parent.y - 10;
                var newLetter:Letters = new Letters(); //create a new instance of the class Letters
                newLetter = e.currentTarget; //assign the new instance to the properties of the current instance
                MovieClip(this.parent).bmc.addChild(newLetter); //add child to the stage
                newLetter.x = e.currentTarget.startPoint.x; //at the correct starting points
                newLetter.y = e.currentTarget.startPoint.x;
This code obviously doesn't even compile, I'm missing something somewhere. I want the new movie clip to be a direct copy of the old movie clip. Each movie clip has a property called startPoint which holds its point of origin so it can snap back into place. I don't know how to spawn a copy of the original movie clip in the right place (since duplicateMovieClip no longer exists). And I'm really not sure if I'm using this or e.current Target correctly since they both trace to the same thing.
Does any of that make sense?

Okay, but what if I need that instance name to be a variable?
I'll be more specific.
I have 26 letters on the stage, A-Z. Each is a class (letterA, letterB, etc) whose base class is Letters.
If I drag the letter A onto a drop point, I need to duplicate that letter in the original movie clip's position so that it can be used again.
So I can't just say "create this new movie clip" because I can't figure out how to tell it WHICH movie clip it needs to duplicate. Does that make sense? Is it duplicating an M or a K? I don't know how to get it to do that.

Similar Messages

  • Bring loaded external swf to the front

    Hi,
    I am now implementing to create a website using side scrolling platform game approach. Since the player/actor (character that moves according to keyborad events) should always be at the top layer, I am having difficulties to get my loaded swf on top of the player. I am currently using Flash cs6 (as3).
    Basically, in my main stage, there are 3 layers. 1 for actionscript, the scond one for player and lastly for background.
    Layer player contains player mc and background mc.
    Background mc contains visual and collisions layers.
    Anything that got to do with visual, i have to put it in visual layer.
    In visual layer i have backgroundcontainer mc
    So, as i put the button in the backgroundcontainer mc to call the external swf, the loaded external swf appears in the container.
    (I am using load/unload snippet code to call the external swf)
    I want the external swf to appear on top of the player.
    for (var fl_ChildIndex_2:int = 0;
            fl_ChildIndex_2 < this.numChildren;
            fl_ChildIndex_2++)
        this.getChildAt(fl_ChildIndex_2).addEventListener(MouseEvent.CLICK, fl_ClickToBringToFront_2);
    function fl_ClickToBringToFront_2(event:MouseEvent):void
        this.addChild(event.currentTarget as DisplayObject);
    Any help would greatly appreciated 

    If you want an object to move atop all others you can just use addChild(thatobject), where thatobject is the item you want to move atop anything else.  I don't know what object(s) your loop is attempting to act on, but it appears to be trying to change the index of all child objects rather than just one.

  • Php vs textfile dynamic text

    ok i am at the last part of my project. it worked all well and reads all text fields from a text file as seen on :
    http://www.myblueranch.com/index2.html
    now i am trying to get the same thing working from MYSQL.
    Notice that the text file i used for index2.html is called
    www.myblueranch.com/trees1.txt
    and it was a direct copy/paste from the php page that gave the results from the MYSQL query. (the php query page is:)
    www.myblueranch.com/flash_names.php
    The problem is i am getting an error in
    www.myblueranch.com/index.html
    which uses the php to get the text for the dynamic fields.
    I get the following error:
    TypeError: Error #2007: Parameter text must be non-null.
        at flash.text::TextField/set text()
        at final_fla::MainTimeline/onDataLoad()
        at flash.events::EventDispatcher/dispatchEventFunction()
        at flash.events::EventDispatcher/dispatchEvent()
        at flash.net::URLLoader/onComplete()
    my flash movie has 113 buttons called button_1 --> button_113 and 113 dynamic text fields tcname_1-->tcname_113
    my AC3 code is the following:
    // button links: to all buttons to open in iframe 'tdes'
    // link corrosponds to button number
    // i have 113 buttons.
        for(var i:int=1;i<=130;i++){
            if(this["button_"+i]){
                this["button_"+i].addEventListener(MouseEvent.CLICK,f);   
        function f(e:MouseEvent):void{
            var n:String=e.currentTarget.name.split("_")[1];
            navigateToURL(new URLRequest("ranch.php?id="+n),"tdes");
    // end of button links
    //Create the URLLOader instance
        var myLoader:URLLoader = new URLLoader()
        //the data will come as URL-encoded variables
        myLoader.dataFormat = URLLoaderDataFormat.VARIABLES
        //Load using an URLRequest, even beeing local
        myLoader.load(new URLRequest("flash_names.php"))
        //onLoad handler listener
        myLoader.addEventListener(Event.COMPLETE, onDataLoad)
        //Error handling   
        myLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError)
        myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError)
        //Could be an error or just a message
        myLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus)   
        //add a listener for the complete event
        function onDataLoad(evt:Event){
            trace(evt.target.data.cant);
            for(var i:uint=1; i<evt.target.data.cant; i++){ 
                this["tcname_"+i].text = evt.target.data["tcname_"+i]
                this["tcname_"+i].autoSize="left"
                this["tcname_"+i].multiline = true;
                this["tcname_"+i].wordWrap = true;
                this["tcname_"+i].width = 70;http://forums.adobe.com/post!input.jspa?container=2066&containerType=14
                this["tcname_"+i].visible = false;
                this["button_"+i].addEventListener(MouseEvent.ROLL_OVER, buttonover);
                this["button_"+i].addEventListener(MouseEvent.ROLL_OUT, buttonout);
                trace(i);
    // ON ROLLOVER make text field visible and change color
        function buttonover(e:Event){
            var tf:TextField=TextField(this["tcname_"+e.currentTarget.name.split("_") [1]]);
            trace (tf.name);
            tf.visible = true;
            tf.textColor=0xff0000;
    // ON ROLLOVER make change color and make invisible
        function buttonout(e:Event){
            var tf:TextField=TextField(this["tcname_"+e.currentTarget.name.split("_") [1]]);
            tf.textColor=0x000000;
            tf.visible = false;
        //error callbacks
        function onIOError(evt:IOErrorEvent){
            trace("IOError: "+evt.text)
        function onHTTPStatus(evt:HTTPStatusEvent){
            trace("HTTPStatus: "+evt.status)
        function onSecurityError(evt:SecurityErrorEvent){
            trace("SecurityError: "+evt.text)

    Kenneth this created another problem:
    1- i changed the code of the php to make it look like:
    &tcname_1=Cherokee SweetGum&tcname_2=cedar&tcname_3=cedar&cant=3
    and now i get this error:
    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
    at Error$/throwError()
    at flash.net::URLVariables/decode()
    at flash.net::URLVariables()
    at flash.net::URLLoader/onComplete()
    Also when i do that even when i load from a textfile (i.e. not from MYSQL through php) i see no text at all!!
    2- Where did you want me to put these trace lines? if i put them in the end of my ac3 script i get this compile error:
    Scene 1, Layer 'Layer 1', Frame 1, Line 97
    1120: Access of undefined property evt.
    did i do something wrong?

  • Code snippet -- "Send to Back"?

    Hello,
    I've modified the code snippet "Bring Object to the Front" to bring a given stage symbol to the front on mouse over. My question is, what code do I add to make the symbol go to the back on mouse out? My code is below -- exact same as the code snippet in CS5, but with MOUSE_OVER in place of CLICK. Many thanks!
    // This code makes all symbol instances on stage clickable by making them listen for the CLICK event.
    for (var fl_ChildIndex:int = 0;
            fl_ChildIndex < this.numChildren;
            fl_ChildIndex++)
        this.getChildAt(fl_ChildIndex).addEventListener(MouseEvent.MOUSE_OVER, fl_OverToBringToFront);
    // This is the function that moves the over object to the front of the display list
    function fl_OverToBringToFront(event:MouseEvent):void
        this.addChild(event.currentTarget as DisplayObject);

    Thanks -- it's getting there but the behavior is weird and I'm getting an error message "TypeError: Error #1009: Cannot access a property or method of a null object reference.at transitshell_fla::lvbutton_5/fl_FadeSymbolIn()"
    My code looks like this:
    // This code makes all symbol instances on stage clickable by making them listen for the CLICK event.
    for (var fl_ChildIndex:int = 0;
            fl_ChildIndex < this.numChildren;
            fl_ChildIndex++)
        this.getChildAt(fl_ChildIndex).addEventListener(MouseEvent.MOUSE_OVER, fl_OverToBringToFront);
        this.getChildAt(fl_ChildIndex).addEventListener(MouseEvent.MOUSE_OUT, fl_OverToSendToBack);
    // This is the function that moves the over object to the front of the display list
    function fl_OverToBringToFront(event:MouseEvent):void
        this.addChild(event.currentTarget as DisplayObject);
        function fl_OverToSendToBack(event:MouseEvent):void
        this.addChildAt(event.currentTarget as DisplayObject, 0);
    Thanks for your help!

  • Dropdownlist handler throws error

    I have this handler for my dropdownlist:
    protected function selectQuality_changeHandler(event:IndexChangeEvent):void {                   
        currentQualityLevel = event.currentTarget.selectedItem.@name;
        counterCostSF = event.currentTarget.selectedItem.@price;}
    As soon as the state that includes this menu is activated, I get the error [code]TypeError: Error #1010: A term is undefined and has no properties.
    However, if I continue past the error the app works fine, and people without the debugging plugin get no error.
    That menu is populated with xml, and which node is chosen by a menu to the left of it.  I guess it is possible that the data is not ready, but that makes sense to me if the menu is chosen; not just on state load.
    Since I don't actually "need" this information until the user uses the menu (there are default values),how can I prevent the error?
    Here is the code that controls that menu:
    private function getCountertops_resultHandler(event:ResultEvent):void {
         countertopData = event.result.type;}
    protected function selectMaterial_changeHandler(event:IndexChangeEvent):void {
         var sel:int = event.currentTarget.selectedIndex;
         currentMaterial = event.currentTarget.selectedItem.name;
         updateCountertopCard(sel);
    protected function selectQuality_changeHandler(event:IndexChangeEvent):void {                        
        currentQualityLevel = event.currentTarget.selectedItem.@name;
        counterCostSF = event.currentTarget.selectedItem.@price;
    private function updateCountertopCard(i:int):void {
          var node:XML = countertopData[i];
          if (!node) return;
          matTitle.text = countertopData[i].title;
          matCaption.text = countertopData[i].caption;
          matBullets.text = countertopData[i].bullets;
          image1.imageSource = "images/"+countertopData[i]..swatches.swatch[0];
          selectQuality.dataProvider = new XMLListCollection(countertopData[i].cost.level);
          selectQuality.selectedIndex = 0;
          profileList.dataProvider = new XMLListCollection(countertopData[i].profiles.profile);

    @Handycam,
    You should always try and verify that the event.currentTarget.selectedItem property is not null before trying to access any of it's properties.
    Either try this:
    if (event.currentTarget.selectedItem) {
        currentQualityLevel = event.currentTarget.selectedItem.@name;
        counterCostSF = event.currentTarget.selectedItem.@price;}
    Or you could try wrapping the code in a try/catch block.
    Peter

  • Buttons don't work if united into MovieClip

    I have an animated image collage with 10+ images. It is brought in into the main stage as a united mc. Each image has to act as a button which links to a labeled section in the flash file.
    I understand that I can not write AS3 on the main stage as I am unable to specify the instance name for each button since they all are brought as a united mc and only that mc is available as an instance.
    So I go inside the mc to the level where I can select each button, give the button an instance name and then put the following code on the AS3 layer inside the mc level where all the images/buttons are assembled as a collage:
    my_btn1.addEventListener(MouseEvent.CLICK,my_btn1_Down);
    my_btn1_Down(event:MouseEvent): void {
    MovieClip(parent.parent.parent.parent.parent.parent.parent.parent.parent.parent).gotoAndPl ay("icysophistication");
    I started with just one parent and kept on adding them up to see if it will change the result, but unfortunately all the same "Error #1009: Cannot access a property or method of a null object reference."
    you can view the site at www.888acolyte.com
    It is still under the development and will take a min to load then wait for the image collage to appear. Those images are the ones which i would like to make into buttons.

    There should be nothing preventing you from having the code on the main timeline.  You just need to target the buttons thru the mc instance name...
    your_mc.my_btn1.addEventListener(MouseEvent.CLICK,my_btn1_Down);
    function my_btn1_Down(event:MouseEvent): void {
        this.gotoAndPlay("icysophistication");
    And if you name your buttons to match the frame labels, you can have all the buttons share the same event handler function...
    your_mc.icysophistication.addEventListener(MouseEvent.CLICK, btnClick);
    your_mc.spicysophistication.addEventListener(MouseEvent.CLICK, btnClick);
    etc....
    function btnClick(event:MouseEvent): void {
        this.gotoAndPlay(evt.currentTarget.name);

  • Hittest only working with 1 added child

    Ive got this piece of script where i place objects on the stage, to hittest eachother.
    Ive got two seperate addchilds: one child must hittest another child
    But for some reason it will only hittest with one object from the 2nd addchild :/
    this is the addchild for the hittesting objects:
    all variables are defined properly
    for(var ringteller=0; ringteller<2; ringteller++) {
    for(var teller1=1; teller1<17; teller1++) {
        //var ringsegment_mc:Ring_1=new Ring_1();
        var ClassReference:Class = getDefinitionByName("Ring_"+teller1) as Class;
        var ringsegment_mc:MovieClip=new ClassReference();
        ringsegment_mc.addEventListener(Event.ENTER_FRAME,vernietig);
        addChild(ringsegment_mc);
    for(var teller2=0; teller2<2; teller2++) {
        var hitte_mc:Hitte=new Hitte();
        Hittes.push(hitte_mc);
        hitte_mc.mousedown=0;
        hitte_mc.addEventListener(Event.ENTER_FRAME, floaten);
        hitte_mc.addEventListener(MouseEvent.MOUSE_DOWN, slepenStart);
        hitte_mc.addEventListener(MouseEvent.MOUSE_UP, slepenStop);
        addChild(hitte_mc);
    and this is the code for the slepenStart and vernietig:
    function vernietig(evt:Event) {
        for(var teller3:int=1;teller3<Hittes.length;teller3++){
            if (evt.currentTarget.hitTestObject(Hittes[teller3]) ) {
                   evt.currentTarget.alpha+= -0.1;
                if (evt.currentTarget.alpha<=0.05) {
                    evt.currentTarget.x=evt.currentTarget.y=-200;
                    this["segmentenkapot"+evt.currentTarget.kerngroep]+=1;
            if (this["segmentenkapot"+evt.currentTarget.kerngroep] == 16) {
                trace("ring kapot");
    function slepenStart (evt:MouseEvent):void {
        evt.currentTarget.startDrag();
        evt.currentTarget.snelheidx=evt.currentTarget.snelheidy=0;
        evt.currentTarget.mousedown=1;
    function slepenStop (evt:MouseEvent):void {
        evt.currentTarget.stopDrag();
        evt.currentTarget.snelheidx=4; evt.currentTarget.snelheidy=2;
        evt.currentTarget.mousedown=0;
    so: only one instance of the hitte_mc will hittest with the instances of Ring_
    what did i miss to fix this :/

    i replaced
    teller3:int=1;
    with
    teller3:int=0;
    which seems to have done it ^^
    that is what you meant, right?
    btw: the for loop was only checking for one, instead of the whole array ^^

  • "Property currentLabel not found on String"

    This is the error message I keep getting with the following setup:
    I have several button instances onstage named "1gun", "2gun", "3gun" and so on.
    There are also several button instances onstage named "1bullseye","2bullseye" and so on.
    When I use this code and click on a button containing an index of gun,it returns the number preceding the string "gun", just as I want it to do.:
    {trace (e.currentTarget.name.slice(0,1))}
    When I use this code and click on a gun button, it returns  the name of the "bullseye" button that corresponds with the "gun": button:
    {trace ("bullseye" + e.currentTarget.name.slice(0,1))}
    However, when I use this code, I get the output error in the title of this thread:
    {trace("bullseye" + e.currentTarget.name.slice(0,1).currentLabel)}
    Property currentLabel not found on String and there is no default value.
    The code is intended to trace the current frame of a bullseye when the corresponding gun is clicked. So if "1gun" is clicked, it would trace the currentFrame of "1bullseye".
    Any ideas about why this isn't working?

    The following is just a String, which does not have a property named currentLabel...
    "bullseye" + e.currentTarget.name.slice(0,1)
    If there is a MovieClip that has an instance name of bullseye#  (where # is some number), then you need to use bracket notation to have that String interpretted as an instance of an object....
    {trace(this[ "bullseye" + e.currentTarget.name.slice(0,1)].currentLabel)}

  • DataGroup Drag Enter Issue/Question (FB4)

    I'm working with Flash Builder 4, Flex 4 and I'm having difficulty in getting the drag events to fire, in particular the Drag Enter event. I have 2 dataGroups with a custom layout and itemRenderer. I'm attempting to drag an element from one DataGroup and drop it into the other DataGroup. In Flex 3, when I dragged something over a container, the event.CurrentTarget was the container, and I could then tell the container to accept the dragged item. In Flex 4, the dragEnter event isn't firing when I drag something over the DataGroup. It ONLY fires when I drag something over one of the rendered items in the DataGroup. Below is the code for the application, DataGroup, CustomLayout, and itemRenderer. If you debug the application and drag an item in the first DataGroup over the second DataGroup, note that you don't get the trace statements. If you drag the item so that the mouse passes over one of the elements in the second DataGroup, THEN the DragEnter events fires.
    Application:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application
    xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="
    library://ns.adobe.com/flex/spark" xmlns:mx="
    library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:ns1="*" >
    <fx:Script>
    <![CDATA[
    import mx.events.DragEvent; 
    private function dragEnterHandler(event:DragEvent):void { 
    trace ("Drag Enter"); 
    trace (" Target: "+event.target.id); 
    trace (" Current Target: "+event.currentTarget.id);}
    private function dragDropHandler(event:DragEvent):void { 
    trace (event.currentTarget.id);}
    ]]>
    </fx:Script>
    <s:SkinnableContainer top="0" left="0" right="0" bottom="0" id="dgContainer" >
    <ns1:myDataGroup left="5" id="dgOne" top="5" bottom="5" width="200" depth="1" dragEnter="dragEnterHandler(event)" dragDrop="dragDropHandler(event)"/>
    <ns1:myDataGroup left="226" id="dgTwo" top="5" bottom="5" width="200" depth="1" dragEnter="dragEnterHandler(event)" dragDrop="dragDropHandler(event)"/>  
    <mx:VRule left="213" top="0" bottom="0"/>
    </s:SkinnableContainer></s:Application>
    DataGroup:
    <?xml version="1.0" encoding="utf-8"?><s:DataGroup xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="
    library://ns.adobe.com/flex/spark" xmlns:mx="
    library://ns.adobe.com/flex/mx" dataProvider="{myAC}" width="
    100%" height="100%" xmlns:myLayout="myLayout.*" itemRenderer="iRenderer"creationComplete="addEventListener(RESIZE_CLICK, resizeHandler,
    false, 0, true);" initialize="cLayout.setLayout();" name="
    myDGroup" >
     <fx:Declarations>
     <!-- Place non-visual elements (e.g., services, value objects) here -->
     </fx:Declarations>
     <fx:Script>
    <![CDATA[
     import mx.collections.ArrayCollection; 
    import mx.events.DragEvent; 
    Bindable] 
    public var myAC:ArrayCollection = new ArrayCollection([{Height: 100, Label:
    "Test # 1", xPos: 0},{Height: 200, Label:
    "Test # 2", xPos: 0}]);
    public static const RESIZE_CLICK:String = "resizeClick"; 
    protected var resizingElement:iRenderer; 
    protected var initX:Number; 
    protected var initY:Number; 
    public var itemID:Number; 
    public function resizeHandler(event:MouseEvent):void { 
    if (event.target.name == 'iRenderer') {resizingElement = iRenderer(event.target);
    initX = event.localX;
    initY = event.localY;
    itemID = Number(resizingElement.uid);
    systemManager.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler,
    true);systemManager.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler,
    true);}
    protected function mouseMoveHandler(event:MouseEvent):void {event.stopImmediatePropagation();
    if (resizingElement.height + event.stageY - initY > 49) {myAC[itemID].Height = myAC[itemID].Height + event.stageY - initY;
    resizingElement.height = resizingElement.height + event.stageY - initY;
    initY = event.stageY;
    protected function mouseUpHandler(event:MouseEvent):void {cLayout.setLayout();
    this.invalidateDisplayList();systemManager.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler,
    true);systemManager.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler,
    true);}
    ]]>
    </fx:Script>
     <s:layout>
     <myLayout:customLayout id="cLayout" />
     </s:layout>
     </s:DataGroup>
    CustomLayout:
    package 
    myLayout {
     import mx.collections.ArrayCollection; 
    import mx.core.ILayoutElement; 
    import spark.components.DataGroup; 
    import spark.components.supportClasses.GroupBase; 
    import spark.components.supportClasses.ItemRenderer; 
    import spark.layouts.supportClasses.LayoutBase; 
    public class customLayout extends LayoutBase { 
    public var layoutTarget:GroupBase; 
    public var count:int; 
    public var dataProvider:ArrayCollection; 
    public var maxHeight:Number = 0; 
    public var maxWidth:Number; 
    public var x:Number; 
    public var y:Number; 
    public function setLayout():void {layoutTarget =
    this.target;dataProvider = ArrayCollection(DataGroup(target).dataProvider);
    count = layoutTarget.numElements;
    dataProvider.source.sortOn([
    "Height"], [Array.NUMERIC | Array.DESCENDING]); 
    if (dataProvider[0].Height > dataProvider[1].Height) {dataProvider[0].xPos = 0;
    dataProvider[1].xPos = 60;
    else if (dataProvider[1].Height > dataProvider[0].Height) {dataProvider[1].xPos = 0;
    dataProvider[0].xPos = 60;
    override public function updateDisplayList(containerWidth:Number, containerHeight:Number):void {  
    for (var ii:int = 0; ii < count; ii++) { 
    // get the current element, we're going to work with the 
    // ILayoutElement interface 
    var element:ILayoutElement = layoutTarget.getElementAt(ii); 
    var item:ItemRenderer = target.getElementAt(ii) as ItemRenderer; 
    // Resize the element to its preferred size by passing 
    // NaN for the width and height constraintselement.setLayoutBoundsSize(NaN, NaN);
    // Find out the element's dimensions sizes. 
    // We do this after the element has been already resized 
    // to its preferred size. 
    var elementWidth:Number = element.getLayoutBoundsWidth(); 
    var elementHeight:Number = element.getLayoutBoundsHeight();item.uid = String(ii);
    y = 0;
    x = dataProvider[ii].xPos;
    // Find maximum element extents. This is needed for 
    // the scrolling support.maxWidth = 50;
    maxHeight = dataProvider[ii].Height;
    // Position the elementelement.setLayoutBoundsPosition(x, y);
    element.setLayoutBoundsSize(maxWidth, maxHeight);
    // Scrolling support - update the content sizelayoutTarget.setContentSize(maxWidth, maxHeight);
    ItemRenderer:
    <?xml version="1.0" encoding="utf-8"?><s:ItemRenderer focusEnabled="false" xmlns:fx="
    http://ns.adobe.com/mxml/2009" xmlns:s="
    library://ns.adobe.com/flex/spark"height="
    100%" width="100%" alpha="1.0" buttonMode="true" useHandCursor="
    true" xmlns:mx="library://ns.adobe.com/flex/halo"mouseOut="mouseOutHandler(event)"
    mouseMove="mouseMoveHandler(event);"
    mouseDown="mouseDownHandler(event);"
    name="
    iRenderer" depth="1" xmlns:ns="library://ns.adobe.com/flex/mx">
     <s:states>
     <s:State name="State1"/>
     <s:State name="modify"/>
     </s:states> 
    <fx:Script>
    <![CDATA[
     import mx.core.DragSource; 
    import mx.managers.CursorManager; 
    import mx.managers.DragManager; 
    Embed(source="images/reSize.gif")]  
    public var reSize:Class; 
    public static const RESIZE_CLICK:String = "resizeClick"; 
    private function mouseDownHandler(event:MouseEvent):void { 
    if (event.localY >= (this.height - 10) && event.localY <= this.height && event.currentTarget.name == 'iRenderer') {CursorManager.setCursor(reSize, 0, 0, -8);
    var rbEvent:MouseEvent = new MouseEvent(RESIZE_CLICK, true);rbEvent.localX = event.stageX;
    rbEvent.localY = event.stageY;
    dispatchEvent(rbEvent);
    private function mouseOutHandler(event:MouseEvent):void { 
    if (event.buttonDown == false) {CursorManager.removeAllCursors();
    private function mouseMoveHandler(event:MouseEvent):void { 
    var target:String = event.currentTarget.toString(); 
    var target2:String = event.target.toString(); 
    if (event.buttonDown == true && event.currentTarget.name == 'iRenderer' && event.localY < (this.height - 10)) { 
    var dragInitiator:ItemRenderer = ItemRenderer(event.currentTarget); 
    var ds:DragSource = new DragSource();DragManager.doDrag(dragInitiator, ds, event);
    else if (event.localY >= (this.height - 10) && event.localY <= this.height && event.currentTarget.name == 'iRenderer') {CursorManager.setCursor(reSize, 0, 0, -8);
    else {CursorManager.removeAllCursors();
    ]]>
    </fx:Script>
     <s:SkinnableContainer id="apPanel" top="0" bottom="0" left="0" right="0" >
     <!-- layer 1: border -->
     <s:Rect left="0" right="0" top="0" bottom="0">
     <s:stroke>
     <s:SolidColorStroke color="#5E7788" alpha="1.0" weight="2" />
     </s:stroke>
     </s:Rect>
     <!-- layer 2: background fill -->
     <s:Rect id="background" left="1" top="1" right="1" bottom="1">
     <s:fill>
     <s:SolidColor color="0x5E7788" id="bgFill" alpha="1.0" />
     </s:fill>
     </s:Rect>
     <!-- layer 3: title bar fill -->
     <s:Rect left="2" right="2" top="2" height.State1="15" height.modify="30">
     <s:fill>
     <s:SolidColor color="white" alpha="1.0"/>
     </s:fill>
     </s:Rect>
     <s:Label id="titleDisplay" text="{data.Label}" top="3" left="2" right="2" height="15" verticalAlign="middle" fontWeight="bold" includeIn="State1" fontSize="10"/>
     </s:SkinnableContainer>
     </s:ItemRenderer> 

    DataGroup and SkinnableDataContainer do have all the necessary drag events, so I should be able to use them for manual drag & drop. I actually do think this could be a bug. However, I found an odd workaround. If I add a mouseOver event that does absolutely nothing, then it appears that I can drag and drop without issue. See following code:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"xmlns:s="library://ns.adobe.com/flex/spark"xmlns:mx="library://ns.adobe.com/flex/mx"height="100%" width="100%" xmlns:ns1="*">
    <fx:Script><![CDATA[
    import mx.events.DragEvent;import mx.managers.DragManager; 
    import spark.components.DataGroup; 
    private function dragEnterHandler(event:Event):void {trace ("Drag Enter");trace (event.currentTarget.id);DragManager.acceptDragDrop(DataGroup(event.currentTarget));
    private function mouseOverHandler(event:MouseEvent):void {//Without this function added, drag & drop stops working.
    private function dragDropHandler(event:DragEvent):void {trace ("Drag Drop");trace (" Target: "+event.currentTarget.id);trace (" y: "+event.localY);}
    ]]>
    </fx:Script>
    <ns1:myDataGroup id="dgOne" left="5" top="5" width="200" bottom="5" dragEnter="dragEnterHandler(event);" mouseOver="mouseOverHandler(event)" dragDrop="dragDropHandler(event)" /><ns1:myDataGroup id="dgTwo" left="220" top="5" width="200" bottom="5" dragEnter="dragEnterHandler(event);" mouseOver="mouseOverHandler(event)" dragDrop="dragDropHandler(event)" /><mx:VRule left="210" top="0" bottom="0" /></s:Application>

  • Calling an array of childSymbols created in compositionReady

    Hi, I'm creating a little puzzle game for fun, I've created a symbol and this is cloned into an array with createChildSymbol 9 times (3x3 puzzle) in document.compositionReady event of Stage. Every element of array store data of id, row, and column.
    Then the first, I need to declare by code click function for each element of array or is enough with primary click event of parentSymbol? if is necessary how it's made?
    Once this, how I access to this array when user click on any childSymbol for get data stored? how do I know which childSymbol (of nine symbols) has been clicked?
    Thank you very much.

    Hi, Xoco.
    In the case of Edge Animate symbol, I think "declare each elem" is better.
    like this,
    //params
    var cells = [];
    var CELL_SIZE = 100;
    var CELL_PADDING = 10;
    var cellPrefixID = "cell_";
    var ROWS = COLUMNS = 3;
    var baseElem = sym.$("baseElem");  //parent element, if you use symbol:sym.$("baseElem").getSymbolElement();
    var size = CELL_SIZE + CELL_PADDING;
    //create child syms
    for(var i=0;i<9;i++){
      var cell = sym.createChildSymbol("Cell",baseElem);  //create child sym from sym named "Cell"
      var $cell = cell.getSymbolElement();
      $cell.css({
          position:"absolute",
          top:i%ROWS*size,
          left:(i/COLUMNS|0)*size
        .attr("id",cellPrefixID+i)  //add ID(as you like)
        .data("index",i)            //add index(as you like)
        .click(onClickCell);        //add click event handler every symbol.getSymbolElement()
      cells.push(cell);
    //event handler method for every child symbol
    function onClickCell(evt){
      //use "this" or "evt.currentTarget" for access to cell.
      console.log("id:",$(this).attr("id"));  //get @id
      console.log("index:",$(this).data("index")); //get data(index)
      console.log("sym from cells:",cells[$(this).data("index")]); //get symbol from array by data(index)
      cells[$(this).data("index")].play(0); //control symbol
    thanks.
    Ume.

  • MP3 Ios External or Internal?

    I have a Flash movie that plays MP3 files on a button click using this:
    function btnClick2(event:MouseEvent):void {
    //SoundMixer.stopAll();
    var mySound:Sound = new Sound();
    mySound.load(new URLRequest("MP3s/name.mp3"));
    mySound.play();
    It works fine in publish preview, and it will work once published to the IPhone but it seems intermittant. It will not always play for each click. Sometimes double press. Just strange results.
    Am I better for IOs actually playing it from the local library (some how)?
    Or is there a better way to get this to work?
    Thanks for your help!

    Hi - This should show the library files. Underneath the screen grab I have put the original code modified and working with mouse down. This is already a lot more reactive in IOs, so your new way we are looking at will just be a bonus
    This works fine and now using MOUSE_DOWN is a lot better in IOS:
    function btnClick2(event:MouseEvent):void {
    var C:Class=Class(getDefinitionByName(event.currentTarget.name+"_mp3"));
    var c:Sound = new C();
    c.play();
    PlayAMajor.addEventListener(MouseEvent.MOUSE_DOWN, btnClick2);
    PlayBMajor.addEventListener(MouseEvent.MOUSE_DOWN, btnClick2);
    New way that causes the error:
    var C:Class;
    var e:Class;
    var buttonA:Array = [AString,BString];
    for(var i:int=0;i<buttonA.length;i++){
    C = Class(getDefinitionByName(buttonA[i].name+"_mp3"));
    this["sound_"+buttonA[i].name]=new C();
    function btnClick2(event:MouseEvent):void {
    this["sound_"+e.currentTarget.name].play();
    AString.addEventListener(MouseEvent.MOUSE_DOWN, btnClick2);
    BString.addEventListener(MouseEvent.MOUSE_DOWN, btnClick2);

  • TotalFrames of dynamically loaded swf

    I've been trying for 2 days now to find the total number of frames of a dynamically loaded .swf.
    Here's an example code:
    var loader:Loader = new Loader;
    loader.load(new URLRequest("mop.swf"))
    master_mc.addChild(loader);
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, xmlLoadedF);
    function xmlLoadedF(event:Event):void
        trace(loader.content.totalFrames);
    I am truly puzzled.
    Any help would be greatly appreciated.

    I think this might be complicated by loading an AS2 movie into an AS3 document.
    The error message is telling you that there is no totalFrames property and in fact AS2 movies would have a _totalframes property.
    So you could try that.
    Also I'm not sure if event.currentTarget.content returns a MovieClip or a DisplayObject. If it is a DisplayObject (which is most likely) then it too wouldn't have  totalFrames property. So you might need to cast it as a MovieClip. Something like this:
    MovieClip(event.currentTarget.content).totalFrames
    And or it could be some combination of these two above issues? I don't know really, I'm just grasping at straws. But I don't see any way to know when a clip is done playing other than to compare its currentFrame to totalFrames.

  • A better way to do this -- add/remove multiple childs

    I have 6 movieClips on stage.  When I roll over any one of them, I want to:
    A) removeChild the remaining 5 movieClips and then
    B) bring a new movieClip onto stage that would hold a description and possible button links
    Upon rollOut, I want to fire a 3 second delay, removeChild the description movieClip and then addChild the original 5 (removed) movieClips.
    Make sense?
    I started typing away and came to the impression that I might be going about this the LONG way.  Any shorter/smarter ideas would be appreciated.
    Here's the code:
    package{
        import flash.display.*;
        import flash.events.*;
        public class mainAS extends MovieClip{
            public var backgroundImage:imageMap2_mc = new imageMap2_mc();
            public var holder1:holder_mc = new holder_mc();
            public var holder2:holder_mc = new holder_mc();
            public var holder3:holder_mc = new holder_mc();
            public var holder4:holder_mc = new holder_mc();
            public var holder5:holder_mc = new holder_mc();
            public var holder6:holder_mc = new holder_mc();
            public function mainAS():void{
                //background image
                backgroundImage.x = 0;
                backgroundImage.y = 0;
                addChild(backgroundImage);
                // holder 1
                holder1.x = 50;
                holder1.y = 30;
                addChild(holder1);
                holder1.addEventListener(MouseEvent.ROLL_OVER, holder1Fire)
                // holder 2
                holder2.x = 250;
                holder2.y = 30;
                addChild(holder2);
                holder2.addEventListener(MouseEvent.ROLL_OVER, holder2Fire)
                // holder 3
                holder3.x = 450;
                holder3.y = 30;
                addChild(holder3);
                holder3.addEventListener(MouseEvent.ROLL_OVER, holder3Fire)
                // holder 4
                holder4.x = 50;
                holder4.y = 225;
                addChild(holder4);
                holder4.addEventListener(MouseEvent.ROLL_OVER, holder4Fire)
                // holder 5
                holder5.x = 250;
                holder5.y = 225;
                addChild(holder5);
                holder5.addEventListener(MouseEvent.ROLL_OVER, holder5Fire)
                // holder 6
                holder6.x = 450;
                holder6.y = 225;
                addChild(holder6);
                holder6.addEventListener(MouseEvent.ROLL_OVER, holder6Fire)
            //Fire away
            private function holder1Fire(e:Event):void{
                trace("holder 1");
                //removeChild all remaining
               //addChild description MovieClip
              // description_mc.addEventListner(function to include rollOff Listener -- fire timer -- remove description + add original mc's)
            private function holder2Fire(e:Event):void{
                trace("holder 2");
                //removeChild
            private function holder3Fire(e:Event):void{
                trace("holder 3");
                //removeChild
            private function holder4Fire(e:Event):void{
                trace("holder 4");
                //removeChild
            private function holder5Fire(e:Event):void{
                trace("holder 5");
                //removeChild
            private function holder6Fire(e:Event):void{
                trace("holder 6");
                //removeChild

    If the main reason for adding and removing is so that only one is visible, then you can just use the visible property along with a reduction in code.  Here's a few thoughts along those lines, though not the whole deal...
    Create a function that turns all of the object visible/invisible using a loop...
    function showAll(truefalse:Boolean){
         for(var i=1; i<7; i++){
              this["holder"+String(i)].visible = truefalse;
    Then have all your object share the same rollover function....
    holder1.addEventListener(MouseEvent.ROLL_OVER, clickHolder);
    holder2.addEventListener(MouseEvent.ROLL_OVER, clickHolder);
    holder3.addEventListener(MouseEvent.ROLL_OVER, clickHolder);
    etc...
    function clickHolder(evt:MouseEvent):void {
         showAll(false);  // hide all first
         evt.currentTarget.visible = true;  // show the one being hovered
         // store the name of the description mc with the clip and call it...
         this[evt.currentTarget.desc].visible = true;

  • I need help to get this working I can't get anything to load in my SWF.

    // drop shadow filter class import
    import flash.filters.DropShadowFilter;
    // transitions imports
    import fl.transitions.*;
    import fl.transitions.easing.*;
    // Determine where on the stage we want to have the thumbnail images start
    xStartPos = 40;
    yStartPos = 20;
    // Create our XML object
    var imageList:XML;
    // Setup our XML loader and tell it the file path to our XML file.
    // Also, add an event listener to call the loadComplete() function
    // when the loading of our XML file is complete.
    var xmlURLLoader:URLLoader = new URLLoader();
    xmlURLLoader.load(new URLRequest(xmlURLRequest("loadImages.xml")));
    xmlURLLoader.addEventListener(Event.COMPLETE, loadComplete);
    function loadComplete(e:Event):void
    try {
      // Build new instance of XML object (imageList) and copy into
      // it the data from e.target which is the xml_loader object (which
      // contains the data loaded from our XML file).
      var imageList:XML = new XML(e.target.data);
      // Grab all of the file_type elements (tags) from our imageList
      // XML object (which now contains all of the data from our XML file)
      // and store them in an XMLList object (somewhat like an array).
      var imageList:XMLList = imageList.file_type;  // our image file locations
      var imageArray:Array = new Array();
      var i:int = 0;
      numImages = xml.ImageList.length;
      // Place all of our image filenames into our imageArray by
      // stepping through the xmlImageList XMLList object one element at a time
      for (i = 0; i < numImages; i++)
       // push the filename text from each element of our XMLList object
       // (xmlImageList), which contains all the file_type elements (tags)
       // from our XML file, onto our array one element at a time.
       // Note: we created a property called our_source in our imageArray
       //       which we will access again in function stageImages().
       imageArray.push({our_source:xmlImageList[i].text()});
      // Call stageImages() function which will put the images on the stage
      stageImages(imageArray);
    catch (error:Error)
      // ignore errors for now - could put trace() statements here
    }  // end function loadComplete()
    function stageImages(imgArray:Array):void
    // Build a loop that creates the image movie clips and puts them on the stage.
    // When we say the image movie clips we really mean the movie clips that hold
    // the images.
    for (var i:int = 0; i < imgArray.length; i++)
      // Begin the image loader
      var imgLoader:Loader = new Loader();
      imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoadCompletes);
      // Reference our image array
      imgLoader.load(new URLRequest(imgArray[i].our_source));
      // Create a movie clip called pic_mc which is the instance name
      // of ALL of our images.  This will allow us to apply effects like
      // drop shadows or whatever we want to our image movie clip instances
      // all at once.
      var pics_mc:MovieClip = new MovieClip();
      // Now, tell our movie clips what their x and y positions will be
      pics_mc.x = xStartPos;
      pics_mc.y = yStartPos;
      // Add the just-added image movie clip as a child of our pics_mc movie clip.
      //     So, another way of saying it is we are throwing each loaded image
      //     movie clip inside our pics_mc movie clip as we load each image in the loop.
      // imgLoader is an array of images (our entire list of images) and it is
      // being loaded here INTO our pic_mc movie clip AS A CHILD.
      pics_mc.addChild(imgLoader);   // pics_mc is a container for our images
      // Here is how we set the number of columns for our thumbnails (based
      // on 7 columns).  CHANGE THE 7 TO HAVE DIFFERENT NUMBER OF COLUMNS
      if (((i + 1) % 7) == 0)
       // Let's set the x and y positions...
       // This is how we separate the amount of space we want in between
       // images as they slide out or stack up.  Change these values if you
       // wish to have more or less columns.
       xStartPos = 10;    // CHANGING THIS VALUE WILL PUSH THE COLUMNS LEFT/RIGHT
       yStartPos += 40;   // CHANGING THIS VALUE WILL ALTER VERTICAL SPACING OF PICS
      else
       // CHANGE THE 100 TO DRAMATICALLY CHANGE WIDTH BETWEEN COLUMNS
       // AND THE 46 TO CREATE MORE SUBTLE DISTANCE BETWEEN COLUMNS
       xStartPos += 100 + 46;
    }  // end function stageImages()
    // Define what happens once our images are loaded...
    function imgLoadCompletes(e:Event)
    // Get access to our image loader object we were using when this
    // function was called.
    // Type-cast e.currentTarget (our imgLoader object from above) as
    // a LoaderInfo object and access its loader property which is the
    // loader object associated with this LoaderInfo object (in our case
    // the imgLoader object which the event listener was listening on above
    // in the stageImages() function).
    // We are now calling it by the name image_loader.
    var image_loader:Loader = e.currentTarget as Loader;
    // Access the parent movie clip of our image loader object.  We called this
    // pics_mc above in the stageImages() function.
    var pics_mc:MovieClip = image_loader.parent;
    // Begin our fill and drawing of graphics - the Polaroid Effect - did this LATER
    var imgWidth:Number = image_loader.width;
    var imgHeight:Number = image_loader.height;
    var spacingFillWidth:Number = 15;
    var totalSpacing:Number = spacingFillWidth;
    var totalSpacingFillWidth:Number = imgWidth + (totalSpacing * 2);
    var totalSpacingFillHeight:Number = imgHeight + (totalSpacing * 2);
    // TRY THIS and then COMMENT IT OUT as we'll be using drop shadow rather than stroke
    // Set a stroke width value and place a stroke around our parent_mc movie clip
    //var strokeWidth:Number = 1;
    //parent_mc.graphics.lineStyle(strokeWidth, 0x000066, 100);
    // Begin drawing art for the fill
    pics_mc.graphics.beginFill(0xCCCCCC, 100);
    // Draw rectangle (add 100 to height to get Polaroid background look)
    pics_mc.graphics.drawRect(-totalSpacing, -totalSpacing, totalSpacingFillWidth, totalSpacingFillHeight + 100);
    // End fill
    pics_mc.graphics.endFill();
    // Create drop shadow instance (shadow) and set its parameters (same as
    // you would if you were manually adding a drop shadow filter
    // DO THIS AFTER COMMENTING OUT STROKE LINESTYLE ABOVE!
    var shadow:DropShadowFilter = new DropShadowFilter();
    shadow.alpha = .5;      // alpha of 50%
    shadow.distance = 15;   // distance of drop shadow from movie clip
    shadow.angle = 90;
    shadow.blurX = 15;
    shadow.blurY = 15;
    // Apply our drop shadow to our movie clip
    pics_mc.filters = [shadow];
    // Scale the image clips down as thumbnails for the initial display of
    // images on the stage.  Set this according to your own image sizes
    pics_mc.scaleX = .05;
    pics_mc.scaleY = .4;
    // optional - rotate our fake_mc movie clip in a random fashion.
    // CAN PLAY WITH THE  3 TO ALTER ROTATION
    pics_mc.rotation = Math.round(Math.random() * - 10) + 3;
    // set up dummy placeholder properties to hold a copy of our
    // x and y position values.
    pics_mc.origX = pics_mc.x;
    pics_mc.origY = pics_mc.y;
    pics_mc.addEventListener(MouseEvent.MOUSE_DOWN, onMouseClick);
    pics_mc.addEventListener(MouseEvent.MOUSE_UP, onMouseRelease);
    }  // end function imgLoadCompletes()
    // Called if user clicks on one of the thumbnail images
    function onMouseClick(e:MouseEvent):void
    // Make each separate movie clip its own target
    var thumb_mc:MovieClip = e.currentTarget as MovieClip;  // cast it as a MovieClip object
    // Expand thumbnail that was clicked so it scales to full size
    thumb_mc.scaleX = 1;     // note 1 = 100% for scaling in AS 3.0
    thumb_mc.scaleY = 1;
    // Last thumbnail image clicked on will be on top -- this part is optional
    // Each item on stage has a childIndex number which defines its depth (z-axis)
    // in the stacking order of items on the stage (or within another object).  The
    // higher the childIndex number of an object the closer the object will be to the front.
    // numChildren is a property that contains the number of children in an object (in
    // our case the stage).
    setChildIndex(thumb_mc, numChildren - 1);
    // Set location of thumbnail image on the stage.  Note that these
    // values are based on the bottom of where our images line up and
    // our stage dimensions of 1000x700.
    thumb_mc.x = 250;
    thumb_mc.y = 250;
    // Set transitions once thumbnail images are clicked
    //var showImage:Object = {type:Fade, direction:0, duration:1, easing:Strong.easeOut};
    // Blinds has a problem letting us select larger image and move it back to thumbnail
    //var showImage:Object = {type:Blinds, direction:0, duration:1, easing:Strong.easeOut};
    // PixelDissolve doesn't always allow us to easily select larger image either
    //var showImage:Object = {type:PixelDissolve, direction:0, duration:1, easing:Strong.easeOut, xSections:30, ySections:30};
    var showImage:Object = (type:Photo, direction:Transition.IN, duration:1, easing:Strong.easeOut);
    TransitionManager.start(thumb_mc, showImage);
    // For more info on Transitions, search for Transition class in Help docs
    }  // end function onMouseClick()
    function onMouseRelease(e:MouseEvent):void
    // Get reference to the larger image that was "moused up" on.
    var big_mc:MovieClip = e.currentTarget as MovieClip;
    // Tell the image to return to its starting location as a thumbnail image
    big_mc.x = int(big_mc.origX);   // Typecast origX and origY properties to int
    big_mc.y = int(big_mc.origY);
    // Scale the larger image back down to thumbnail image
    big_mc.scaleX = 0.2;
    big_mc.scaleY = 0.2;
    }  // end function onMouseRelease()

    Here it is without comments.  No didnt do any tracing.  I only get one error saying Scene 1, Layer 'Actions', Frame 1, Line 236 1084: Syntax error: expecting rightparen before colon.  I know there has to be more wrong with the code please help me find them.
    import flash.filters.DropShadowFilter;
    import fl.transitions.*;
    import fl.transitions.easing.*;
    xStartPos = 40;
    yStartPos = 20;
    var imageList:XML;
    var xmlURLLoader:URLLoader = new URLLoader();
    xmlURLLoader.load(new URLRequest(xmlURLRequest("loadImages.xml")));
    xmlURLLoader.addEventListener(Event.COMPLETE, loadComplete);
    function loadComplete(e:Event):void
    try {
      var imageList:XML = new XML(e.target.data);
      var imageList:XMLList = imageList.file_type;
      var imageArray:Array = new Array();
      var i:int = 0;
      numImages = xml.ImageList.length;
      for (i = 0; i < numImages; i++)
       imageArray.push({our_source:xmlImageList[i].text()});
        stageImages(imageArray);
    catch (error:Error)
    }  // end function loadComplete()
    function stageImages(imgArray:Array):void
    for (var i:int = 0; i < imgArray.length; i++)
      var imgLoader:Loader = new Loader();
      imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoadCompletes);
      imgLoader.load(new URLRequest(imgArray[i].our_source));
      pics_mc.x = xStartPos;
      pics_mc.y = yStartPos;
      pics_mc.addChild(imgLoader);
      if (((i + 1) % 7) == 0)
       xStartPos = 10;
       yStartPos += 40;
      else
       xStartPos += 100 + 46;
    }  // end function stageImages()
    function imgLoadCompletes(e:Event)
    var image_loader:Loader = e.currentTarget as Loader;
    var pics_mc:MovieClip = image_loader.parent;
    var imgWidth:Number = image_loader.width;
    var imgHeight:Number = image_loader.height;
    var spacingFillWidth:Number = 15;
    var totalSpacing:Number = spacingFillWidth;
    var totalSpacingFillWidth:Number = imgWidth + (totalSpacing * 2);
    var totalSpacingFillHeight:Number = imgHeight + (totalSpacing * 2);
    pics_mc.graphics.beginFill(0xCCCCCC, 100);
    pics_mc.graphics.drawRect(-totalSpacing, -totalSpacing, totalSpacingFillWidth, totalSpacingFillHeight + 100);
    pics_mc.graphics.endFill();
    var shadow:DropShadowFilter = new DropShadowFilter();
    shadow.alpha = .5;
    shadow.distance = 15;
    shadow.angle = 90;
    shadow.blurX = 15;
    shadow.blurY = 15;
    pics_mc.filters = [shadow];
    pics_mc.scaleX = .05;
    pics_mc.scaleY = .4;
    pics_mc.rotation = Math.round(Math.random() * - 10) + 3;
    pics_mc.origX = pics_mc.x;
    pics_mc.origY = pics_mc.y;
    pics_mc.addEventListener(MouseEvent.MOUSE_DOWN, onMouseClick);
    pics_mc.addEventListener(MouseEvent.MOUSE_UP, onMouseRelease);
    function onMouseClick(e:MouseEvent):void
    var thumb_mc:MovieClip = e.currentTarget as MovieClip;
    thumb_mc.scaleX = 1;
    thumb_mc.scaleY = 1;
    setChildIndex(thumb_mc, numChildren - 1);
    thumb_mc.x = 250;
    thumb_mc.y = 250;
    var showImage:Object = (type:Photo, direction:Transition.IN, duration:1, easing:Strong.easeOut);
    TransitionManager.start(thumb_mc, showImage);
    }  // end function onMouseClick()
    function onMouseRelease(e:MouseEvent):void
    var big_mc:MovieClip = e.currentTarget as MovieClip;
    big_mc.x = int(big_mc.origX);
    big_mc.y = int(big_mc.origY);

  • What's wrong with this code (AS3)?

    I want to publish a live stream and, when a button is pressed, publish the same stream for vod.  I haven't been able to get an answer as to whether I can do this...my code is below.  Can someone please tell me if I can do this, or what may be wrong with my code?
    The live stream and playback works fine; but the recording doesn't start.  Also, I want other objects on the client, such as the current camera and audio information, and the aspect ratio being used.  I havent' been able to get these to show up (i.e., the incomingLbl and outgoingLbl do not show up).
    Thank you,
    Phillip A
    My code:
    package {
        import flash.display.MovieClip;
        import flash.net.NetConnection;
        import flash.events.NetStatusEvent; 
        import flash.events.MouseEvent;
        import flash.events.AsyncErrorEvent;
        import flash.net.NetStream;
        import flash.media.Video;
        import flash.media.Camera;
        import flash.media.Microphone;
        import fl.controls.Button;
        import fl.controls.Label;
        import fl.controls.TextArea;
        import fl.controls.CheckBox;
        public class vodcast1 extends MovieClip {
            private var nc:NetConnection;
            private var nc2:NetConnection;
            private var ns:NetStream;
            private var ns2:NetStream;
            private var nsPlayer:NetStream;
            private var vid:Video;
            private var vidPlayer:Video;
            private var cam:Camera;
            private var mic:Microphone;
            private var camr:Camera;
            private var micr:Microphone;
            private var clearBtn:Button;
            private var startRecordBtn:Button;
            private var outgoingLbl:Label;
            private var incomingLbl:Label;
            private var myMetadata:Object;
            private var outputWindow:TextArea;
            private var cb1:CheckBox;
            public function vodcast1(){
                setupUI();
                nc = new NetConnection();
                nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                nc.connect("rtmp://localhost/publishLive");
                nc2 = new NetConnection();
                nc2.connect("rtmp://localhost/vod/videos");
                nc2.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus2);
            private function startRecordHandler(event:MouseEvent):void {
                publishRecordStream();
            private function onNetStatus(event:NetStatusEvent):void {
                trace(event.target + ": " + event.info.code);
                switch (event.info.code)
                    case "NetConnection.Connect.Success":
                        trace("Congratulations! you're connected to live");
                        publishCamera();
                        displayPublishingVideo();
                        displayPlaybackVideo();
                        break;
                    case "NetStream.Publish.Start":
            // NetStatus handler for Record stream       
            private function onNetStatus2(event:NetStatusEvent):void {
                trace(event.target + ": " + event.info.code);
                switch (event.info.code)
                    case "NetConnection.Connect.Success":
                        trace("Congratulations! you're connected to vod");                   
                        break;
                    case "NetConnection.Connect.Rejected":
                    case "NetConnection.Connect.Failed":
                    trace ("Oops! the connection was rejected");
                        break;
                    case "NetStream.Publish.Start":
                        sendMetadata();
                        break;
            private function asyncErrorHandler(event:AsyncErrorEvent):void {
                trace(event.text);
            private function sendMetadata():void {
                trace("sendMetaData() called")
                myMetadata = new Object();
                myMetadata.customProp = "Recording in progress";
                ns.send("@setDataFrame", "onMetaData", myMetadata);
            private function publishRecordStream():void {
                camr = Camera.getCamera();
                micr = Microphone.getMicrophone();
                ns2 = new NetStream(nc2);
                ns2.client = new Object();
                ns2.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus2);
                ns2.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                ns2.attachCamera(camr);
                ns2.attachAudio(micr);
                ns2.publish("vodstream", "record");           
            private function publishCamera():void {
                cam = Camera.getCamera();
                mic = Microphone.getMicrophone();
                ns = new NetStream(nc);
                ns.client = this;
                ns.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                ns.attachCamera(cam);
                ns.attachAudio(mic);
                ns.publish("livestream", "live");
            private function displayPublishingVideo():void {
                vid = new Video(cam.width, cam.height);
                vid.x = 10;
                vid.y = 30;
                vid.attachCamera(cam);
                addChild(vid); 
            private function displayPlaybackVideo():void {
                nsPlayer = new NetStream(nc);
                nsPlayer.client = this;
                nsPlayer.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
                nsPlayer.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
                nsPlayer.play("livestream");
                vidPlayer = new Video(cam.width, cam.height);
                vidPlayer.x = cam.width + 100;
                vidPlayer.y = 30;
                vidPlayer.attachNetStream(nsPlayer);
                addChild(vidPlayer);
            private function setupUI():void {
                outputWindow = new TextArea();
                outputWindow.move(250, 175);
                outputWindow.width = 200;
                outputWindow.height = 50;
                outgoingLbl = new Label();
                incomingLbl = new Label();
                outgoingLbl.width = 100;
                incomingLbl.width = 100;
                outgoingLbl.text = "Publishing Stream";
                incomingLbl.text = "Playback Stream";
                outgoingLbl.move(20, 200);
                incomingLbl.move(300, 200);
                outgoingLbl.condenseWhite = true;
                incomingLbl.condenseWhite = true;
                startRecordBtn = new Button();
                startRecordBtn.width = 150;
                startRecordBtn.move(250, 345);
                startRecordBtn.label = "Start Recording";
                startRecordBtn.addEventListener(MouseEvent.CLICK, startRecordHandler);
                //cb1 = new CheckBox();
                //cb1.label = "Record";
                //cb1.move(135,300);
                //cb1.addEventListener(MouseEvent.CLICK,publishRecordStream);
                //clearBtn = new Button();
    //            clearBtn.width = 100;
    //            clearBtn.move(135,345);
    //            clearBtn.label = "Clear Metadata";
    //            clearBtn.addEventListener(MouseEvent.CLICK, clearHandler);
                addChild(outgoingLbl);
                addChild(incomingLbl);
    //            addChild(clearBtn);
                addChild(startRecordBtn);
    //            addChild(cb1);
                addChild(outputWindow);
            public function onMetaData(info:Object):void {
                outputWindow.appendText(info.customProp);

    use event.currentTarget (and you don't need to repeatedly define the same function):
    var c:int;
    var buttonName:String;
    for (c = 1;c < 5;c++) {
         buttonNum = "button"+c;
         this[buttonNum].addEventListener(MouseEvent.MOUSE_DOWN, pressStepButton);
    function pressStepButton(event:MouseEvent) {          trace(event.currentTarget,event.currentTarget.name);     }

Maybe you are looking for