Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    Flash




Getter/Setter Methods



Hi,

"Getting" the hang of Getter/Setter methods, but could use a review of my syntax. Does the follwing demonstrate best practices, meaning the least awarkward application of the technique?


Code:
// in Calculator.as
class Calculator {
private var _priceCD:Number;
private var _priceShocks:Number;
private var _priceCover:Number;
//Constructor
function Calculator(newPriceCD:Number, newPriceShocks:Number, newPriceCover:Number) {
_priceCD = newPriceCD;
_priceShocks = newPriceShocks;
_priceCover = newPriceCover;
}
public function get priceCD():Number {
return _priceCD;
}
public function set priceCD(newPriceCD:Number):Void {
if (_priceCD == undefined) {
_priceCD = 0;
}
_priceCD = newPriceCD;
}
public function get priceShocks():Number {
return _priceShocks;
}
public function set priceShocks(newPriceShocks:Number):Void {
if (_priceShocks == undefined) {
_priceShocks = 0;
}
_priceShocks = newPriceShocks;
}
public function get priceCover():Number {
return _priceCover;
}
public function set priceCover(newPriceCover:Number):Void {
if (_priceCover == undefined) {
_priceCover = 0;
}
_priceCover = newPriceCover;
}

}
On timeline:



Code:
var myCalculator:Calculator = new Calculator(100, 500, 250);
trace(myCalculator.priceCD);//100
trace(myCalculator.priceShocks);//500
trace(myCalculator.priceCover);//250




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Getter / Setter Methods
I'm reading on objects and classes right now and there is one thing I don't really understand which would be pretty easy to answer

My question is:

If you have lets say a numSides property on an object and you want to use/change that property...do you need to write out the getNumSides and setNumSides functions or are they automatic!

Cheers!

Getter/setter Methods
I am trying to understand creating methods.
Since I am an AS newbie I want to learn the most efficent way to code. It seems with object properties there are 3 ways to access them.

1. Direct access ( i was told and read this way is frowned upon)
2. getProperty() / setProperty ( I read this is harder to read and "verbose")
3. object.addProperty

Right now I only really understand how to script Direct, which is better to use and why ?

FEK315...OUT!

Public/private Getter/setter Methods
Hi.

When creating a custom class in an .as file, I declared getter/setter methods using the get/set keywords. When I make the methods public, Flash says there are no errors, but if I make any of them private I get the following error message:

"A member attribute was used incorrectly."

So far I haven't found an explanation for this, is there a requirement that all getter/setter methods be public? Doesn't make much sense to me, but perhaps there is a reason for this (if it is indeed the case that they must be public).

Thanks in advance.

Getter And Setter ?
howdy~

i saw description of getter and setter methods from Implicit get/set methods chapter on help doc but i cant get it work, here is my code:

Code:
// X.as
class X
{
private var userName:String;
public function X(un:String)
{
userName = un;
}
function get user():String
{
return userName;
}
function set user(name:String):Void
{
userName = name;
}
}


// test.fla
var x:X = X("someone");
x.user = "anyone";
trace(x.user);


the output is always: undefined, what's wrong here ???

Help In Getter Setter.
Hi,
I am a newbie in actionscript 3.0. I just created a property and the code goes like this..

private var _lastname:String;
private var _firstname:String;

// create a "lastname" property
public function get lastname():String {
return this._lastname;
}
public function set lastname(value:String):void {
this._lastname = value;
}

// create a "lastname" property
public function get firstname():String {
return this._firstname;
}
public function set firstname(value:String):void {
this._firstname = value;
}

When i tried to build this, i got the compile time error
"The private attribute may be used only on class property definitions".
your help is highly appreciated!

Help In Getter And Setter
Hi,
I am a newbie in actionscript 3.0. I just created a property and the code goes like this..

private var _lastname:String;
private var _firstname:String;

// create a "lastname" property
public function get lastname():String {
return this._lastname;
}
public function set lastname(value:String):void {
this._lastname = value;
}

// create a "lastname" property
public function get firstname():String {
return this._firstname;
}
public function set firstname(value:String):void {
this._firstname = value;
}

When i tried to build this, i got the compile time error
"The private attribute may be used only on class property definitions".
your help is highly appreciated!

Help In Getter Setter.
Hi,
I am a newbie in actionscript 3.0. I just created a property and the code goes like this..

private var _lastname:String;
private var _firstname:String;

// create a "lastname" property
public function get lastname():String {
return this._lastname;
}
public function set lastname(value:String):void {
this._lastname = value;
}

// create a "lastname" property
public function get firstname():String {
return this._firstname;
}
public function set firstname(value:String):void {
this._firstname = value;
}

When i tried to build this, i got the compile time error
"The private attribute may be used only on class property definitions".
your help is highly appreciated!

[AS2] Getter/Setter
I am not sure if I am having a brain fart because I am tired or from working with AS3 and having to go back to AS2 for something. Anyways why is this not working.


ActionScript Code:
var foo:Foo = new Foo();
foo.destination = 300;



ActionScript Code:
class Foo
{
   
    //
    // Getter/Setter Values
    //
   
    private var _destination:Number;
   
    public function Foo()
    {
  // when I trace 'destination' I keep getting undefined.
  // I am trying to set the variable instead of having to pass it in as a parameter.
 
        trace( destination );
    }
   
    public function get destination():Number // read-only
    {
        return _destination;
    }
   
    public function set destination( value:Number ):Void
    {
        _destination = value;
    }
}

Getter/setter Question
does anyone see any point to using public variables at all in a class definition, if getter/setter methods are used for accessing the class's properties?

in other words, do getter/setters (for private properties) make public properties obsolete?

Problems With Setter/getter In AS 3.0
hi everyone

i'm trying to convert an AS 2.0 component to an AS 3.0 component but i'm having some problems with getter and setter methods.

here is something similar to what i'm trying to do:

this component has only one variable, _path. in the component inspector i give my variable the value "myFile"


the AS 2.0 component is working fine



Code:
class as2Class extends MovieClip{

private var _path:String;

[Inspectable(defaultValue="", type=String, name="file path")]
public function set path(value:String):Void{
_path = value;
trace("set")
}
public function get path():String{
return _path;
}
public function as2Class(){
trace(_path);
trace("constructor")
}
}


if i test the component in the output panel i get :
set
myFile
constructor

but the AS 3.0 component isn't working



Code:
package{
import flash.display.MovieClip;

public class as3Class extends MovieClip{

private var _path:String;

[Inspectable(defaultValue="", type=String, name="file path")]
public function set path(value:String):void{
_path = value;
trace("set")
}
public function get path():String{
return _path;
}
public function as3Class(){
trace(_path);
trace("constructor")
}
}
}


if i test this component, in the output panel i get:
null
constructor
set

why isn't the as3 component working like the as2 component? and how could i
fix this problem?

Thank you.

Dynamic Getter/setter?
Is it possible to have a dynamic getter/setter for variables? Like PHP has.

I want to be able to do: class.value = 5; and trace(class.value);

But without having value defined in the class. I know, I know, dynamic class. But that's not the entire case. I need to handle the input and retrieval with a getter/setter. I'd really rather not do a class.setVariable("variable", "value"); thing.

Thanks.

Getter And Setter Query ?
in a class im trying to work out is see the following

Code:
function get( lab:String )
{
return this.obj[lab];
}
shouldnt there be a name after the get ?

New To OOP AS Getter/Setter Question
Hi i am trying some oop AS 2.0, reading the book Object - Oriented Programming with Action script 2.0 by Jeff Tapper.

The book states that getter and setter methods shoub be used to access and modify variables. But surly that will created a hug about of code.
Take for example the following:

Code:
class gameInfo {
private var gameTime:String;
private var itemSpeed:Number;
function gameInfo(gameTime:String, itemSpeed:Number) {
trace('Constructor loaded');
gameTimer = gameTime;
itemVelocity = itemSpeed;
}
public function get gameTimer():String {
return this.gameTime;
}
public function set gameTimer(gameTimer:String):Void {
this.gameTime = gameTime;
//set the txtbox timer
}
public function get itemVelocity():Number {
return this.itemSpeed;
}
public function set itemVelocity(itemVelocity:Number):Void {
this.itemSpeed = itemSpeed;
}
}
// fla
import gameInfo;
var gInfo = new gameInfo();
gInfo.gameTime =10;
gInfo.itemSpeed =20;
trace('Game Time: '+gInfo.gameTime);
trace('Items Speed: '+gInfo.itemSpeed);
Just to get and set two variables i have had to write a 22 line class. Surely this class is going to be huge by the time i have finished. I have a few more variables to create and access before the processing is added.

Problems With Setter/getter In AS 3.0
hi everyone

i'm trying to convert an AS 2.0 component to an AS 3.0 component but i'm having some problems with getter and setter methods.

here is something similar to what i'm trying to do:

this component has only one variable, _path. in the component inspector i give my variable the value "myFile"


the AS 2.0 component is working fine



ActionScript Code:
class as2Class extends MovieClip{
           
    private var _path:String;
   
    [Inspectable(defaultValue="", type=String, name="file path")]
    public function set path(value:String):Void{
        _path = value;
        trace("set")
    }
    public function get path():String{
        return _path;
    }
    public function as2Class(){
        trace(_path);
        trace("constructor")
    }
}

if i test the component in the output panel i get :
set
myFile
constructor


but the AS 3.0 component isn't working


ActionScript Code:
package{
    import flash.display.MovieClip;
   
    public class as3Class extends MovieClip{
           
        private var _path:String;
   
        [Inspectable(defaultValue="", type=String, name="file path")]
        public function set path(value:String):void{
            _path = value;
            trace("set")
        }
        public function get path():String{
            return _path;
        }
        public function as3Class(){
            trace(_path);
            trace("constructor")
        }
    }
}

if i test this component, in the output panel i get:
null
constructor
set

why do you think it doesn't work?

Thank you.

Getter And Setter.. How Does It Work?
Hi there, i am trying to study Object-Oriented Actionscript for flash.

I have a little bit trouble understanding the getter and setter functions.

Why do they use it? And is there a usable sample somewhere?

-- Update: 11:14 .. i found someting usefull on the web:

http://livedocs.adobe.com/flash/mx2004/main_7_2/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flash_MX_2004&file=00001074.html
































Edited: 04/11/2008 at 02:15:06 AM by Michealnl

Class, Setter And Getter.
Hi Everyone


Does anyone use this kind of syntax for creating the setter and getter for their custom classes?

public function get foo():dataType {
return _foo;
}
public function set foo(value:dataType):Void {

}


Does the above syntax have any advantages over the bottom one?
I find the top one quite confusing (esp. with the extra space).

public function getFoo():dataType {
return _foo;
}
public function setFoo(value:dataType):Void {

}

Thanks in advance

Getter/Setter Using Different Accessors
Hey all,


ActionScript Code:
public function set varName(list:XMLList):void {    _varName = int(list.@value);}        public function get varName():int {    return _varName;}


As you can see, I'm trying to set varName using an XMLList object and trying to get the getter method to spit back the value, an int(). This gives me an error:

1053: Accessor types must match.

I know this must be because I'm trying to get an XMLList object as the input and output an int, but is there any way I can do this without having to use normal methods? I desperately need to be able to use getter/setter methods simply because I can use variable syntax...

Problems With Setter/getter In AS 3.0
hi everyone

i'm trying to convert an AS 2.0 component to an AS 3.0 component but i'm having some problems with getter and setter methods.

here is something similar to what i'm trying to do:

this component has only one variable, _path. in the component inspector i give my variable the value "myFile"


the AS 2.0 component is working fine



Code:
class as2Class extends MovieClip{

private var _path:String;

[Inspectable(defaultValue="", type=String, name="file path")]
public function set path(value:String):Void{
_path = value;
trace("set")
}
public function get path():String{
return _path;
}
public function as2Class(){
trace(_path);
trace("constructor")
}
}
if i test the component in the output panel i get :
set
myFile
constructor

but the AS 3.0 component isn't working


Code:
package{
import flash.display.MovieClip;

public class as3Class extends MovieClip{

private var _path:String;

[Inspectable(defaultValue="", type=String, name="file path")]
public function set path(value:String):void{
_path = value;
trace("set")
}
public function get path():String{
return _path;
}
public function as3Class(){
trace(_path);
trace("constructor")
}
}
}
if i test this component, in the output panel i get:
null
constructor
set

am i doing something wrong or it is a bug?

Thank you.

Getter / Setter Being Taken Advantage Of
Okay, an interesting question that I haven't found a definitve answer for yet (but I'm sure there is one out there )

If I have a class that has an object such as a Point that uses getter / setter methods to set it, I seem to be able to bypass the setter and rely only on the getter to get and set, which is a little strange.

For example, pretend this is part of a class called PointTest:


Code:
private var myPoint:Point = new Point();

public function get thePoint ():Point
{
return myPoint;
}
And then elsewhere...


Code:
var myPointTest:PointTest = new PointTest();

myPointTest.thePoint.x = 50;
The above works, even though no setter is defined. It seems to bypass the setter and set through the getter, which is... well, not quite what I was expecting

Any thoughts on how I might try and control this? An alternative would be to have getter/setters for the X and Y values only that set the point's X and Y internally, but that's a little messy. Thanks

Class, Setter And Getter.
Hi Everyone


Does anyone use this kind of syntax for creating the setter and getter for their custom classes?

public function get foo():dataType {
return _foo;
}
public function set foo(value:dataType):Void {

}


Does the above syntax have any advantages over the bottom one?
I find the top one quite confusing (esp. with the extra space).

public function getFoo():dataType {
return _foo;
}
public function setFoo(value:dataType):Void {

}

Thanks in advance

TabIndex = [getter/setter] Undefined
I'm getting this error in most all of my MX stuff...
the stuff that's really button heavy adds a crapload of code which makes it annoying to debug:

Variable _level0.instance6.tabIndex = [getter/setter] undefined

what is this and what do i do to make it go away?

TabIndex = [getter/setter] Undefined?
Variable _level0.empty_navigation_mc.contact_btn.tabIndex = [getter/setter] undefined

im working in flash mx 2004, i have tested project and clicked debug, list variables. In the list of variable some of my buttons have the tabIndex = [getter/setter] undefined and i would like to know what it means?
Any ideas?

Getter/Setter Within A Class With A Component
I have a class file which loads comboboxes on the stage. In the interaction various things happen which need to be recorded, and I had done this in the past by setting properties on movie clips. I.E. -

mc1.propertyName = true/false;

I try to do that with a component and get a message saying that the property can't be created on fl.controls.ComboBox.

The property name is: isRed. It's being set like this:

combo1.isRed = true/false;

Here's the getter/setter:

public function get isRed():Boolean {
return _isRed;
}
public function set isRed(value:Boolean):void {
_isRed = value;
}


Also tried this:

[Inspectable(defaultValue=false)]

public function get isRed():Boolean {
return _isRed;
}
public function set isRed(value:Boolean):void {
_isRed = value;
}

Any ideas? Thanks.

Getter And Setter Function - Explain Syntax
Hey there:

Just a quick question:

Why is there a difference in syntax between the getter and setter functions within a class? For example, consider the following:

code:
public function set username(value:String):Void {
this.__username = value;
}

public function get password():String {
return this.__password;
}


Why does the setter function use: username(value:Strong):Void, and the getter function use password():String? Why don't they both use the same syntax?

Getter/Setter And Information Hiding Question
Howdy Folks,

I'm parsing through a pile of xml and breaking into chunks of regional data.

I've built two classes RegionalData.as and DataArray.as files. to hide the QuestionData.as and FactData.as classes as plain objects for retrival using a getter within the RegionalData.as but unfortunately things aren't working like I thought they would.

Can a getter in one object be used to retrieve values from another object as long as the references and pointers are correct?

Here's RegionalData.as class

ActionScript Code:
package gameClasses
{
    ////////////////
    import DataArray;
    ////////////////
    public class RegionalData
    {
        ////////////////
        private var oQuestions:DataArray = new DataArray();
        private var oFacts:DataArray= new DataArray();
        ////////////////
        private var _region:String;
        ////////////////
        public function RegionalData ()
        {
        }
        ////////////////
        public function set RegionName (x:String):void
        {
            _region = x;
        }
        ////////////////
        public function get RegionName ():String
        {
            return _region;
        }
        ////////////////
        public function get RegionQuestion ():Object
        {
            return oQuestions.ArrayItem;
        }
        ////////////////
        public function set RegionQuestion (x:Object):void
        {
            oQuestions.ArrayItem = x;
        }
        ////////////////
        public function get RegionFact ():Object
        {
            return oFacts.ArrayItem;
        }
        ////////////////
        public function set RegionFact (x:Object):void
        {
            oFacts.ArrayItem = x;
        }
        ////////////////
        public function randomizeQuestionArray ():void
        {
            oQuestions.RandomizeArray ();
        }
        ////////////////
        public function randomizeFactsArray ():void
        {
            oFacts.RandomizeArray ();
        }
        ////////////////
    }
}

Here's the DataArray.as class:

ActionScript Code:
package gameClasses
{
    ////////////////
    import Utils;
    ////////////////
    public class DataArray
    {
        ////////////////
        private var oUnusedItemArray:Array = new Array();
        private var oUsedItemArray:Array = new Array();
        ////////////////
        public function DataArray(){}
        ////////////////
        public function get ArrayItem ():Object  
        {
            var myObj:Object;
           
            if (oUnusedItemArray.length > 0)
            {
                myObj = oUnusedItemArray.pop();
                oUsedItemArray.push(myObj);
            }
            else // the oUnusedItemArray array is empty time to reset it
            {
                oUnusedItemArray = oUsedItemArray.splice(0);
                oUnusedItemArray.sort (Utils.RANDOMIZE);
                myObj = oUnusedItemArray.pop();
                oUsedItemArray.push(myObj);
            }
            return myObj;
        }
        ////////////////
        public function set ArrayItem (x:Object):void
        {
            oUnusedItemArray.push(x);
        }
        ////////////////
        public function RandomizeArray():void
        {
            oUnusedItemArray.sort (Utils.RANDOMIZE);
        }
        ////////////////
    }
}

In a nutshell I am trying to use a getter in the RegionalData.as class to call the getter of the DataArray.as class and its doesn't seem to be working properly.

In fact when I debug this function:

ActionScript Code:
////////////////
public function set ArrayItem (x:Object):void
{
    oUnusedItemArray.push(x);
}
////////////////

I see that the oUsedItemArray array already has a length of 1 which is incredibly strange because I haven't placed anything it, nor have I called getter which would have triggered this behavior.


Also, I noticed that when debugging. This function:

ActionScript Code:
////////////////
public function get RegionQuestion ():Object
{
  return oQuestions.ArrayItem;
}
////////////////

The value in the debugger says <exception thrown by getter> and Im beginning to wonder if this getter calling another getter approach is not the best solution.

Any suggestions would be greatly appreciated.

cheers,

frank grimes

Adding Dynamically A Getter Setter Function To A Dynamic Class
Does someone know how to add getter and setter methods dynamically to a dynamic class ?


Code:
function get foo():Object {return _foo;}
function set foo(Object f) {_foo=f;}

For example I would like to do something like :




Code:
var mc:MovieClip=new MovieClip();
mc.get foo=function() {...}
mc.set foo=function(...) {...}
But it doesn't work...

Using Setter Methods With Arrays?
Hey, I'm trying to use a setter method on a private property in a class, the property is an array.

What i'm trying to do is change one of the indexes in the array, but when it changes I want it to loop through that whole array and set the rest of the values equal to 0.


ActionScript Code:
class MyClass{

    private var _Captain         :Array = new Array();


    public function MyClass(){
    /* the players unformation is indexed according to their jersey number */
        this._Captain[23]        = 0;
        this._Captian[10]        = 0;
        this._Captain[32]        = 1;
        this._Captian[13]        = 0;
        this._Captian[11]        = 0;
    };//end MyClass


    public function set Captain(n:Number){

        for(var v in this._Captain){
            if(typeof this._Captain[v] == 'function') continue;
            this._Captain[v]     = (Number(v) == n) ? 1 : 0;
        }
    };

}//end MyClass


var h:Object = new MyClass();

changeCaptainBut.onPress = function(){
// so when the user clicks on the button it is going to change #23 to
// the captain, then make everyone else !!NOT!! a captain
// (i.e. h._Captain[(their jersey number )] = 0)
        h.Captain[23] = 1;
};


So what i was wondering is, how can I do this?

MovieClip Setter Methods Override Problem
Hi, i am new to this forum

I came upon this problem hope someone already did and can give me few tips or a solution. I created some kind of encapsulator class which extends MovieClip here it goes:


Code:
dynamic class com.fw20.EncapsulatorMC extends MovieClip
{
private var __m_mcEncapsulator:MovieClip;

public function set _xscale(p_nValue:Number):Void
{
trace("overriden _xscale set method");
this.__m_mcEncapsulator._xscale = p_nValue;
}
public function get _xscale() : Number
{
return this.__m_mcEncapsulator._xscale;
}

public function set _rotation(p_nValue:Number) : Void
{
this.__m_mcEncapsulator._rotation = p_nValue;
}

public function EncapsulatorMC()
{
__m_mcEncapsulator = this.createEmptyMovieClip("encapsulator", 0);
}
}
As you can see the aim of this encapsulator is for offseting purposes and that it will not _rotate nor _scale clip itself but internal mc instead. But thats not an issue

I stripped the class of the unnecessary code so you can see the main problem, and that is if i attach movie like this just for test purposes (of course encapsulatorMC id is linked to com.fw20.EncapsulatorMC):


Code:
_root.attachMovie("encapsulatorMC", "testEncapsulator", 1);
_root.testEncapsulator._rotation = 90;
It will not call my overridden setter method just MovieClips original setter method. I can go around it type casting it to my class like this:


Code:
EncapsulatorMC(_root.testEncapsulator)._rotation = 90;
Which will call my overriden method but its impossible to always type cast (especially passing it to tweening :/) so i am asking if there is any other method to do this, or is there something i am missing?

I am aware that easiest solution is to encapsulate it without extending movieclip and then just reference everything to internal clip, but that will be last thing i am goin to do

Any suggestions are welcomed, thanks.

Sappho

Getter/Setters Or Public Methods?
When you all write your classes, and you want to expose certain elements of your class to outside parties etc. Do you generally use getter/setters or public functions?

To me a getter/setter is for adjusting a property of your class where as a method is more for say adjusting its behaviour state. For instance, a method called classInstance.play() that plays a video file makes more sense than say a setter classInstance.play = true.

But then, in some cases the distinction is less defined. For instance, changing the volume of something, volume is a property, and seems to fit with a getter/setter pair well: classInstance.volume = .1 as opposed to classInstance.volume(.1).

I guess its a matter of style, but are there any 'hard and fast' rules about when to use a getter/setter verses when to use a public method?

(I realise that getters/setters are also public)

Call Class Getter & Setter From Another Class
I have 2 classes (triangle.as and circle.as) each of the classes draws a shape and another shape inside a movieclip which acts as a button.
Then from the document root (main.as) I create an instance of the triangle.as (tri) and the circle.as (cir) and add them to the displaylist.
when run displays a triangle + button and a circle + button on the stage.

The triangle class has getter and setter functions which are getValue & setValue.

when I call these getter and setter functions from main.as

tri.setValue = 100;
trace(tri.getValue);

everything works fine, but then when I try

tri.setValue = 100;
trace(tri.getValue);

from within the circle class the error says it doesn't recognize 'tri' which I can understand as it is referencing another class outside of the current class it is called in.

I did try....

parent.tri.setValue = 100;
trace(parent.tri.getValue);

but made no difference.

So the problem is how to reference a classes getter & setter functions from within another class.

Any help would be much appreciated. Thanks

Overriding Base Class Methods While Calling Original Methods
I would like to write a class that extends XMLSocket. I'd like to call my class RPCSocket. Among other things, I want to add a property which indicates that the socket is 'waiting to connect'. This would mean that the connect() method of XMLSocket has been called but the CONNECT event has not yet been dispatched. I'll therefore need to override the CONNECT and CLOSE methods of XMLSocket in my class, RPCSocket.

I haven't yet seen any reason why I can't override these methods -- they are neither constant nor static nor final and do not implement an interface method (as far as I can tell) and they are inherited.

I obviously need to call the original connect() and close() methods of the XMLSocket, however. Is this code the proper way to do this? Can anyone see any particular problem with this?

code:
package {
class RPCSocket extends XMLSocket {
public var boolWaitingToConnect:Boolean = false;

public override function connect(host:String, port:int):void {
boolWaitingToConnect = true;
super.connect(host, port);
}
public override function close(host:String, port:int):void {
boolWaitingToConnect = false;
super.close();
}
}
}

Static Methods Vs. Instance Methods And Memory Usage
Hello all, I'm pretty green to OOP (at least "real" OOP) and am trying to wrap my tiny little brain around something. I understand the difference between static and instance methods in the practical sense, i.e. how the static modifier affects a method for in a class. What I'm not 100% on is memory usage and whether I should even care. Here’s my specific scenario for context:

I am creating a package for list generation, rendering and editing, there are a number of classes in the package; Item, PlainList, EditableList and DragDropList. At a minimum, one of the list constructors is passed a target movie (where to draw the list), itemName (symbol name for Item constructor) and dataList (data items for Item constructor). There is also an EventDispatcher that fires "onInitList", "onInitItem", "onSelectItem", etc. These lists could be hundreds of items long and contain sub-list instances. So, long story there could be thousands of list/item instances at a time.

The majority of methods (in pretty much all classes) could be written as static by simply passing the target instance. For public methods, I would make lightweight wrappers that call the appropriate static method, for example:


Code:

class PlainList {
public function PlainList( target:MovieClip, itemName:String, dataList:Object, margin:Number, xOffset:Number, yOffset:Number, rows:Number ){
//bunch'o'code here
}
public function draw( type:String ){
if ( type == "grid" ) PlainList.drawGrid( this );
else PlainList.drawList( this );
}
private static function drawGrid( pl:PlainList ){
//bunch'o'code here
}
private static function drawList( pl:PlainList ){
//bunch'o'code here
}
}



As I understand it, if I use static methods, the method is instantiated only once for the class and there is only one pointer to it. If I were using instance methods each method is uniquely instantiated with it's own memory space and pointer for ever instance of the class. Given that there could be thousands of class instances at a time each with 20-30 methods, does the technique described above make sense? Will I be saving memory? Is this bad OOP? And finally, although right now I am using AS2 in Flash 8, I will be updating to Flash 9 ASAP, any implications regarding AS3? For example, usage of the "protected" and "final" modifiers? Thanks.

Overriding Methods While Accessing Original Methods
I would like to write a class that extends XMLSocket. I'd like to call my class RPCSocket. Among other things, I want to add a property which indicates that the socket is 'waiting to connect'. This would mean that the connect() method of XMLSocket has been called but the CONNECT event has not yet been dispatched. I'll therefore need to override the CONNECT and CLOSE methods of XMLSocket in my class, RPCSocket.

I haven't yet seen any reason why I can't override these methods -- they are neither constant nor static nor final and do not implement an interface method (as far as I can tell) and they are inherited.

I obviously need to call the original connect() and close() methods of the XMLSocket, however. Is this code the proper way to do this? Can anyone see any particular problem with this?


ActionScript Code:
package {
    class RPCSocket extends XMLSocket {
        public var boolWaitingToConnect:Boolean = false;

        public override function connect(host:String, port:int):void {
            boolWaitingToConnect = true;
            super.connect(host, port);
        }
        public override function close(host:String, port:int):void {
            boolWaitingToConnect = false;
            super.close();
        }
    }
}

Value Setter Knobs
Here's my swf of the day.. What do you folks think?
I can think of a few good applications for it.

http://www.themuseav.com/weisel/knobs.htm

and the scroll knob:
http://www.themuseav.com/weisel/scrollknob.htm

-theweisel
[Edited by theweisel on 12-06-2001 at 05:17 PM]

Having An Array Setter
Is it difficult to have a setter function for an array so that when one of the items in the array is set, a function gets called? Does it need to be an ArrayCollection with an event listener?

Thanks in advance for any help
B

Setter Problem With My Class
Hey All, can anyone tell me why the setter function of my Class does not affect the trace in the Event Handler of my Class? I have commented the problem spots of my code. Thanks in advance, Dvl

Code:
// ** AUTO-UI IMPORT STATEMENTS **
import com.acmewebworks.controls.BaseClip;
import mx.utils.Delegate;
import com.creativenetdesign.imageviewer.ImageViewer;
import mx.controls.Label;
import com.creativenetdesign.imageviewer.ControlPanel;
// ** END AUTO-UI IMPORT STATEMENTS **
class com.creativenetdesign.imageviewer.Main extends BaseClip{
// Constants:
public static var CLASS_REF = com.creativenetdesign.imageviewer.Main;
public static var LINKAGE_ID:String = "com.creativenetdesign.imageviewer.Main";
// Public Properties:
var imgViewerFrame:Number
// Private Properties:
// UI Elements:
// ** AUTO-UI ELEMENTS **
private var controlPanel:ControlPanel;
private var ImageViewer:ImageViewer;
private var labelTitle:Label;
// ** END AUTO-UI ELEMENTS **
// Initialization:
public function Main() {}
private function onLoad():Void { configUI(); }
// Public Methods:
// PROBLEM ***************************************************************
// This is the setter function that is beling called from the FLA timeline:
// imv_mc.setImageViewerFrame = 3
public function set setImageViewerFrame(frame:Number):Void {
imgViewerFrame = frame;
//this trace works fine
trace("setImageViewerFrame() is setting var imgViewerFrame to "+frame)
}
// END PROBLEM ***********************************************************
// Semi-Private Methods:
// Private Methods:
private function configUI():Void {
trace("MAIN INIT")
// init ImageViewer
controlPanel.addEventListener("controlClick", Delegate.create(this, handleButtonClicked));
}
//
// PROBLEM ************************************************************
// imgViewerFrame always traces out to UNDEFINED
private function handleButtonClicked(obj:Object):Void {
trace("MAIN HEARD "+obj.type+" FROM "+obj.target+" image viwer is on frame: "+imgViewerFrame);
// END PROBLEM ********************************************************
var viewerOnFrame:Number = _level0.main.imageViewer_mc._currentframe
//trace("VIEWER FRAME IS "+viewerOnFrame)
if (obj.target == _level0.main.controlPanel.next_btn){
if (viewerOnFrame == 1 ){
_level0.main.imageViewer_mc.gotoAndStop(2)
}else if (viewerOnFrame == 2){
_level0.main.imageViewer_mc.gotoAndStop(3)
}else if (viewerOnFrame == 3){
_level0.main.imageViewer_mc.gotoAndStop(4)
}
else if (viewerOnFrame == 4){
_level0.main.imageViewer_mc.gotoAndStop(5)
}
else if (viewerOnFrame == 5){
_level0.main.imageViewer_mc.gotoAndStop(6)
}
else if (viewerOnFrame == 6){
_level0.main.imageViewer_mc.gotoAndStop(1)
}
}
//
if (obj.target == _level0.main.controlPanel.prev_btn){
if (viewerOnFrame == 1 ){
_level0.main.imageViewer_mc.gotoAndStop(6)
}else if (viewerOnFrame == 2){
_level0.main.imageViewer_mc.gotoAndStop(1)
}else if (viewerOnFrame == 3){
_level0.main.imageViewer_mc.gotoAndStop(2)
}
else if (viewerOnFrame == 4){
_level0.main.imageViewer_mc.gotoAndStop(3)
}
else if (viewerOnFrame == 5){
_level0.main.imageViewer_mc.gotoAndStop(4)
}
else if (viewerOnFrame == 6){
_level0.main.imageViewer_mc.gotoAndStop(5)
}
}
}

}

Getter Not Returning Value
I was hoping someone can give me a hand with the following class which I have a setter and getter method , the getter method should return an array collection but it's always returning an empty array collection even when I've run trace to check on it.

Class file is attached below , and here's how I'm calling it

Code:
var webService:WebService = new WebService();
webService.searchText = searchText.text;
webService.searchParam = searchComboBox.selectedLabel;
webService.searchBook();
trace("WEBSERVICE ARRAY OF Book ----->" + webService.arrayOfBook); // This would return as empty array

Code:
package
{
import com.something.*;

public class WebService{

public var _arrayOfBook:ArrayOfBook;
private var _magazine:Book;
private var _service:Service = new Service();
private var _searchText:String;
private var _searchParam:String;

public function WebService(){
_arrayOfBook = new ArrayOfBook();
}

public function set searchText(value:String):void{
this._searchText = value;
}

public function get searchText():String{
return _searchText;
}

public function set searchParam(value:String):void{
this._searchParam = value;
}

public function get searchParam():String{
return _searchParam;
}

public function get arrayOfBook():ArrayOfBook{
trace(this._arrayOfBook) // this trace shows an empty array collection
return this._arrayOfBook;

}


public function searchBook():void{
_service.addgetTitleEventListener(handleServiceError);
var request:GetTitle_request = new GetTitle_request();
request.searchString = _searchText;
request.searchParameter = _searchParam.toLowerCase();
_service.getTitle_request_var = request;
_service.getTitle_send();
_service.addgetTitleEventListener(convertData);
}

public function convertData(e:GetTitleResultEvent):void{
_arrayOfBook = e.result;
_arrayOfBook.filterFunction = filterImage;
_arrayOfBook.refresh();
}

public function filterImage(item:Object):Boolean{
return item.imagename;
}



private function handleServiceError(event:GetTitleResultEvent):void{
trace(event.result); // trace here shows that my array is filled
}


}
}

[AS3] Getter Or Method?
I have been doing some thinking and wanted to know peoples approach. In my classes that I build if I have a private variable that I want to access outside the class I will use a getter method to return the value.

Is there a rule/good practice way of when to use a getter method, or is it just a matter of preference. Below are two examples that do the exact thing except one is a getter the other is not.


Code:
public function get foo():String {
return _foo;
}

public function getFoo():String {
return _foo;
}

Getter Not Returning Value
was hoping someone can give me a hand with the following class which I have a setter and getter method , the getter method should return an array collection but it's always returning an empty array collection even when I've run trace to check on it.

Class file is attached below , and here's how I'm calling it
Code:

var webService:WebService = new WebService();
webService.searchText = searchText.text;
webService.searchParam = searchComboBox.selectedLabel;
webService.searchBook();
trace("WEBSERVICE ARRAY OF Book ----->" + webService.arrayOfBook);      // This would return as empty array


Code:

package
{
        import com.something.*;
       
        public class WebService{
               
                public var _arrayOfBook:ArrayOfBook;
                private var _magazine:Book;
                private var _service:Service = new Service();
                private var _searchText:String;
                private var _searchParam:String;
               
                public function WebService(){
                        _arrayOfBook = new ArrayOfBook();
                }
                       
                public function set     searchText(value:String):void{
                        this._searchText = value;
                }
               
                public function get searchText():String{
                        return _searchText;
                }       
                       
                public function set searchParam(value:String):void{
                        this._searchParam = value;
                }       
               
                public function get searchParam():String{
                        return _searchParam;
                }
                               
                public function get arrayOfBook():ArrayOfBook{
                       trace(this._arrayOfBook) // this trace shows an empty array collection
                        return this._arrayOfBook;

                }
                       
                       
                public function searchBook():void{
                        _service.addgetTitleEventListener(handleServiceError);
                        var request:GetTitle_request = new GetTitle_request();
                        request.searchString = _searchText;
                        request.searchParameter = _searchParam.toLowerCase();
                        _service.getTitle_request_var = request;
                        _service.getTitle_send();
                        _service.addgetTitleEventListener(convertData);
                }
                       
                public function convertData(e:GetTitleResultEvent):void{
                                _arrayOfBook = e.result;
                                _arrayOfBook.filterFunction = filterImage;
                                _arrayOfBook.refresh();
                        }       
                       
                public function filterImage(item:Object):Boolean{
                        return item.imagename;
                }       
               
               
                       
                private function handleServiceError(event:GetTitleResultEvent):void{
                            trace(event.result); // trace here shows that my array is filled
                }
               

        }
}

Setter Function Won't Take Array Of Objects
hi,

is there any reason why my class's setter function won't take an array of objects as a value to set with?

in plain style code i can do:

Code:
obj = {v1:"foo",v2:"bar"};
myArr = [obj];
trace(myArr[0].v1);// outputs "foo"
all seems fine.

but if i do something like:

Code:
class Simple extends MovieClip
{
private var __myArray = [];

function Simple ()
{}

public function set myArray (val)
{
__myArray = val
}
}
and then set myArray = anArrayOfObjects
the length of the array is available but each object has been flattened to the string "[object Object]", the object itself has not been passed.

why? any way around it?
please help if you can, thanks

Calling Setter From Inside The Class
Is it possible to call a setter function from inside the class? If yes, then how to reference it?

Suppose we have the code


ActionScript Code:
class My {
private var _myVar:String;

public function set myVar (something:String) : void {
_myVar = somethig.substr(1,5);
}

public function get myVar () : String {
return _myVar.substr(20,30); // whatever it means
}

private function callFromInside (someString:String) : void {
//I want to assign a value to _myVar but not to repeat the procedure of making a substring, I want to use once defined setter procedure, but if I call something which should mean _myVar = setter (someString):
this.myVar = someString;
//then it first calls getter function to resolve this.myVar and then setter function. This is not what I want ! I need to call only setter...
}
}

Do I need to define third function which performs what setter should perform and then call this function from both setter and all other places I need (and this way still have the substringing procedure defined in one place), or is it somehow possible to call a setter function directly from inside a class?

Methods Called From Methods
I created a class, set some methods for the class, and registered to an object. Is it possible to call methods for this class inside other methods inside the class? I mean, if there were two functions called 'a' and 'b', would it be possible to do something like:



Code:
myClass.prototype=function(){}
...
myClass.prototype.a=function(){
...

b()

...
}
myClass.prototype.b=function(){
...
}
...

Methods Called From Methods
I created a class, set some methods for the class, and registered to an object. Is it possible to call methods for this class inside other methods inside the class? I mean, if there were two functions called 'a' and 'b', would it be possible to do something like:



Code:
myClass.prototype=function(){}
...
myClass.prototype.a=function(){
...

b()

...
}
myClass.prototype.b=function(){
...
}
...

Override Protected Getter?
I have 3 classes set up. An abstract, a concrete and a utility that needs access to the concretes getter. When I try to access the property of the concrete from within the utility it throws an error.

//abstract

PHP Code:



package{  import flash.errors.IllegalOperationError;  class{    protected function get left():Number{      throw new IllegalOperationError("Abstract method: must be overridden in a subclass");    }  }}




//concrete

PHP Code:



package{  class extends abstract{    override protected function get left():Number{      return someVal;    }  }}




//utility

PHP Code:



package{  class utility{    private var concrete:abstract;    public function utility(concreteClass:abstract){      this.concrete = concreteClass;      init();    }    private class init():void{      trace(concrete.left); //1178: Attempted access of inaccessible property left through a reference with static type abstract.    }  }}




//client

PHP Code:



package{  class{    public function client():void{      var c = new concrete();      var u = new utility(c);    }  }}




Any idea how to gain access?

OOP - Problem With Getter Method...
Hi guys

I'm experimenting a little with Flashr 0.5, but got stuck cause of my newbie knowledge of OOP :/

My problem is, that my array - _arrReturn traces fine in my private method, but in my getter method it returns undefined!?!


ActionScript Code:
import com.kelvinluck.flashr.core.Flashr;
import com.kelvinluck.flashr.core.FlashrResponse;
import com.kelvinluck.flashr.core.Person;
import com.kelvinluck.flashr.core.Photo;
import com.dynamicflash.utils.Delegate;

class com.jboy.slider.FlickrLoader
{
    private var _apiKey:String = "xxx";
    private var _userNsid:String = "94146040@N00";
    private var _arr:Array;
    private var _arrReturn:Array;
   
    // Allow me to get the array of info
    public function get getCollection():Array
    {
        return _arrReturn; // returns undefined!??
    }
   
    // CONSTRUCTOR
    public function FlickrLoader()
    {
        var _flickr:Flashr = Flashr.getFlashr();
        _flickr.apiKey = _apiKey;
       
        var _responseListener:FlashrResponse = new FlashrResponse();
        _responseListener.setSuppressOutput(true);
        _responseListener.onPeopleGetPublicPhotos = Delegate.create(this, onPeopleGetPublicPhotos);
        _flickr.peopleGetPublicPhotos(_userNsid, null, 12,1);
    }
   
    // Add info to Array
    private function onPeopleGetPublicPhotos(p:Person):Void
    {
        var _arrReturn:Array = new Array();
        var _arr:Array = new Array();
        _arr = p.getPhotos();
       
        for (var i:Number=0; i<_arr.length; i++)
        {
            var pic:Photo = Photo(_arr[i]);
            _arrReturn.push(pic.thumbnailUrl);
        }
        trace(_arrReturn); // Works fine here!!
    }
}

Hope somebody can help me out here....

Thnx

OOP Problem: Getter ( Flex 2 )
I'm having an issue with event handlers here. Take the following code:


ActionScript Code:
public class Test {

    private var _data:XML = null;
    public function get Data():XML {
        if( _data == null ) {
            var sampleService:HTTPService = new HTTPService();
            sampleService.url = "products.xml";
            sampleService.resultFormat = "xml";
            sampleService.addEventListener(ResultEvent.RESULT,SampleServiceResultHandler);
            sampleService.send();
        } else {
            return _data;
        }
    }

}

The _data variable is read only and I want, if it's null, to give it the value of the result of that HTTPService. But that can't work because I have to go to the "SampleServiceResultHandler" method to get and assign that value. And this will take me out of the getter. Is there a cleaner way to make this?

Another solution for me will be to make the HTTPService request from the MXML application, but I don't know how to make the result available to the class methods.

If anyone can help me on this...

Thank you.

Exception Thrown By Getter
I'm working with a loader. Here's my code:

ActionScript Code:
import flash.display.Loader;
    import flash.display.LoaderInfo;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.net.URLRequest;

        private function loadPages():void{
            if (counter < aPageLocations.length){
                loader=new Loader();
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE, doneLoading);
                loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorLoading);
                loader.load(new URLRequest(aPageLocations[counter]));      
            } else {
                trace("FINISHED");
            }
        }
       
        private function doneLoading(e:Event):void{
            trace("LOADED");
            var page:Page = Page(e.currentTarget.content);
            aPages.push(page);
            counter++;
            loadPages();
        }

       
        private function errorLoading(e:Event):void{
            trace("THE ERROR WAS CAUGHT");
        }

The error handler never fires but when I try to assign e.currentTarget.content to my Page object i get a null error. When I debug I look in e.currentTarget.content and it says: <exception thrown by getter>

I tried using target instead of currentTarget but it is the exact same issue. There is nothing about this on the net. Does anyone know why this happens?

Getter Not Returning An Updated Value
Hi,

I'm trying to get the value of a read-only class property via the document class, but when the variable I want to reference is called from the getter function the value is not updated. here's simplified form of what I'm trying to accomplish. Any ideas?

testClass:


Code:
package {

import flash.display.*;
import flash.events.*;

public class testClass extends Sprite {

private var testVar:Number = 10;

public function testClass() {
addEventListener(Event.ENTER_FRAME, waitFrame);
}
private function waitFrame(e:Event):void {
removeEventListener(Event.ENTER_FRAME, waitFrame);
updateVariable();
}
private function updateVariable() {
testVar = 20;
}
public function get newVar():Number {
return testVar;
}
}
}
Document Class:


Code:
package {

import flash.display.*;
import flash.events.*;
import testClass;

public class docClass extends Sprite {

private var anotherVar:Number;
private var _testClass:testClass;

public function docClass() {
getNewValue();
}
public function getNewValue():Number {
_testClass = new testClass;
trace(_testClass.newVar);
}
}
}

Getter With An Array Index?
So, I can do this:

ActionScript Code:
public class Frank {
  public function get mod():String {
    return "hello";
  }
}
And that means I can treat mod as a read-only variable

ActionScript Code:
var blah:String =frank.mod;

But what if I wanted to make a read-only array, like this?

ActionScript Code:
var blah:String=frank.modlist[3];
;
Is this not possible? Is my only solution is to use a function instead?


ActionScript Code:
public function getMod(index:int):String {
...

Copyright © 2005-08 www.BigResource.com, All rights reserved