class DemoElement extends Polymer.Element {
static get is() { return "demo-element" }
static get properties() {
return {
prop1 : {
type:String,
notify: true,
reflectToAttriubute: true,
}
}
}
}
我无法理解此处属性的 notify 和 reflectToAttribute 设置。谁能用一些简单适用的例子来解释一下?
最佳答案
通知:
来自:https://www.polymer-project.org/2.0/docs/devguide/properties
notify Type: boolean
If true, the property is available for two-way data binding. In addition, an event, property-name-changed is fired whenever the property changes. See Property change notification events (notify) for more information.
来自:https://www.polymer-project.org/2.0/docs/devguide/data-system
A notifying property supports upward data flow. By default, properties are non-notifying, and don't support upward data flow.
意味着用户对此属性所做的任何更改都将通过 dom 树“向上”传播,或“目标到主机”
例如https://www.polymer-project.org/2.0/docs/devguide/data-system
<script>
class XTarget extends Polymer.Element {
static get is() {return 'x-target';}
static get properties() {
return {
someProp: {
type: String,
notify: true
}
}
}
}
customElements.define(XTarget.is, XTarget);
</script>
...
<dom-module id="x-host">
<template>
<!-- changes to "value" propagate downward to "someProp" on target -->
<!-- changes to "someProp" propagate upward to "value" on host -->
<x-target some-prop="{{value}}"></x-target>
</template>
<script>
class XHost extends Polymer.Element {
static get is() {return 'x-host';}
}
customElements.define(XHost.is, XHost);
</script>
.
ReflectToAttribute
reflectToAttribute Type: boolean
Set to true to cause the corresponding attribute to be set on the host node when the property value changes. If the property value is Boolean, the attribute is created as a standard HTML boolean attribute (set if true, not set if false). For other property types, the attribute value is a string representation of the property value. Equivalent to reflect in Polymer 0.5. See Reflecting properties to attributes for more information.
简而言之,reflectToAttribute 的存在是为了提高性能。除非指定为 true,否则polymer 会避免操纵 dom 属性。如果指定为 true,该属性将更新 dom 元素属性。
iron-checked-element-behavior 可能是将属性反射回属性的最规范的示例。
html 中的复选框,为了满足规范,应该有一个选中时出现的选中属性。
checked: {
type: Boolean,
value: false,
reflectToAttribute: true,
notify: true,
observer: '_checkedChanged'
},
通过指定checked反射(reflect)到属性中,查看演示,https://www.webcomponents.org/element/PolymerElements/iron-checked-element-behavior/demo/demo/index.html
使用浏览器进行检查,我们可以看到当单击简单复选框时,简单复选框的状态更新为选中。
//L32
<input type="checkbox" id="checkbox" on-tap="_onCheckTap">
//...
//this.checked is inherited from L43
behaviors: [Polymer.IronCheckedElementBehavior],
//...
//L53
_onCheckTap: function() {
this.checked = this.$.checkbox.checked;
},
关于polymer - 无法理解 Polymer 2.0 自定义元素属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44753879/