In Polymer 2.0 how to observe edits to properties of an object bound to an element inside dom-repeat?

China☆狼群 提交于 2019-12-06 08:20:11

Your observer usage in 2.0 seems correct already, and I think you might be seeing a bug in the 2.0-preview branch. I recommend creating a GitHub issue for this, so that the Polymer team could confirm/clarify.

FWIW, the issue does not occur in Polymer 1.x (i.e., the observer is only invoked for the newly added item), as seen in this demo:

HTMLImports.whenReady(() => {
  class EditorElement {
    beforeRegister() {
      this.is = 'editor-element';
      this.properties = {todo: Object};
      this.observers = ["observe(todo.description)"];
    }

    observe(p1) {
      console.log("Observed change for TODO item description: "+p1);
    }
  }
  Polymer(EditorElement);

  class ListElement {
    beforeRegister() {
      this.is = 'list-element';

      this.properties = {
        list: {
          type: Array,
          value: () => []
        }
      };
    }

    _pushItem() {
      this.push("list", {description: `item ${this.list.length}`});
    }
  }
  Polymer(ListElement);
});
<head>
  <base href="https://polygit.org/polymer+1.8.1/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <list-element></list-element>

  <dom-module id="editor-element">
    <template>
      <div>Editor for [[todo.description]]</div>
    </template>
  </dom-module>
  
  <dom-module id="list-element">
    <template>
      <button on-click="_pushItem">Push item</button>

      <template is="dom-repeat" items="{{list}}">
        <div class="item">
          <editor-element todo="{{item}}">
          </editor-element>
        </div>
      </template>
    </template>
  </dom-module>

</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!