spacer
  • Tutorials\
  • Workflow

Understanding the PureMVC Open Source Framework

Ahmed Nuaman on Dec 30th 2010 with 98 comments
Tutorial Details
  • Difficulty: Intermediate
  • Libraries: TweenLite, PureMVC
Tweet
Download Source Files
Demo View It Online

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. 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.

spacer

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 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:

spacer

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.


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:

		package 
		{
			import flash.display.Sprite;

			public class App extends Sprite
			{	
				public function App()
				{

				}
			}
		}
	

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:

		package 
		{
			import flash.display.GradientType;
			import flash.display.Sprite;
			import flash.geom.Matrix;
			import flash.text.Font;

			[SWF( '600', '400', frameRate='30', backgroundColor='#000000' )]

			public class App extends Sprite
			{	
				[Embed( systemFont='Arial', fontName='Arial', mimeType='application/x-font' )]
				private var arialFont:Class;

				public function App()
				{
					init();
				}

				private function init():void
				{
					var mat:Matrix = new Matrix();
					var bg:Sprite = new Sprite();

					mat.createGradientBox( stage.stageWidth, stage.stageHeight, Math.PI * .5 );

					bg.graphics.beginGradientFill( GradientType.LINEAR, [ 0x333333, 0x000000 ], [ 1, 1 ], [ 0, 255 ], mat );
					bg.graphics.drawRect( 0, 0, stage.stageWidth, stage.stageHeight );
					bg.graphics.endFill();

					addChild( bg );

					Font.registerFont( arialFont );
				}
			}
		}
	

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:

		package com.flashtuts
		{
			import com.flashtuts.controller.*;
			import com.flashtuts.model.*;
			import com.flashtuts.view.*;
			import com.flashtuts.view.component.ImagesView;
			import com.flashtuts.view.component.URLsView;

			import org.puremvc.as3.interfaces.IFacade;
			import org.puremvc.as3.patterns.facade.Facade;
			import org.puremvc.as3.patterns.observer.Notification;

			public class ApplicationFacade extends Facade implements IFacade
			{
				public static const NAME:String							= 'ApplicationFacade';

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

				public static function getInstance():ApplicationFacade
				{
					return (instance ? instance : new ApplicationFacade()) as ApplicationFacade;
				}

				override protected function initializeController():void
				{
					super.initializeController();

					registerCommand( STARTUP, StartupCommand );

					registerCommand( URLsView.DATA_GET, DataCommand );
					registerCommand( ImagesView.DATA_GET, DataCommand );
				}

				public function startup(stage:Object):void
				{
					sendNotification( STARTUP, 	stage );
				}

				override public function sendNotification(notificationName:String, body:Object=null, type:String=null):void
				{
					trace( 'Sent ' + notificationName );

					notifyObservers( new Notification( notificationName, body, type ) );
				}
			}
		}
	

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:

		public static const NAME:String							= 'ApplicationFacade';

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

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):

		public static function getInstance():ApplicationFacade
		{
			return (instance ? instance : new ApplicationFacade()) as ApplicationFacade;
		}
	

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

		override protected function initializeController():void
		{
			super.initializeController();

			registerCommand( STARTUP, StartupCommand );

			registerCommand( URLsView.DATA_GET, DataCommand );
			registerCommand( ImagesView.DATA_GET, DataCommand );
		}
	

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:

	
		public function startup(stage:Object):void
		{
			sendNotification( STARTUP, 	stage );
		}
	

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:

		override public function sendNotification(notificationName:String, body:Object=null, type:String=null):void
		{
			trace( 'Sent ' + notificationName );

			notifyObservers( new Notification( notificationName, body, type ) );
		}
	

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:

		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:

		package 
		{
			import com.flashtuts.ApplicationFacade;

			import flash.display.GradientType;
			import flash.display.Sprite;
			import flash.geom.Matrix;
			import flash.text.Font;

			[SWF( '600', '400', frameRate='30', backgroundColor='#000000' )]

			public class App extends Sprite
			{	
				[Embed( systemFont='Arial', fontName='Arial', mimeType='application/x-font' )]
				private var arialFont:Class;

				public function App()
				{
					init();
				}

				private function init():void
				{
					var mat:Matrix = new Matrix();
					var bg:Sprite = new Sprite();

					mat.createGradientBox( stage.stageWidth, stage.stageHeight, Math.PI * .5 );

					bg.graphics.beginGradientFill( GradientType.LINEAR, [ 0x333333, 0x000000 ], [ 1, 1 ], [ 0, 255 ], mat );
					bg.graphics.drawRect( 0, 0, stage.stageWidth, stage.stageHeight );
					bg.graphics.endFill();

					addChild( bg );

					Font.registerFont( arialFont );

					ApplicationFacade.getInstance().startup( this );
				}
			}
		}
	

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()":

		package com.flashtuts.controller
		{
			import com.flashtuts.model.DataProxy;
			import com.flashtuts.view.ApplicationMediator;

			import org.puremvc.as3.interfaces.ICommand;
			import org.puremvc.as3.interfaces.INotification;
			import org.puremvc.as3.patterns.command.SimpleCommand;

			public class StartupCommand extends SimpleCommand implements ICommand
			{
				override public function execute(notification:INotification):void
				{
					facade.registerProxy( new DataProxy() );

					facade.registerMediator( new ApplicationMediator( notification.getBody() as App ) );
				}
			}
		}
	

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):

		facade.registerProxy( new DataProxy() );
	

and then our mediator:

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

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):

		package com.flashtuts.model
		{
			import com.flashtuts.model.vo.DataVO;

			import org.puremvc.as3.interfaces.IProxy;
			import org.puremvc.as3.patterns.proxy.Proxy;

			public class DataProxy extends Proxy implements IProxy
			{
				public static const NAME:String							= 'DataProxy';

				public function DataProxy()
				{
					super( NAME, new DataVO() );
				}

				public function get vo():DataVO
				{
					return data as DataVO;
				}
			}
		}
	

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:

		public static const NAME:String							= 'DataProxy';

		public function DataProxy()
		{
			super( NAME, new DataVO() );
		}
	

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:

		public function get vo():DataVO
		{
			return data as DataVO;
		}
	

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:

		package com.flashtuts.model.vo
		{
			public class DataVO
			{
				public var dataURL:String								= 'assets/xml/data.xml';
				public var urlsArray:Array								= [ ];
				public var urlsDataArray:Array							= [ ];
			}
		}
	

These are the contents of the XML file:

		<?xml version="1.0" encoding="UTF-8"?>
		<urls>
			<url>api.flickr.com/services/rest/?method=flickr.photos.search&amp;tags=london&amp;api_key=YOURAPIKEY</url>
			<url>api.flickr.com/services/rest/?method=flickr.photos.search&amp;tags=paris&amp;api_key=YOURAPIKEY</url>
			<url>api.flickr.com/services/rest/?method=flickr.photos.search&amp;tags=new%20york&amp;api_key=YOURAPIKEY</url>
		</urls>
	

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:

		package com.flashtuts.view
		{
			import org.puremvc.as3.interfaces.IMediator;
			import org.puremvc.as3.interfaces.INotification;
			import org.puremvc.as3.patterns.mediator.Mediator;

			public class ApplicationMediator extends Mediator implements IMediator
			{
				public static const NAME:String							= 'ApplicationMediator';

				public function ApplicationMediator(viewComponent:Object=null)
				{
					super( NAME, viewComponent );
				}
			}
		}
	

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 u

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.