ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Flex and MVC - Part I
http://www.actionscript.org/resources/articles/751/1/Flex-and-MVC---Part-I/Page1.html
Kapil Viren Ahuja
I still remember the day when I was so much excited to get my hands for the very first time on a computer and I can not believe that it was 12 years ago. The journey since then has been truly wonderful.

Currently, I am with Sapient as an Technical Architect work in J2EE tech stack. Front-ends have been my fort always while I continue to get my head around the services and business. My recent endeavor is in Adobe Flex which I am very excited about. 
By Kapil Viren Ahuja
Published on 12/31/1969
 
This article will explain how to use MVC design pattern in Flex. MVC (Model View Controller) is a very common architectural design pattern in software engineering. It helps in seperating the view with the model and the controller and also introduces a great level of de-coupling while making sure that there is right set of code reuse.

In J2EE world there are frameworks like Struts, JSF that implement MVC in a very effective way. This series of articles will focus on explaining how can you effectively use the MVC design pattern in Flex. In Part I, I will explain the hand-rolled way of usng MVC.


MVC: Introduction
Successful use of Model View Controller (MVC) isolates the business logic from the user interface, resulting in an application which is easier to modify and manage the user interface or the business logic without affecting the other.

Model
Model represents the data for the application.

View
Renders the model in a human readable form called the User Interface

Controller
Holds the business logic that is responsbile for changing the data help in the model

In a typical web application, the the HTML pages (JSP/ASP) form the view, while the model is represented by the data stored in View State/Session/Database. Business Services are used to interact with the model and update the underlying data.

You can find more information on Wikipedia.

Hello Word - the quick and dirty way
For this article, we will try and do the most simple thing "Hello World"

In the following example, we have accepted an input from the user and then said Hello to the user.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Script>
<![CDATA[
import mx.controls.Alert;

// Business Logic
private function clickHandler():void
{
// Model
result.text += personName.text;
}
]]>
</mx:Script>

// View
<mx:TextInput id="personName" />

<mx:Text id="result" text="" />

<mx:Button id="showHello" label="Say Hello" click="clickHandler();"/>
</mx:Application>


What you will notice that in the same file, we have added all the 3 components. The MXML lines hold the view, while the click handles the business logic (in our case it is suffixing the name of the user and saying back hello) and the model that holds the data which is the user name.

You may be thinking why do we need to complicate things? For this example, things may look simple, but as your code starts to grow you will find this pattern very useful.




Creating the view
Let us now create the view which is solely responsible for displaying the data to the user.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
   
    <mx:TextInput id="personName" />
   
    <mx:Text id="res" text="" />
   
    <mx:Button id="showHello" label="Say Hello" />
</mx:Application>

This will create a simple interface, which displays:
  • TextInput: for the user to enter his/her name
  • Text: That will show the results
  • Button: Clicking will initiate the event

Creating the Model
The model is responsible for holding the business data. In our case we would be creating a singleton class so that the data can be persisted across calls.


package classes.MVCPart1
{
    [Bindable]
    public class Model
    {
        private static var _model:Model;
       
        public static function getInstance():Model
        {
            if(_model == null)
            {
                _model = new Model();
            }
           
            return _model;
        }
       
        public function Model()
        {
            _model = this;
        }
       
        public var result:String = "Hello ";
    }
}

Some key things to note:
  1. The class has been marked as [Bindable], so that any changed to any of the members should update the view.
  2. The variable "result" holds the data and will be responsible for updating the view


Creating the Controller
Controller holds the business logic and in our case that is very simple - appends the user name to a "hello" string.

package classes.MVCPart1
{
    public class Controller
    {
        public function showName(name:String):void
        {
            var model:Model = Model.getInstance();
            model.result +=  name;
        }
    }
}

Note, that we are using the Model as a singleton class and then updating the values in the "result"

Wiring up the View
Now the time has come for us to wire up the view to the model and controller. Refer to the following code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
   
    <mx:Script>
        <![CDATA[
            import classes.MVCPart1.Controller;
            import classes.MVCPart1.Model;
           
            [Bindable]
            private var model:Model = Model.getInstance();
           
            private function clickHandler():void
            {
                var controller:Controller = new Controller();
                controller.showName(personName.text);
            }
        ]]>
    </mx:Script>
   
    <mx:TextInput id="personName" />
   
    <mx:Text id="res" text="{model.result}" />
   
    <mx:Button id="showHello" label="Say Hello" click="clickHandler();"/>
</mx:Application>


Note:
  1. Button's event handler makes a call to the Controller
  2. The Text is bound to the "result" variable in the model
And now we have our hand-rolled MVC all setup.