Adobe/Apache Flex: Modify View in an ActionScript class

66 views Asked by At

I have a WindowedApplication in Apache/Adobe Flex 4 which currently consists of one view (the view defined in the WindowedApplication MXML).

In that application I have an object which listens to data coming from a network. When data is available a method is called on that object and it shall update my view by changing the text of a label.

I do not have a reference to the view in the network listener object though. How can I get it?

This is part of my MXML where I define my view.

<fx:Script source="./ViewCodeBehind.as"/>

<!-- ommited stuff -->

<s:Label id="errorLabel"
    text=""
    fontSize="14"/>

<!-- Stuff in between -->

<s:Button label="Get Status" 
        click="getStatus();"/>

The code which is called when the button is clicked:

public function getStatus(): void 
{
    var networkGateway: NetworkGateway = new NetworkGatewayImpl();
    networkGateway.getConnectionStatus();
}

And the NetworkGatewayImpl

public class NetworkGatewayImpl implements NetworkGateway
{
    public function NetworkGatewayImpl()
    {
    }

    public function getConnectionStatus(): void
    {
        // Start asynchronous network call
        // when error occurs onNetworkError() is called
    }

    private function onNetworkError(): void
    {
        // Set "errorLabel" here: How?
    }
}

Essentially I want to know some ways to update "errorLabel" from the NetworkGatewayImpl.

1

There are 1 answers

2
Gurtej Singh On BEST ANSWER

Based on your code, there could be multiple ways to solve this. Easiest way (as per me) would be to dispatch an event from the NetworkGatewayImpl class and listen to it on the instance you have created in the view class. So sample code would look like this:

public function getStatus(): void 
{
    var networkGateway: NetworkGateway = new NetworkGatewayImpl();
    networkGateway.addEventListener("networkError", onNetworkError);
    networkGateway.getConnectionStatus();
}

private function onNetworkError(e:Event):void
{
    networkGateway.removeEventListener("networkError", onNetworkError);
    this.errorLabel.text = "Your Text Here";
}

Dispatch your event like this from your NetworkGatewayImpl class:

private function onNetworkError(): void
{
    this.dispatchEvent("networkError");
}

You will have to ensure that your NetworkGatewayImpl also implements the IEventDispatcher interface to be able to dispatch events.

Also, best practice would be to create a custom Event class (extending the Event class) and use constants instead of the literal 'networkError'

Hope this helps.