2009-03-06 3 views
1

Data binding in ActionScript은 정말 멋지다. 하지만 원하는 경우 어떻게하면 예를 들어, 함수로 괄호 안에 큰 스위치 또는 if 문을 리팩토링하기 :플렉스에서 중괄호 안의 코드를 리팩터링하는 방법

 
{person.gender == 'male' ? 'Mr.' : 'Ms.'} 

로 :

 
{salutation(person)} 

컴파일러 나 그렇게하지 않습니다. 나는 속성에 대해 알고 있으며, getter와 setter를 person 객체에 쓸 수 있습니다. 하지만 인라인 된 JSON 객체를 사용하고 있으므로 편리하지 않습니다 (제 생각 엔). 이 코드를 리팩토링하는 다른 좋은 방법은 무엇입니까?

Matt 님의 의견에 답변 해주십시오. 사람의 데이터 유형은 단순한 Object입니다. 서비스 호출에서 JSON 형식으로 디코딩되었습니다.

+0

데이터 유형 "에 대한 의미 : 모든 당신이, 당신이 ByteArray의 트릭을 사용하여 바닐라 오브젝트의 강력한 타입의 객체를 생성 할 수 있습니다 만들 개체에 대한 사용자 정의 JSON 파서를 작성하는 것을 피하기 위해 사람"? –

답변

4

이 작업을 수행하려면 Person 클래스가 바인딩 가능해야한다고 가정합니다.

그러나 JSON 개체를 사용한다고 말하고 있기 때문에 JSON 문자열에서 구문 분석 한 익명 개체가 있다고 가정합니다. 이 경우에는 작동하지 않을 것이라고 확신합니다. 바인딩 할 수있는 속성이있는 강력한 형식의 개체를 만들어야합니다. 그냥 참고로

:

public static function toInstance(object:Object, clazz:Class):* { 
    var bytes:ByteArray = new ByteArray(); 
    bytes.objectEncoding = ObjectEncoding.AMF0; 

    // Find the objects and byetArray.writeObject them, adding in the 
    // class configuration variable name -- essentially, we're constructing 
    // and AMF packet here that contains the class information so that 
    // we can simplly byteArray.readObject the sucker for the translation 

    // Write out the bytes of the original object 
    var objBytes:ByteArray = new ByteArray(); 
    objBytes.objectEncoding = ObjectEncoding.AMF0; 
    objBytes.writeObject(object); 

    // Register all of the classes so they can be decoded via AMF 
    var typeInfo:XML = describeType(clazz); 
    var fullyQualifiedName:String = [email protected]().replace(/::/, "."); 
    registerClassAlias(fullyQualifiedName, clazz); 

    // Write the new object information starting with the class information 
    var len:int = fullyQualifiedName.length; 
    bytes.writeByte(0x10); // 0x10 is AMF0 for "typed object (class instance)" 
    bytes.writeUTF(fullyQualifiedName); 
    // After the class name is set up, write the rest of the object 
    bytes.writeBytes(objBytes, 1); 

    // Read in the object with the class property added and return that 
    bytes.position = 0; 

    // This generates some ReferenceErrors of the object being passed in 
    // has properties that aren't in the class instance, and generates TypeErrors 
    // when property values cannot be converted to correct values (such as false 
    // being the value, when it needs to be a Date instead). However, these 
    // errors are not thrown at runtime (and only appear in trace ouput when 
    // debugging), so a try/catch block isn't necessary. I'm not sure if this 
    // classifies as a bug or not... but I wanted to explain why if you debug 
    // you might seem some TypeError or ReferenceError items appear. 
    var result:* = bytes.readObject(); 
    return result; 
} 
+0

와우! 내 델파이 RTTI 일 이후로 이런 불쾌한 해킹을 보지 못했습니다. 쿨 ... –

+0

아프거나 병 들고 크리스토프 해킹! 나는 그것을 좋아한다. 나는 그것을 사용할지도 모른다. – airportyh

관련 문제