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.
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:
If you want something else, you’ll have to elaborate.
Yes, make it a static method. Something like this:
then you can call the static method like this:
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:
I have initial reservations about an approach like that though, so would not recommend it without fully understanding the use case.