将数组嵌套到主干模型中

Nested array into backbone model

本文关键字:模型 数组 嵌套      更新时间:2023-09-26

我有以下主干模型:

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

我想更改"direccion"中数组的"direcion"矩阵的值。

我使用了以下代码,但不起作用:

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

在这里,我获得了值已更改的数组,并且运行良好:

console.log(direccionArray);

现在,我将数组设置为我的主干模型,如下所示,但不起作用(模型不会改变),我得到了相同的模型(改变其他矩阵,如"nombre"或"tipo",效果很好,但不适用于数组):

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

有人能帮帮我吗?

如前所述,模型的direccion属性是一个数组,包含索引为0的对象。

当你尝试做:

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

这不会更新要更新的direccionArray[0],只会向数组对象添加新属性。

你想做的是:

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

试试console.dir(direccionArray)这个老数组,你会发现不同的地方。

更新:

请参阅这篇文章,并附上对该问题的解释。出现这种情况的主要原因可能是,您正在字符串中使用jquery的val()方法获取非输入元素的值。