Alejandro
Alejandro

Reputation: 1159

Polymer 1 get element from deep sub-property changes path

So from the following docs https://www.polymer-project.org/1.0/docs/devguide/properties.html#deep-sub-property-changes-on-array-items

I made the following code:

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

I'm able to obtain the callback through data binding update. :D

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

My question is: Is there any clean way of obtaining the 'id' of the object that is referenced by the #0?

I mean I could do something to analyze the String and obtain the '0' then convert it to an integer and then get the object id like this:

this.skills[varWith0].id

But this doesn't feel like the right clean way. I also feel like this would be a common thing to do.

So is there any clean way of doing this?

Thank you

Upvotes: 1

Views: 351

Answers (2)

DocDude
DocDude

Reputation: 2873

There's a get method on the element's prototype that can be used to retrieve values by path. So if you have the path, you can retrieve the value.

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

It's also handy to know that you can pass the path as an array of paths or path segments, so you could also do:

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

If you want to make sure data bindings and observers update, you'll also want to use this.push and this.splice to update your responseSkills array, so end code could look something like:

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

Upvotes: 1

Alejandro
Alejandro

Reputation: 1159

Ok.. I decided to write my own code to solve the problem. Like I said I think there should be some stard way of doing it. Nonetheless this works too.

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

I know the comments are in spanish (sorry about that) but for people that don't understand spanish the code is very simple. Hope it helps

Upvotes: 0

Related Questions