2013-05-04 60 views

回答

4

飛鏢還沒有正式支持枚舉。我們希望在將來添加枚舉:http://news.dartlang.org/2013/04/enum-proposal-for-dart.html

在此期間,這裏是模擬枚舉一個共同的模式:

class Enum { 
    final _value; 
    const Enum._internal(this._value); 
    toString() => 'Enum.$_value'; 

    static const FOO = const Enum._internal('FOO'); 
    static const BAR = const Enum._internal('BAR'); 
    static const BAZ = const Enum._internal('BAZ'); 
} 

How can I build an enum with Dart?

來創建Web UI自定義元素有一個枚舉字段,您可以使用setter和getters將字符串(從HTML)轉換爲枚舉。

像這樣的東西應該工作:

import 'package:web_ui/web_ui.dart'; 

class Color { 
    final _value; 
    const Color._internal(this._value); 
    factory Color(String value) { 
    switch (value) { 
     case 'RED': 
     return Color.RED; 
     case 'BLUE': 
     return Color.BLUE; 
     case 'GREEN': 
     return Color.GREEN; 
     default: 
     throw 'not a color'; 
    } 
    } 
    toString() => 'Color.$_value'; 

    static const RED = const Color._internal('RED'); 
    static const BLUE = const Color._internal('BLUE'); 
    static const GREEN = const Color._internal('GREEN'); 
} 

class PersonComponent extends WebComponent { 
    Color favoriteColor; 

    String get favColor => ((x) => x == null ? null : x._value)(favoriteColor); 

    void set favColor(String value) { 
    favoriteColor = new Color(value); 
    } 
} 

然後將HTML是:

<html> 
    <body> 
    <element name="x-person" extends="div" constructor="PersonComponent"> 
     <template> 
     <div> 
      Favorite Color: <select bind-value="favColor"> 
      <option>RED</option> 
      <option>GREEN</option> 
      <option>BLUE</option> 
      </select> 
     </div> 
     <div> 
      You picked {{favoriteColor}} 
     </div> 
     </template> 
     <script type="application/dart" src="person_component.dart"></script> 
    </element> 
    </body> 
</html> 
+0

我希望會有一些方法來指定解析器功能。這種污染班級的接口。感謝你的回答。 – jz87 2013-05-04 04:46:07

+0

我們預計會添加過濾器,因此您可以在HTML中執行此操作。類似於bind-value =「color | toColorEnum」。 – 2013-05-04 16:19:16