在以下视频中: http://tv.adobe.com/watch/actionscript-11-with-doug-winnie/communicating-between-classes-episode-52/
他有两个对象通信实例,这两个对象都是从Flash专业创建的,他们只是简单地说话#34;使用点符号。
我的程序动态创建对象,如何在创建的实例中从一个类与另一个类进行通信?创建可以来自主.as文件,也可以来自Main,
创建的对象这甚至可能吗?
答案 0 :(得分:0)
如果你不能保持对象引用,你可能需要第三个类作为对象之间的桥梁。
这是一个例子
public class NotifyMgr
{
private static var _instance:NotifyMgr = new NotifyMgr();
public static function getInstance():NotifyMgr
{
return _instance;
}
//send a message
public function sendMessage(msgType:String, data:*):void
{
var observers:Vector.<IObserver> = notifies[msgType] as Vector.<IObserver>;
if (observers == null)
{
return;
}
for each (var obj:IObserver in observers)
{
obj.notify(msgType, data);
}
}
private var notifies:Dictionary = new Dictionary();
//regiter a observer by msgType
public function register(msgType:String, obj:IObsever):void
{
if (notifies[msgType] == null)
{
notifies[msgType] = new Vector.<IObserver>();
}
var observers:Vector.<IObserver> = notifies[msgType] as Vector.<IObserver>;
if (obj != null && observers.indexOf(obj) == -1)
{
observers.push(obj);
}
}
public function unRegister(msgType:String, obj:IObserver):void
{
}
}
/**
*Your object should implement this interface
*/
public interface IObserver
{
function notify(msgType:String, data:*):void;
}
所以你可以创建对象A和b,它们都实现接口IObserver,并在NotifyMgr中注册A,在B中调用NotifyMgr.sendMessage,然后A就会知道它。
答案 1 :(得分:0)
在此示例中,Main是您的Document Class,Die是Sprite Class的扩展。您可以在主类中调用其rollDie()
方法,因为访问修饰符设置为public
package{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite{
public var die:Die;
public function Main()
{
//create a die
this.die = new Die();
addChild(die);
var button:MovieClip = new MovieClip();
addChild(button);
button.addEventListener(MouseEvent.CLICK, onButtonClick);
}
private function onButtonClick(e:MouseEvent):void
{
this.die.rollDie();
}
}
/**
* Die inherits from Sprite
*/
public class Die extends Sprite {
public function Die() {}
public function rollDie():void
{
var result:int = Math.ceil( Math.random()*6 );
trace("rolling die: " + result);
}
}
}