Search code examples
javascriptpolymerweb-component

Private state variables in Polymer


What is the recommended practice of storing private state properties in Polymer elements? For example, properties that have meaning only for internal rendering (e.g. some boolean flags indicating which parts of the element are rendered, or temporary arrays built from objects that dom-repeat can iterate over). They are not meant to be exposed through the element's API and are meant for internal use only.

What I have been doing so far is declaring properties which can be used through element's API in the properties object, while "private" properties have been set in ready and other functions (e.g. this._tempArray = []) without explicitly declaring them in properties. I don't know if that's a good idea however?

<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>

Solution

  • The best way to do this is to declare your property as a normal property, but with an underscore (_) prefix in front of the name, and set the property as read-only so that external consumers cannot overwrite the variable.

    For example:

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

    This approach communicates to consumers that they should not be utilizing this property, as it is internal, and the read-only attribute prevents the property from being incorrectly set outside of it's normal workflow.