I am new to Backbone.js and struggling with a complex problem. I need to save a form with infinite fields, some of which also have infinite options. My concern is that I started with a JSON response instead of building the models/collections first. Here's a brief pseudocode detailing what I'm trying to achieve.
id:
parent: <blockid>
fields: array(
id:
title:
helpertext
options: array(
id:
type:
value:
)
)
Currently, I'm working with a manually created fake JSON response from the server, and now I want to organize it into models and collections on the client side.
//Fake a server response
var JSONresponse = {
"formid":"1",
"fields":[
{
"fieldid":"1",
"title":"Empty title",
"helper":"Helper text",
"type":"radio",
"options":[
{
"optionid":"1",
"value":"Empty option.."
},
{
"optionid":"2",
"value":"Empty option.."
}
]
},
{
// fieldid2
}
]
};
The plan is to dynamically add fields, and for specific field types like radio/checkbox/ul/ol, include an "options" array within the field.
Here's my progress so far:
var app = {};
app.Models = {};
app.Collections = {};
app.View = {};
app.Models.Option = Backbone.Model.extend({
});
app.Collections.Options = Backbone.Collection.extend({
model: app.Models.Option
});
app.Models.Field = Backbone.Model.extend({
options: new app.Collections.Options()
});
app.Collections.Fields = Backbone.Collection.extend({
model: app.Models.Field
});
app.Models.Form = Backbone.Model.extend({
formid : "1",
fields: new app.Collections.Fields(),
initialize: function() {
}
});
How can I separate my JSON response into these models and collections? (Should I reconsider my approach and use something like form.fieldList and form.optionList[fieldListId] instead? If so, how should that be implemented?)
Edit: Check out this jsfiddle after multiple corrections, although I still need help with integrating the inner options list.