You are on page 1of 45

Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

Advertise Here

Ahmed Nuaman on Dec 30th 2010 with 82 comments

Tutorial Details
Difficulty: Intermediate
Libraries: TweenLite, PureMVC

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+.
This tutorial was first published in May, 2009.

Now and again you may be asked to work on a project which requires a lot of coding and/or collaboration with
colleagues. It’s safe to say that frameworks are often the best choice regarding structure, semantics and
productivity.

Understanding a framework can take a lot of time, but once you’re happy with your knowledge, you can literally
code at the speed of thought. PureMVC is a great framework for AS3; some may say it’s a bit difficult to get
your head around, but you’ll be happy you did.

As you can see from the demo, what we’re working towards is pretty simple, but it’s enough to give you an
understanding of how PureMVC works.

Before we Start
Before we begin I’d like to make sure the following bases are covered. This is a tutorial for intermediate to
advanced Actionscripters, but don’t be intimidated if you’re neither, there’s no time like the present to start
learning!

1 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

1. This example is built using Flex Builder. You can go to Adobe’s web site and download yourself a copy
(60 day free trial!). However, it’ll happily work in an IDE of your choice, whether it be FlashDevelop,
FDT, or good ol’ TextMate.
2. Like I’ve said, this tutorial is for intermediate to advanced Actionscripters, so I’m going to skip the
mundane parts such as setting up your project in your chosen IDE, etc…
3. It’s worth noting that next time you go to do your business, it’s advisable to first print off a copy of
PureMVC’s best practices. It’s fairly heavy, but you’ll be glad you read it.

Step 1: Set Up
It would be wise to grab yourself a copy of the project .zip file. Within it, you will see the basic set up for this
tutorial. Fire up your IDE (mine is Flex Builder) and create a new project. The next thing you’ll need to do is set
up the Flex compiler to use the "src" folder for the source path, the "debug" folder for the debug bin and the
"deploy" folder for the release bin. Simple.

Secondly, I’ve included two additional libraries within the "src" folder: Greensock’s TweenLite ("src/gs") and
PureMVC ("src/assets/swc"). You’ll notice that I’ve used a .swc for the PureMVC library rather than the source
folder, this is because I prefer using .swc files. Make sure that both these libraries are set to compile when you
debug and eventually deploy. Below is a screenshot of the target layout for the project. Although you’re more
than welcome to import the project and go through it file by file, I’m going to tell you how to write each file so
you end up with a project similar to the example.

Step 2: Fundamentals
The concept of PureMVC may make the best of us shy away, but once you’ve got your head around the bare
fundamentals, you’ll soon be flying your way around it. PureMVC’s structure means that notifications are used

2 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

to run certain commands whether they be within models, views or controllers. These notifications consist of the
name and an optional body. The body parameter allows you to send data from the view (such as which button
was clicked on) to a controller that can then pass it to model which then returns the relative data.

This notion of notifications means that PureMVC has a very definite structure to how the source files are set up:

Proxies (model):
A proxy is simply a model. A model, to those who may not know, is a class that handles all data
transactions such as loading XML data, storing it and retrieving it. Unlike mediators or commands, proxies
never listen to or handle notifications; they only ever dispatch them. This means that in order for a
command or a mediator to get a hold of some data, the data will have to either be passed back to the called
via a notification’s body or by retrieving the instance of the proxy from the facade. Proxies store their data
within public classes called VO (value objects). They are just simple classes that have public variables
where we can keep our data for retrieving and updating via our proxies.
Mediators and their views (view):
A mediator is a class that acts on behalf of a view. Within your application you may have several views
and all these views will be extending a DisplayObject class (otherwise they wouldn’t be views). A
mediator will be the class that adds your view to your base (the "viewComponent"; it’s the first argument
that’s passed to a mediator) and it will also handle all incoming and outgoing notifications relating to that
view. This means that the mediator is in charge of notifying your application if the user has triggered an
event in the view (such as by clicking a button) and will also be in charge of passing data from a proxy to
the view in order to update it. A mediator listens and handles notifications itself and is able to register new
mediators into the facade when they’re needed rather than loading them all at once.
Commands (controller):
A command is simply a controller. Although it doesn’t listen to notifications itself, it does have
notifications piped to it from the facade. This means that a command has to run a conditional statement to
allow it to determine which notification it’s received and what to do next. As well as receiving
notifications, commands are allowed to send them out too. They are also able to register proxies, mediators
and more commands.

Hopefully that should have given you a simple understanding of how PureMVC is set out. For a visual
representation of how notifications can "fly" around your application, check out PureMVC’s conceptual
diagram:

3 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

You’ll be forgiven if you think that’s all very daunting, but once you sit down and plan out what your application
is going to look like, you’ll soon understand what we’re going for:

1. Our base class will fire up the facade


2. The facade will then call the start up command
3. The start up command will register our proxy and application mediator
4. The proxy will then reference its value object and wait for further notifications
5. The application mediator will register the progress mediator
6. The progress mediator will create the progress view and then send a notification to load the data
7. The facade will receive this notification and pass it to the data command
8. The data command will then filter the notification and tell the proxy to load the data
9. The proxy will notify the progress view that it’s loading the data (it will be shown), the progress (it will be
updated) and when it’s finished (it will be hidden); the mediator will handle all of this
10. The proxy will then send a notification for the application mediator to handle
11. The application mediator will register the urls view where we’ll create buttons for the user to click
12. The urls view mediator will pass the data from the proxy to the urls view and add the urls view to the stage
13. The user will click on a button, this will then be handled by the mediator and a notification will be sent to
the proxy
14. The proxy will then again load the data, always relaying the state to the progress view
15. The proxy will then again send a notification for the application mediator to handle
16. The application mediator will then tell the urls view mediator to hide the urls view and then register the
images view
17. The images view mediator will create the images view from the proxy’s data

That may sound complex, but it’s just a case of braking down your application’s function into small bit-size
chunks.

4 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

Step 3: Everything Starts With the Facade


Whenever you work with PureMVC, you must understand that coding always starts with the facade. The facade
is a layer that links the PureMVC framework, your MVC code and your base Actionscript file; in this case
mine’s called "App.as". At runtime, App.as will do it’s business, whether it be setting up the scaling of the stage,
the frame rate and whatnot; and when it’s ready, it’ll call upon the facade to start up the application.

Let’s create our base Actionscript file. Using your favourite IDE create a new file, name it "App.as" within "src"
and be sure that it extends the Sprite class like so:

01 package ?

02 {
03 import flash.display.Sprite;
04
05 public class App extends Sprite
06 {
07 public function App()
08 {
09
10 }
11 }
12 }
13

Step 4: Setting Up the Base


Now that we’ve created our base class, feel free to add stuff such as setting the width, height, background
colours and so on. It’s also handy to import any assets you may need, such as fonts or images. Once you’re
happy with your base class, we can then move on to creating the facade. Below is a preview of my base class:

5 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package ?

02 {
03 import flash.display.GradientType;
04 import flash.display.Sprite;
05 import flash.geom.Matrix;
06 import flash.text.Font;
07
08 [SWF( width='600', height='400', frameRate='30', backgroundColor='#000000'
09
10 public class App extends Sprite
11 {
12 [Embed( systemFont='Arial', fontName='Arial', mimeType='application/x-font'
13 private var arialFont:Class;
14
15 public function App()
16 {
17 init();
18 }
19
20 private function init():void
21 {
22 var mat:Matrix = new Matrix();
23 var bg:Sprite = new Sprite();
24
25 mat.createGradientBox( stage.stageWidth, stage.stageHeight, Math.PI * .
26
27 bg.graphics.beginGradientFill( GradientType.LINEAR, [ 0x333333, 0x000000
28 bg.graphics.drawRect( 0, 0, stage.stageWidth, stage.stageHeight );
29 bg.graphics.endFill();
30
31 addChild( bg );
32
33 Font.registerFont( arialFont );
34 }
35 }
36 }
37

Step 5: Setting Up the Facade


In this step we delve straight into the world of PureMVC. Like I said in Step 2, the facade is an important layer
which holds your application together. Create a new class called "ApplicationFacade.as" within "src/com
/flashtuts", make sure it extends Facade and implements IFacade. Note that our facade doesn’t have a
constructor as it’s extending the Facade class. Within our facade we’re going to have 3 functions with a 4th
optional one. Additionally, we’re going to have 2 public constants. Below is what we’ll aim to get our facade
class looking like:

6 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts ?

02 {
03 import com.flashtuts.controller.*;
04 import com.flashtuts.model.*;
05 import com.flashtuts.view.*;
06 import com.flashtuts.view.component.ImagesView;
07 import com.flashtuts.view.component.URLsView;
08
09 import org.puremvc.as3.interfaces.IFacade;
10 import org.puremvc.as3.patterns.facade.Facade;
11 import org.puremvc.as3.patterns.observer.Notification;
12
13 public class ApplicationFacade extends Facade implements IFacade
14 {
15 public static const NAME:String = 'ApplicationFacade
16
17 public static const STARTUP:String = NAME + 'StartUp'
18
19 public static function getInstance():ApplicationFacade
20 {
21 return (instance ? instance : new ApplicationFacade()) as ApplicationFac
22 }
23
24 override protected function initializeController():void
25 {
26 super.initializeController();
27
28 registerCommand( STARTUP, StartupCommand );
29
30 registerCommand( URLsView.DATA_GET, DataCommand );
31 registerCommand( ImagesView.DATA_GET, DataCommand );
32 }
33
34 public function startup(stage:Object):void
35 {
36 sendNotification( STARTUP, stage );
37 }
38
39 override public function sendNotification(notificationName:String, body:
40 {
41 trace( 'Sent ' + notificationName );
42
43 notifyObservers( new Notification( notificationName, body, type ) );
44 }
45 }
46 }
47

Within PureMVC, events or "notifications" are used to route data and trigger functions to be carried out within
our views or controllers. Therefore since our facade is going to send a notification to a command telling it to start
up the application, we create a unique constant that will be used by the facade to send the command and the
start up function listening to the command:

7 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

1 public static const NAME:String = 'ApplicationFacade';


?

2
3 public static const STARTUP:String = NAME + 'StartUp';
4

Although you don’t need to have a constant called NAME, it’s a good idea to always create it in classes that
have notification constants within them as to keep these notifications unique and less susceptible to human error
(such as spelling mistakes).

Next we come to the first of our required functions, "getInstance()". This is the first and foremost function of the
facade and allows our base class to retrieve an instance of the facade, then fire the start up command (we’ll get
to that):

1 public static function getInstance():ApplicationFacade ?

2 {
3 return (instance ? instance : new ApplicationFacade()) as ApplicationFacade;
4 }
5

Now we come to the function which controls the routing of notifications to our controllers, or as PureMVC calls
them, commands:

01 override protected function initializeController():void ?

02 {
03 super.initializeController();
04
05 registerCommand( STARTUP, StartupCommand );
06
07 registerCommand( URLsView.DATA_GET, DataCommand );
08 registerCommand( ImagesView.DATA_GET, DataCommand );
09 }
10

It’s pretty important to keep "registerCommand( STARTUP, StartupCommand );" as without this, the application
wouldn’t start. All it basically means is that the facade will pass the notification called "STARTUP" to a
command called "StartupCommand". As you can see, I have two more. They both point to another controller
called "DataCommand" and both notifications are requests to get data.

We now get to our last required function without our facade, "startup()". All this simply does is fire a notification
which is routed to "StartupCommand" via the "registerCommand" handlers:

1 public function startup(stage:Object):void ?

2 {
3 sendNotification( STARTUP, stage );
4 }
5

Finally, last but by no means least, we have our final function. This is an optional function that I like to add when
I’m working with PureMVC as it allows me to see what events are being fired and in what order. The function
simply overwrites the "sendNotification()" function which you use within PureMVC to send notifications. As
well as notifying the application’s observers, it traces the events for you to see:

8 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

1 override public function sendNotification(notificationName:String, body:Object


?

2 {
3 trace( 'Sent ' + notificationName );
4
5 notifyObservers( new Notification( notificationName, body, type ) );
6 }
7

So that’s our facade. Before we’re finished, we need to apply one more line to our base class. This line will
simply get an instance of our facade and then run the start up command:

1 ApplicationFacade.getInstance().startup( this ); ?

Make sure you put this file at the end of whatever your base class is doing. For example, I’ve put it under all the
stuff that sets the background gradient for my application:

9 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package ?

02 {
03 import com.flashtuts.ApplicationFacade;
04
05 import flash.display.GradientType;
06 import flash.display.Sprite;
07 import flash.geom.Matrix;
08 import flash.text.Font;
09
10 [SWF( width='600', height='400', frameRate='30', backgroundColor='#000000'
11
12 public class App extends Sprite
13 {
14 [Embed( systemFont='Arial', fontName='Arial', mimeType='application/x-font'
15 private var arialFont:Class;
16
17 public function App()
18 {
19 init();
20 }
21
22 private function init():void
23 {
24 var mat:Matrix = new Matrix();
25 var bg:Sprite = new Sprite();
26
27 mat.createGradientBox( stage.stageWidth, stage.stageHeight, Math.PI * .
28
29 bg.graphics.beginGradientFill( GradientType.LINEAR, [ 0x333333, 0x000000
30 bg.graphics.drawRect( 0, 0, stage.stageWidth, stage.stageHeight );
31 bg.graphics.endFill();
32
33 addChild( bg );
34
35 Font.registerFont( arialFont );
36
37 ApplicationFacade.getInstance().startup( this );
38 }
39 }
40 }
41

Now we’re ready to get our hands dirty.

Step 6: The Start Up Command


As discussed within Step 4, the facade handles all notification routing to our commands (the controllers). The
first command we have to create is the "StartupCommand". So create a new file called "StartupCommand.as"
within "src/com/flashtuts/controller". Make sure that it extends SimpleCommand and implements ICommand.
Just like our facade, our commands won’t have constructors, instead override a public function from the
SimpleCommand class called "execute()":

10 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.controller ?

02 {
03 import com.flashtuts.model.DataProxy;
04 import com.flashtuts.view.ApplicationMediator;
05
06 import org.puremvc.as3.interfaces.ICommand;
07 import org.puremvc.as3.interfaces.INotification;
08 import org.puremvc.as3.patterns.command.SimpleCommand;
09
10 public class StartupCommand extends SimpleCommand implements ICommand
11 {
12 override public function execute(notification:INotification):void
13 {
14 facade.registerProxy( new DataProxy() );
15
16 facade.registerMediator( new ApplicationMediator( notification.getBody()
17 }
18 }
19 }
20

You’ll notice that within our "execute()" function, there’s one argument called "notification". We don’t need to
use that as this stage, but this will become something that we do use within our other commands. As this
command is used to start up our application, the first thing it does it register a proxy (a model):

1 facade.registerProxy( new DataProxy() ); ?

and then our mediator:

1 facade.registerMediator( new ApplicationMediator( notification.getBody() as App


? ) );
2

So now we have our start up command ready. What we’ll do now is create our proxy and then get on to our
ApplicationMediator.

Step 7: Creating a Proxy


Now that we have our "StartupCommand" registering our proxy, we need to make sure that the proxy exists. So
create a new file called "DataProxy.as" within "src/com/flashtuts/model", and make sure it extends Proxy and
implements IProxy. To start off with we’re just going to have two functions within our proxy: the constructor and
a "get" function to retrieve the VO (value object):

11 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.model ?

02 {
03 import com.flashtuts.model.vo.DataVO;
04
05 import org.puremvc.as3.interfaces.IProxy;
06 import org.puremvc.as3.patterns.proxy.Proxy;
07
08 public class DataProxy extends Proxy implements IProxy
09 {
10 public static const NAME:String = 'DataProxy'
11
12 public function DataProxy()
13 {
14 super( NAME, new DataVO() );
15 }
16
17 public function get vo():DataVO
18 {
19 return data as DataVO;
20 }
21 }
22 }
23

As you can see, the first function within our proxy is our constructor where we "super()" two variables: the
proxy’s name (set by the NAME constant) and the VO. We need to pass the name of the proxy as this will allow
us to retrieve the facade’s instance of it rather than creating a new instance and losing our VO’s data:

1 public static const NAME:String = 'DataProxy'; ?

2
3 public function DataProxy()
4 {
5 super( NAME, new DataVO() );
6 }
7

The second function is a simple get function that returns our VO. This allows the proxies, commands and
mediators to easily access the VO via the proxy:

1 public function get vo():DataVO ?

2 {
3 return data as DataVO;
4 }
5

Before we finish with our proxy, we need to create our VO, so create a new class called "DataVO.as" within
"src/com/flashtuts/model/vo". Then we’re going to add three public variables: "dataURL:String",
"urlsArray:Array" and "urlsDataArray:Array". We’re going to set the "dataURL" to point to our XML file in
"src/assets/xml" called "data.xml" and for the other two we’re just going to set them as empty arrays:

12 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.model.vo ?

02 {
03 public class DataVO
04 {
05 public var dataURL:String = 'assets/xml/data.x
06 public var urlsArray:Array = [ ];
07 public var urlsDataArray:Array = [ ];
08 }
09 }
10

These are the contents of the XML file:

1 <?xml version="1.0" encoding="UTF-8"?> ?

2 <urls>
3 <url>http://api.flickr.com/services/rest/?method=flickr.photos.search&amp;tags=lo
4 <url>http://api.flickr.com/services/rest/?method=flickr.photos.search&amp;tags=pa
5 <url>http://api.flickr.com/services/rest/?method=flickr.photos.search&amp;tags=ne
6 </urls>
7

Note: You’ll see that I’ve removed my API key. You can easily apply for one by going to Flickr’s API
documentation site.

Now that we’ve got our proxy and VO in place, we’ll need to set up our mediators and views.

Step 8: Creating the ApplicationMediator


The "ApplicationMediator" is the layer that will sit between our "StartupCommand" and your view mediators.
As your application gets bigger and bigger, it will no longer make sense to register all your mediators at once (for
example, at start up). Therefore, by having a parent mediator (the ApplicationMediator) you can have that listen
to the notifications being sent around your application and register mediators when they are needed. Since
mediators act on behalf of the views, sometimes the data required for a view may not have been loaded yet,
therefore it seems silly to register the mediator and create the view without being able to pass it any data.

To begin with, create a new file called "ApplicationMediator.as" within "src/com/flashtuts/view" and make sure
it extends Mediator and implements IMediator. Below is what you should be aiming your "ApplicationMediator"
to look like:

13 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import org.puremvc.as3.interfaces.IMediator;
04 import org.puremvc.as3.interfaces.INotification;
05 import org.puremvc.as3.patterns.mediator.Mediator;
06
07 public class ApplicationMediator extends Mediator implements IMediator
08 {
09 public static const NAME:String = 'ApplicationMediat
10
11 public function ApplicationMediator(viewComponent:Object=null)
12 {
13 super( NAME, viewComponent );
14 }
15 }
16 }
17

As you can see, the mediator starts with our old friend the "NAME" constant and its constructor. Back when we
registered the mediator in Step 6, we passed an instance of the stage, our base class ("App.as") as the first
argument. Within our constructor we super the NAME and the first argument, the "viewComponent" as it’s the
viewComponent that’s going to allow our mediators to add their views to the stage, our base class.

Now is a good time to start talking about our views. Within my example I have three: a progress view, a url
selection view and an images view. For each view we have a mediator. Since the first thing we want to do is load
the data from our XML file, it seems fitting to create our progress view, then the mediator and then register the
mediator with our "ApplicationMediator".

By extending the class Mediator, it allows us to override a handy function called "onRegister()". This function is
called when the facade registers a mediator, so that seems the best place to get our "ApplicationMediator" to
register the mediator for our progress view:

1 override public function onRegister():void ?

2 {
3 facade.registerMediator( new ProgressViewMediator( viewComponent ) );
4 }
5

As you can see, it’s the same style that we used within the "StartupCommand" and we’re passing the
"viewComponent" to the mediator so it’s able to add the progress view to the stage. Your application mediator
should look like this:

14 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.ProgressView;
04
05 import org.puremvc.as3.interfaces.IMediator;
06 import org.puremvc.as3.interfaces.INotification;
07 import org.puremvc.as3.patterns.mediator.Mediator;
08
09 public class ApplicationMediator extends Mediator implements IMediator
10 {
11 public static const NAME:String = 'ApplicationMediat
12
13 public function ApplicationMediator(viewComponent:Object=null)
14 {
15 super( NAME, viewComponent );
16 }
17
18 override public function onRegister():void
19 {
20 facade.registerMediator( new ProgressViewMediator( viewComponent ) );
21 }
22 }
23 }
24

Step 9: Creating Our Progress Mediator and View


Now that we’ve set our "ApplicationMediator" to register our "ProgressViewMediator", we first of all start by
creating a "ProgressView.as" class within "src/com/flashtuts/view/components". This is a class that simply
extends the DisplayObject, in this case Sprite. I won’t go through the code for the view as it’s pretty standard for
any Actionscripter but I will talk about the interaction between the view and its mediator below:

15 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view.component ?

02 {
03 import flash.display.Sprite;
04 import flash.text.TextField;
05 import flash.text.TextFieldAutoSize;
06 import flash.text.TextFormat;
07
08 import gs.TweenLite;
09
10 public class ProgressView extends Sprite
11 {
12 public static const NAME:String = 'ProgressView'
13
14 public static const SHOW:String = NAME + 'Show'
15 public static const HIDE:String = NAME + 'Hide'
16 public static const UPDATE:String = NAME + 'Update'
17
18 private var textField:TextField;
19
20 public function ProgressView()
21 {
22 init();
23 }
24
25 private function init():void
26 {
27 var textFormat:TextFormat = new TextFormat();
28
29 textFormat.color = 0xFFFFFF;
30 textFormat.font = 'Arial';
31
32 textField = new TextField();
33
34 textField.autoSize = TextFieldAutoSize.CENTER;
35 textField.defaultTextFormat = textFormat;
36 textField.embedFonts = true;
37 textField.text = 'Please wait...';
38 textField.x = 300 - ( textField.width / 2 );
39 textField.y = 200 - ( textField.height / 2 );
40
41 addChild( textField );
42 }
43
44 public function show():void
45 {
46 textField.text = 'Please wait...';
47
48 TweenLite.to( this, .5, { autoAlpha: 1 } );
49 }
50
51 public function hide():void
52 {
53 TweenLite.to( this, .5, { autoAlpha: 0 } );
54 }
55
56 public function update(percent:Number):void
57 {

16 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

As the mediator does ‘all the talking’ for the view, it’s important the view and the mediator can pass information
to one another. The mediator can pass information to the view as the mediator will have an instance of the view
declared within it, but for the view to pass information to the mediator (such as a user clicking on a button) we
rely on events (not to be mixed up with notifications). We simply get our view to dispatch an event and get our
mediator to listen to that event. The mediator can therefore handle the event from the view, digest the
information and run something accordingly. We declared the name of these events by using public constants, so
our view has three events: SHOW, HIDE and UPDATE (much like our facade).

Note: the placing of event names can be placed within the facade ("ApplicationFacade.as" file) or within the
relative views. I find it easier and cleaner to keep them within the views, but it’s up to you which way you think
works better for you.

As you can tell, I’ve created a text field that will be used to display the percentage of the data loaded through
our application.

We can now move on to the mediator, so create a new file called "ProgressViewMediator.as" in "src/com
/flashtuts/view" and be sure that it extends Mediator and implements IMediator. It’ll follow the same style as our
"ApplicationMediator" and therefore have a constructor that has one argument (the "viewComponent"), a public
constant called NAME and our friend the overridden "onRegister()". Below is what your mediator should look
like:

01 package com.flashtuts.view ?

02 {
03 import org.puremvc.as3.interfaces.IMediator;
04 import org.puremvc.as3.interfaces.INotification;
05 import org.puremvc.as3.patterns.mediator.Mediator;
06
07 public class ProgressViewMediator extends Mediator implements IMediator
08 {
09 public static const NAME:String = 'ProgressViewMedia
10
11 public function ProgressViewMediator(viewComponent:Object=null)
12 {
13 super( NAME, viewComponent );
14 }
15
16 override public function onRegister():void
17 {
18
19 }
20 }
21 }
22

The first thing we need to add to our view as a reference into our mediator:

17 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.ProgressView;
04 import com.flashtuts.view.component.URLsView;
05
06 import org.puremvc.as3.interfaces.IMediator;
07 import org.puremvc.as3.interfaces.INotification;
08 import org.puremvc.as3.patterns.mediator.Mediator;
09
10 public class ProgressViewMediator extends Mediator implements IMediator
11 {
12 public static const NAME:String = 'ProgressViewMedia
13
14 private var progressView:ProgressView;
15 ...
16

and now we get the mediator to add our view to the "viewComponent" so we have:

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.ProgressView;
04 import com.flashtuts.view.component.URLsView;
05
06 import org.puremvc.as3.interfaces.IMediator;
07 import org.puremvc.as3.interfaces.INotification;
08 import org.puremvc.as3.patterns.mediator.Mediator;
09
10 public class ProgressViewMediator extends Mediator implements IMediator
11 {
12 public static const NAME:String = 'ProgressViewMedia
13
14 private var progressView:ProgressView;
15
16 public function ProgressViewMediator(viewComponent:Object=null)
17 {
18 super( NAME, viewComponent );
19 }
20
21 override public function onRegister():void
22 {
23 progressView = new ProgressView();
24
25 viewComponent.addChild( progressView );
26 }
27 }
28 }
29

Now that we’ve got the bare-bones of our mediator, we need to look at what our view is going to do. Well, as
you can probably tell from the constants, our view is going to tell the user how much has been loaded so far,
therefore it has the public constants SHOW, HIDE and UPDATE. Since these are going to be something that
our view will react to (as you can tell by the "show()", "hide()" and "update()" functions within our view), we
need our mediator to handle these notifications and run these functions accordingly.

18 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

We’ll add two new functions to our mediator: "listNotificationInterests()" and "handleNotification()". The first
function returns an array of all the notifications this mediator is interested in (this is why it’s so important to stick
these notifications in public constants so they’re easy to reference). The latter actually does something with
them. This mediator is only interested in SHOW, HIDE and UPDATE so that’s what we add to the first function
and handle in the second:

19 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.ProgressView;
04 import com.flashtuts.view.component.URLsView;
05
06 import org.puremvc.as3.interfaces.IMediator;
07 import org.puremvc.as3.interfaces.INotification;
08 import org.puremvc.as3.patterns.mediator.Mediator;
09
10 public class ProgressViewMediator extends Mediator implements IMediator
11 {
12 public static const NAME:String = 'ProgressViewMedia
13
14 private var progressView:ProgressView;
15
16 public function ProgressViewMediator(viewComponent:Object=null)
17 {
18 super( NAME, viewComponent );
19 }
20
21 override public function onRegister():void
22 {
23 progressView = new ProgressView();
24
25 viewComponent.addChild( progressView );
26
27 sendNotification( URLsView.DATA_GET );
28 }
29
30 override public function listNotificationInterests():Array
31 {
32 return [
33 ProgressView.SHOW,
34 ProgressView.HIDE,
35 ProgressView.UPDATE
36 ];
37 }
38
39 override public function handleNotification(notification:INotification):
40 {
41 var name:String = notification.getName();
42 var body:Object = notification.getBody();
43
44 switch ( name )
45 {
46 case ProgressView.SHOW:
47 progressView.show();
48
49 break;
50
51 case ProgressView.HIDE:
52 progressView.hide();
53
54 break;
55
56 case ProgressView.UPDATE:
57 progressView.update( body.percent );

20 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

You can simply see that our "handleNotification()" takes the argument of an INotification, a class that contains
the name and body of a notification. We use a "switch" statement to determine which notification is to be
handled and run the functions accordingly. Simple.

Congratulations! You’ve reached the first milestone! Haven’t we come far? Test your file and you should see the
following:

Milestone
So far we’ve created our facade, added a command, proxy and application mediator, then created a view and
added it to our application using the view’s facade.

Step 10: Creating Our URLs View


Now we want to load some data. Before we do this, let’s create the view that will be used to display this data. As
we’re loading three Flickr API feeds, I see it fitting that in our next view we create three buttons which allow the
user to click, at which point our application will return the images from the corresponding feed. Let’s then create
a new file called "URLsView.as’" in "src/com/flashtuts/view/component" and just like our "ProgressView", this
will extend the Sprite class:

21 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view.component ?

02 {
03 import flash.display.Sprite;
04 import flash.events.DataEvent;
05 import flash.events.MouseEvent;
06 import flash.text.TextField;
07 import flash.text.TextFieldAutoSize;
08 import flash.text.TextFormat;
09
10 import gs.TweenLite;
11
12 public class URLsView extends Sprite
13 {
14 public static const NAME:String = 'URLsView';
15
16 public static const DATA_GET:String = NAME + 'DataGet'
17 public static const DATA_READY:String = NAME + 'DataReady'
18 public static const SHOW:String = NAME + 'Show'
19 public static const HIDE:String = NAME + 'Hide'
20 public static const CLICKED:String = NAME + 'Clicked'
21
22 public function init(urls:Array):void
23 {
24 var i:Number = 0;
25 var textFormat:TextFormat = new TextFormat();
26 var textContainer:Sprite;
27 var textField:TextField;
28
29 textFormat.color = 0xFFFFFF;
30 textFormat.font = 'Arial';
31
32 for each ( var url:String in urls )
33 {
34 textContainer = new Sprite();
35
36 textContainer.addEventListener( MouseEvent.CLICK, handleContainerCli
37
38 textContainer.buttonMode = true;
39 textContainer.graphics.lineStyle( 1, 0xFFFFFF );
40 textContainer.graphics.beginFill( 0x333333 );
41 textContainer.graphics.drawRoundRect( 0, 0, 150, 30, 5, 5 );
42 textContainer.graphics.endFill();
43 textContainer.mouseChildren = false;
44 textContainer.y = i * 40;
45
46 textField = new TextField();
47
48 textField.autoSize = TextFieldAutoSize.CENTER;
49 textField.defaultTextFormat = textFormat;
50 textField.embedFonts = true;
51 textField.text = 'Select URL ' + ( ++i );
52 textField.x = 75 - ( textField.width / 2 );
53 textField.y = 15 - ( textField.height / 2 );
54
55 textContainer.addChild( textField );
56
57 addChild( textContainer );

22 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

I’m not going to walk you through this view class, as with all the view classes. They’re basic AS3 classes and
you should be familiar with them. However, as you can see I’ve left the constructor out as we only want to build
the buttons when the data has been loaded by our "DataProxy". Also, take note of the public constants at the top
of the class, mainly DATA_GET and DATA_READY. These are events that will be fired off in order to signal
that the data needs to be loaded, then that the data has loaded and is ready for the view.

We now come to our view’s mediator, so create a file called "URLsViewMediator.as" within "src/com/flashtuts
/view" and make sure it extends Mediator and implements IMediator. This is just like all mediators within our
application. As with our "ProgressViewMediator" this one has a constructor where it supers its NAME and the
"viewComponent" and also has the overridden "onRegister" function. Again, just like "ProgressViewMediator",
we declare a new instance of our view:

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.URLsView;
04
05 import org.puremvc.as3.interfaces.IMediator;
06 import org.puremvc.as3.interfaces.INotification;
07 import org.puremvc.as3.patterns.mediator.Mediator;
08
09 public class URLsViewMediator extends Mediator implements IMediator
10 {
11 public static const NAME:String = 'URLsViewMediator'
12
13 private var urlsView:URLsView;
14
15 public function URLsViewMediator(viewComponent:Object=null)
16 {
17 super( NAME, viewComponent);
18 }
19
20 override public function onRegister():void
21 {
22 urlsView = new URLsView();
23 }
24 }
25 }
26

We now need to think about what our view is going to do. Well, it’s going to allow the user to click on a button

23 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

within it and dispatch an event (that’s what the function "handleContainerClick()" within the view does). We
need to tell our mediator to give our view a listener for that event and handle it accordingly:

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.URLsView;
04
05 import flash.events.DataEvent;
06
07 import org.puremvc.as3.interfaces.IMediator;
08 import org.puremvc.as3.interfaces.INotification;
09 import org.puremvc.as3.patterns.mediator.Mediator;
10
11 public class URLsViewMediator extends Mediator implements IMediator
12 {
13 public static const NAME:String = 'URLsViewMediator'
14
15 private var urlsView:URLsView;
16
17 public function URLsViewMediator(viewComponent:Object=null)
18 {
19 super( NAME, viewComponent);
20 }
21
22 override public function onRegister():void
23 {
24 urlsView = new URLsView();
25
26 urlsView.addEventListener( URLsView.CLICKED, handleURLsViewClicked );
27 }
28
29 private function handleURLsViewClicked(e:DataEvent):void
30 {
31
32 }
33 }
34 }
35

Now we need to think about when this mediator will come into use. Remember earlier I said that there’s no point
running a mediator before it’s needed? Well this mediator isn’t going to be run before we need it, so we’re
assuming that when it’s first registered, the data will be ready for the view to build the buttons, so we update our
"onRegister()" function to send the data to the view, show the view and add it to the stage. Since our data is
stored within our "DataProxy" VO, we’ll need to add another function which allows us to access the facade’s
instance of the proxy and retrieve data from the VO:

24 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 override public function onRegister():void ?

02 {
03 urlsView = new URLsView();
04
05 urlsView.addEventListener( URLsView.CLICKED, handleURLsViewClicked );
06
07 urlsView.init( proxy.vo.urlsArray );
08
09 urlsView.show();
10
11 viewComponent.addChild( urlsView );
12 }
13
14 private function get proxy():DataProxy
15 {
16 return facade.retrieveProxy( DataProxy.NAME ) as DataProxy;
17 }

Finally, as this mediator will be created when the data’s ready, we need to tell our "ProgressView" that we no
longer want it to be visible, so we fire a notification called "ProgressView.HIDE" which will be picked up by the
"ProgressViewMediator" and will tell "ProgressView" to hide itself:

01 override public function onRegister():void ?

02 {
03 urlsView = new URLsView();
04
05 urlsView.addEventListener( URLsView.CLICKED, handleURLsViewClicked );
06
07 urlsView.init( proxy.vo.urlsArray );
08
09 urlsView.show();
10
11 viewComponent.addChild( urlsView );
12
13 sendNotification( ProgressView.HIDE );
14 }
15

Once again, before we can continue, we need to think about which notifications this mediator will need to listen
to. Since we’re going to make this a usable application, there’s no point in not letting the user go back and pick
another Flickr feed url, so it makes sense to allow this view to be shown again. This is where the public const
SHOW comes in to play (you’ll notice that I have a naming convention when it comes to all my notifications,
this is a good thing and will speed up your development). Just like with our "ProgressViewMediator", we add
"listNotificationInterests()" and "handleNotification()" functions to our class:

25 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.model.DataProxy;
04 import com.flashtuts.view.component.ProgressView;
05 import com.flashtuts.view.component.URLsView;
06
07 import flash.events.DataEvent;
08
09 import org.puremvc.as3.interfaces.IMediator;
10 import org.puremvc.as3.interfaces.INotification;
11 import org.puremvc.as3.patterns.mediator.Mediator;
12
13 public class URLsViewMediator extends Mediator implements IMediator
14 {
15 public static const NAME:String = 'URLsViewMediator'
16
17 private var urlsView:URLsView;
18
19 public function URLsViewMediator(viewComponent:Object=null)
20 {
21 super( NAME, viewComponent);
22 }
23
24 override public function onRegister():void
25 {
26 urlsView = new URLsView();
27
28 urlsView.addEventListener( URLsView.CLICKED, handleURLsViewClicked );
29
30 urlsView.init( proxy.vo.urlsArray );
31
32 urlsView.show();
33
34 viewComponent.addChild( urlsView );
35
36 sendNotification( ProgressView.HIDE );
37 }
38
39 override public function listNotificationInterests():Array
40 {
41 return [
42 URLsView.SHOW
43 ];
44 }
45
46 override public function handleNotification(notification:INotification):
47 {
48 var name:String = notification.getName();
49 var body:Object = notification.getBody();
50
51 switch ( name )
52 {
53 case URLsView.SHOW:
54 urlsView.show();
55
56 break;
57 }

26 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

You’ll notice that I’ve added some stuff to the "handleContainerClick()" function. All this function does is
simply pass the index of the button pressed (like 0, 1, 2…) with the event name "URLsView.CLICKED". We
will handle this event shortly as this is the event we’ll use to load the Flickr feed the user has picked.

Now that our view is ready for our data, we can proceed to the proxy and load some XML. Whoop whoop!

Step 11: Loading Data


As I mentioned above, our "ProgressViewMediator" fires off a notification called "URLsView.DATA_GET". In
order for our proxy to receive this notification, we need it to go via our facade and then a command that will
then call the proxy’s function. First then, we need to register the command within our facade, so open up
"ApplicationFacade.as" and add the "registerCommand" function to the "initializeController()" function like so:

27 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts ?

02 {
03 import com.flashtuts.controller.*;
04 import com.flashtuts.model.*;
05 import com.flashtuts.view.*;
06 import com.flashtuts.view.component.ImagesView;
07 import com.flashtuts.view.component.URLsView;
08
09 import org.puremvc.as3.interfaces.IFacade;
10 import org.puremvc.as3.patterns.facade.Facade;
11 import org.puremvc.as3.patterns.observer.Notification;
12
13 public class ApplicationFacade extends Facade implements IFacade
14 {
15 public static const NAME:String = 'ApplicationFacade
16
17 public static const STARTUP:String = NAME + 'StartUp'
18
19 public static function getInstance():ApplicationFacade
20 {
21 return (instance ? instance : new ApplicationFacade()) as ApplicationFac
22 }
23
24 override protected function initializeController():void
25 {
26 super.initializeController();
27
28 registerCommand( STARTUP, StartupCommand );
29
30 registerCommand( URLsView.DATA_GET, DataCommand );
31 }
32
33 public function startup(stage:Object):void
34 {
35 sendNotification( STARTUP, stage );
36 }
37
38 override public function sendNotification(notificationName:String, body:
39 {
40 trace( 'Sent ' + notificationName );
41
42 notifyObservers( new Notification( notificationName, body, type ) );
43 }
44 }
45 }
46

You’ll see that we’re telling our facade to pass this notification to a command called "DataCommand", this is the
name of the controller we’re going to make to handle this notification and run the proxy. Next, create a file
called "DataCommand.as" in "src/com/flashtuts/controller" and it’ll need to extend SimpleCommand and
implement ICommand. Our class won’t need a constructor as we’re interested in the "execute()" function (just
like the "StartupCommand"):

28 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.controller ?

02 {
03 import org.puremvc.as3.interfaces.ICommand;
04 import org.puremvc.as3.interfaces.INotification;
05 import org.puremvc.as3.patterns.command.SimpleCommand;
06
07 public class DataCommand extends SimpleCommand implements ICommand
08 {
09 override public function execute(notification:INotification):void
10 {
11
12 }
13 }
14 }
15

If you have a sharp eye, you’ll notice that we’re facing our friend the INotification class. Just as with a mediator,
this class gives us the name and body of a notification, so we handle it in the same way – with a switch:

01 package com.flashtuts.controller ?

02 {
03 import com.flashtuts.view.component.URLsView;
04
05 import org.puremvc.as3.interfaces.ICommand;
06 import org.puremvc.as3.interfaces.INotification;
07 import org.puremvc.as3.patterns.command.SimpleCommand;
08
09 public class DataCommand extends SimpleCommand implements ICommand
10 {
11 override public function execute(notification:INotification):void
12 {
13 var name:String = notification.getName();
14 var body:Object = notification.getBody();
15
16 switch ( name )
17 {
18 case URLsView.DATA_GET:
19
20 break;
21 }
22 }
23 }
24 }
25

Since we want that notification to tell the proxy to load some data, we need to get the facade’s instance of the
proxy and get it to fire a function. We use the same method we used within our mediator and create a get
function:

29 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.controller ?

02 {
03 import com.flashtuts.model.DataProxy;
04 import com.flashtuts.view.component.URLsView;
05
06 import org.puremvc.as3.interfaces.ICommand;
07 import org.puremvc.as3.interfaces.INotification;
08 import org.puremvc.as3.patterns.command.SimpleCommand;
09
10 public class DataCommand extends SimpleCommand implements ICommand
11 {
12 override public function execute(notification:INotification):void
13 {
14 var name:String = notification.getName();
15 var body:Object = notification.getBody();
16
17 switch ( name )
18 {
19 case URLsView.DATA_GET:
20 proxy.urlsDataGet();
21
22 break;
23 }
24 }
25
26 private function get proxy():DataProxy
27 {
28 return facade.retrieveProxy( DataProxy.NAME ) as DataProxy;
29 }
30 }
31 }
32

Finally, you’ll see that we’re calling a function within our proxy called "urlsDataGet()". This will load our data,
so we’d better create it. Open up "DataProxy.as" and create a function called "urlsDataGet()" which will load
the data, like so:

30 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.model ?

02 {
03 import com.flashtuts.model.vo.DataVO;
04 import com.flashtuts.view.component.ProgressView;
05 import com.flashtuts.view.component.URLsView;
06
07 import flash.display.LoaderInfo;
08 import flash.events.Event;
09 import flash.events.ProgressEvent;
10 import flash.net.URLLoader;
11 import flash.net.URLRequest;
12 import flash.utils.Dictionary;
13
14 import org.puremvc.as3.interfaces.IProxy;
15 import org.puremvc.as3.patterns.proxy.Proxy;
16
17 public class DataProxy extends Proxy implements IProxy
18 {
19 public static const NAME:String = 'DataProxy'
20
21 private var indexDic:Dictionary = new Dictionary();
22
23 public function DataProxy()
24 {
25 super( NAME, new DataVO() );
26 }
27
28 public function urlsDataGet():void
29 {
30 var request:URLRequest = new URLRequest();
31 var loader:URLLoader = new URLLoader();
32
33 sendNotification( ProgressView.SHOW );
34
35 request.url = vo.dataURL;
36
37 loader.addEventListener( ProgressEvent.PROGRESS, handleProgress );
38 loader.addEventListener( Event.COMPLETE, handleURLsDataGetComplete );
39
40 loader.load( request );
41 }
42
43 private function handleURLsDataGetComplete(e:Event):void
44 {
45 var data:XML = new XML( e.target.data );
46
47 for each ( var url:XML in data..url )
48 {
49 vo.urlsArray.push( url.toString() );
50 vo.urlsDataArray.push( '' );
51 }
52
53 sendNotification( URLsView.DATA_READY );
54 }
55
56 private function handleProgress(e:ProgressEvent):void
57 {

31 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

You’ll notice that we’re making use of our VO here by again creating a get function so that we can use and add
data to it. You should be familiar with loading XML data so I won’t walk through the functions; you should be
able to see what they do. You may be wondering why I’m running through a loop of the urls from the XML data
and populating an array with an empty string, you’ll find out later…

The main things I will mention are the "handleProgress()" and "handleURLsDataGetComplete()" functions. They
both send notifications to the application, the first sends a percentage of the data load to our progress view
(remember I said a notification is made up of a name and body?) and the latter sends a notification to the
application stating that our first bit of data has finished loading.

Finally, because we only want our "URLsViewMediator" and "URLsView" to be registered when the data is
ready, we need to amend the application mediator to register the mediator when that event is sent:

32 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.ProgressView;
04 import com.flashtuts.view.component.URLsView;
05
06 import org.puremvc.as3.interfaces.IMediator;
07 import org.puremvc.as3.interfaces.INotification;
08 import org.puremvc.as3.patterns.mediator.Mediator;
09
10 public class ApplicationMediator extends Mediator implements IMediator
11 {
12 public static const NAME:String = 'ApplicationMediat
13
14 public function ApplicationMediator(viewComponent:Object=null)
15 {
16 super( NAME, viewComponent );
17 }
18
19 override public function onRegister():void
20 {
21 facade.registerMediator( new ProgressViewMediator( viewComponent ) );
22 }
23
24 override public function listNotificationInterests():Array
25 {
26 return [
27 URLsView.DATA_READY
28 ];
29 }
30
31 override public function handleNotification(notification:INotification):
32 {
33 var name:String = notification.getName();
34 var body:Object = notification.getBody();
35
36 switch ( name )
37 {
38 case URLsView.DATA_READY:
39 facade.registerMediator( new URLsViewMediator( viewComponent ) );
40
41 break;
42 }
43 }
44 }
45 }
46

That code shouldn’t be too unfamiliar, but as you can see we’re setting which notifications we want it to listen to
and then handling them. In this case registering the "URLsViewMediator" which runs its "onRegister()" function
and builds the view.

We’re at the next mile stone! Now we should see that our application will load the XML data and then pass this
data to our "URLsViewMediator" which will in turn tell the "URLsView" to create some buttons ready for the
user to click:

33 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

Milestone
Give yourself a pat on the back as you’ve achieved a lot! By now you should be familiar with how notifications
play a big part in the application and how the whole structure is brought together by the facade. The next bit will
be a breeze…

Step 12: Handling a User Event


As I explained earlier, a view will dispatch a user event, such as mouse move or in this case mouse click. This
event will then be picked up by its mediator which then decides what to do. Since we’ve set up the function
"handleContainerClick()" within "URLsViewMediator" to send an index of the button, we now need to handle
that event and load the subsequent data. First we’ll need to build our final view and mediator.

Here’s the view:

34 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

001 package com.flashtuts.view.component ?

002 {
003 import flash.display.Loader;
004 import flash.display.Sprite;
005 import flash.events.Event;
006 import flash.events.MouseEvent;
007 import flash.net.URLRequest;
008 import flash.text.TextField;
009 import flash.text.TextFieldAutoSize;
010 import flash.text.TextFormat;
011
012 import gs.TweenLite;
013
014 public class ImagesView extends Sprite
015 {
016 public static const NAME:String = 'ImagesView'
017
018 public static const DATA_GET:String = NAME + 'DataGet'
019 public static const DATA_READY:String = NAME + 'DataReady
020 public static const SHOW:String = NAME + 'Show'
021 public static const HIDE:String = NAME + 'Hide'
022 public static const GO_BACK_CLICKED:String = NAME + 'GoBackCli
023
024 public function init(images:XML):void
025 {
026 var maxImages:Number = 15;
027 var perRow:Number = 5;
028 var xRowCount:Number = 0;
029 var yRowCount:Number = 0;
030 var element:XML;
031 var request:URLRequest;
032 var loader:Loader;
033
034 for ( var i:Number = 0; i < maxImages; i++ )
035 {
036 element = images..photo[ i ];
037
038 request = new URLRequest();
039
040 request.url = 'http://farm' + element.@farm + '.static.flickr.com/'
041
042 loader = new Loader();
043
044 if ( xRowCount == perRow )
045 {
046 xRowCount = 0;
047 yRowCount++;
048 }
049
050 loader.contentLoaderInfo.addEventListener( Event.COMPLETE, handleLo
051
052 loader.alpha = 1;
053 loader.x = xRowCount * 120;
054 loader.y = yRowCount * 120;
055
056 loader.load( request );
057

35 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

All this view does is take the XML data loaded in from the Flickr API, build a grid of images and a back button.
Here’s the mediator:

36 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.model.DataProxy;
04 import com.flashtuts.view.component.ImagesView;
05 import com.flashtuts.view.component.ProgressView;
06 import com.flashtuts.view.component.URLsView;
07
08 import flash.events.Event;
09
10 import org.puremvc.as3.interfaces.IMediator;
11 import org.puremvc.as3.interfaces.INotification;
12 import org.puremvc.as3.patterns.mediator.Mediator;
13
14 public class ImagesViewMediator extends Mediator implements IMediator
15 {
16 public static const NAME:String = 'ImagesViewMediato
17
18 private var imagesView:ImagesView;
19
20 public function ImagesViewMediator(viewComponent:Object=null)
21 {
22 super( NAME, viewComponent );
23 }
24
25 override public function onRegister():void
26 {
27 imagesView = new ImagesView();
28
29 imagesView.addEventListener( ImagesView.GO_BACK_CLICKED, handleImagesVie
30
31 viewComponent.addChild( imagesView );
32 }
33
34 override public function listNotificationInterests():Array
35 {
36 return [
37 ImagesView.DATA_READY
38 ];
39 }
40
41 override public function handleNotification(notification:INotification):
42 {
43 var name:String = notification.getName();
44 var body:Object = notification.getBody();
45
46 switch ( name )
47 {
48 case ImagesView.DATA_READY:
49 imagesView.init( proxy.vo.urlsDataArray[ body.index ] );
50
51 imagesView.show();
52
53 sendNotification( ProgressView.HIDE );
54
55 break;
56 }
57 }

37 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

Again, none of this should be new to you as we’re simply creating an instance of our view, adding it to the stage,
adding listeners to our view (and their handlers) and then setting out the notifications its going to listen to and
how it will handle them.

In order to to handle this notification, we update the application mediator one last time and set it to listen to the
"URLsView.CLICKED" notification:

38 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.view ?

02 {
03 import com.flashtuts.view.component.ImagesView;
04 import com.flashtuts.view.component.ProgressView;
05 import com.flashtuts.view.component.URLsView;
06
07 import org.puremvc.as3.interfaces.IMediator;
08 import org.puremvc.as3.interfaces.INotification;
09 import org.puremvc.as3.patterns.mediator.Mediator;
10
11 public class ApplicationMediator extends Mediator implements IMediator
12 {
13 public static const NAME:String = 'ApplicationMediat
14
15 public function ApplicationMediator(viewComponent:Object=null)
16 {
17 super( NAME, viewComponent );
18 }
19
20 override public function onRegister():void
21 {
22 facade.registerMediator( new ProgressViewMediator( viewComponent ) );
23 }
24
25 override public function listNotificationInterests():Array
26 {
27 return [
28 URLsView.DATA_READY,
29 URLsView.CLICKED
30 ];
31 }
32
33 override public function handleNotification(notification:INotification):
34 {
35 var name:String = notification.getName();
36 var body:Object = notification.getBody();
37
38 switch ( name )
39 {
40 case URLsView.DATA_READY:
41 facade.registerMediator( new URLsViewMediator( viewComponent ) );
42
43 break;
44
45 case URLsView.CLICKED:
46 if ( !facade.hasMediator( ImagesViewMediator.NAME ) )
47 {
48 facade.registerMediator( new ImagesViewMediator( viewComponent )
49 }
50
51 sendNotification( ImagesView.DATA_GET, body );
52
53 break;
54 }
55 }
56 }
57 }

39 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

One thing to note about the handling of this event: the first thing the code does is check if the mediator has been
registered. If not, it registers and everyone gets on with it. The reason for this, as opposed to re-registering it is
that we’re going to create a back button for the user to be able to go back and pick another Flickr feed. Since we
only need to show and hide the buttons that allow the user to choose, there’s no need to rebuild them. However,
since the user will then potentially choose another Flickr feed, we need to rebuild our images. To save
duplicating our code, we only build images when the "ImagesViewMediator" has received the event
"ImagesView.DATA_READY".

Since our application sends "ImagesView.DATA_GET" whenever the user selects a Flickr API, we need to adjust
"ApplicationFacade", "DataCommand" and "DataProxy" to a) handle the event and b) load the data and send an
event back.

We first edit "ApplicationFacade" adding a "registerCommand()" to the "initializeController()" function:

40 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts ?

02 {
03 import com.flashtuts.controller.*;
04 import com.flashtuts.model.*;
05 import com.flashtuts.view.*;
06 import com.flashtuts.view.component.ImagesView;
07 import com.flashtuts.view.component.URLsView;
08
09 import org.puremvc.as3.interfaces.IFacade;
10 import org.puremvc.as3.patterns.facade.Facade;
11 import org.puremvc.as3.patterns.observer.Notification;
12
13 public class ApplicationFacade extends Facade implements IFacade
14 {
15 public static const NAME:String = 'ApplicationFacade
16
17 public static const STARTUP:String = NAME + 'StartUp'
18
19 public static function getInstance():ApplicationFacade
20 {
21 return (instance ? instance : new ApplicationFacade()) as ApplicationFac
22 }
23
24 override protected function initializeController():void
25 {
26 super.initializeController();
27
28 registerCommand( STARTUP, StartupCommand );
29
30 registerCommand( URLsView.DATA_GET, DataCommand );
31 registerCommand( ImagesView.DATA_GET, DataCommand );
32 }
33
34 public function startup(stage:Object):void
35 {
36 sendNotification( STARTUP, stage );
37 }
38
39 override public function sendNotification(notificationName:String, body:
40 {
41 trace( 'Sent ' + notificationName );
42
43 notifyObservers( new Notification( notificationName, body, type ) );
44 }
45 }
46 }
47

We then tell the "DataCommand" how to handle it (through the proxy):

41 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

01 package com.flashtuts.controller ?

02 {
03 import com.flashtuts.model.DataProxy;
04 import com.flashtuts.view.component.ImagesView;
05 import com.flashtuts.view.component.URLsView;
06
07 import org.puremvc.as3.interfaces.ICommand;
08 import org.puremvc.as3.interfaces.INotification;
09 import org.puremvc.as3.patterns.command.SimpleCommand;
10
11 public class DataCommand extends SimpleCommand implements ICommand
12 {
13 override public function execute(notification:INotification):void
14 {
15 var name:String = notification.getName();
16 var body:Object = notification.getBody();
17
18 switch ( name )
19 {
20 case URLsView.DATA_GET:
21 proxy.urlsDataGet();
22
23 break;
24
25 case ImagesView.DATA_GET:
26 proxy.imagesDataGet( body.index );
27
28 break;
29 }
30 }
31
32 private function get proxy():DataProxy
33 {
34 return facade.retrieveProxy( DataProxy.NAME ) as DataProxy;
35 }
36 }
37 }
38

Finally we edit the "DataProxy":

42 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

001 package com.flashtuts.model ?

002 {
003 import com.flashtuts.model.vo.DataVO;
004 import com.flashtuts.view.component.ImagesView;
005 import com.flashtuts.view.component.ProgressView;
006 import com.flashtuts.view.component.URLsView;
007
008 import flash.display.LoaderInfo;
009 import flash.events.Event;
010 import flash.events.ProgressEvent;
011 import flash.net.URLLoader;
012 import flash.net.URLRequest;
013 import flash.utils.Dictionary;
014
015 import org.puremvc.as3.interfaces.IProxy;
016 import org.puremvc.as3.patterns.proxy.Proxy;
017
018 public class DataProxy extends Proxy implements IProxy
019 {
020 public static const NAME:String = 'DataProxy'
021
022 private var indexDic:Dictionary = new Dictionary();
023
024 public function DataProxy()
025 {
026 super( NAME, new DataVO() );
027 }
028
029 public function urlsDataGet():void
030 {
031 var request:URLRequest = new URLRequest();
032 var loader:URLLoader = new URLLoader();
033
034 sendNotification( ProgressView.SHOW );
035
036 request.url = vo.dataURL;
037
038 loader.addEventListener( ProgressEvent.PROGRESS, handleProgress );
039 loader.addEventListener( Event.COMPLETE, handleURLsDataGetComplete );
040
041 loader.load( request );
042 }
043
044 private function handleURLsDataGetComplete(e:Event):void
045 {
046 var data:XML = new XML( e.target.data );
047
048 for each ( var url:XML in data..url )
049 {
050 vo.urlsArray.push( url.toString() );
051 vo.urlsDataArray.push( '' );
052 }
053
054 sendNotification( URLsView.DATA_READY );
055 }
056
057 public function imagesDataGet(index:Number):void

43 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

You’ll notice I’ve performed a bit of Actionscript wizardry in the "imagesDataGet()" function. Again, it’s just
loading some XML, nothing special about that, but it’ll only load unique data once. This is the beauty of having
VOs and using indexes when buttons are pressed. Essentially what happens is that if the user presses button 2
(the 3rd one), it’ll check to see if that index has any data bound to it (as the loop when the urls were first loaded
created an array with empty strings). If it has, there’s no need to load the data again, otherwise the data’s loaded
and using the beauty of Dictionaries, we’re able to put it into the array.

Finally, this proxy then pushes the notification "ImagesView.DATA_READY" back to our application and to our
view where some magic will happen..

You’ve done it!


There’s your first PureMVC application! You should know have an understanding of how PureMVC works and,
most valuably, a skeleton so when it comes to developing more applications you can take this code, rework it or
just use it as reference.

Footnote
PureMVC is a great tool and I use it on many projects, but there are some key differences between using it with
Actionscript 3.0 and MXML. When you use MXML, you add the views using XML, like so:

01 <?xml version="1.0" encoding="utf-8"?> ?

02 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width=


03 creationComplete="ApplicationFacade.getInstance().startup( NAME, this )"
04 xmlns:component="com.application.view.component.*">
05
06 <mx:Script>
07 <![CDATA[
08
09 import com.application.ApplicationFacade;
10
11 public static const NAME:String = 'Showcase';
12
13 public static const STACK_PROGRESS:Number = 0;
14 public static const STACK_MAIN:Number = 1;
15
16 ]]>
17 </mx:Script>
18
19 <mx:Style source="Showcase.css" />
20
21 <mx:ViewStack id="stack" width="980" height="750" horizontalCenter="0" verticalC
22 <component:ProgressView id="progress" />
23 <component:ShowcaseMainView id="main" />
24
25 </mx:ViewStack>
26
27 </mx:Application>
28

44 of 45 3/1/2011 4:47 PM
Understanding the PureMVC Open Source Framework | Activetuts+ http://active.tutsplus.com/tutorials/workflow/understanding-the-puremvc-...

Flex automatically creates those views rather than allowing your to defer their creation. Therefore, when you’re
ready to dive into more PureMVC, they’ve created a little application that tells you how you can use deferred
instantiation.

I hope you enjoyed following this tutorial, feel free to leave any questions or feedback in the comments!

By Ahmed Nuaman
I'm a freelancer. For the past 11 months I've been working for an agency called TangoZebra, that was then
bought out by DoubleClick and the DoubleClick was bought out by Google. So in the past 11 months I've been
working on projects ranging from advertising creatives (MPUs, leaderboards, expandables), to microsites and
games, to integrated tools (using Google products for our clients' sites), to YouTube brand channels and gadgets
(youtube.com/davos is something I created) to internal presentational tools. You can check out my portfolio
here: www.ahmednuaman.com

45 of 45 3/1/2011 4:47 PM

You might also like