SherWood
SherWood

Reputation: 91

AS3 interclass variables

I have a button, that's a class, say, Button. And a main document(class Main) where I can see all the changes in a text field, refreshed every frame (yeah, I don't like trace()). The button has a function of changing a variable that's used in main file. So when I press the button, that I add in the main file to the stage, I need it's function to work. Button class has this.addEventListener(MouseEvent.CLICK,function), further function adds to the var from main class. So if it did add, I would see the changes in the text field. I see changes made by an object I add directly, in the graphic editor, but no changes from the button, whose child I add. Variables are public. Functions are all public. So...

Classes cannot exchange variables freely?

How do I change a variable via a function in a different class?

Maybe I need to export and import var? I thought they all work as a united program that shares all public variables.

Main: I create var i, add Button child to stage and show i every frame =D

Button: When you press me, I add 1 to i =D

SherWood: Main, Y U don't show i, changed by Button? T_T

Code example:

http://piratepad.net/g5tTMFX4Bo

Upvotes: 0

Views: 121

Answers (1)

The Button (or any other class) has no built-in knowledge of the environment that is using it's instance.

The DisplayObject ancestors have the ability to check the parent container, and "main" container via parent and stage properties.

The programmers role (you) is to code flexible way to exchange information that any 2 (or more) classes needs to have, e.g. by exposing public methods/properties, dispatching events (that other party can listen) etc.

So, if the Main needs to know that Button (instance of Button) was clicked add listener to that button for click event, and then you will be able to do whatever you want e.g. add one to i

If Button then, for instance needs to present up-to-date value Main via exposed method can do that e.g. myButton.setLabel("Value of i="+i); which may be executed in aforementioned click listener,

regards

Upvotes: 1

Related Questions