2012-07-18 46 views
0

在Backbone中,我有一個集合了一些JSON數據的集合,如下所示。Backbone.js添加到集合

[ 
{ 
    "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數據添加到模型中的正確方法是什麼?然後將這些數據添加到集合中。

感謝

UPDATE

只是爲了澄清,測試1和2是不是單獨的對象,它們是相互關聯的,需要在同一個模型

回答

3

編輯,這取決於如何你的模型被定義了,如果你將它設置爲如下格式,你可能會更好地調試一下。

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有沒有問題,並且你的文檔沒有準備好?

+0

感謝您的回覆,沒有即時只是試圖添加一個對象作爲test1和test2一個相關的對方,需要在同一個模型 – 2012-07-18 10:40:16

+0

你可以包含代碼定義'TFS.Test'嗎? – 2012-07-18 10:52:55

+0

我們走了,模型加入:) – 2012-07-18 11:01:23