按触发的顺序: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了那么会被执行两次。