如何从子元素更改父元素属性?

时间:2018-06-24 11:42:21

标签: polymer polymer-1.0 web-component

如何让子元素更改父元素中属性的值并能够观察父元素中的变化

<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
    }
  })

注意到纸树节点是一个子元素,在其模板中进行纸质支票,目的是获取单击的纸树节点ID attr并将其推送到ChapterIds属性。

问题是当我单击任何复选框时_chapterChanged不会触发

我正在附加一个示例项目,因为它无法像jsbin这样的东西发布,这是项目https://drive.google.com/file/d/1yCeXkZu8Yp-8GUgadGHIfeP5w5uyI12J/view?usp=sharing的gdrive zip文件夹

2 个答案:

答案 0 :(得分:1)

您使用的是正确的思维,而不是完整的思维。

release应该在属性notify: true,下的子元素paper-tree-node中声明,而不是在chapterIds元素下声明。在开始使用Polymer时,我也犯了这个错误。

此外,每当Polymer看到camelCase变量时,都会假定该变量包含破折号:

paper-tree

...应该是...

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

...我将属性 <paper-tree-node id="root" data="[[data]]" actions="[[actions]]" on-click='_handlePaperCheck' chapter-ids={{chapterIds}}></paper-tree-node> 切换为chapterIds。创建新元素时,我很少使用camelCase变量,因为此错误很容易造成。

答案 1 :(得分:0)

您可以使用eventdata绑定来完成此操作。

相关问题