Polymer 中的私有状态变量

Private state variables in Polymer

在 Polymer 元素中存储私有状态属性的推荐做法是什么?例如,仅对内部渲染有意义的属性(例如,一些布尔标志指示元素的哪些部分被渲染,或者从 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>

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

例如:

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
    );
}

此方法向消费者表明他们不应使用此 属性,因为它是内部的,并且 read-only 属性可防止 属性 在其外部被错误设置正常的工作流程。