Javascript 当在聚合物组件中时';是否为声明性指定的值启动了已更改的监视程序?
从中可以看出,大多数回调的生命周期是明确的:Javascript 当在聚合物组件中时';是否为声明性指定的值启动了已更改的监视程序?,javascript,polymer,web-component,Javascript,Polymer,Web Component,从中可以看出,大多数回调的生命周期是明确的: created -> ready -> attached -> domReady ^ | | | ---------- detached <---------- 但是,如果我的元素的一个实例以声明方式提供了一个值,该怎么办 <my-element attribute="ne
created -> ready -> attached -> domReady
^ |
| |
---------- detached <----------
但是,如果我的元素的一个实例以声明方式提供了一个值,该怎么办
<my-element attribute="newValue"></my-element>
在这种情况下,在元素生命周期中何时触发属性更改观察程序?我不是100%理解您的意思,但通过一个简单的测试,结果表明
属性更改事件在附加后和domReady
之前调用。但是,属性值已经可以从ready
开始读取。这很容易理解,因为attributeChanged
事件是从javascript回调函数调用的,这同样适用于domReady
事件,但是它们不会立即触发,因为代码已经在运行
如果在创建的
事件中设置该值,它将不会以任何方式反映出来(当然,分配该值的函数本身除外)。属性在created
事件之后,但在ready
事件之前处理
如果您想亲自看到这一点:
<my-element myAttribute="attributeValue"></my-element>
元素本身被定义为
<polymer-element name="my-element" attributes="myAttribute">
<template>
<span>Hello from <b>my-element</b>. This is my Shadow DOM.</span>
</template>
<script>
Polymer({
created: function() {
//has no effect on the element:
//this.myAttribute = "newValue";
console.log("created", this.myAttribute);
},
ready: function() {
//works fine:
//this.myAttribute = "newValue";
console.log("ready", this.myAttribute);
},
attached: function() {
console.log("attached", this.myAttribute);
},
domReady: function() {
console.log("domReady", this.myAttribute);
},
myAttributeChanged: function() {
console.log("myAttributeChanged", this.myAttribute);
}
});
</script>
</polymer-element>
你好,来自我的元素。这是我的影子。
聚合物({
已创建:函数(){
//对元素没有影响:
//this.myAttribute=“newValue”;
console.log(“已创建”,this.myAttribute);
},
就绪:函数(){
//工作正常:
//this.myAttribute=“newValue”;
log(“ready”,this.myAttribute);
},
附:函数(){
console.log(“attached”,this.myAttribute);
},
domReady:function(){
log(“domReady”,this.myAttribute);
},
myAttributeChanged:函数(){
log(“myAttributeChanged”,this.myAttribute);
}
});
一个简单的测试可以确定您的答案,但我想硬编码值(不同于dom集值)在技术上不会改变,直到它改变。谢谢您的答案,David!我在刚刚发现的服务(ele)上运行了一个版本,证实了这一点:
<polymer-element name="my-element" attributes="myAttribute">
<template>
<span>Hello from <b>my-element</b>. This is my Shadow DOM.</span>
</template>
<script>
Polymer({
created: function() {
//has no effect on the element:
//this.myAttribute = "newValue";
console.log("created", this.myAttribute);
},
ready: function() {
//works fine:
//this.myAttribute = "newValue";
console.log("ready", this.myAttribute);
},
attached: function() {
console.log("attached", this.myAttribute);
},
domReady: function() {
console.log("domReady", this.myAttribute);
},
myAttributeChanged: function() {
console.log("myAttributeChanged", this.myAttribute);
}
});
</script>
</polymer-element>