Add a property to a Button or other type of Objects - actionscript-3

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.

Related

Assign super to variable in AS3

I have this:
public class Base {
public function whoAmI() {
trace("base");
}
}
public class Extended extends Base {
public function Extended() {
this.whoAmI() //prints extended
super.whoAmI() //prints base
var test = super;
test.whoAmI() //prints extended
}
public override function whoAmI() {
trace("extended");
}
}
The problem is when I do var test = super, it seems like this is assigned to test instead of super.
Is it possible to do the assignment so that test.whoAmI() prints "base"?
Edit: In the comments it is being said that using super in the way I propose would break overriding. I don't think that's the case. The way I am thinking of it, super could be used the same way as this. I understand that is not the way super is implemented, but using it that way would not break overriding as people are claiming. So for example the same way this is possible:
var test = this;
test.whoAmI();
This should be possible:
var test = super;
super.whoAmI();
It is obviously the choice of the language implementer to not do things this way, and I don't understand the reason why. It doesn't break things, but I guess it does make them more complicated.
I am not suggesting type-casting this to the super class. Obviously that wouldn't work.
You are thinking of "this" and "super" as 2 different instances, 2 different things but they in fact point to the same object (obviously) so at the end it's always "this". Using super is just a special keyword that allows the instance to point to the overrided definitions up the inheritance chain, it does not point to a different object. So "super" does correctly its job, it points to the instance and allow you each time you use it to access overrided definitions and that's it. There's of course no point on trying to store that keyword in a variable since in that case it just return correctly the instance it points to which is always "this".
It's simply a case of misunderstood inheritance principle and I've seen it before, super is mistaken for some kind of instance wrapper up the inheriatnce chain around the object "this" while it's in fact and always the same object.
No, this is not possible.
If this were possible, then overriding methods wouldn't be possible!
For example, take this function...
public function test(a:Object):void {
trace(a.toString());
}
You'd only get [object Object] back if your idea was how things worked.
Ok I understand what you mean your question is more about language definition and specification.
Look at this exemple in c# that explain how you can manage more precisely overriding in c# :
http://www.dotnet-tricks.com/Tutorial/csharp/U33Y020413-Understanding-virtual,-override-and-new-keyword-in-C
But
let's explain a litlle how it's work.
when you extend a class, it's like if you create an object composed of all the object in the inheritance tree so if B extends A and C extends B you have two objects like this:
(B+A) and (C+B+A) with hierarchy between each other B->A and C->B->A. Super is just a way to ascend in the hierachy.
When you cast a C in A for example. In memory you always have an object (C+B+A) but interpreted as A. When you override you just say that a method in child has an higher priority than in parent.
You can try downcasting this manually to any of your class's predecessors. The pointer will still be equal to this but the methods called will use the class table of the class used to downcast.
public class Extended extends Base {
public function Extended() {
this.whoAmI() //prints extended
super.whoAmI() //prints base
var test:Base = this;
test.whoAmI() //should print base
}
public override function whoAmI() {
trace("extended");
}
}
Should your Base extend something, which methods are known or the superclass is dynamic, and there is code that adds methods to prototype of a class, you might use such a downcast to call a superclass's method that might not be there at compile time, but make sure you first call hasOwnProperty in case of a dynamic class to determine whether a method or property exists.

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

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?).

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...

Bindable property change event in Flex

Can anyone please help me solve this mystery:
I've got a component called Box.as that has following two properties, and have their getters & setters defined:
private var _busy:Boolean;
private var _errorMessage:String;
In MXML that uses this component I define it like this:
<components:Box skinClass="skins.components.BoxSkin"
busy="{presenter.boxBusy}"
errorMessage="{presenter.boxErrorMessage}"/>
Where presenter variable is defined here in MXML and a Presenter class has boxBusy and boxErrorMessage variables defined as bindable property change events:
[Bindable(event="propertyChange")]
function get boxBusy():Boolean;
function set boxBusy(value:Boolean):void;
[Bindable(event="propertyChange")]
function get boxErrorMessage():String;
function set boxErrorMessage(value:String):void;
PROBLEM is that whenever I change boxErrorMessage for the presenter, I see the affect in MXML but nothing happens at all when I change boxBusy. Is there something extra I need to do with boolean variable?
Thanks a lot in advance.
You should omit the (event="propertyChange") specification from your [Bindable] metadata tags on both boxBusy and boxErrorMessage. Also, make sure your get/set methods are declared public.
So, the property, boxBusy, would look something like this:
[Bindable]
public function get boxBusy():Boolean { return _busy; }
public function set boxBusy(value:Boolean):void { _busy = value; }
When you qualify [Bindable] with (event="..."), you're telling Flex, "I will dispatch the named event whenever the binding should be updated".
If you omit the event specification, then flex assumes that the event is named propertyChange. But that's not all it does. It also automatically "wraps" your setter with generated code that transparently dispatches a 'propertyChange' event any time the setter is used to modify the value. This is described in more detail here, at adobe livedocs.
So... by explicitly specifying (event="propertyChange"), you disable flex's default behavior. Even though you're using the default event name, flex will not generate the wrapper code -- instead, it will expect you to dispatch the event from your code, at the appropriate time.
I imagine that your boxErrorMessage property appears to be working, because some other [Bindable] property of your class is changing in the same pass -- thus dispatching propertyChange, and causing your boxErrorMessage binding to update as a side-effect.
It is completely possible that if you are setting busyBox to true the first time the setter is getting called but it will not get called again if you again try to set to true. The code that is by the flex compiler when you use the [Bindable] tag will adds a check to see if you are setting the new value to what the getter will currently will return. If that is the cause it isn't called.
If you were to oscillate between true and false it would get called every time because the new value differs from the current value. But setting it to true-true-true-true-false would only result in it getting called the first time to set to your and the last time to set to false.

Linq2Sql: Force discriminator property to be set

The problem I'm having is while using Linq2Sql with inheritance after declaring a new instance of the inherited class the discriminator property is still set to its initial value, not the correct value for the sub-type. It gets the correct value after attaching it to a context and calling SubmitChanges(). There are times where I want to declare a new object of the inherited type and call methods on the base class with the base class knowing inherited type it is working with and the most logical choice would be to use the discriminator property.
Is there a way to force the setting of the discriminator property? I don't want to go to all my sub-classes and implement the OnCreated() partial method for something the context already knows how to do.
I did come up with a slightly better workaround than putting code in the OnCreated() method of each inheriting class and figured I'd leave it here in case anyone stumbles here.
In the OnCreated() of the base class I added code that looked similar to this:
partial void OnCreated()
{
if (this is BaseClass1)
{
this.[DiscriminatorProperty] = DiscriminatorValueForBaseClass1;
}
else if(this is BaseClass2)
{
this.[DiscriminatorProperty] = DiscriminatorValueForBaseClass2;
}
}
It is still duplicating the functionality that the context already knows how to do but at least I'm not implementing the OnCreated() in every base class. I also don't like the fact that if a new class is added or a discriminator value changes you have to update it in the DBML and in the OnCreated(). For this reason I'd still like a way for the context to assign the value, in fact it should be doing this when the inherited class is created.