Intro to MVC Part 1: The Controller Class

– taterboy | July 13th, 2010

Filed under: ActionScript 3, Flash, Flex, Games, Tutorials

About a year ago, @devgirl, introduced me to the MVC framework and provided me with a stubbed out demo of everything working together. There were many more class files than I was used to, one for data and variables (Model), one for all the graphic elements and UI controls (View), and one to control all the information between the two (Controller). My brain hurt for a couple weeks as I attempted to absorb what seemed like magic and how to apply it to a new job that was about to start. This process has changed the way I approach every project, even simple tasks with only a few lines of code. On smaller projects I may only leverage one part of the MVC framework and figured this was the best way to introduce it to others without it being so overwhelming. So today, I what to present the Controller class, which is part of the MVC framework.



Why MVC?
Better organization, more flexibility and easier expandability are the biggest reasons to use an MVC based framework. It may seem like extra coding at first, with so many extra class files, but it’s well worth it. Think of a hub and spoke system, where everything communicates through one central location and each component can individually listen for events and updates as data changes. The code for each component is not intertwined or daisy chained allowing new components to be plugged in and out.

MVC in Action (an Interactive Overview):


Get Adobe Flash player


The First Step, the Controller Class:
In many cases the controller is a singleton class, this means it can be accessed from anywhere in the application. Components can be nested inside a few objects and still have direct access to the Controller. No need for calling out to parent.parent.function or parent.parent.variable, it’s all accessed directly from the controller class.

A Simple Demo:
First we setup the controller class, then import that class into any component or child object that needs to have access to data or events found in the controller. This is especially useful in games, a child object can connect directly to scoring or current game status. Imagine implementing a game pause feature using the traditional pass it along or water fall method. With an MVC approach, every object that needs to know about the pause event can check it directly from one place.


Get Adobe Flash player


Some Code:
The singleton class sends an instance of itself with access to non-static variables and functions.

?View Code ACTIONSCRIPT
package framework{
 
	import flash.events.EventDispatcher;
	import flash.events.Event;
 
	[Event(name="UPDATE", type="flash.events.Event")]
 
	//class extends EventDispatcher so it can dispatch Events.
	public class Controller extends EventDispatcher{
 
		//static vars - instance equals self
		private static var _instance:Controller = new Controller();
 
		//returns self as an object - allows access to non-static variables and methods
		public static function get instance():Controller{
			return _instance;
		}
 
		//public vars (MODEL)
		public var isPaused:Boolean;
 
		//constructor
		public function Controller():void{
			//Controller should be used as a singleton or static class"
			if(_instance != null){
				throw(new Error("There should only be one instance of Controller"));
			}
			else{
				//on first run....
			}
		}
 
		//handle value updates - cheat way of updating multiple variables
		//without a bunch of setters and getters.
		public function updateModel(str:String, val:*):void{
			this[str] = val;
			shoutOut();
 
		}
 
		//dispatch event on update
		private function shoutOut():void{
			dispatchEvent(new Event("UPDATE"));
 
		}
	}
}

The objects that need access to information found in the static class, just imports the class and makes calls directly to functions and variables needed.

?View Code ACTIONSCRIPT
package{
 
	//import Controller
	import framework.Controller;
	import flash.display.MovieClip;
	import flash.events.Event;
 
	public class DemoBall extends MovieClip{
 
		//constructor
		public function DemoBall():void{
			//check paused state in Controller
			if(Controller.instance.isPaused){
			   //game is paused
			}
 
			//on Controller update
			Controller.instance.addEventListener("UPDATE", controlHandler);
		}
 
		public function controlHandler(ev:Event):void{
			// if anything occures in the controller, we can capture it.
		}
 
		//cleanup event listeners and remove self
		public function cleanup():void{
			if(Controller.instance.hasEventListener("UPDATE")){
				Controller.instance.removeEventListener("UPDATE", controlHandler);
			}
		}
	}
}

Where To Go From Here:
Adding a score, level or power up values could cause all the balls behave differently. This type of approach can really expand the power of each line of code.

Download sample code here.

Technorati Tags: , , , , , , , , , , ,

| 2 Comments » | facebook:

2 Comments »

  1. Awesome, keep this series coming!

    Comment by Robert — July 28, 2010 @ 6:44 pm

  2. Very useful information, the pictorial representation of how MVC is implemented is very useful..

    Thanks lot

    Comment by Quicknol — April 15, 2012 @ 6:36 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

*