在 Polymer 组件的生命周期中,何时会因声明指定的值而触发更改的观察者?
When in a Polymer component's life cycle are changed watchers fired for declaratively-specified values?
从Polymer docs开始,大多数回调的生命周期很清楚:
created -> ready -> attached -> domReady
^ |
| |
---------- detached <----------
而且我想 attributeChanged() 会在这个生命周期中的任何时候当一个属性被修改时被触发,例如甚至早在创建时:
created: function() {
this.attribute = 'newValue';
}
但是,如果以声明方式为我的元素的实例提供值怎么办?
<my-element attribute="newValue"></my-element>
在这种情况下,元素生命周期中何时触发属性更改观察者?
不是 100% 我明白你的意思,但使用简单测试发现 attributeChanged
事件是在 attached
之后和 domReady
之前调用的。然而,属性值从 ready
开始就已经是可读的了。这很容易理解,因为 attributeChanged
事件是从 javascript 回调函数调用的,同样适用于 domReady
事件,但是它们不会立即触发,因为代码是已经 运行.
如果您在 created
事件中设置该值,它将 不会 以任何方式反映(当然除了您分配它的函数本身)。属性在 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>
从Polymer docs开始,大多数回调的生命周期很清楚:
created -> ready -> attached -> domReady
^ |
| |
---------- detached <----------
而且我想 attributeChanged() 会在这个生命周期中的任何时候当一个属性被修改时被触发,例如甚至早在创建时:
created: function() {
this.attribute = 'newValue';
}
但是,如果以声明方式为我的元素的实例提供值怎么办?
<my-element attribute="newValue"></my-element>
在这种情况下,元素生命周期中何时触发属性更改观察者?
不是 100% 我明白你的意思,但使用简单测试发现 attributeChanged
事件是在 attached
之后和 domReady
之前调用的。然而,属性值从 ready
开始就已经是可读的了。这很容易理解,因为 attributeChanged
事件是从 javascript 回调函数调用的,同样适用于 domReady
事件,但是它们不会立即触发,因为代码是已经 运行.
如果您在 created
事件中设置该值,它将 不会 以任何方式反映(当然除了您分配它的函数本身)。属性在 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>