您的位置:首页 > Web前端 > AngularJS

Angular2入门(三)

2015-12-10 15:52 741 查看

注解/Annotation

你一定好奇@Component和@View到底是怎么回事。看起来像其他语言(比如python) 的装饰器,是这样吗?

ES6规范里没有装饰器。这其实利用了traceur的一个实验特性:注解。给一个类 加注解,等同于设置这个类的annotations属性:

//注解写法
@Component({selector:"ez-app"})
class EzApp{...}


与下面的写法产生的效果相同

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


很显然,注解可以看做编译器(traceur)层面的语法糖,但和python的装饰器不同, 注解在编译时仅仅被放在annotation里,编译器并不进行解释展开 - 这个解释的工作是 Angular2完成的:



据称,注解的功能就是Angular2团队向traceur团队提出的,这不是traceur的默认选项, 因此你看到,配置systemjs在使用traceur模块时打开注解:

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


例如:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>hello,angular2</title>
<!--模块加载器-->
<script type="text/javascript" src="lib/system@0.16.11.js"></script>
<!--Angular2模块库-->
<script type="text/javascript" src="lib/angular2.dev.js"></script>
<script>
//设置模块加载规则
System.baseURL = document.baseURI;
System.config({
map:{traceur:"lib/traceur"},
traceurOptions: {annotations: true}
});
</script>
</head>
<body>
<!--组件渲染锚点-->
<ez-app></ez-app>

<!--定义一个ES6脚本元素-->
<script type="module">
//从模块库引入三个类型定义
import {Component,View,bootstrap} from "angular2/angular2";

//组件定义 (注解写法)
//@Component({selector:"ez-app"})
//@View({template:"<h1>Hello,Annotation</h1>"})
//class EzApp{}

//组件定义 (非注解写法)
class EzApp{}
EzApp.annotations = [new Component({selector:"ez-app"}),
new View({template:"<h1>Hello,Annotation</h1>"})];

//渲染组件
bootstrap(EzApp);
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: