javascript - Backbone.js 添加到集合

标签 javascript json backbone.js

在 Backbone 中,我有一个集合,其中填充了一些 JSON 数据,如下所示。

[
{
    "test1": {
        "fistName": "test",
        "lastName": "example"
    },
    "test2": {
        "fistName": "test",
        "lastName": "example"
    }
},
{
    "test1": {
        "fistName": "test",
        "fistName": "example"
    },
    "test2": {
        "fistName": "test",
        "fistName": "example"
    }
},

]

目前我正在尝试向包含上述数据的集合添加一个新模型。

这是模型。

Test = Backbone.Model.extend({
defaults : {
        test1: {
            firstName: null,
            lastName: null
        },
        test2: {
            firstName: null,
            lastName: null
        }
    },

});

下面是我正在尝试的

var test = new Test({test1: {firstName: $("#test1 option:selected").val(), score: $("#test1lastName").val()}}, {test2: {firstName: $("#test2 option:selected").val(), score: $("#test2lastName").val()}});

myCollection.add(test);

但是,这样做只会填充 test1 数据,而不填充 test2 数据。将 test1 和 test2 数据添加到模型中的正确方法是什么,然后可以将其添加到集合中。

谢谢

更新

澄清一下,测试 1 和 2 不是独立的对象,它们彼此相关并且需要位于同一模型中

最佳答案

根据模型的定义方式进行编辑,如果按如下格式对其进行格式化,则可能可以更好地调试。

var test = new TFS.Test({
    test1: {
        firstName: $("#test1 option:selected").val(),,
        lastName: '', // code for last name? 
        score: $("#test1lastName").val()
    },
    test2: {
        firstName: $("#test2 option:selected").val(),
        lastName: '', 
        score: $("#test2lastName").val()
    }
});

myCollection.add(test);

如果您更好地了解整个操作/流程,我也许可以为您提供更多帮助 - 即是什么触发了这些模型的创建? jQuery 是否有问题,并且您的文档尚未准备好?

关于javascript - Backbone.js 添加到集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11539362/

相关文章:

javascript - 无法从 Angular 中的 JSON 对象填充数组

javascript - 使用 Backbone.js 设置我的模型

javascript - 发出 RESTful JSON 请求

python - 当发送到 Pyramid/Cornice 应用程序时,Backbone.js HTTP PUT 请求失败并出现 404 错误

javascript - 理解 JavaScript 的值传递

Javascript 用单反斜杠替换双反斜杠

php - CSS/PHP 用 div 填充屏幕

json - 如何用Alamofire+ObjectMapper映射JSON响应的多维数组?

javascript - AudioContext createMediaElementSource 来自从 blob 中获取数据的视频

javascript - 解析 JSON 数据并打印