开发者

invoke actionscript package function from MXML

开发者 https://www.devze.com 2023-04-11 11:58 出处:网络
How can I invoke a function 开发者_高级运维in btn.as from MXML and is it possible to call a function without creating an instance of btn?

How can I invoke a function 开发者_高级运维in btn.as from MXML and is it possible to call a function without creating an instance of btn?

main.mxml which contain a Spark button:

<s:Button text="Add Image"/>

btn.as is a package:

package {
    public class btn extends Sprite {
        public function btn() {
        }

        public function addImage():void {
           var im:Image = new Image("background.png");
           addChild(im);
        }
    }
}


It is a bit confusing what exactly you're after, but I'll give it a shot.

How can I invoke a function in btn.as from MXML

I'm going to assume you want tocall the addImage function on an instance of the btn component when the button is clicked. You can it like this:

<s:Button text="Add Image" click="{btnInstance.addImage()}"/>

If you want something else, you'll have to elaborate.

is it possible to call a function without creating an instance of btn?

Yes, make it a static method. Something like this:

    package {
        public class btn extends Sprite {
            public function btn() {
            }

            public static function addImage():void {
               var im:Image = new Image("background.png");
               addChild(im);
            }
        }
    }

then you can call the static method like this:

<s:Button text="Add Image" click="{btn.addImage()}"/>

The caveat is that I don't expect "addChild" would do anything useful inside a static method. If there is no component instance, then it isn't on the display list; and your new "child" will never be displayed. In fact, there would be no way to reference the new child. I suppose you could pass in a container to the addImage function and add the child there. Conceptually like this:

            public static function addImage(container:UIComponent):void {
               var im:Image = new Image("background.png");
               container.addChild(im);
            }

I have initial reservations about an approach like that though, so would not recommend it without fully understanding the use case.

0

精彩评论

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

关注公众号