ActionScript 3.0 Design Patterns

(Chris Devlin) #1

432 | Chapter 12: Model-View-Controller Pattern


addEventListener(type:String,
listener:Function,
useCapture:Boolean = false,
priority:int = 0,
useWeakReference:Boolean = false):void

removeEventListener(type:String,
listener:Function,
useCapture:Boolean = false):void

dispatchEvent(event:Event):Boolean

For the model to serve as a concrete subject in an observer pattern, it needs to imple-


ment theIEventDispatcherinterface. However, the easiest way for a user-defined


class to gain event dispatching capabilities is to extend theEventDispatcher class.


Observers register listener methods to receive event notifications from


EventDispatcher objects through theaddEventListener( ) method.


The model


Our model holds the character code of the last key pressed in a property. It needs to


implementsetterandgettermethods to enable the view and controller to access and


modify it. Let’s first define an interface for our model (Example 12-1).


TheIModelinterface shown in Example 12-1 extends theIEventDispatcherinterface


and defines two methods to get and set the character code of the last key pressed.


Because theIModelinterface extendsIEventDispatcher, any class implementing it has


to implement all the methods defined in both interfaces. TheModelclass shown in


Example 12-2 implements theIModel interface.


Example 12-1. IModel.as


package
{
import flash.events.*;


public interface IModel extends IEventDispatcher
{
function setKey(key:uint):void
function getKey( ):uint
}
}


Example 12-2. Model.as


package
{
import flash.events.*;


public class Model extends EventDispatcher implements IModel
{

Free download pdf