通过查看Polymer dev指南,在properties对象中声明的属性将成为元素的公共API。所以我通常不会在属性对象中声明私有属性,而是执行
ready: function() {
this.privatePropertyName = 'random text';
}
我也看到一些代码在带有'_'前缀命名约定的属性中声明私有属性,比如
properties: {
_privateProperty: {
type: Number,
readOnly: true,
value: 0,
}
}
这方面的最佳做法是什么?我们是否应该坚持只有公共属性进入属性对象的规则?
答案 0 :(得分:2)
如果你看一下code developed by Polymer team,他们遵循的做法就是声明属性对象中的所有属性。他们使用_
将私有财产与公共财产分开。
<link rel="import" href="https://polygit.org/components/polymer/polymer.html">
<dom-module id="has-private">
<template>{{newProp}}</template>
</dom-module>
<script>
Polymer({
is: 'has-private',
properties: {
_private: 'privateMember',
inSide: {
type: String,
value: 'ousidePropertiesObject',
reflectToAttribute: true,
observer: '_insideChanged'
}
},
outSide: {
type: String,
value: 'ousidePropertiesObject',
reflectToAttribute: true,
observer: '_changed'
},
_changed: function(newVal) {
alert("New value if outSide is: " + newVal);
},
_insideChanged: function(newVal) {
alert("New value if inSide is: " + newVal);
},
attached: function() {
console.log("value of outSide", this.outSide);
alert("From internal element \n outside: " + this.outSide + " inside: " + this.inSide);
alert("New Prop: " + this.newProp);
this.undeclaredProperty = "i'm not declared anywhere in the code";
}
})
</script>
<dom-module id="access-private">
<template>
<has-private id="private" out-side="doesn't matter" in-side="doesn't matter" new-prop="hello"></has-private>
</template>
</dom-module>
<script>
Polymer({
is: 'access-private',
attached: function() {
this.$.private.outSide = "i work";
this.$.private.inSide = "i work";
alert("value of has-private element's private property in access private is: " + this.$.private._private);
alert("value of property outside properties object is: " + this.$.private.outSide);
alert("value of undeclared property is: " + this.$.private.undeclaredProperty);
}
})
</script>
<access-private>
</access-private
以下是关于这些属性的几点建议。
properties
对象。 向属性对象添加属性允许用户从标记配置属性(有关详细信息,请参阅属性反序列化)。 应该在属性对象中声明属于元素的公共API的任何属性。
正如您所看到的,Polymer文档说明属性应该在properties
对象中声明,而必须或需要> strong>这意味着强烈推荐而不是强制性