views:

678

answers:

3

I have a custom login component in Flex that is a simple form that dispatches a custom LoginEvent when a user click the login button:


<?xml version="1.0" encoding="utf-8"?>
<mx:Form xmlns:mx="http://www.adobe.com/2006/mxml" defaultButton="{btnLogin}">

    <mx:Metadata>
        [Event(name="login",tpye="events.LoginEvent")]
    </mx:Metadata>

    <mx:Script>

        import events.LoginEvent;

        private function _loginEventTrigger():void {
            var t:LoginEvent = new LoginEvent(
                LoginEvent.LOGIN,
                txtUsername.text,
                txtPassword.text);
            dispatchEvent(t);
        }

    </mx:Script>

    <mx:FormItem label="username:">
        <mx:TextInput id="txtUsername" color="black" />
    </mx:FormItem>
    <mx:FormItem label="password:">
        <mx:TextInput id="txtPassword" displayAsPassword="true" />
    </mx:FormItem>
    <mx:FormItem>
        <mx:Button id="btnLogin" 
            label="login" 
            cornerRadius="0" 
            click="_loginEventTrigger()" />
    </mx:FormItem>
</mx:Form>
I then have a main.mxml file that contains the flex application, I add my component to the application without any problem:

<custom:login_form id="cLogin" />

I then try to wire up my event in actionscript:


import events.LoginEvent;
cLogin.addEventListener(LoginEvent.LOGIN,_handler);
private function _handler(event:LoginEvent):void {
    mx.controls.Alert.show("logging in...");
}

Everything looks good to me, but when I compile I get an "error of undefined property cLogin...clearly I have my control with the id "cLogin" but I can't seem to get a"handle to it"...what am I doing wrong?

Thanks.

+1  A: 

ah! I figured it out...it was a big oversight on mine...it's just one of those days...

I couldn't get the handle on my component because it was not yet created...I fixed this by simply waiting for the component's creationComplete event to fire and then add the event listener.

mmattax
A: 

You can also do something like this I believe:

<custom:login_form id='cLogin' login='_handler' />
JustFoo
A: 

You can also do something like this I believe:

<custom:login_form id='cLogin' login='_handler' />

Minor clarification as there seem to be some confusion in the original code.

Indeed and the reason for this is that a metadata tag has been used to declare the event that is to be made available that way.

<mx:Metadata>
    [Event(name="login", type="events.LoginEvent")]
</mx:Metadata>

However, there was no need to add the event metadata when instead of a component "event" property (login='_handler') an event listener was used:

cLogin.addEventListener(LoginEvent.LOGIN,_handler);
  • addEventListener -> no metadata tag needed
  • event property in the component tag -> metadata tag required