Search code examples
stringactionscript-3flashif-statementflash-cs6

Need if-else advice in actionscript3


function clickButtonHandler(event:MouseEvent):void
{
    var message:Object = new Object();
    message.text = txtMessage.text;
    message.userName = txtUser.text;
    //Posts to this swf
    showMessage(message);
    //Posts to ALL OTHER swf files..
    group.post(message);

}

function showMessage(message:Object):void
{
    output_txt.appendText(message.userName+": "+message.text + "\n");

}

function jsalertwindow(event:MouseEvent):void
{
    var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
    navigateToURL(alert, "_self");
}

As you can see there are two function which are contain mouseevent. I want to send those function with an if-else statement. If user write something in text input component which name is txtUser and,

send_btn.addEventListener(MouseEvent.CLICK, clickButtonHandler);

will work, else(if the user forget writing anything)

send_btn.addEventListener(MouseEvent.CLICK, jsalertwindow);

will work. And one more question should i use MouseEvent.CLICK or MouseEvent.MOUSE_DOWN? Thanks for your advice.


Solution

  • Assign a single handler to the button click (MouseEvent.CLICK is the right event to use) and check the field is populated in the handler:

    function clickButtonHandler(event:MouseEvent):void
    {
        var message:Object = new Object();
    
        // Check the field is populated
        if (txtUser.text != "")
        {
            message.text = txtMessage.text;
            message.userName = txtUser.text;
    
            showMessage(message);
            //Posts to ALL OTHER swf files..
            group.post(message);
        } 
        else 
        {
            // Nothing in the input field, show the alert
            showAlert();
        }
    }
    
    function showMessage(message:Object):void
    {
        output_txt.appendText(message.userName+": "+message.text + "\n");
    
    }
    
    function showAlert():void
    {
        var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
        navigateToURL(alert, "_self");
    }