开发者

Flash AS2 detecting dynamically attached components are initialised

开发者 https://www.devze.com 2023-03-15 08:49 出处:网络
OK, driving myself mad trying to remember AS2 here, hoping for someone with better memory to lend a hand...

OK, driving myself mad trying to remember AS2 here, hoping for someone with better memory to lend a hand...

Basically, my problem is using composition and 'waiting' for components - eg. a Button component - to be ready to attach a click handler..for various reasons I can't do anything about the whole setup so here's the situation...

I have a movieclip in the library, no class, just a linkage ID ("AttachMe"). That clip has an AS2 Button component inside it ('btn').

I have a class that gets a reference to a timeline, then attaches the mc from the library, then adds an event listener to the button. Simple right?

var foo:Foo = new Foo(this);

class Foo {

    private var tl:MovieClip; // timeline
    private var mc:MovieClip; // the attached movieclip

    function Foo(t:MovieClip){
        tl = t;
        mc = tl.attachMovie("AttachMe", "mc", 10);
        var b:Button = mc.btn;
        b.addEventListener("click", Delegate.create(this, onClick));
    }
    private function onClick(e:Object):Void{
        trace("Hi!");
    }
}

This won't work, as b.addEventListener is undefined at the point I'm doing it...

So really, what is best practice here? i.e. this is a real pain, and I know it's the case of 'waiting' for the button component (in this case) to initial开发者_开发知识库ise before adding the event handler.

Could do an interval/timeout - hate the idea of that. Could do enterFrame on the mc, clear it on first call then add the handler..again, just seems wrong. onLoad doesn't fire for the movieclip so can't add that (if I used inheritance and a custom sub class for the library movieclip I could use onLoad).

Each way seems to be a hack and the thought of doing many times is depressing! It must have been done to death over the years, but I really can't find anything directly mentioning the problem and accepted solutions...

Any thoughts appreciated!

Rich


Right, third attempt, and I've marked the other answers for deletion. After getting into the UIObject and Button classes I came up with this, which seems to work:

import mx.utils.Delegate;
import mx.controls.Button;
import mx.events.EventDispatcher;

class Foo {

    private var tl:MovieClip; // timeline
    private var mc:MovieClip; // the attached movieclip

    function Foo(t:MovieClip)
    {
        tl = t;
        mc = tl.attachMovie("AttachMe", "mc", 10);
        var b:Button = mc.btn;
        EventDispatcher.initialize(b);
        b.addEventListener("click", Delegate.create(this, onClick));
    }
    private function onClick(e:Object):Void
    {
        trace("Hi!");
    }
}

This important bit is EventDispatcher.initialize(b); which seems to force the methods into existence straight away.

0

精彩评论

暂无评论...
验证码 换一张
取 消