Showing posts with label get. Show all posts
Showing posts with label get. Show all posts

Thursday, March 10, 2011

Associative array

There no such thing like associative array in ActionScript. It would be too easy. In the other hand every object in AS3 is an associative collection of values. Here is example of how it works:

var assocArray:Object = new Object();

And that is all for creating. to set value we call setter

assocArray.price = 10000;

or more like aray

assocArray['price'] = 10000;

Reading looks similar:

assocArray.price

or

assocArray['price']

More complicated situation is with displaying full array. Trying to trace instance will cause something like this:

[object Object]

Also checking the size or length by variable of method doeas not help because returns zero. The easiest option is to create a for-each loop that displays all variables:

for (var item in assocArray)
{
    trace(item,' : ',assocArray[item]);
}

For counting elements the fastest solution is creating a loop that increments value for each item. But it's not good solution for big structures. In this situation good solution will be own class that controls records with push() and pop() methods.

Tuesday, February 22, 2011

Setters and Getters

Similar to other programming languages like C# there is possibility to create setters and getters in ActionScript. Here is an example:

//method accesed privately
private var _title:String = "Title";


//getter
public function get title():String
{
    return m_title;
}


//setter
public function set title(aTitle:String):void
{

    _title = aTitle;

    /*
     * here can be other code that you need to be executed 
     * when somebody sets your variable
     * example:
     * this.dispatchEvent(new Event('ModelTitleChangeEvent'));
     */
}

Use it or not? It depends on You and Your project. If project is advanced it is useful solution. And in my opinion code is easy to understand.