Putting objects in objects in ActionScript 3 - actionscript-3

I created a class of objects called questions, in each question there is a Question and several Answers. I would like to create a second class of objects called games and have several questions in each game. I would then like to have several games (with several questions) stored locally in a sharedObject?
Is this considered "nesting" an object within another object?

Here's some generic code for a Game class. It contains an array of questions. This basically means it contains as many Question objects as you want that are accessible through the addQuestion() and getQuestion() functions.
public class Game {
private var questions:Array = [];
public function Game() {
}
public function addQuestion(q:Question):void {
questions.push(question);
}
public function getQuestion(i:uint):Question {
return questions[i];
}
}
Likewise, here is the class for a question. It contains a prompt, and an array of answers. Each answer is basically just a String, so there's no real need for an Answer class. If, however, you wanted to expand on this implementation so that each Answer also has other attributes, such as a timestamp, you could make a class for it.
public class Question {
private var prompt:String;
private var answers:Array = [];
public function Question(prompt:String) {
this.prompt = prompt;
}
public function getPrompt():String {
return prompt;
}
public function addAnswer(answer:String):void {
answers.push(answer);
}
public function getAnswer(i:uint):String {
return answers[i];
}
}
So to access the second answer of the first question in a game, you would write 'myGame.getQuestion(0).getAnswer(1)`.
Hope this helped. Let me know if you have any more questions.

Related

How to define an object in actionscript 3 using a custom class

Hi my problem is i have to be able to reference certain fields inside my Customer object.]
I am studying AS3 at the moment and being taught custom classes, but we are taught to use the toString method of returning a value i guess you could call it, what i need is to be able to call one field to identify the object i.e. name field from the object in the array, here's my code
package valueObjects
{
public class Person
{
//instance variables
protected var name:String;
protected var address:String;
protected var phoneNo:String;
public function Person(n:String,a:String,p:String)
{
name=n;
address=a;
phoneNo=p;
}
public function toString():String
{
//returns string
return name+":"+address+":"+phoneNo;
}
}
}
some reason it will not put that whole block of code together like THIS IS
So now how do i define it not toString but in object form ??
I think what you are trying to do is access the name, address and phoneNo vars from a different class?
If so, you have to declare them as public vars instead of private vars.
public var name:String; //now this can be accessed from other classes: thisClassInstance.name
If you want to have them read-only from other classes, you have to use a getter method:
protected var name_:String; //local var name for full access;
public function get name():String {
return name_; //this can be access by doing thisClassInstance.name
}

CircularList in ActionScript 3

I have been working on an AS3 project for some while and I think that I've hit a wall. My project requires a series of elements to be arranged in a Circular List, so I copied myself in a Circular List I had done before in C#.
Problem is, that one was heavily dependant on the usage of Generics. Now I don't have those.
Here are the codes. The T variable type represents the generics that I wish existed.
Node.as:
package
{
public class Node
{
var nodeContent:T;
var nextNode:Node;
function Node(nodeElement:T)
{
this.nodeContent = nodeElement;
}
}
}
CircularList.as:
package
{
public class CircularList
{
var head:Node;
var tail:Node;
var listLength:int;
function CircularList()
{
this.head = null;
this.tail = null;
this.listLength = 0;
}
function Add(addition:T)
{
adding:Node = new Node(addition);
if(this.head == null)
{
this.head = adding;
this.tail = adding;
head.nextNode = tail;
tail.nextNode = head;
}
else
{
tail.nextNode = adding;
tail = adding;
tail.nextNode = head;
}
listLength++;
}
function Find(requested:T):Node
{
var finder:Node = null;
var searching = head;
var i:int;
while(i <= listLength)
{
if(searching.nodeContent == requested)
{
finder = searching;
}
searching = searchig.nextNode;
i++;
}
return finder;
}
}
}
Is there a way to make this thing work without the generics?
EDIT: The real problem with this is that I want the NodeContent in the Node class to be an object. I want to make a list of people sitting on a circular table, basically, but I would like to have a code that I can reuse, rather than something specifically made for this problem
From the comments it seems like your best option here would be to use an interface.
Instead of using a type have all classes T implement an interface like INode. In this interface you can define all the functionality that your type T requires and implement it as needed in each of your implementing classes. This way you can change your function signatures to take type INode instead of Class or * and have a common set of methods that these functions can act upon.
function Add(addition:INode){
//add logic on INode
}
function Find(requested:INode):Node{
//find logic on INode
}
edit: a bit of info about interfaces,
http://active.tutsplus.com/tutorials/actionscript/as3-101-oop-introduction-to-interfaces/
say we have two Classes, A, B and each of these classes have a similar method, doTrace, that needs to be implemented differently. We can define an interface, implement it in both of these classes and pass that type into any method looking to call doTrace
Start with the interface called ITraceable,
public interface ITraceable{
function doTrace():void //all methods defined in interfaces are seen as public
}
Now our two Classes, A and B
public class A implements ITraceable { //implementing our interface, when we do this we need to define all methods in ITraceable
public function doTrace():void{
trace("I am A");
}
}
Do a similar thing for B
public class B implements ITraceable {
public function doTrace():void{
trace("I am B");
}
}
Now in some outside class we want to use this
public function letsTrace():void{
doTheTrace(new A()) //I am A
doTheTrace(new B()) //I am B
}
public function doTheTrace(object:ITraceable):void { //now we can pass both A and B into this function
object.doTrace(); //since ITraceable requires all objects that implement it have this method we can guarantee it will be here
}
Hope this helps you through your application

Passing a variable between 2 actionscript3 files (.as)

How can I pass a variable between 2 actionscript3 files (.as) ?
I have a main fla file and 3 as files, with a class each one...
I have a basic knownelge in AS2 but not too much in AS3
Thanks for help.
It seems that you are trying to access some variables from anywhere in Flash. One way is to create some class with static methods and variables. For example:
package somenamespace {
class Registry {
static private var something_:String;
public function get something():String {
return something_;
}
public function set something(v:String):void {
if (something_ === v) return;
something_ = v;
}
}
}
Then you can access this variable from anywhere in Flash:
Registry.something = "example";
The correct way to pass data between classes is to pass it by reference. This is better than maintaining data with global scope as it permits you to decouple your classes.
It's hard to give you specific advice without seeing your classes and the data you are trying to pass, but here's a simple example using a document class (Main.as) and a child class (Child.as):
Main.as:
package {
class Main extends MovieClip
{
private var someData:String;
//constructor
function Main()
{
//create the data
someData = "my string";
//create an instance of child
var child:Child = new Child(someData);
}
}
}
Child.as:
package {
class Child
{
private var someData:String;
//constructor
function Child(initData:String)
{
someData = initData;
trace(someData); // my string
}
}
}
It sounds like in your case you need a controller class to instantiate the classes you have and to manage the relationships between them. This would be a variation of the Main class above, instantiating all three classes and extracting and passing around their data.

Flex Strongly Typed Proxy Classes for Lazy Instantiation

Does anyone know of a framework, preferably some way to have the Flex compiler run an extension or perhaps just a build step that we could generate strongly typed proxy classes of our application's data models.
There are 2 main things we want to do with the proxy's:
At runtime we want to lazily parse and instantiate the instance as accessed (similiar to how Java's Hibernate has Lazy proxy objects)
In an editor application we want to implement setter calls so we can track which objects have been modified
The Proxy is really necessary in this situation beyond things like programatically setting up ChangeWatcther's because we need to track Array adds/remove and possibly track "reference" objects so that when a "reference key" is changed we know to save those objects that are referencing it by key
In the first case we want the proxy to basically abstract when that object is loaded from serialized data, but still pass around references of it with the same public properties and data access pattern if it were the real object.
Basically the proxy would instantiate the object the first time a method is called on it.
I know we could use some AS3 byte-code libraries like as3-commons-bytecode.
Or possibly repurposing the GraniteDS Code Generation.
I'd prefer to generate code because it is a deterministic thing and it'd be nice if we could have a way to debug it at runtime easier.
Does anyone know if I could do something like MXMLC does when it generates AS3 code from MXML files.
Also is there anyway to control "when" in the compilation pipeline I can generate code, because we have a lot of data objects using public fields instead of getter/setters, but that are [Bindable] and so if I could generate the proxy based on the generated getter/setter methods that would work.
Here's an example application data object and proxy classes:
[Bindable]
public class PersonDTO implements Serializable {
private var _name:String;
private var _age:Number
public function get age():Number {
return _age;
}
public function set age(a:Number):void {
_age = a;
}
public function get name():String {
return _name;
}
public function set name(n:String):void {
_name = n;
}
public void readObject(data:*) {
//...
}
}
// GENERATED CLASS BASED ON PersonDTO
public class LazyProxy_PersonDTO extends PersonDTO {
private var _instance:PersonDTO = null;
private var _instanceData:*;
private function getInstance():void {
if (_instance == null) {
_instance = new PersonDTO();
_instance.readObject(_instanceData);
}
}
override public function get age():Number {
//Ensure object is instantiated
return getInstance().age;
}
override public function get name():String {
//Ensure object is instantiated
return getInstance().name;
}
}
// GENERATED CLASS BASED ON PersonDTO
public class LogChangeProxy_PersonDTO extends PersonDTO {
//This will be set in the application
public var instance:PersonDTO;
//set by application
public var dirtyWatcher:DirtyWatcherManager;
override public function set age(a:Number):void {
dirtyWatcher.markAsDirty(instance);
instance.age = a;
}
}
Digging a little deeper into AS3-Commons byte code library it looks like they support generating proxy classes and interceptors.
http://www.as3commons.org/as3-commons-bytecode/proxy.html
public class DirtyUpdateInterceptor implements IInterceptor {
public function DirtyUpdateInterceptor() {
super();
}
public function intercept(invocation:IMethodInvocation):void {
if (invocation.kind === MethodInvocationKind.SETTER) {
if (invocation.arguments[0] != invocation.instance[invocation.targetMember]) {
invocation.instance.isDirty = true;
}
}
}
}

AS3 - References to argument, is that bad?

I read a question on stackoverflow (couldn't find it now) about how variables in a method can be only accessed in that method, but the code still works with the answer being an analogy of a hotel room. In AS3, I believe everything that's not primitive gets passed as a reference. So, the following code would be the same as that question and isn't guaranteed to work?
public class Testy {
private var foo:Array;
public function Testy(input:Array) {
// Allow the whole class to access it
foo = input;
}
public function traceFoo(){
trace(foo);
}
}
Now, foo would be a reference to the input argument in the class' constructor. Is this safe code/good practice? Thanks!
Yes this is safe/good code practice as long as you don't want to manipulate the original Array. If you want to manipulate the original array, allow public access to the array by making it a public var or using a public getter/setter.
What you've described is a property, and is inline with encapsulation of object oriented programming.
This would expose a getter and setter:
package
{
import flash.display.Sprite;
public class Testy extends Sprite
{
private var _foo:Array;
public function get foo():Array
{
return _foo;
}
public function set foo(value:Array):void
{
_foo = value;
}
public function Testy()
{
super();
}
}
}
Also it's better to return _foo.concat() in getter not to break encapsulation.