天天看點

Angular2入門(三)

注解/Annotation

你一定好奇@Component和@View到底是怎麼回事。看起來像其他語言(比如python) 的裝飾器,是這樣嗎?

ES6規範裡沒有裝飾器。這其實利用了traceur的一個實驗特性:注解。給一個類 加注解,等同于設定這個類的annotations屬性:

1 //注解寫法
2 @Component({selector:"ez-app"})
3 class EzApp{...}      

與下面的寫法産生的效果相同

1 class EzApp{...}
2 EzApp.annotations = [new Component({selector:"ez-app"})];      

很顯然,注解可以看做編譯器(traceur)層面的文法糖,但和python的裝飾器不同, 注解在編譯時僅僅被放在annotation裡,編譯器并不進行解釋展開 - 這個解釋的工作是 Angular2完成的:

Angular2入門(三)

據稱,注解的功能就是Angular2團隊向traceur團隊提出的,這不是traceur的預設選項, 是以你看到,配置systemjs在使用traceur子產品時打開注解:

1 System.config({
2   map:{traceur:"lib/traceur"},
3   traceurOptions: {annotations: true}
4 });      

例如:

1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>hello,angular2</title>
 6     <!--子產品加載器-->
 7     <script type="text/javascript" src="lib/[email protected]"></script>
 8     <!--Angular2子產品庫-->
 9     <script type="text/javascript" src="lib/angular2.dev.js"></script>
10     <script>
11         //設定子產品加載規則
12         System.baseURL = document.baseURI;
13         System.config({
14             map:{traceur:"lib/traceur"},
15             traceurOptions: {annotations: true}
16         });
17     </script>        
18 </head>
19 <body>
20     <!--元件渲染錨點-->
21     <ez-app></ez-app>
22     
23     <!--定義一個ES6腳本元素-->
24     <script type="module">
25         //從子產品庫引入三個類型定義
26         import {Component,View,bootstrap} from "angular2/angular2";
27         
28         //元件定義 (注解寫法)
29         //@Component({selector:"ez-app"})
30         //@View({template:"<h1>Hello,Annotation</h1>"})
31         //class EzApp{} 
32         
33         //元件定義 (非注解寫法)
34         class EzApp{} 
35         EzApp.annotations = [new Component({selector:"ez-app"}),
36         new View({template:"<h1>Hello,Annotation</h1>"})];
37                 
38         //渲染元件
39         bootstrap(EzApp);
40     </script>
41 </body>
42 </html>