In AS3, how do I run code when a when the movie starts? - actionscript-3

I'm making a level editor for my game, and would like to be able to access a list of all the classes included in my game. I have a static function in my Main class:
public static function register(c:Class, category:String):void {
if (classRegister[category] == null) {
classRegister[category] = new Array();
}
classRegister[category].push(c);
}
Then, in each class I want registered, I put a static initializer:
{
Main.register(prototype.constructor, "motion");
}
However, the static initializers only get called when the class first gets used. Is there a way for a class to force itself to be used right when the game starts? I'm aware that I could explicitly list all the registered classes in the Main file, but that's suboptimal in that the Main file would have to be edited whenever a new class is added that wants registration.
Thanks,
Varga

List all the class definition in the ApplicationDomain, and filter them based on a naming convention or a type (an interface?).
To achieve this, you can use ApplicationDomain.getQualifiedDefinitionNames() (docs), but only if you target FlashPlayer 11.3+.
As a side note, you MUST reference this class somewhere, as a class field so the compiler knows it must include this class in the SWF. You can also put the classes you want to reference inside a SWC library and use -compiler.include-libraries as compiler setting (in that case I wonder if your static initializers gets called?).

Related

How to check Custom Element is registered?

Some method creates new instance of my custom element (created with polymer) and attaches it on page. But I want to check is Element registered before add it and print error to console in bad case. I mean what if I forgot import component html declaration:
<!--I forgot write it in my HTML file -->
<!--<link rel="import" href="packages/visualytik/vis_starter.html">-->
So, in case when I forgot import I want to print error in console.
I know one tricky method:
import 'my_custom_component.dart';
Element component = new Element.tag('my-custom-component');
bool registered = component is MyCustomComponent;
But it's hard method because we should create component first and have to import MyCustomComponent.dart in dart file. Can I check it in other way? Something like:
document.isRegistered('my-custom-component');
Update3
You can also use the new #HtmlImport annotation. If you import the class, then you can be sure you also have imported the HTML of the element. See also https://stackoverflow.com/a/29710355/217408
Update2
See Hunting down unregistered elements
Update
Use a custom constructor in your elements class and do the registration there but only if it wasn't done already.
class MyCustomComponent extends ... {
bool _isRegistered;
bool get isRegistered => _isRegistered;
factory MyCustomComponent() {
if(!isRegistered) {
registerElement();
_isRegistered = true;
}
return new Element.tag('my-custom-element');
}
}
and then create new instances like
new MyCustomElement();
and you can always be sure the element is registered only once (but you always need to use this constructor of course).
Original
If you register your elements by calling document.RegisterElement() yourself instead of relying on Polymer for example, you need to hold a reference to the constructor reference document.RegisterElement() returns, otherwise you won't be able to create an instance of the element.
Therefore you just need to check if you already have a reference to the constructor. See also https://developer.mozilla.org/en-US/docs/Web/API/Document/registerElement

Is it possible to access a class outside package from other package?

I have a class like this
package test{
class Test{}
}
class TestInnerClass{}
I can access the TestInnerClass from Test class but I need to access the TestInnerClass(as class, not its instance) from other class as well. And I don't really want to make TestInnerClass an independent class as all it contains are a few variables.
Is there any way to access the class from outside Test class?
[edit]
More specifically, I need the access for the following code to work.
registerClassAlias("TestInnerClass",TestInnerClass);
If you have a class that would not otherwise be accessed except internally by a public class you may define it as internal.
Internal classes are visible to references inside the current package.
In your example, TestInnerClass is only visible to Test.
Otherwise, to access the class or register class alias it must be defined public in its own .as file.
Packages help to order and classify code in hierarchy. Often, I'll keep Value Object or Data Transfer Objects within their own package, such as:
com.jasonsturges.model.vo
This helps to group smaller model classes together.
If you wanted to make a class visible outside of it's containing package your class would be defined as so:
// SampleCode.as file
package samples{
public class SampleCode {}
}
// CodeFormatter.as file
package samples{
class CodeFormatter {}
}
The SampleCode class is visible whilst the CodeFormatter class is not.
Hope I've answered your question

AS3: One class with parameter, or two similar classes

In case of creating two similar custom AS3 visual components, ex. Button, with different look, but same function, which methodology is better, more efficient from the aspect of code-execution, speed, performance?
Creating two, almost identical classes, where the only difference is
in the visual components, so I have to write the button-controlling functions two times?
Creating one class, with a parameter input
that defines, which kind of button I would like to have
1:
package {
public class bigButton {
public function bigButton() {
//make a bigButton
}
}
}
and
package {
public class smallButton {
public function smallButton() {
//make a smallButton
}
}
}
or
2:
package {
public class OneKindOfButton {
public function OneKindOfButton(thisIsBigButton:Boolean) {
if (thisIsBigButton == true) {
//make it big
} else {
//make it small
}
}
}
}
In terms of an academic argument about the two structures (not this particular example), I'd have to argue that the first option is "better." Although opinion based posts are generally regarded as worthless by most of the SO community, I have a couple of points to bring up and would like to hear counter arguments.
For the second option of doing it, first off it makes me think that potentially there should be a base class that contains all the original functionality then a sub-class that tweaks some part of the functionality. Secondly it requires a condition in the constructor (and probably elsewhere littered throughout that class) to deal with the two scenarios the one class is handling. I think part of the issue here is that in AS3 there is a tendency to mash up all of the functionality and the view logic into one class, just because it's possible doesn't make it a good idea.
All said, I would probably go the route of having a base class that contains the functionality for the buttons, then make some sub-classes that do things different visually.
Also in terms of run-time efficiency I believe the first scenario will work out better again due to the extra conditions that will have to be checked at run-time with the second scenario. In any case, when performance and optimization is the issue it's always best to just run a test (build a little test app that makes 10,000 of each, run it a couple of times and get an average).
I would just create one kind of button class since you can draw or add other display objects into it. You don't even need a boolean to control that. For example :
public class OneKindOfButton extends Sprite{
public function OneKindOfButton(width:Number,height:Number) {
create(width,height);
}
private function create(width:Number,height:Number):void
{
graphics.clear();
graphics.beginFill(0xff0000,1.0);
graphics.drawRect(0,0,width,height);
graphics.endFill();
}
}
Now you can use this class to create any size of button.
var myButton:OneKindOfButton = new OneKindOfButton(200,20);
myButton.x = 100;
myButton.y = 300;
addChild(myButton);
If you want to use images instead of drawing into the button you can do that too by just adding bitmaps into the button sprite.
I think all these answers kind of miss the point of Flash.
Firstly, I don't think that View classes should ever have constructor arguments in Flash, because right off the bat you're making it impossible to ever use them on the timeline/stage. The Flash player can't (and shouldn't) provide these constructor arguments. The stage and timeline are Flash's biggest strength, so if you're not using them, you're wasting at least 25% of your time (the time where you're setting x, y, width, height, drawing graphics programmatically and all that unnecessary crap). Why lock yourself into a design that actively prevents you from using all the tools at your disposal?
The way I do it is I have one Class that defines the behavior of the button. Then the buttons are differentiated by having a library symbol for the big button, one for the small button, one for the button shaped like a pig, one for the button that looks like a spaceship, whatever. Any of these symbols will have that single Button Class as the Base Class (or more likely, just be defined as a Button in the library, so they subcass SimpleButton). Then I just place an instance of the library symbol on the stage and the variable in whatever parent Class is typed to my Button Class or SimpleButton.
The advantage of doing this is that the parent Classes don't need to know the specific implementation type, just the more general type. This means that the library symbols can have "export for Actionscript in frame N" unchecked, and they can just be compiled in where they are used. This means that initial load time can be reduced to the point that you may not ever need a preloader, depending on what else you have going on.
For more on this approach, see Combining the Timeline with OOP in AS3.
If the only difference between you two buttons is their look, but all the logic is shared, then you should definitely use only one common class.
If you're dealing with spark button, then you can simply specify a different skin for each of your instances (about spark skins).
package
{
import spark.component.Button;
public class MyCustomButton extends Button
{
static public const SMALL:String = "smallButton";
static public const BIG:String = "bigButton";
static private const DEFAULT_SIZE:String = SMALL;
public function MyCustomButton(type:String = DEFAULT_SIZE)
{
super();
if (type == SMALL)
{
setStyle("skinClass", SmallButtonSkin);
}
else
{
setStyle("skinClass", BigButtonSkin);
}
}
}
}
You then have to create to different skin classes where you'll define the visual logic of your buttons.

Is it possible to change an inherited access modifier in ActionScript 3?

I'm currently working on a project where I have a ton of classes inheriting from other classes which inherit from other classes and so on. It's probably more complex than it should be, but I am a sucker for abstraction.
Anyway, at times I need to change a getter/setter from being public to private. I suppose it's not really a need, but a desire to cut off things that are preset in child classes, but still need to be publicly accessible in the parent classes.
So an example would be:
Class Base {
public function set label( value:String ):void{};
}
Class A extends Base {}
Class B extends A {
public function B() {
super();
this.label = "stuff";
}
override public function set label( value:String ):void {
//this setter should not be publicly available since the label should not be possible to change in this class
}
}
Currently, I am doing one of two things in these cases:
override the setter to do nothing or set it to the default value so that it can still update/render/whatever
throw an error saying it is unavailable in that class
I've done some searching and everything seems to point to this being impossible, but I've never found it explicitly stated that it is impossible. So is it possible to change the access modifier on an inherited property/function?
It is not possible, and it really should not be, because it leads to confusing and unpredictable class hierarchies. For starters, if you did something like that, you would break the Liskov Substitution Principle: A super class should at all times be replaceable by its derived classes. Changing the API would clearly prevent that - and thus possibly lead to runtime errors and/or inexplicable glitches, if another programmer accidentally exchanged types.
If the classes you are modeling have different behavior in such a way that would make you "hide" an otherwise public API method, you should probably not use inheritance for this - or perhaps in a different way. From what you are describing, I would guess that in a larger part of your hierarchy, you should probably be using composition instead of inheritance, anyway.
It is not possible for the very reason in the comments by Marty Wallace. But it's not an uncommon thing to do.
However in the alternative you used, The property owner is the base class & hence it should always know of anything that the derived class does with it's own properties.
Instead of your hack I would thus prefer something like this :
public class Base {
protected var _isLabelUsable:Boolean = true;
public function set label( value:String ):void {
if (!_isLabelUsable)
throw new Error("Access of undefined property label.");
// Set Label here
}
}
public class A extends Base {
}
public class B extends A {
public function B() {
super();
_isLabelUsable = false;
}
}
These are all valid points, but...
There are cases where they are all void.
Given a base class that comes from an external source. Like, say, mx:Panel.
It has the property 'titleIcon:Class'
The derived class inherits all properties and functions. But people using it shall never set the titleIcon directly, because part of the derived class' functionality depends on the availability of an icon name being known. It provides a property iconName:String. Setting it will also set the titleIcon.
Now how to prevent people from still setting the icon directly? The UI is offering the old property for AS3 and MXML, and the compiler will (of course) not complain.
If titleIcon is a setter/getter pair (in this case, it is), and not final, then the derived class can override the setter and throw an error, while the iconName setter will assign the icon class to super.titleIcon.
However, this is clumsy and will not work for final functions or variables.
If there were a way to at least tell the UI to not offer the property anymore or show a warning...

Add a property to a Button or other type of Objects

I always created additional property to MovieCLips using the syntax
myMC.myProperty
without any sort of declaration... But i can use this method only with MovieClips.. What about if i want to add a property to a button or any different type of object? I need to extend the class? Do you can me suggest how? Many thanks
You can add property to movieclips in runtime because MovieClip is dynamic class. If the class is not dynamic, you should extend it to create methods and properties.
Read about dynamic classes.
I tend to create custom classes for nearly everything.
I would extend the relevant class and set up a private var for your new property. You can then pass in the value to the constructor or add a getter/setter method to call externally.
private function _myProperty:int;
public function get myProperty():int
{
return _myProperty;
}
public function set myProperty(newVal:int):void
{
_myProperty = newVal;
}
Getter/setter methods add a few lines of code that may seem unnecessary but on big projects when you find a property is being set and you don't know why, you can put a break point in your set myProperty
Subclass is main solution.
Next works only with mx components (flex sdk 3).
Most components have data : Object property that you can freely use to store data.
Monkey patching sometimes is the only way to go. It allows you to add custom properties to flex sdk classes. I don't think you should use it in your case. But I used it to change core logic that is locked by private keyword in flex sdk.
Hope that helps.