【问题标题】:Polymer 1 get element from deep sub-property changes path聚合物 1 从深层子属性更改路径中获取元素
【发布时间】:2016-07-07 11:30:45
【问题描述】:

所以来自以下文档https://www.polymer-project.org/1.0/docs/devguide/properties.html#deep-sub-property-changes-on-array-items

我做了以下代码:

            properties:{
                skills:{
                    type:Array,
                    notify: true,
                    value: [
                        {
                          id:1,
                          name:"UNOOOOOO",
                          description: "aaa a a aa a aaaa adicionales con el fin de exceder sus expectativas y "+
                          "mejorar su calidad de vida. La orientación al "+
                          "cliente es una actitud permanente  que caracteriza a la persona."
                        },
                        {
                          id:2,
                          name:"Capacidad para plantear identificar y resolver problemas",
                          description: "aaa a a aa a aaaa adicionales con el fin de exceder sus expectativas y "+
                          "mejorar su calidad de vida. La orientación al "+
                          "cliente es una actitud permanente  que caracteriza a la persona."
                        }
                    ]
                }
            },
            observers: [
                'skillIsSelectedChanged(skills.*)'
            ],
            skillIsSelectedChanged: function(changeRecord){
                console.log(changeRecord);
            }

我可以通过数据绑定更新获取回调。 :D

Object {path: "skills.#0.isSelected", value: true, base: Array[2]}

我的问题是:是否有任何干净的方法来获取 #0 引用的对象的“id”?

我的意思是我可以做一些事情来分析字符串并获得“0”,然后将其转换为整数,然后像这样获取对象 id:

this.skills[varWith0].id

但这感觉不是正确的干净方式。我也觉得这将是一种常见的事情。

那么有什么干净的方法可以做到这一点吗?

谢谢

【问题讨论】:

  • 使用调试器.. 浏览“obj updated”上的一长串对象。看看你是否可以在某处找到对 id 的引用
  • 感谢您的回复!我不确定我是否理解。什么是“obj 更新”?我在哪里以及如何找到它?谢谢

标签: javascript polymer polymer-1.0 observers


【解决方案1】:

元素原型上有一个get 方法,可用于按路径检索值。因此,如果您有路径,则可以检索该值。

if (changeRecord.path.indexOf('.isSelected') >= 0) {
  var itemPath = changeRecord.path.replace('.isSelected', '');
  var item = this.get(itemPath);
}

知道您可以将路径作为路径数组或路径段传递也很方便,因此您也可以这样做:

var parts = changeRecord.path.split('.');
var last = parts.pop();
if (/* last is something interesting */) {
  var item = this.get(parts);
}

如果您想确保数据绑定和观察者更新,您还需要使用 this.pushthis.splice 来更新您的 responseSkills 数组,因此最终代码可能类似于:

if (changeRecord.path.indexOf('.isSelected') >= 0) {
  var itemPath = changeRecord.path.replace('.isSelected', '.id');
  var id = this.get(itemPath);
  if (changeRecord.value) {
    this.push('responseSkills', id);
  } else {
    for (var i=0; i<this.responseSkills.length; i++) {
      if (this.responseSkills[i] == id) {
        this.splice('responseSkills', i, 1);
        break;
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    好的.. 我决定编写自己的代码来解决问题。就像我说的那样,我认为应该有一些明星的方式来做到这一点。尽管如此,这也有效。

                skillIsSelectedChanged: function(changeRecord){
                    //primero tenemos que obtener la posicion del skill que cambio.
                    //path nos da un string asi: skills.#0.isSelected donde el 0 despues del # es la posicion.
                    //por otro lado cuando se cargan los elementos inicialmente tambien llama este callback
                    //pero con un string en path asi: skills
    
                    //primero hacemos split en #.
                    var arr = changeRecord.path.split("#");
    
                    //luego si el length del arreglo es mayor a 1 estamos en el caso que nos interesa.
                    if(arr.length > 1){
                        //como desconocemos el largo del numero, le volvemos e hacer un split al arr[1] en '.'
                        //de ese segundo arreglo resultante, la posicion 0 es el numero deseado. Ese lo convertimos en int
                        var arr2 = arr[1].split(".");
                        var position = parseInt(arr2);
    
                        //finalmente buscamos en skills el id del objeto en la posicion obtenida
                        var id = this.skills[position].id;
    
                        //lo metemos en el arreglo de respuesta
                        this.responseSkills.push(id);
                    }
                }
    

    我知道 cmets 是西班牙语(对此感到抱歉),但对于不懂西班牙语的人来说,代码非常简单。希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      相关资源
      最近更新 更多