這篇會講下組件內部的事件處理機制,以及組件和外界通信的處理方式(父子通信,兄弟通信等)html
第一種,直接寫在標籤裏,用on-eventName=「eventHandler」的方式前端
<link rel="import" href="../bower_components/polymer/polymer.html"> <dom-module id="event-element"> <template> <button id="myBtn" on-click="handleClick">Alert</button> </template> <script> Polymer({ is: "event-element", handleClick: function(e){ alert("clicked by "+ e.currentTarget.localName); } }); </script> </dom-module>
第二種使用EventListener的方式web
<link rel="import" href="../bower_components/polymer/polymer.html"> <dom-module id="event-element"> <template> <button id="myBtn">Alert</button> </template> <script> Polymer({ is: "event-element", handleClick: function(e){ alert("clicked by "+ e.currentTarget.localName); }, listeners: { 'click': 'handleClick', 'myBtn.click': 'handleClick' } }); </script> </dom-module>
你們注意,這裏使用了myBtn.click這種 id+.+eventName的方式,能夠對內部某個id的dom進行監聽。而不寫id,則監聽是加在整個組件之上的。你們能夠跑下上面的代碼看看區別。api
組件分裝好了最終仍是要被其它組件調用,與外界通信的,若是把屬性賦值做爲 輸入in, 那麼事件就能夠稱爲輸出out了。就拿原生的input標籤進行舉例。 input組件的輸入就是type屬性賦值,輸出則是onclick事件的觸發。dom
<input type=「xxx」 onclick="xxxx">
同理,對於自定義組件也同樣,對於輸入來講前面幾篇已經介紹了properties如何在組件外被賦值。那麼事件的觸發咱們由如何來處理呢?
Polymer給咱們提供了一個fire的api讓咱們來觸發自定義事件,來看下面的代碼組件化
<link rel="import" href="../bower_components/polymer/polymer.html"> <dom-module id="event-element"> <template> <button id="myBtn">Alert</button> </template> <script> Polymer({ is: "event-element", handleClick: function(e){ //第一個參數爲eventname,第二個參數爲傳遞的值 this.fire('kick',{'data':'transfer data'}); }, listeners: { 'myBtn.click': 'handleClick' } }); </script> </dom-module>
對自定義事件添加監聽後就能夠捕獲到這個「kick」的自定義事件了。我嘗試了直接在組件上使用on-kick進行監聽卻不行,非得使用addEventListener方式,多是polymer不支持這種寫法,指望在後續版本中加以改進。this
<!DOCTYPE html> <html> <head> <script src="bower_components/webcomponentsjs/webcomponents-lite.min.js"></script> <link rel="import" href="components/event-element.html"> </head> <body> <event-element id="eventElement"></event-element> </body> <script> HTMLImports.whenReady(function () { var el = document.getElementById("eventElement"); el.addEventListener("kick", function (e) { alert(e.detail.data); }); }); </script> </html>
運行結果spa
這裏來聊聊組件化開發的消息機制,這個並不侷限於polymer或者web應用,適用於全部的組件式開發技術。其實概括下來就是幾條準則:設計
父子通信:code
父->子 設置子的公共屬性 子->父 子觸發事件,父監聽事件,父捕獲到子發出的事件後再作後續處理。
兄弟通信:
兄->父 跟父子通信同樣,先經過事件把需求提交給父 父->弟 父拿到兄的需求後,統一調度,經過設屬性的方式來訪問弟
爺孫通信:
參照父子通信,一層層向上傳遞事件,再一層層向下設置屬性,實際開發時儘可能將組建的接口都設計合理避免跨n級通信的尷尬場面
遠親通信:
請使用前端消息總線(如單例的消息總線類)來解決這裏剪不斷理還亂的case,可是這類方式不宜大面積使用,父子,和兄弟間通信仍是請使用上面的幾種方式。