PDA

View Full Version : Object informing Other Object


Lucky_PHP_Man
02-07-2009, 05:15 AM
Hi people,

I need some help on understanding Observer Pattern,

If let's say, I have an Object on the left and another Object on the right of the stage.

How do i code it, if let's say, I click on the Left Object the the Right Object will change its properties.

PS: They are 2 different Object with 2 Different Actionscript Classes

ranacseruet
02-07-2009, 05:53 AM
Hi,
u can do it easily by using custom event....

My Blog (http://ranacseruet.blogspot.com)

Flash Gordon
02-07-2009, 08:28 AM
it's the same principle the entire AS3 clicking buttons is built around.

matbury
02-07-2009, 08:30 AM
Hi Lucky_PHP_Man,

I recommend creating an observer class that the two display objects subscribe to. I think it's important to separate functions like that into separate classes.

Lucky_PHP_Man
02-07-2009, 10:16 AM
Hi,
u can do it easily by using custom event....

My Blog (http://ranacseruet.blogspot.com)

it's the same principle the entire AS3 clicking buttons is built around.

Hi Lucky_PHP_Man,

I recommend creating an observer class that the two display objects subscribe to. I think it's important to separate functions like that into separate classes.

Mind if you give me some of the observers class code?

I would be grateful.

Thanks

Regards,
LPM

matbury
02-07-2009, 03:07 PM
Here's a very simple example of an implementation of an observer design pattern:

observer class:

package {

public class ObserverExample {

private var _subscribers:Array; // list of subscribers

public function ObserverExample() {
_subscribers = new Array();
}

public function subscribe(obj:Object):void {
_subscribers.push(obj); // add object to list
}

public function unsubscribe(obj:Object):void {
var len:uint = _subscribers.length;
for (var i:uint = 0; i < len; i++) {
if(_subscribers[i] == obj) { // multiple instances of same class might need === instead
_subscribers.splice(i,1); // remove object from list
break; // stop loop
}
}
}

public function notify():void {
for(var i:String in _subscribers) {
_subscribers[i].update();
}
}
}
} // end of ObserverExample class

Doc class or FLA code:

var obs:ObserverExample = new ObserverExample();
var subs1:Object = new Object();
var subs2:Object = new Object();
// object is a dynamic class so we can add functions at runtime
subs1.update = function():void {
trace("subs1 subscriber notified by ObserverExample");
}

subs2.update = function():void {
trace("subs2 subscriber notified by ObserverExample");
}

obs.subscribe(subs1);
obs.subscribe(subs2);
obs.notify();

This is a pretty "rough and ready" example but it illustrates the pattern well enough.