Simple Observer Pattern in Actionscript 3

Posted: February 8th, 2009

I was just posting on a forum on kirupa.com that started with someone asking about how to listen for a variable to change values. I thought about how this is a key part of the MVC design so I wrote a couple classes and posted them. After I did this I realized that it was most likely a good example of the observer pattern and after consulting my newest nerd bible I realized that I had it down, except for implementing the interfaces.

Click Here to See the Thread on kirupa.com

Anyways I thought I would post these classes here.


This is the Subject Class:

package
{
	import flash.events.*;
	public class Subject extends EventDispatcher
	{
		private var yourVariable:String;
		public function getYourVariable():String
		{
			return yourVariable;
		}
		public function setYourVariable(newOne:String):void
		{
			yourVariable = newOne;
			this.update();
		}
		protected function update():void
		{
			dispatchEvent(new Event(Event.CHANGE));
		}
	}
}

This is the Subscriber Class:


package
{
	import flash.events.*;
	public class Subscriber
	{
		private var variableHolder:VariableHolder;
		private var theOneInTheHolder:String;
		//this will take the VariableHolder as a parameter when instantiated
		public function Subscriber(vHolder:VariableHolder)
		{
			this.variableHolder = vHolder;
		}
		public function update(event:Event = null):void
		{
			theOneInTheHolder = variableHolder.getYourVariable();
			trace(theOneInTheHolder);
		}
	}
}

The next code is what goes on the timeline, After you build it the output will say:
new Variable
new Variable
new Variable2
new Variable2


import VariableHolder;
import ListensForEvent;

var theHolder:VariableHolder = new VariableHolder();

var listener1:ListensForEvent = new ListensForEvent(theHolder);
theHolder.addEventListener(Event.CHANGE, listener1.update);

var listener2:ListensForEvent = new ListensForEvent(theHolder);
theHolder.addEventListener(Event.CHANGE, listener2.update);

theHolder.setYourVariable(’new Variable’);
theHolder.setYourVariable(’new Variable2′);

Leave a Reply