gpt4 book ai didi

javascript - Polymer 中的私有(private)状态变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:43:26 26 4
gpt4 key购买 nike

在 Polymer 元素中存储私有(private)状态属性的推荐做法是什么?例如,仅对内部渲染有意义的属性(例如,一些 bool 标志指示元素的哪些部分被渲染,或者从 dom-repeat 可以迭代的对象构建的临时数组)。它们不打算通过元素的 API 公开,仅供内部使用。

到目前为止,我一直在做的是在 properties 对象中声明可通过元素 API 使用的属性,而“私有(private)”属性已在 ready 中设置,并且其他函数(例如 this._tempArray = []),而无需在 properties 中明确声明它们。不过,我不知道这是否是个好主意?

<dom-module id="test">
<template>
<style>

</style>

<template is="dom-if" if="[[_isDataReady]]">

</template>

</template>

<script>
(function() {
'use strict';

Polymer({
is: 'test',

properties: {
dataUrl: {
type: String
}
},

ready: function() {
this._isDataReady = false;
this._tempArray = [];

// Get data asynchronously from dataUrl
// ...
}
});
})();
</script>
</dom-module>

最佳答案

最好的方法是将您的属性声明为普通属性,但在名称前加上下划线 (_) 前缀,并将该属性设置为只读,以便外部消费者无法覆盖该变量。

例如:

properties: {
_isDataReady: {
type: Boolean,
value: false,
readOnly: true
}
}

ready: function () {
...
this.async(function () {
//Some async logic
...
this._set_isDataReady(true); //You will need to use this special generated setter to set the value
);
}

这种方法向消费者表明他们不应使用此属性,因为它是内部属性,并且只读属性可防止在正常工作流之外错误地设置该属性。

关于javascript - Polymer 中的私有(private)状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com