Targeting movieclip from an AS3 class file - reply

This is a reply to Brian Chau’s post here, but my comment didn’t go through too well, so I’ll repeat it here…

————————————-

As Tink says, it’s normally better to encapsulate the functionality of each class using events and public methods instead of exposing the internals.

For this simple example, you might rewrite it something like…

Test.as

package
{
 import flash.display.MovieClip;
 
 public class Test extends MovieClip
 {
  private var blackbox_mc:BlackBox;
	 
  public function Test()
  {
	blackbox_mc = new BlackBox();
	this.stage.addChild(blackbox_mc);
	var myTest:Control = new Control(this);
  }
  
  public function positionBlackBox(x=null,y=null) : void {
	blackbox_mc.x = (x==null)?blackbox_mc.x:x;
	blackbox_mc.y = (y==null)?blackbox_mc.y:y;
  }
 }
 
}

Control.as

package
{
	import flash.display.MovieClip;
 public class Control
 { 
  private var view:MovieClip;
  public function Control(mc:MovieClip)
  {
	view = mc;
    view.positionBlackBox(null,100);
  }
 }
}

..although to me this still feels a bit odd as the main class is the view, it kinda shows how to break the two. The controller only knows what to view controll and what public methods it’s allowed to call on the view, nothing of how the view works internally.

If you then want to use a design time created blackbox you can simply plop the mc on stage, call it blackbox_mc and delete the instantiation references from the view, e.g….

Test.as

package
{
 import flash.display.MovieClip;
 
 public class Test extends MovieClip
 {
	 
  public function Test()
  {
	var myTest:Control = new Control(this);
  }
  
  public function positionBlackBox(x=null,y=null) : void {
	blackbox_mc.x = (x==null)?blackbox_mc.x:x;
	blackbox_mc.y = (y==null)?blackbox_mc.y:y;
  }
 }
 
}

As the blackbox_mc is already on the views stage flash auto creates the reference, so you can just use blackbox_mc without creating it.

Hope that helps.

A

Add to:
Bloglines | | Digg it | +Google | Spurl | Y! MyWeb

Leave a Reply