Flash ActionScript 3 (AS3) and MVC Pattern Example

Oct 26, 2010
German Villacreces

Lately I've been working on several flash pieces, I decided to try out the Model View Controller pattern and see how it goes.  I've used this pattern before with other technologies like Java and PHP. The concept is the same in Actionscript 3, the use of events makes the application design very modular, easy to understand and the code well organized. Below is a graphic I made to illustrate how the MVC pattern works in AS3.


The view consists of all the classes that display elements like Sprites and MovieClips. The controller has "handler" classes that trigger changes in the model based on how the user interacts with the views.  The model has all the classes that reflect the state of the entire application.

I built a very simple example to show you how the MVC pattern can be implemented. It’s very minimalistic so it should be easy to understand. This type of small flash piece is a very popular component on sites. It displays panels that expand when you mouse over it.

To build this example, I created the following class diagram.

The document class is called Main, it has an instance of the Model, View and Controller classes. Model is a super class of the EventDispatcher class, it can send events to the view. The View class is the container of all the panels, so it holds several instances of the PanelView.

When the user puts the mouse over any of the panels, the controller action is triggered, changing the "currentActivePanel" property in the Model class. The model is affected so it dispatches an event capture by the View class, which updates all panels.

That’s all this example does but I hope you now have a clear understanding of how to implement the MVC pattern in a simple flash piece.

Related Blog Posts: