Week 17 | Observers

polymer 1.0
Wed Dec 21 2016

Observers are something like the computed properties we went over last week. However it won’t set the value of the property but just run the observer method every time the property set in the observer changes adding the newValue and the oldValue as arguments.

In our demo whenever the “message” value changes the observer “messageChanged” will trigger.

Lastly, we can set an array of observers to trigger various methods whenever the values passed in change, like in our loadingCheck example.

<!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$="{{!loading}}">loading (<span>{{loadingPercentage}}%</span>)...</div>
      [[message]]
      <paper-input value="{{message}}"></paper-input>
    </template>
  </dom-module>
  <script>
    HTMLImports.whenReady(function() {
      Polymer({
        is: "alert-element",
        properties: {
          loadingPercentage: {
            type: Number,
            value: 0
          },
          loading: {
            type: Boolean,
            value: true
          },
          message: {
            type: String,
            value: "hello",
            observer: 'messageChanged'
          }
        },
        observers: [
          'loadingCheck(loadingPercentage, loading)'
        ],
        messageChanged: function(newValue, oldValue) {
          console.log(oldValue, ":", newValue);
        },
        loadingCheck: function(loadingPercentange, loading) {
          console.log("loadingPercentage:", loadingPercentange, " loading:", loading);
        },
        ready: function() {
          this.message = "Not quite my tempo.";
          this.loading = true;
          this.loadingPercentage = 20;
        }
      });
    });
  </script>
</body>
</html>

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!