首页 > 解决方案 > Polymer 2 更新 paper-listbox 项

问题描述

我有一组具有name属性的对象。为了编辑这些对象,我有一个纸质列表框,其中列出了对象的名称并让用户按名称选择其中一个对象。在列表框旁边,我有一个带有纸张输入等的表单来编辑所选对象的属性。其中一个纸张输入绑定到所选对象的名称属性,因此用户可以更改名称。

我的问题是对 name 属性的更改不会反映到列表框。用户更改名称后如何更新列表框?

我确认名称更改确实发生了,因为当我更改为另一个对象并返回到前一个对象时,更改的名称仍然存在。问题只是列表框没有更新。

我试过类似的东西:

this.notifyPath("myObjects")

但这无济于事。

纸张列表框是这样创建的

<paper-listbox selected="{{selectedObjectIndex}}">
    <template is="dom-repeat" items="[[myObjects]]">
        <paper-item>[[item.name]]</paper-item>
    </template>
</paper-listbox>

selectedObjectIndex有一个设置选定对象的观察者

selectedPageIndexChanged(newValue, oldValue) {
    ...
    this.selectedObject = this.myObjects[this.selectedObjectIndex];
}

标签: polymerpolymer-2.x

解决方案


下面是一些工作和不工作的例子。(我尝试将codepen中的代码说明为show DEMO,这里也部分代码以便快速查看。

 <paper-listbox selected="{{selectedObjectIndex}}">
  <template is="dom-repeat" items="{{myObjects}}" >
    <paper-item>[[index]].[[item.name]]</paper-item> <br/>
  </template>
 </paper-listbox>
 <paper-input value="{{selectedObject.name}}" ></paper-input>

……

     selectedObjectIndex:{
           type:Number,
           observer:'selectedPageIndexChanged'
         }
      }} 
      static get observers() {return ['nameValueChanged(selectedObject.name)']}
      constructor() {
            super();
       }

       ready() {
            super.ready();

        }

  selectedPageIndexChanged(newValue, oldValue) {

      this.selectedObject = this.myObjects[newValue];
  }
 nameValueChanged(name){
      //this.myObjects[this.selectedObjectIndex].name = name;
      //this.set('myObjects.' + this.selectedObjectIndex + ".name", name ) // --> Does not work
      this.set('myObjects.' + this.selectedObjectIndex, { name: name} ) // --> Works
      // this.splice('myObjects', this.selectedObjectIndex,1, this.selectedObject) -- Does not work

      //this.notifyPath('myObjects.' + this.selectedObjectIndex + ".name") // -- works (with one of above)

 }
}

上面的签名Does not work行改变了对象,但在dom-repeat


推荐阅读