前端组件化Polymer入门教程(5)——生命周期

以前我对生命周期这个概念还真不是很清楚,不过想想也简单,比如说人的生命周期,无非就是生老病死。而对于程序的生命周期就是说,它在每个阶段都会做不同的事,再比如说回调函数把,ajax返回的时候它才执行,那么这个返回你就可以看做是一个阶段,也是它生命终结的时候。

按触发的顺序:

created:当组件被 new 时调用,最早被触发,此时还不能访问组件的属性,但不知道为什么直接通过HTML的方式也会执行,可能是内部实例化了。

ready:当组件内部依赖的子组件或者原生dom组件加载成功会调用,使你的组件一次性配置后局部DOM初始化。

factoryImpl:只有使用new ElementClass()方式创建组件时会被调用,发生在ready后

attached:组件被添加到父组件中时触发(显示在页面中时),只会触发一次。

attributeChanged:组件被父组件设置属性时触发,只有使用setAttribute()方式设置属性才会触发,当一个元素的属性更改时调用。

detached:当被父组件removeChild的时候触发。

参考:开坑,写点Polymer 1.0 教程第4篇——组件的生命周期

created和ready

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了那么会被执行两次。

完。

原文地址:https://www.cnblogs.com/pssp/p/5920919.html