聚合物1.x:访问'选择'铁清单中的项目

Polymer 1.x: Accessing 'selected' items from iron list

本文关键字:单中 项目 选择 访问 聚合物      更新时间:2023-09-26

如何访问元素、属性以及以其他方式迭代iron-listselected项?

这是JSBin。

  1. 打开控制台
  2. 从列表中选择两个或三个项目
  3. 单击标有"在控制台中显示项目"的按钮
  4. 请注意控制台输出的最后三行中的输出问题。它们显示了未定义的数组长度,并且任何对象键所在的数组都是空的

那么,我们如何访问这些选定项目的值呢?

http://jsbin.com/duwasisoyo/1/edit?html输出
_showItems: function(){
  console.log(this.selectedList);            // Okay
  console.log(this.selectedList[0]);         // Okay
  console.log(this.selectedList[0]['name']); // Okay
  console.log(this.selectedLength);          // Undefined
  console.log(this.selectedKeys);            // Empty array
  console.log(this.selectedNames);           // Empty array
}

注意:此问题使用iron-list"选定项目"演示的源代码

也许铁名单没有通知selectedList的更改。您可以将方法更改为

    _showItems: function(){
      console.log(this.selectedList);
      console.log(this.selectedList[0]);
      console.log(this.selectedList[0]['name']); 
      console.log(this._computeSelectedItemsLength(this.selectedList)); 
      console.log(this._computeSelectedKeys(this.selectedList));
      console.log(this._computeSelectedNames(this.selectedList));
    }

此外,您还应该更改:

    _computeSelectedNames: function(ob) {
      var out = [];
      for(x in ob){
        out.push(ob[x]['name']);
      }
      return out;
    },

啊,添加控件检查selectedList是否为空;)

聚合物松弛网站的@jeanpokou说:

也许你需要使用<array-selector id="selector" items="{{employees}}" selected="{{selected}}" multi toggle></array-selector>就像这里建议的那样https://www.polymer-project.org/1.0/docs/devguide/templates.html#array-选择器

聚合物松弛网站的rob说:

这是一个固定版本https://jsbin.com/hiruducole/1/edit?html,输出

您需要观察(selectedItems.*)

然后你可以使用更改记录来找出的更改

https://www.polymer-project.org/1.0/docs/devguide/properties.html#array-观察

你也可以观察(selectedItems.peets),但我很懒,只做(selectedItem.*),它会捕捉到任何变化。

以下是关于变更记录的解释:https://www.polymer-project.org/1.0/docs/devguide/properties.html#deep-观察

关键变更:https://jsbin.com/hiruducole/1/edit?html输出
/** / Before
selectedLength: {
  computed: '_computeSelectedLength(selectedItems)'
},
/**/
// After
selectedLength: {
  computed: '_computeSelectedLength(selectedItems.*)'
},
...
/** / Before
_computeSelectedLength: function(ar) {
  return ar.length;
},
/**/
// After
_computeSelectedLength: function(record) {
  return record.base.length;
},