Week 18 | Observer Sub-properties

polymer 1.0
Sat Dec 31 2016

In this example we will go over ways to observe sub-properties.

We have one object named “loadStatus” with two properties “percent”, “loading”. Then in the observers array we will trigger two methods every time the percent property changes and when the “*” property changes which basically means any property.

When we pass one property in the observer method we will receive every time the property changes the new property value.

When we pass the * value, every time one of the parameters is updated we will receive an object with the new values and some meta-information.

<!DOCTYPE html>

<html>
    <head>
        <script src="https://polygit.org/polymer+:1.3.1/components/webcomponentsjs/webcomponents-lite.min.js"></script>
        <link rel="import" href="https://polygit.org/polymer+:1.3.1/components/polymer/polymer.html" />
    </head>
    <body>
      
    <alert-element></alert-element>
    
    <dom-module id="alert-element">
      <template>
          <div hidden$="{{!loadStatus.loading}}">loading (<span>{{loadStatus.percent}}%</span>)...</div>
          [[message]]
          <paper-input value="{{message}}"></paper-input>
      </template>
    </dom-module>
    
    <script>
      HTMLImports.whenReady(function () {
        Polymer({
            is: "alert-element",
            properties:{
                message:{
                    type: String,
                    value: "hello"
                },
                loadStatus:{
                    type: Object,
                    value: function(){
                        return { percent: 0, loading: true }
                    }
                }
            },
            observers:[
                'loadingCheck(loadStatus.percent)',
                'loadingCheckAll(loadStatus.*)'
            ],
            loadingCheckAll: function(changeRecord){
              console.log(changeRecord);
            },
            loadingCheck: function(loadingPercentange){
              console.log(loadingPercentange, '%');
            },
            ready: function(){
              this.message = "Not quite my tempo.";
              this.loadStatus.percent = 10;
              this.set("loadStatus.percent", 20);
            }
        });
      });
    </script>
    </body>
</html>

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!