22nd August 2006

Document Class in AS2

posted in Flash |

One of the really cool features of AS3 is that you specify a document class which extends MovieClip or Sprite, and that class is your application. As the class extends Sprite/MovieClip, "this" refers to the main timeline, _root, _level0, whatever you are used to thinking of it as.

In AS2 I've been using a static main function that passes in a ref to the main timeline and stores that in order to attach things, etc.:

Actionscript:
  1. class MyClass
  2. {
  3.     private var target:MovieClip;
  4.  
  5.     public static function main(target:MovieClip):Void
  6.     {
  7.         var app:MyClass = new MyClass(target);
  8.     }
  9.  
  10.     public function MyClass(target:MovieClip)
  11.     {
  12.         this.target = target;
  13.         init();
  14.     }
  15.    
  16.     private function init():Void
  17.     {
  18.         trace("init");
  19.         target.lineStyle(1, 0, 100);
  20.         target.lineTo(100, 100);
  21.     }
  22. }

Then, on the main timeline of the fla, you say:

Actionscript:
  1. MyClass.main(this);

This has the advantage of working the same in both the IDE and in MTASC.

I was always pretty happy with this until I started using document classes. Now, having to prepend "target" every time I want to attach something, etc. seems a pain. So I started playing around with alternatives. I know I'm very far from the only one or even the first one to come up with a solution for this, but I figured I'd post it, if only for my own future reference. If someone else finds it useful, great.

Here's what I came up with, that I'm pretty happy with:

Actionscript:
  1. class MyClass extends MovieClip
  2. {
  3.     public static function main(target:MovieClip):Void
  4.     {
  5.         target.__proto__ = MyClass.prototype;
  6.         target.init();
  7.     }
  8.    
  9.     private function init():Void
  10.     {
  11.         trace("init");
  12.         lineStyle(1, 0, 100);
  13.         lineTo(100, 100);
  14.     }
  15. }

The code in the fla is exactly the same:

Actionscript:
  1. MyClass.main(this);

And it still works just fine with MTASC.

And it's actually even smaller and simpler than my earlier method.

What it's doing is replacing _root's (or whatever movie clip you pass in) prototype with my document class's. Of course, at that point, as _root has already been constructed, the document class's constructor will never be called. So I just omitted it and called init directly.

With this setup, the class again is the main timeline. I can attach movie clips directly there, draw directly, whatever. Works for me.

Again, I'm sure I'm not the first one to come up with this. And I'm sure others have solutions that they find better. Feel free to share them.

Post to Twitter

This entry was posted on Tuesday, August 22nd, 2006 at 9:52 am and is filed under Flash. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 18 responses to “Document Class in AS2”

  1. 1 On August 22nd, 2006, Actionscript Classes » Document Class in AS2 said:

    [...] Document Class in AS2 [...]

  2. 2 On August 22nd, 2006, Tink said:

    I always just stick this on frame one

    import Application;
    this.__proto__ = Application.prototype;
    Application[ "apply" ]( this, null );

  3. 3 On August 22nd, 2006, Tink said:

    Note that also makes a call to the classes constructor which you might want to do in your implementation and fire the init function from within there.

  4. 4 On August 22nd, 2006, kp said:

    Nice one Tink. So the main method would become this:

    public static function main(target:MovieClip):Void
    {
    target.__proto__ = MyClass.prototype;
    MyClass["apply"](target, null);
    }

    Pity about the array notation. This also works:

    public static function main(target:MovieClip):Void
    {
    target.__proto__ = MyClass.prototype;
    Function(MyClass).apply(target, null);
    }

    Though I’m not sure I like calling the “constructor” of something that has already been instantiated. I think I’ll stick to just calling init. But always good to get feedback.

  5. 5 On August 22nd, 2006, Just Another Rant » Blog Archive » Take ALL of your code off the timeline said:

    [...] Well almost all…Most have already heard about the new feature in the Flash 9 preview for AS3 that allows you to specify a document class (a class file for the main timeline), and if you havent heard… well now you have. This is a pretty cool feature and will do wonders for getting nearly all code off the timeline. The bummer is that its an AS3 only feature. I realize that many people have been doing this for a while now already, but I never knew it was possible to do until now.  Keith Peters, has posted a nice article on how to do this is AS2. Pretty slick! [...]

  6. 6 On August 23rd, 2006, Danny Patterson said:

    Great minds think alike. I just posted on this last month. ;)
    http://www.dannypatterson.com/Resources/Blog/EntryDetail.cfm?id=106

    Tink, great tip on the constructor call. I’ll definately be using that in the future.

  7. 7 On August 23rd, 2006, kp said:

    Damn, if I didn’t know me, I’d say I copied you! :)

  8. 8 On August 26th, 2006, Mundt said:

    Anyone who puts

    import Application;
    this.__proto__ = Application.prototype;
    Application[ “apply” ]( this, null );

    is a dipshit. Instantiate the object like normal, jesus. Im so sick of you morons overcomplicating everthing. IT SUCKS to not be able to specify the entry point in AS3. The application class is stupid. A static main method is good enough for java — it should be good enough for actionscript.

  9. 9 On August 26th, 2006, kp said:

    Please tell me more. I really value the opinions of people who start out discussions by calling me a dipshit and a moron and then remain anonymous. “If it’s good enough for Java, it’s good enough for ActionScript” is going to be my new sarcastic catch phrase.

  10. 10 On September 12th, 2006, Tink said:

    Well I don’t see your actaully doing that so it must be me.

    Also by application class in AS 3.0 i presume he means the Document class, which as far as I’m concerned is a great addition and a great entry point.

    I don’t see any overcomplication, and the reason I use it is for simplicity. each to their own i guess :) .

    And thanks for the cuss Mundt ;) . brought a smile to the end of my day.

  11. 11 On October 13th, 2006, steanson said:

    this __proto__ techique is pretty funky.

    I did notice that my static references to clips were left undefined.
    So i have to set static references up manually
    is there a way around this, or is it me being lazy :)

    so for example

    public static var dbg_txt:TextField;

    static function main(target:MovieClip):Void{
    target.__proto__ = AppClass.prototype;
    // set static debug field to refer to target debug text field
    AppClass.dbg_txt = target.dbg_txt;
    target.init();
    }

  12. 12 On January 2nd, 2007, Kipple » Blog Archive » Flash, OOP and an AS2 Document Class said:

    [...] Ok, so I came across this post by Keith Peters in which he explains a way to mimic a document class in AS2. Danny Patterson had the same idea and blogged about it around the same time. [...]

  13. 13 On January 31st, 2007, kaiphilipp said:

    Hi. Nice hint. But I have problems compiling in the flash IDE: I get one error message: The property being referenced does not have the static attribute. any suggestions?

    sincerely
    kaiphilipp

  14. 14 On February 2nd, 2007, Helmut Granda said:

    Hi Kaiphillipp,

    The sample supplied works great, if you are hand typing the class maybe you are missing something.

  15. 15 On February 5th, 2007, kaiphilipp said:

    Hi Helmut.

    You’re so right. Thank you all again. I was really missing something, replaced init with main and vice versa plus a stupid mistake in my sources. Should have gotten more sleep. Sorry for my last post. This is really great.

  16. 16 On April 18th, 2007, Mr Siegal! Im gonna burn this hotel down » Blog Archive » Hur man fĂ„r rootklassen att fungera under bĂ„de Flash och MTASC said:

    [...] KĂ€lla Keith Peters (Bit-101) [...]

  17. 17 On October 1st, 2008, Tekkaman Slade said:

    The embed technique your using to load an image in, how would you do that for AS 2?

  18. 18 On July 26th, 2009, mmarch said:

    Hallo,
    first of all thank you for sharing this nice piece of code!
    I’d like to share some minor modifications that I made to use it in a project of mine.
    I didn’t want to copy-n-paste the template for every new swf, so I tried to factor out as much code as possible.
    I have therefore a generic “fake-documentclass” class that looks like this:

    class MyDocumentClass extends MovieClip {
    private targetClip:MovieClip;

    public function MyDocumentClass(tgt:MovieClip) {
    targetClip = tgt;
    }

    // we don’t have friend qualifier;
    // also, this makes the reference read-only for the child classes,
    // which is a good thing…
    public function getTarget():MovieClip {
    return targetClip;
    }

    public function run():Void {
    trace(“MyDocumentClass run() called.”);
    }
    }

    And for every new SWF I write a specific document class that looks like this:

    class ProductsDocumentClass extends MyDocumentClass {
    //
    // swf-specific private variables
    //

    public sub ProductsDocumentClass(tgt:MovieClip) {
    super(tgt);
    //
    // swf-specific initialization code
    //
    }

    public sub run():Void {
    var targetClip:MovieClip;

    trace(“ProductsDocumentClass run() called.”);

    targetClip = this.getTarget();

    // swf-specific code goes here
    }
    }

    In products.fla I write:

    var app:MyDocumentClass = new ProductsDocumentClass(this);
    app.run();

    cons:
    - two lines instead of one in fla
    - more lines of code
    - slightly more complex than the original technique
    pro:
    - the fake document class imposes MovieClip as parent class
    and requires that one stores a reference to the root movie clip
    - avoids cut-n-paste of template code.
    - I find the name “run” more appropriate for the role of the method, than “init”

    These are my 2 (euro) cents.

Leave a Reply

Who is reading BIT-101?

Copyright ©2009 by Keith Peters. All rights reserved. This means that you may not reprint or repost the contents of this site without express written permission of the author.


  • Calendar

  • February 2010
    M T W T F S S
    « Jan    
    1234567
    891011121314
    15161718192021
    22232425262728
hoodia order buy Levitra Plus betablockers weight loss information buy pills without a prescription arthritis menopause ambien doses cat's eye health information on cholesterol cialis online order valtrex cheapest phentermine onlin e increase breast size lower blood sugar immediately terramycin which is better cialis or viagra buy cheap cialis reduce cholesterol naturally new blood pressure treatment products for back pain cheapest cialis index will levitra help piroxicam 20 mg order viagra online in germany buy tadalafil online buy levitra onlines how to naturally lower cholesterol buy generic viagra where to buy soma anti allergic drug levothyroxine dogs new hair loss treatmen buy levitra pain meds buy cheap malaria therapy weight loss after baby asthma medications chronic snoring viagra gel prostate cancer cures order viagra cialis alprazolam men health natural cure arthritis immune system support diet medicine cialis approval lipitor effects where can i buy arthritis drugs overactive bladder in men self help weight loss natural cholesterol control ativan medication cialis approval best cure for snoring breast enhancing pills order prozac celebrex pharmacy buy levitra onlines premature ejaculation cure confidence hypnotherapy free stop smoking bust enhance diet weight loss supplements skin fungal infection valium with no prescription viagra with out prescription breast enhancement products alpha blocker medications azithromycin 250mg skin disease chronic heart failure medicines dog care products buying cialis online gerd in children antibiotics to buy my drug store muscle building diet drugs affecting levitra anti anxiety medications really large breast enhancement help for constipation ulcers stomach drugs for high blood pressure selling pet products buy pain medicine viagra online overnight fucidin ointment generic zyrtec prices soft tab cialis smoking treatment dog products online weight loss solution cialis on line blue pills weight loss diet pill nitroglycerin sublingual floxin prevention of heart attack imuran order gasex vermox treatment of depression Viagra On Line buy generic cialis professional tooth whitening kits to buy valium 2mg treatment for hypertension ultram cheapest online stores hair loss products cheap weight loss diovan prescription malaria preventative taurine treating prostate cancer immune system support natural constipation cure phentermine no prescription fast delivery purchase meds without prescription buy plendil diet drug taking viagra after cialis protonix cheapest generic cialis online viagra levitra cialis yohimbe benefits muscle mass gain diet and health products medical treatment for insomnia buy blood pressure meds buy celexa levaquin interactions blood pressure drug skin disorder where can i buy arthritis drugs natural breast enhancer acute pain control online diazepam natural acne remedy antifungal strategies triphala pravachol online how can i stop smoking breast enhancement natural nautral breast enhancement beta blocker medications wellbutrin dosages order viagra cialis lower high blood pressure mass muscle phentermine from canada how to loss weight osteoporosis bone health lipitor use dog medication drug allergies buy diazepam buyviagra cialis phentermine 37.5 mg zestril medication parkinsons treatment generic revatio free nexium cosmetic dentistry tooth whitening avalide generic buy cheap tadalafil uk simvastatin tablets buy cialis online in usa breast pain cat care ovulating clomid medical skin care lines viagra to canada viagra or cialis cheap cialis tramadole buy azulfidine drugs used for cancer ear pain oral ketoconazole raloxifene evista taurine sex with levitra stop smoking today heart failure natural cholesterol control protonix dose oxybutynin 5mg irritable bowel syndrome treatments new treatment for hepatitis c cheap prescription drugs viagra online prescription depression therapy buy sumycin menopause treatment hair loss treatments medication pletal what is a natural antibiotic viagra purchase synthroid tablets generic prilosec lipitor cat health info discount vitamin cholesterol and health bacterial diarrhea weight loss medicine new treatment for depression removing retention fluids diuretic medicines soma 250mg cat anxiety loss weight online pharmacy viagra buy phentermine without a prescription herbs for breast growth cymbalta dosage fast weight loss supplement arthritis menopause levitra online order cheapest place to buy phentermine cold flu medications for nausea buy ultram where pills for acne free weight loss programs help with anxiety improve skin valium 2mg urinary tract health cat urinary tract disease crestor dosage drug zofran calan zyrtec buy nirdosh dosage digoxin buy pain patch acomplia alendronate cialis best price cheap wellbutrin small dog products depression medicine sildenafil dosage dog health depression and anxiety lamictal withdrawal viagra, levitra and cialis online drug buy bone maker strontium cures for hair loss nitroglycerin tablets natural arthritis treatment arimidex buy buy energy patch how to treat a yeast infection viagra herb alternative viagra cialis levitra order sublingual cialis cialis comparison breast lift augmentation seroquel for depression carisoprodol mg new treatment for depression cialis soft tabs safe sleep aid severe leg muscle pain natural weight loss gabapentin medication what is ambien clozapine medication viagra online ordering cures for hair loss free weight loss help buy viagra levitra pet treats order plan b diabetes type 2 phentermine risk ultram er side effects treatment for hepatitis b constipation cures drugs used in treating depression leg pain buy cheap generic cialis anti anxiety meds hypnotherapy for weight loss motilium body building fitness dog skin relieve upper back pain cures for high blood pressure cardura celecoxib Viagra Online Cheap cheap bactrim ambien online lamisil cost infertility meds progesterone clomid osteoporosis hormon urinary tract infection symptoms hypnotherapy for health how to buy viagra online joint pain cure online allegra buy generic cialis uk generic abilify cures for lung cancer new treatments for lung diseases pain meds buy cheap treatment for dry skin disease of the skin nexium drug free stop smoking buy tooth whitening products viagra tablet naprosyn dosage women's fertility male sexual power carisoprodol purchase asthma attack treatment estradiol pills phentermine from canada pet health care hair loss products online astelin generic cheap estrace free weight loss program buy rimonabant relieve lower back pain lexapro prescription new breast cancer drug buying ambien best online viagra scams home scabies treatment hair loss in woman buy generic cialis uk eye drop gabapentin medication amitriptyline uses ultram no prescription natural pain cures buy cla products back pain lowest price generic viagra pain meds buy cheap mg buy phentermine acne skin care cialis rx weight loss and fitness nitrofurantoin buy phentermine without a prescription high blood pressure medicines stop hair loss viagra china use levitra female health coreg dosage carisoprodol price pain relief product breast enlargement depression pills buy how to treat flu home neck pain relief order imitrex online vitamin b-6 cialis soft tabs pharmacy software description of soma buy isoniazid cheap prevacid help ear infections on dog fat burning stop smoking remedies rhinitis treatment chronic pain relief birth control online meds without prescriptions buy lovastatin drug stores penis enlargement without pill cancer medicine buy deltasone cure for throat infection thyroid dogs dosage cipro viagra from uk cheap alcoholism treatment natural cure for constipation paxil cialis 5mg tablets amitriptyline uses topamax drugs lower heart rate drug discount codes dog medicines body fat loss joint pain recurring urinary tract infections ativan information buy drugs online cheap fast valium body building ambien maximum dosage information on valium how to sperm more chlamydia medication dosage buy cialis online viagra chest pain heart fluconazole interaction calcium channel blocker side effects zolpidem dosage online drug stores zelnorm muscle strength fluconazole buy stress gum free weight loss products information on gout low immune system online viagra cialis 20 buy cefixime phentermine from canada gain muscle mass fast lasix side effects buy singulair penis enlargement free natural muscle and joint health viagra online overnight cialis online aceon allergies and asthma diamox side effects weight loss software generic compazine price for tramadol high blood pressure symtoms osteoporosis help treatment severe constipation drug new smoking stop pain relief product xanax online dog health info clonazepam .5mg buy tribulus pregnancy prevention methods allergy hives