前端组件化Polymer深入篇(1)

时间:2023-03-08 15:50:12
前端组件化Polymer深入篇(1)

在前面的几节里面简单的介绍了一下Polymer的基本功能,但还有一些细节的东西并没有讨论,所有打算花点时间把Polymer的一些细节写一下。

new和createElement有区别吗?
<script>
var SayHello = Polymer({
is:'say-Hello'
})
var el1 = document.createElement('say-Hello');
console.log(el1);
var el2 = new SayHello();
console.log(el2);
</script>

前端组件化Polymer深入篇(1)

看起来好像没有差别,但还是有些差别的,new的方式可以传递参数。

<script>
var SayHello = Polymer({
is:'say-Hello',
factoryImpl:function(){
console.log(arguments);
}
})
var el = new SayHello('css','js','html');
console.log(el);
</script>

前端组件化Polymer深入篇(1)

注:factoryImpl:只有使用new ElementClass()方式创建组件时会被调用。更多关于函数的调用时机可以看前端组件化Polymer入门教程(5)——生命周期

属性值还可以通过函数return返回。

例1

<say-Hello></say-Hello>
<dom-module id="say-Hello">
<template>
<h1>{{say}}</h1>
</template>
</dom-module>
<script>
Polymer({
is:'say-Hello',
properties:{
say:{
type:String,
value:function(){
return '国庆七天乐!';
}
}
}
})
</script>

前端组件化Polymer深入篇(1)

例2

<say-Hello></say-Hello>
<dom-module id="say-Hello">
<template>
<h1>{{say.title}}</h1>
</template>
</dom-module>
<script>
Polymer({
is:'say-Hello',
properties:{
say:{
type:Object,
value:function(){
return {"title":"这是一段标题"};
}
}
}
})
</script>

前端组件化Polymer深入篇(1)

异步方法async
<say-Hello></say-Hello>
<dom-module id="say-Hello">
<template>
<h1>{{say}}</h1>
</template>
</dom-module>
<script>
Polymer({
is:'say-Hello',
properties:{
say:{
type:String,
value:'hello',
observer:'attrChange'
}
},
listeners:{
'click':'setAttr'
},
setAttr:function(){
this.async(function(){
console.log('async ' + this.say);
},300);
this.say = 'attr';
},
attrChange:function(){
console.log('属性值已改成' + this.say);
}
})
</script>

this.async和setTimeout使用差不多。

前端组件化Polymer深入篇(1)

this.push(name,value)和push(value)的区别
<x-custom></x-custom>
<dom-module id="x-custom">
<template>
<ul>
<template is="dom-repeat" items="{{users}}
<li>{{item.userName}}</li>
</template>
</ul>
</template>
</dom-module>
<script>
Polymer({
is: 'x-custom',
ready: function() {
this.users = [
{userName:'老王'}
];
},
listeners:{
'click':'addUser'
},
addUser:function(){
this.push('users',{userName:'老李'})
this.users.push({userName:'老于'});
console.log(this.users);
}
});
</script>

前端组件化Polymer深入篇(1)

区别在于一个会更新视图,一个不会更新。

计算功能

可以通过computed来设置计算功能

<x-custom first="国庆" last="快乐"></x-custom>
<dom-module id="x-custom">
<template>
My name is <span>{{fullName}}</span>
</template>
<script>
Polymer({
is: 'x-custom',
properties: {
first: String,
last: String,
fullName: {
type: String,
computed: 'computeFullName(first, last)'
}
},
computeFullName: function(first, last) {
return first + ' ' + last;
},
listeners:{
'click':'changeFullName'
},
changeFullName:function(){
this.first = 'Hello';
this.last = 'World';
}
});
</script>
</dom-module>

注意只有当first和last都改变的时候才会执行computed里面的方法。

前端组件化Polymer深入篇(1)