2009-03-06 12 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文字列から解析された匿名オブジェクトがあると仮定しています。その場合、私はそれがうまくいかないと確信しています。バインド可能なプロパティを持つ厳密に型指定されたオブジェクトを作成する必要があります。ただ、FYI

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

うわー! DelphiのRTTI日以降、この種の厄介なハッキングを見たことはありません。クール... –

+0

病気、病気、ハッククリストフ!私はそれが好きです。私はそれを使うかもしれない。 – airportyh

関連する問題