Search code examples
javascriptpolymerweb-componentpolymer-1.0custom-element

Polymer 1.0 Array Observers on Binding Change


I am trying to observe changes to an array of objects that is passed in to a Polymer element. When a new item is added to the array, the array is also changed in the Polymer element. However, the observer method is never called.

Containing Element

<dom-module is="table-container">
  <template>
    <selectable-table table-items="{{items}}"></selectable-table>
    <button on-click="addItem">Add Item</button>    
  </template>
  <script>
    Polymer({
      is : "table-container",
      attached : function() {
        this.items = [];
        for (var i = 0; i < 3; i++) {
          this.push("items", {
            numerical: "1",
            english: "one"
          });
        }
      },
      addItem : function() {
        this.push("items", {
          numerical: "3",
          english: "three"
        })
      }
    })
  </script>
</dom-module>

Trying to observe changes here:

<dom-module id="selectable-table>
  <template>
    <div>{{tableItems}}</div>
  </template>
  <script>
    Polymer({
      is : "selectable-table",
      properties : {
        tableItems: {
          type: Object,
          notify: true,
          observer: "updateTableItems"
        }
      }
      updateTableItems : function() {
        // Updates here
      }
    });
  </script>
</dom-module>

The "updateTableItems" method is being called at first when the items array is first populated but never when the button is clicked to add more objects.


Solution

  • To observe changes to the array use the following style of observers.

    Polymer({
      is : "selectable-table",
      properties : {
        tableItems: {
          type: Array,
          notify: true,
        }
      },
    
      observers: [
          'updateTableItems(tableItems.*)'
      ],
      updateTableItems : function() {
        // Updates here
      }
    });
    

    Because tableItems is an array of objects, you should use type Array in your property declaration. The type of observer that you use will only trigger, if you assign a new array instance to the tableItems property. For manipulations of the array, add your callback to observers. You can find more details in the docs.