Angular2組件開發—屬性與事件(二)

事件聲明 - 暴露事件源

與屬性相反,事件從組件的內部流出,用來通知外部世界發生了一些事情:javascript

在Angular2中爲組件增長事件接口也很是簡單:定義一個事件源/EventEmitter, 而後經過Component註解的events接口包括出來html

1 //EzCard
2 @Component({
3     events:["change"] 4 })
5 class EzCard{
6     constructor(){
7         this.change = new EventEmitter(); 8     }
9 }

上面的代碼將組件EzCard的事件源change暴露爲同名事件,這意味着在調用者EzApp組件的模板中,能夠直接使用小括號語法掛接事件監聽函數java

1 //EzApp
2 @View({
3     template : "<ez-card (change)="onChange()"></ez-card>"
4 })

每次EzCard觸發change事件時,EzApp的onChange()方法都將被調用。bootstrap

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>hello,angular2</title>
 6     <script type="text/javascript" src="lib/system@0.16.11.js"></script>
 7     <script type="text/javascript" src="lib/angular2.dev.js"></script>
 8     <script type="text/javascript" src="lib/system.config.js"></script>
 9 </head>
10 <body>
11     <ez-app></ez-app>
12     
13     <script type="module">
14         import {Component,View,bootstrap,EventEmitter} from "angular2/angular2";
15         
16         //根組件 - EzApp
17         @Component({selector:"ez-app"})
18         @View({
19               directives:[EzCard],
20             template:`
21                 <div class="ez-app">
22                     <h1>EzApp</h1>
23                     <ez-card (change)="onChange($event)"></ez-card>
24                     <pre>{{evtStr}}</pre>
25                 </div>`
26         })
27         class EzApp{
28             constructor(){
29                 this.evtStr 30             }
31             onChange(evt){
32                console.log("sth. occured"); 33                 this.evtStr = JSON.stringify(evt,null,"\t"); 34             }
35         }       
36         
37         //具備事件接口的組件 - EzCard
38         @Component({
39             selector:"ez-card",
40             events:["change"]
41         })
42         @View({
43             template : `<div class='ez-card'>
44                     My name is <b>{{name}}</b>, 
45                     I am from <b>{{country}}</b>.</div>`
46         })
47         class EzCard{
48             constructor(){
49                 this.name = "Mike";
50                 this.country = "Sweden";
51                this.change = new EventEmitter(); 52                 //模擬觸發事件
53                setTimeout(()=>this.change.next({ 54                   src:"EzCard", 55                    desc:"模擬事件"
56                }),1000); 57             }
58         }
59                 
60         //渲染組件
61         bootstrap(EzApp);
62     </script>
63 </body>
64 </html>
相關文章
相關標籤/搜索