Pregunta

Esto es similar a la pregunta que se hace aquí. Estoy enviando el evento personalizado "shopent" pero estoy recibiendo error "Tipo de coerción fallida: no se puede convertir flash.events::event@81ecb79 a com.events.shopevent"

NOTA: El error se arroja desde el componente personalizado principal (fragmento del tercer código), he agregado más detalles allí

Este es mi evento personalizado. Vea la primera constante, copié el nombre del evento en componentes personalizados.

package com.events
{
    import flash.events.Event;

    public class ShopEvent extends Event
    {

        public static var MENU_SELECTED:String = "menuSelected";
        public static var SUBMENU_SELECTED:String = "submenuSelected";
        public static var ITEM_SELECTED:String = "itemSelected";
        public static var NAV_NEXT:String = "navNext";
        public static var NAV_PREVIOUS:String = "navPrevious";
        public static var NAV_LAST:String = "navLast";
        public static var NAV_FIRST:String = "navFirst";
        public static var CLOSE:String = "close";

        public var menuIdx:int;
        //public var menuType:String;
        public var menuId:int;
        public var menuName:String;
        public var itemId:int;
        public function ShopEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
        {
            super(type, bubbles, cancelable);
        }
    }
}

Componente personalizado. Revise las etiquetas de metadatos. El evento registrado correctamente

<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
         xmlns:s="library://ns.adobe.com/flex/spark" 
         xmlns:mx="library://ns.adobe.com/flex/mx" width="72" height="82"
         mouseChildren="false"
         creationComplete="init()"
         click="onClick()"
         buttonMode="true">
    <s:layout>
        <s:VerticalLayout horizontalAlign="center"/>
    </s:layout>
    <fx:Script>
        <![CDATA[
            import com.events.ShopEvent;

            import mx.controls.Image;
            public var menuId:int;

            [Bindable]
            public var menuText:String;
            [Bindable]
            public var bmp:Bitmap;

            private function init():void{
                //img.addChild(bmp);
            }
            private function onClick():void{
                var e:ShopEvent = new ShopEvent(ShopEvent.MENU_SELECTED);
                e.menuId = menuId;
                e.menuName = menuText;
                dispatchEvent(e);
            }

        ]]>

    </fx:Script>
    <fx:Metadata>
        [Event(name="menuSelected", type="com.events.ShopEvent")]
    </fx:Metadata>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Label text="{menuText}" fontWeight="bold" fontSize="12" width="44"/>
    <mx:Image id = "img" width="57" height="47" source="{bmp}"/>

</s:Group>

Componente personalizado principal. Este es el componente principal del componente personalizado anterior. Escucha el evento menuselado y simplemente enruta el evento a los oyentes. Revise las etiquetas Meatadata. El registro del evento se realiza correctamente.

Sin embargo, el error está llegando a

           menus[i].addEventListener( ShopEvent.MENU_SELECTED,function(e:ShopEvent):void{dispatchEvent(e);});

Con mi conocimiento, no veo ningún problema en el código. ¿Hay algo malo en él?

Actualizar

Sorprendentemente, si creo una "nueva" instancia de ShopWevent, resolverá el problema, Pero lamentablemente, necesito cerrar todas las propiedades del objeto del evento. Espero que esto no sea una limitación de Flex.

                menus[i].addEventListener( ShopEvent.MENU_SELECTED,function(e:ShopEvent):void{dispatchEvent(new ShopEvent(ShopEvent.MENU_SELECTED));});

Código completo

<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" 
         xmlns:s="library://ns.adobe.com/flex/spark" 
         xmlns:mx="library://ns.adobe.com/flex/mx"
         width="720" height="605"
         creationComplete="init()" xmlns:shop="UI.shop.*" xmlns:hasu="UI.shop.hasu.*"
         >
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <fx:Metadata>
        [Event(name="navNext", type="com.events.ShopEvent")]
        [Event(name="navPrevious", type="com.events.ShopEvent")]
        [Event(name="menuSelected", type="com.events.ShopEvent")]
        [Event(name="submenuSelected", type="com.events.ShopEvent")]
        [Event(name="itemSelected", type="com.events.ShopEvent")]
        [Event(name="close", type="com.events.ShopEvent")]
    </fx:Metadata>

    <fx:Script>
        <![CDATA[
            import com.events.ShopEvent;

            private const MAX_SLOTS:int = 6;

            public var menus:Vector.<ShopMenuItemView>;
            public var itemSlots:Vector.<ShopItemSlotView> = new Vector.<ShopItemSlotView>(MAX_SLOTS);

            private function init():void{
                trace("BEGIN:UI.shop.hasu.ShopView.init");
                initSlots();
            }

            private function initSlots():void{

                for (var i:int = 0;i<itemSlots.length;i++){
                     var slot:ShopItemSlotView = new ShopItemSlotView();
                    itemSlots[i] = slot; 
                    itemSlotsContainer.addElement(slot);
                }
            }

            public function initMenus():void{
                trace("BEGIN:UI.shop.hasu.ShopView.initMenus");
                for (var i:int = 0;i < menus.length;i++){
                    menuContainer.addElement(menus[i]);
                    menus[i].addEventListener(ShopEvent.MENU_SELECTED,function(e:ShopEvent):void{dispatchEvent(e);});
                    //menus[i].addEventListener( ShopEvent.MENU_SELECTED,function(e:ShopEvent):void{dispatchEvent(new ShopEvent(ShopEvent.MENU_SELECTED));});
                }
            }



        ]]>
    </fx:Script>

    <s:layout>
        <s:VerticalLayout />
    </s:layout>
    <s:VGroup name="top">
        <hasu:ShopPlayerAttributesView id="attribsComp"/>
        <s:Group id="menuContainer" name="menus">
            <s:layout>
                <s:HorizontalLayout />
            </s:layout>
        </s:Group>
    </s:VGroup>
    <s:Group>
        <s:layout>
            <s:HorizontalLayout />
        </s:layout>
        <s:Button label="&lt;" />
        <s:Group id = "itemSlotsContainer" name="items">
            <s:layout>
                <s:TileLayout requestedColumnCount="3" requestedRowCount="3"/>
            </s:layout>
        </s:Group>
        <s:Button label="&gt;" />
    </s:Group>
</s:Group>
¿Fue útil?

Solución

Debe sobrescribir el método Clone () para clases de eventos personalizados. Los eventos podrían clonarse varias veces durante la propagación.

Otros consejos

La respuesta de Jack es correcta. Se da en la documentación flexible.

Debe anular el método event.clone () en su subclase. El método Clone () devuelve una copia clonada del objeto de evento estableciendo la propiedad de tipo y cualquier propiedad nueva en el clon. Por lo general, define el método Clone () para devolver una instancia de evento creada con el nuevo operador.

Para obtener detalles completos lee Trabajando con eventos por debajo Creación de subclase del evento sección

Un buen lugar para comprender los eventos personalizados para que lean nuevos desarrolladores Flex/AS3 Enviar los eventos personalizados

Nota: Los enlaces apuntan a la documentación Flex 4.6, pero la parte de eventos personalizados no depende de la versión (solo la parte mxml puede diferente para Flex 3 y versiones anteriores)

Debe devolver un nuevo constructor de la clase de evento como:

return new ShopEvent(type,...); //in the clone() method;

los clone() El método devuelve una copia clonada del objeto de evento estableciendo la propiedad de tipo y cualquier propiedad nueva en el clon. Por lo general, define el clone() Método para devolver una instancia de evento creada con el nuevo operador.

El evento que está enviando es de type flash.events.event y el evento que espera su oyente es de type: com.events.shopent.

Esto es simplemente lo que significa el mensaje de error.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top