views:

779

answers:

1

For an open source project I am looking for a way to send multiple variables to methods. These variables are, for example, variables I want to directly pass onto an object I'm creating.

I figured an object would be a good way to go, as I can send as many variables as I like without having to think about every possible variable beforehand and creating a method that accepts 40+ variables. That would kinda suck.

The problem is, though, I have no idea how I can 'walk' through an object and find all it's variables. With an Array this is simple to do, but I can't easily sent the variable's name with it.

For clarification, an example:

public function create(settings:Object=undefined):void{
    var item:Panel = new Panel();

    /*
    the idea is that 'settings' should contain something like:

    settings.width=300;
    settings.height=500;
    settings.visible=false;

    and I want to be able to walk through the provided variables,
    and in this case inject them into 'item'.
    */
}

Is there anyway to do this? Or is my idea of using Object wrong, and should I opt to use another solution? Please advice.

Many thanks in advance!

-DJ

+5  A: 

You can look through an objects properties using a for(var prop:String in obj) loop. The ...args parameter allows you to pass undefined numbers of variables to a method:

public function test()
{
    var bar:Object = {x:1, y:2, z:3};
    var baz:Object = {a:"one", b:"two", c:"three"};
    foo(bar, baz);
}

public function foo(...args):void {
    for(var i:int = 0; i<args.length; i++) {
     for(var s:String in args[i]) {
  trace("prop :: "+s);
  trace("value :: "+args[i][s]);
     }
    }
}

prints

prop :: z
value :: 3
prop :: x
value :: 1
prop :: y
value :: 2
prop :: b
value :: two
prop :: c
value :: three
prop :: a
value :: one

You take a bit of a performance hit for this, but sometimes it's what's needed.

Joshua Noble
Fantastic! The for(var s:String in args[i]) part was exactly what I was looking for! You made my day, Joshua!
Dave