简体   繁体   中英

Nested array into backbone model

I have the following backbone model:

var Info = Backbone.Model.extend({
    urlRoot: 'http://localhost:8080/info',
    defaults : {
        nombre: '',
        tipo : '',
        telf : 0,
        icono : '',
        direccion:[{
            direccion:'',
            latitud:'',
            longitud:''
        }]
    },
    idAttribute:"_id"
});

I want to change the value of the "direccion" atribute of the array inside "direccion".

I have used the following code but is not working:

//clone the array
var direccionArray = _.clone(this.collection.get(idInfo).get('direccion'));
direccionArray.direccion = this.$('#dir-info-edit').val();

Here I obtain the array with the values changed and works fine:

console.log(direccionArray);

Now I set the array into my backbone model as follow and is not working (the model don't change) and I get the same model (changing other atributes like "nombre" or "tipo" works fine but not with the array):

this.collection.get(idInfo).set('direccion',direccionArray);
console.log(this.collection.get(idInfo));

Could someone help me please?

As stated direccion attribute of model is an array that contains object at index 0.

When you trying to do:

//clone the array
var direccionArray = _.clone(this.collection.get(idInfo).get('direccion'));
direccionArray.direccion = this.$('#dir-info-edit').val();

This will not update the direccionArray[0] , which you want to update, and just will add new attribute to your array object.

What you want to do is:

direccionArray[0].direccion = this.$('#dir-info-edit').val();

Try console.dir(direccionArray) the old array and you will see the difference.

Update:

Please see this jsfiddle with the explanation of the issue. The main reason for your case can be that you are tring to get the value with jquery's val() method on an element that is not an input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM