Week 19 | Observer Array-mutations

polymer 1.0
Mon Jan 09 2017

In the previous demo we mentioned observers and object sub-properties.To listen to changes made in an array now we can use some additional methods.

For example to listen to whether an item is added/removed we can add a splice observer

        observers: [
          'messagesAddedOrRemoved(messages.splices)'
        ]

This will trigger the method specified offering an object with multiple information concerning the items added/removed.

Lastly, have in mind that when working with Polymer if you want to update an array and trigger the binding effects of it you can use the Array Mutation with the syntax of:

this.[the method](the property, additional parameters)

for example

 this.splice('messages', 0, 1);

 

You can preview the full demo here:

<!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>
  <script>
    HTMLImports.whenReady(function() {
      Polymer({
        is: 'alert-element',
        properties: {
          messages: {
            type: Array,
            value: function() {
              return [{
                text: 'Loading Messages'
              }, {
                text: 'Messages Loaded'
              }];
            }
          }
        },
        observers: [
          'messagesAddedOrRemoved(messages.splices)'
        ],
        messagesAddedOrRemoved: function(changeRecord) {
          // Array Observation Step 2
          if (!changeRecord) {
            return;
          }
          changeRecord.indexSplices.forEach(function(s) {
            console.log(s.index + ' position where the splice started');
            s.removed.forEach(function(item) {
              console.log(item.text + ' was removed');
            });
            console.log(s.addedCount + ' items were added');
          }, this);
          console.log('--------------');
        },
        ready: function() {
          this.splice('messages', 0, 1); // Array Mutation Step 1
          this.push('messages', {
            text: 'Message Added'
          }, {
            text: 'Message Added1' 
          }); // Array Mutation Step 1
        }
      });
    });
  </script>
</body>
</html>

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!