Search code examples
polymerpolymer-1.0web-component

How to change parent element property from child element?


How can I let a child element change the value of a property in the parent element with the ability to observe that change in the parent element

<link rel="import" href="paper-tree-node.html">

<dom-module id="paper-tree">
  <template>
    <div>
      <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapterIds={{chapterIds}}></paper-tree-node>
    </div>
  </template>
</dom-module>

<script>
  Polymer({

    is: 'paper-tree',

    properties: {
      chapterIds: {
        type: Array,
        value: [],
        notify: true,
        observer: "_chapterChanged"

      }
    },
    _handlePaperCheck: function (e) {
      let element = e.target.parentElement
      if (element.checked) {
        this.push('chapterIds', parseInt(element.id.substr(2)))
        // console.info(this.chapterIds);


      } else {
        var index = this.chapterIds.indexOf(element.id);

        this.splice('chapterIds', index, 1)
        // console.info(this.chapterIds);

      }

    },
    _chapterChanged: function () {
      console.log(this.chapterIds)
      //   this.$.root.chapterIds = this.chapterIds
    }
  })

noting that paper-tree-node is a child element hosts a paper-check inside it's template, the purpose of this is to harvest the clicked paper-tree-node id attr and push it to the chapterIds property.

Problem is that _chapterChanged wont fire when i click on any checkbox

I am attaching a sample project since this cannot be posted on somthing like jsbin, here is a gdrive zip folder for the project https://drive.google.com/file/d/1yCeXkZu8Yp-8GUgadGHIfeP5w5uyI12J/view?usp=sharing


Solution

  • You're using the right thinking, but not the entire way.

    notify: true, should be stated in your child element paper-tree-node under the property chapterIds, and not under your paper-tree element. I made this mistake too when I began with Polymer.

    Also, whenever Polymer sees camelCase variables, it assumes the variable contains dashes:

      <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapterIds={{chapterIds}}></paper-tree-node>
    

    ... should be ...

      <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapter-ids={{chapterIds}}></paper-tree-node>
    

    ... where I switched the property chapterIds to chapter-ids. I rarely use camelCase variables when creating a new element because this mistake is so easy to make.