views:

311

answers:

3

I have many Flex objects like this one:

public class MyData {
    public var time: Date;
    public var label: String;
}

I am populating this object from a DB record retrieved via AMF that looks something like this:

{
    label: "Label",
    incident: "2009-08-15 11:12:14.12233"
}

I want to write a generic value mapper for these object that, given a target object (instance of MyData here) and an input record, will be able to tell that MyData.time is a Date field and perform type mapping automatically. Something like this:

function map(obj, targetType): * {
    var newInstance: * = new targetType();
    for (var property: String in obj) {
        if (getPropertyType(targetType, property) == Date) {
            newInstance[property] = parseDate(obj[property]);
        }
        else {
            newInstance[property] = obj[property];
        }
    }
}

function getPropertyType(type_var: Class, property: String): Class {
    // .. this is what I have no idea how to do
}

Can someone fill in the blank here?

+2  A: 

You possibly need something like describeType. And maybe you need to use getDefinitionByName() if you want to make to a real object. So something like this for the contents of your function:

var typeXml:XML = describeType(type_var[property]);
return getDefinitionByName(typeXml.type[0].@name);

I haven't compiled it. Just throwing it out there to see if it helps.

Glenn
Thank you, that is exactly what I needed!
Chris R
A: 

You can use the 'is' operator to check the type of an object.

The is operator

function map(obj, targetType): * {
  var newInstance: * = new targetType();
  for (var property: String in obj) {
    if (obj[property] is Date) {
      newInstance[property] = parseDate(obj[property]);
    }
    else {
      newInstance[property] = obj[property];
    }
  }
}

hth

Koen

Koen Weyn
Does that work if obj[property] is undefined?
Chris R
Using the 'is operator' on an undefined property will always return false
Koen Weyn
Then, regrettably, this is not the answer that I'm looking for.
Chris R
I don't understand. I think 'undefined' means the property has no value and no type. Why would you want that to return true?
Koen Weyn
A: 

Hello

If you need to map an Object variable to a variable class as MyData you can do the following

public class MyData 
{
    public var time: Date;
    public var label: String;

    function map(obj:Object):void
    {
      for (var property: String in obj) 
      {
          this[property] = obj[property];
      }
    }
}

Note: The object obj must contain the exact "time" and "label" properties.

Hope it solves your problem


Adrian - http://www.timeister.com

Adrian Pirvulescu