Using array to change ToggleButton visibility on/off (AS3/Flex) - arrays

So I'm trying to be able to change the visibility of an array of togglebuttons that I have right now. Using the flex interface tool, I made 10 toggle buttons and named their caller IDs b1,b2,b3...etc. I then placed those IDs into the array I mentioned. I also have a numeric stepper which I changed the called ID to numericstepper.
var buttonArray: Array= new Array (b1,b2,b3,b4,b5,b6,b7,b8,b9,b10)//global ;
protected function numericstepper_changeHandler(event:Event):void {
var x:int=0
var y:int
x=numericstepper.value //the value of the numericstepper
for (y=0; y<x; y++) {
buttonArray[y].visible= false // trying to change the visibility of each button in the array
}
But this doesn't work and gives me an error. Actually, even when I just trace buttonArray[1] it gives me null....not sure what to do here.
Newbie coder here so please advise!

ok I probably know what the problem is: you are creating the array variable in a component, but at that time (on construction of the component) that buttons are uninitialized yet (i.e == null). Common practice is to wait for some of the component's life cycle event before working with inner components. Usually it is the creationComplete event.
something like this:
<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"
creationComplete="onCreationComplete()">
<fx:Script><![CDATA[
private var buttonArray:Array;
private function onCreationComplete():void {
buttonArray = [b1, b2, b3, b4, b5, b6, b7, b8, b9, b10];
}
protected function numericstepper_changeHandler(event:Event):void {
const x:int = numericstepper.value;
for (var i:int = 0; i < x; i++) {
buttonArray[i].visible = false;
}
}
]]></fx:Script>
<!-- inner components here -->
</s:Application>

It is indeed a newbie error. You need to understand the difference between variables and objects. b1 is a variable, a ToggleButton is an object, a variable holds a reference to an object but is not the object itself, it is just a reference. So in your case you correctly add your variable to an array but at this point those variable do not reference any objects so in that case their default value (what they really reference) is "null". null is a special type of object that has no methods and no properties and can be used in place of any complex object.
When you add those variables b1, b2, etc to an array you truly add what they reference, you do not add the variable themselves to the array so whatever the variable reference get in the array so in your case it's 'null'.
To make sure you add the ToggleButton objects you can simply delay everything and check for value for example:
var buttonArray: Array;
protected function numericstepper_changeHandler(event:Event):void
{
if(!buttonArray && b1)//b1 is not null so time to fill the array
{
buttonArray = [b1,b2,b3,b4,b5,b6,b7,b8,b9,b10];
}
else if(!b1)
{
return;//still no b1 so exit.
}
const x:int = numericstepper.value;
for (var i:int = 0; i < x; i++)
{
buttonArray[i].visible = false;
}
}

Related

Angular - Objects seem bound to eachother but arent

I have an edit page where the user can edit a file in the system, and then save it. When loading the file, I make two objects out of the result, one is bound to the view and the other I wish to keep (in its original state) until "save" is clicked, and then use it to compare vs the view-bound object, to see if any changes have been made.
So, when the page loads, this is being run
$http.get('/api/files/' + $stateParams.id)
.then(function (result) {
vm.fileTemp = result.data;
vm.fileTempCopy = result.data;
The fileTempCopy is not being touched or referenced by anything in the view or elsewhere in the controller, except in the save-method, where i check if they are alike or not. But somehow, both of them are updated when i make changes to the input fields (as if they were both used as ng-model for the inputs).
if(vm.fileTemp === vm.fileTempCopy)//in save-function
is always true, and their fields are exactly the same.
Why does this happen and how can I solve it?
Using the assignment operator, you are actually just referencing the original array. Arrays are reference types. That means, that they don't actually store values, they only store references to those values. What you where doing is copying a reference to a memory location, meaning that any changes to the memory at that location (including removing elements) will be reflected in both arrays.
So you will want to do this instead:
vm.fileTemp = angular.copy(result.data);
vm.fileTempCopy = angular.copy(result.data);
here is a very basic approach to checking an object's "value equality".
function isEquivalent(a, b) {
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
return false;
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
//After your update Outputs: false
console.log(isEquivalent(vm.fileTemp, vm.fileTempCopy));

Listener for every array element

i've created an array. Each element is a button object. Is there a possibility to hook mouseclick on every array at the same time? I mean something like this.
var Objects:Array = new Array
Objects[0] = new button(parameters)
Objects[1] = new button(parameters)
Objects[2] = new button(parameters)
Objects[n].addEventListener(MouseEvent.CLICK, Clicked(n));
function Clicked(n,...)
{
THECODE PROCEEEEDS for Objects[n]
}
I know that's not the clearest and most correct writing, but I'm asking if this is possible in similiar way? And how to do it? I know I can hook every mouseclick and then check if the clicked under the mouse is one of the array elements with for loop, but I'm asking about this way.
Yes. You are unable to directly pass an index into a listener, but you can retrieve that via calling indexOf() inside it.
for each (b in Objects) b.addEventListener(MouseEvent.CLICK, clicked);
// note, you just put function name here!
public function clicked(e:MouseEent):void {
var i:int=Object.indexOf(e.target);
if (i==-1) {
// panic behavior
return;
}
// now you can parse that index into something valuable
}

Instantiation attempted on a non-constructor

I'm trying to make a bomb catching game (I'm actually using the code from the AS3 Classroom in a Book on arrays). As soon as I changed the word fruit to bomb in the code I got error 1007. With the exception of changing basket_mc to eod_mc and fruit to bomb (I used command-F and replaced with case sensitive on) I haven't changed much. It worked with eod_mc, but doesn't with bomb.
var bombArray:Array = new Array(bomb);
var bombsOnstage:Array = new Array();
var bombsCollected:int = 0;
var bombsLost:int = 0;
for (var i:int = 0; i<20; i++) {
var pickBomb = bombArray[int(Math.random() * bombArray.length)];
var bomb:MovieClip = new pickBomb();
addChild(bomb);
bomb.x = Math.random() * stage.stageWidth-bomb.width;// bomb.width is subtracted from the random x position to elimate the slight possibility that a clip will be placed offstage on the right.
bomb.y = Math.random() * -500;
bomb.speed = Math.random() * 15 + 5;
bombsOnstage.push(bomb);
}
eod_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragEod);
stage.addEventListener(MouseEvent.MOUSE_UP, dragStop);
function dragEod(e:Event):void {
eod_mc.startDrag();
}
function dragStop(e:Event):void {
eod_mc.stopDrag();
}
stage.addEventListener(Event.ENTER_FRAME, catchBomb);
function catchBomb(e:Event):void {
for (var i:int = bombsOnstage.length-1; i > -1; i--) {
var currentBomb:MovieClip = bombsOnstage[i];
currentBomb.y += currentBomb.speed;
if (currentBomb.y > stage.stageHeight - currentBomb.height) {
currentBomb.y = 0 - currentBomb.height;
bombsLost++;
field2_txt.text = "Total Bombs Detonated: " + bombsLost;
}
if (currentBomb.hitTestObject(eod_mc)) {
bombsCollected++;
removeChild(currentBomb);
bombsOnstage.splice(i,1);
field1_txt.text = "Total Bombs Caught: " + bombsCollected;
if (bombsCollected >= 20) {
eod_mc.gotoAndStop(20);
} else if (bombsCollected > 15) {
eod_mc.gotoAndStop(15);
} else if (bombsCollected>10) {
eod_mc.gotoAndStop(10);
} else if (bombsCollected>5) {
eod_mc.gotoAndStop(5);
}
}
}
if (bombsOnstage.length <= 0) {
field1_txt.text = "You Win! You have defused the bombs.";
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchBomb);
}
if (bombsLost >= 20) {
field1_txt.text = "Sorry you lose. You have lost your foot!";
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchBomb);
for (var j:int = bombsOnstage.length-1; j > -1; j--) {
currentBomb = bombsOnstage[j];
removeChild(currentBomb);
bombsOnstage.splice(j,1);
}
}
}
Maybe to avoid making your programming life more twisted than it is now...
There are objects and classes in programming, a class is a description of a set of objects, say "table" (or, as it's better to differ in names for classes and variables, "Table", first letter capitalized) is a name of a class. An instance or an object is a structure that belongs to one or more classes, with Object being the topmost, as everything in programming is either an object or a "simple variable", that is, a number, a true/false, a string of characters (these are object types in AS3 too, though, Number, Boolean, String, but these generally not need to be instantiated via new) or probably some other simple type I don't remember right now.
Classes have properties and methods. A property is something that can be requested off any object of the class, say "height" for tables. Properties can be of any type, including nested objects, depending on what your base class is. Say stage in AS3 is a property of any DisplayObject which is used to get the only Stage object there is at runtime[1]. Methods are what any object of a class can be told to do. Say, bombs fall, explode, MovieClips can be told to stop(), etc. You write class code keeping in mind that all of the objects of this class will have to behave exactly like you've written, but since they can differ in properties, you can give them conditional behavior. For example, if a bomb has already exploded, it cannot blow up once more.
A variable, whether a property or a standalone var (if you declare one in a function) is a reference to an object of a given type. Say var i:int refers to some kind of an integer. Simple type vars are containers instead, that is, i=2; will place a 2 in the referred integer, and i=j; will copy the value from j into i, while var theStage:Stage=this.stage will instead create a reference to an existing object, and if that object will change, the reference will give you the changed object instead of its previous state. An array is a collection of variables, reachable by indexes, in AS3 they don't have to be of one type, and a Vector is a typed array.
Next, the lifetime of objects. An object only lives while there's an active reference to it, whether in a property of another alive object, or in a visible variable, or in an event listener (AS3 specific). An object is created via new ClassName(<parameters>), lives while you can reach it somehow, and is destroyed once you have no active links to it and Flash player decides to run garbage collector. Prior to this programmers had to deallocate objects themselves, a rudiment can be seen at BitmapData.dispose(). So, in order to avoid Flash player to run out of free memory, take full control over creation and destruction of links. You don't need to care for simple vars, they are being cared for by Flash player.
A lot of basic functions for interactions has already been implemented in AS3, look for them and examples of how they work in Adobe's manual, navigate through packages in the lower left, most of the interactive stuff is in flash.display package, refer to other packages as necessary.
Hope this will bring you some insight into programming basics.
[1]: There is one stage unless you're doing a load of an SWF, then there could be more, one Stage per one SWF.

Scope Issue: double array not accessible in if statement

I have a class method that is supposed to take an object and populate a few values in place. This is at the stage of functional demonstration, so the implementation will be better later. right now I just would like this to work.
In the code below, the districtID integer is successfully passed to the if statements. The rgb double array does not make it into the if statement scope. The values set at initialization make it all the way to the districtPoint.color without getting set inside the if statement.
the code below will not compile as is. I would like to know how to get the rgb variable to be visible within the if statement scope.
(note: I tried the naive solution of initializing the variables within the if statement. This clears the error, but doesn't let the new rgb variables out of the if scope)
// This method populates properties
+(void)setContantPropertiesForID:(DistrictPoint *)districtPoint
{
int districtID = [districtPoint.districtID intValue];
double rgb[3] = {0,0,0};
if (districtID == 1) {
districtPoint.title = #"District 1";
rgb = {1.0,0.0,0.0}; // error is expected expression
} else if (districtID == 2) {
districtPoint.title = #"District 1";
rgb = {0.0,1.0,0.0};
} else if (districtID == 3) {
districtPoint.title = #"District 1";
rgb = {0.0,0.0,1.0};
} else {
districtPoint.title = nil;
rgb = {1.0,1.0,1.0}; // error condition
}
districtPoint.color = [UIColor colorWithRed:rgb[0] green:rgb[1] blue:rgb[2] alpha:0.5];
}
This has nothing to do with the if statement. You can use the curly-braces notation to set an array's elements only when initializing (as you do, in fact, earlier in the code).

Actionscript 3.0 Get all instances of a class?

I got a ton of movieclips in a class. Is there a more efficient way to apply a function to every instance in the class other than this?
var textArray:Array = [
interludes.interludeIntro.interludeBegin1,
interludes.interludeIntro.interludeBegin2,
interludes.interludeIntro.interludeBegin3,
interludes.interludeIntro.interludeBegin4,
interludes.interludeIntro.interludeBegin5,
interludes.interludeIntro.interludeBegin6,
interludes.interludeIntro.interludeBegin7,
//... ... ...
interludes.interludeIntro.interludeBegin15
];
for each (var interludeText:MovieClip in interludeBeginText)
{
interludeText.alpha = 0 //clear all text first
}
Also for some reason this doesn't work:
interludes.interludeIntro.alpha = 0;
It permanently turns that class invisible, even if I try to make specific instances visible later with:
interludes.interludeIntro.interludeBegin1.alpha = 1;
I have NO idea why the above doesn't work. I want to turn every single instance in the class interludeIntro invisible, but I want to turn specific instances visible later.
(btw I have no idea how to insert code on this website, pressing "code" doesn't do anything, so pardon the bad formatting)
I'm not really sure what you're asking, but what may be useful is that, in ActionScript you can refer to properties by name, like myObject["someProperty"].
Using that, you can iterate over properties if they follow some naming scheme, so for example:
for (var i:int = 1; i <= 15; i ++)
interludes.interludeIntro["interludeBegin" + i].alpha = 0;
That iterates over interludes.interludeIntro.interludeBegin1 through ...15 and sets their alpha properties to 0.
When you do that:
interludes.interludeIntro.alpha = 0;
you turn the movie clip and all its children invisible.
So later when you do that:
interludes.interludeIntro.interludeBegin1.alpha = 1;
You make the movie clip visible, but since its parent is still invisible, you don't see anything. The solution is to loop through the movie clips and make each of them invisible/visible.
// Keep the parent visible at all time
interludes.interludeIntro.alpha = 1;
for (var i:int = 0; i < textArray.length; i++) {
textArray[i].alpha = 0;
}
// Now this will work:
interludes.interludeIntro.interludeBegin1.alpha = 1;

Resources