按觸發的順序:html
created:當組件被 new 時調用,最先被觸發,此時還不能訪問組件的屬性,但不知道爲何直接經過HTML的方式也會執行,多是內部實例化了。web
ready:當組件內部依賴的子組件或者原生dom組件加載成功會調用,使你的組件一次性配置後局部DOM初始化。segmentfault
factoryImpl:只有使用new ElementClass()方式建立組件時會被調用,發生在ready後dom
attached:組件被添加到父組件中時觸發(顯示在頁面中時),只會觸發一次。this
attributeChanged:組件被父組件設置屬性時觸發,只有使用setAttribute()方式設置屬性纔會觸發,當一個元素的屬性更改時調用。code
detached:當被父組件removeChild的時候觸發。component
參考:開坑,寫點Polymer 1.0 教程第4篇——組件的生命週期htm
created和readyblog
template.html教程
<dom-module id="my-element"></dom-module> <script> Polymer({ is: 'my-element', created: function() { console.log('created'); } }); </script>
index.html
<my-element><my-element/>
執行了兩下,還沒搞懂。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <!-- 這是一個基礎版的兼容庫 --> <script src="webcomponents-lite.min.js"></script> <!-- 將rel修改成import能夠引入另一個HTML,它將會被執行 --> <!-- <link rel="import" href="./template/template.html"> --> <link rel="import" href="polymer-1.7.0/polymer.html"> </head> <body> <my-hello></my-hello> <script> Polymer({ is:'my-hello', properties:{ msg:{ type:String, value:'why?' } }, ready:function(){ console.log(this.msg + ' ready'); }, created:function(){ console.log(this.msg + ' created'); } }) </script> </body> </html>
確實在created階段是訪問不了屬性的。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <!-- 這是一個基礎版的兼容庫 --> <script src="webcomponents-lite.min.js"></script> <!-- 將rel修改成import能夠引入另一個HTML,它將會被執行 --> <!-- <link rel="import" href="./template/template.html"> --> <link rel="import" href="polymer-1.7.0/polymer.html"> </head> <body> <my-hello> <div>什麼啊?</div> </my-hello> <script> var hello = Polymer({ is:'my-hello', properties:{ msg:{ type:String, value:'why?' } }, // 組件加載完畢會執行 ready:function(){ console.log(this.msg + ' ready'); }, // 自定義元素被建立會執行 created:function(){ console.log(this.msg + ' created'); }, factoryImpl:function(){ console.log(this.msg + ' factoryImpl'); }, // 組件顯示在頁面的時候會執行 attached:function(){ console.log(this.msg + ' attached'); // factoryImpl會被執行 new hello(); // 設置屬性 會執行attributeChanged方法 this.setAttribute('msg',this.msg); // 刪除組件 會執行detached方法 console.log('removeChild'); document.body.removeChild(this); }, attributeChanged:function(){ console.log(this.msg + ' attributeChanged'); }, detached:function(){ console.log(this.msg + ' detached'); } }) </script> </body> </html>
結果以下:
這裏能夠看出一些問題來,就是說你直接經過手動的方式添加組件,那麼Polymer內部會幫你建立,若是你手動添加了而且又用JS new了那麼會被執行兩次。