Utilize Backbone.js to organize and structure JSON data by populating it into nested collections and models within

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.

Answer №1

If you're looking for a simple solution, consider utilizing Backbone Relational or Backbone Associations.

The provided documentation should give you a good starting point.

Alternatively, if you prefer not to rely on a library, you can customize the parse function in the Form model.

app.Models.Form = Backbone.Model.extend({
    defaults: {
        fields: new app.Collections.Fields()
    },

    parse: function(response, options) {
        return {
            formid: response.formid,
            fields: new app.Collections.Fields(_.map(response.fields, function(field) {
                if (field.options) {
                    field.options = new app.Collections.Options(field.options);
                }

                return field;
            }))
        };
    }
});

By fetching a form from the server, the response will be parsed into a hierarchical structure of models and collections.

form.get('fields') will retrieve an app.Collections.Fields collection. Use

form.get('fields').first().get('options')
to access an app.Collections.Options collection, if available.

In addition, you have the option to create the form model as follows:

var form = new app.Models.Form(JSONresponse, {
    parse: true
});

This approach will yield the same object layout.

Answer №2

Dealing with nested models and collections in plain Backbone can be a challenging task.

An easy way to tackle this issue is by structuring your code like this:

   var Option = Nested.Model.extend({
       idAttribute : 'optionid',

       defaults : {
          optionid : Integer
          value : ""
       }
    });

    var Field = Nested.Model.extend({
        idAttribute : 'fieldid',

        defaults : {
          fieldid : Integer,

          title : "",
          helper : "",
          type : "radio",
          options : Option.Collection
        }
    });

    var Form = Nested.Model.extend({
        idAttribute : 'formid',

        defaults : {
          formid: Integer,
          fields: Field.Collection
    });

https://github.com/Volicon/backbone.nestedTypes

By following this structure, you'll have direct access to the attributes without having to use get and set methods. Simply do

form.fields.first().options.first().value
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the process of aggregating all values associated with the same key in JSON data using Python

I am looking for a way to aggregate all the values for the same keys in JSON data using Python. Any assistance would be greatly appreciated. Here is the input data provided: {'MESSAGE_DATA': {'BGEN_CENQO_XTRA_KEY': {'BGEN_CENQO_CLN ...

Collaborate by sharing local storage with other systems

One of my systems (x.x.x.x: 8000) creates a localstorage after logging in. Now, when a user interacts with another system (x.x.x.x: 8001) by clicking a specific button, the information stored in the initial system's localstorage (x.x.x.x: 8000) is nee ...

Compare the values in the table before sending the email

After attempting to execute this particular script, I am encountering an issue where no emails are being sent to the user's email address. The functionality of the script involves comparing values in a specific column in a sheet (column 10) and sendin ...

Utilize drag and drop functionality to interact with an HTML object element

I am struggling with a div that contains a PDF object and draggable text: <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function drop(ev) { alert("DROP"); } </script> </head> <body> <di ...

Trouble with executing a jQuery dynamic loop for each item

I have a unique situation where I am dealing with a table containing multiple tables for various users. The number of users can vary, so I am aiming to create a dynamic solution. Below are two sample tables for reference. <div class="timecard"> < ...

Iterate over each key in a JSON object to verify if its corresponding value is blank

I am dealing with a JSON object that has empty values for the keys remarks and address. When extracting the JSON, it displays undefined for these empty values. However, I want to replace the empty values with a - sign instead. I understand that I can achie ...

The JSON.stringify function encounters difficulties when trying to format an object into

Why does JSON.stringify refuse to format objects and keep everything on a single line? <!DOCTYPE html> <html> <head> <script> var obj = { "a" : "1547645674576457645", "b" : "2790780987908790879087908790879087098", "c" ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

Guide to deploying a React application that utilizes Node/Express for server calls in conjunction with IIS

My React application is designed to make calls to a server.js file that includes requests for data from a database using queries (specifically MSSQL). The server.js file looks like this: var express = require('express'); var app = express(); var ...

When attempting to search and parse input text using a code replication technique, a console error is generated

Trying to extract the answer from this question's comment. The current code is displayed below, but struggling with removing the Dealing with an Unexpected token } error in Chrome console. Any ideas on how to fix this? Also looking for a Chrome pl ...

Setting up a personalized JSPM registry configuration

I have chosen to use Verdaccio as the platform for hosting a private package. In my current project, I am looking to incorporate this package locally. The package has been successfully published and is now hosted on Verdaccio running on localhost (http://l ...

Processing JSON data in django view

I am looking to integrate the api that I have created using django_rest_framework into my API. I need to utilize the JSON data produced in both my views and templates. The JSON data structure looks like this - [ { "url": "http://127.0.0.1:8000/app/clubs/ ...

Accurate understanding of URL parameters and hashtags

Imagine an HTML document containing two blocks, where the content of only one block can be displayed at a time by toggling between them using menu buttons and/or URL parameters with the same JavaScript functions provided below: <div class="block1&q ...

Automatically updating the scope of the .filter() function

Is there a way to update the filter in the code below? .controller('MainCtrl', ["$rootScope", "$scope", function($rootScope, $scope) { $rootScope.number = 1; $scope.text = "foo|baz|bar" }]).filter("MyFormat", ["$rootScope", function($rootS ...

A guide on including a node as a parameter, alongside other data types, in a function using ajax within Umbraco

When attempting to pass a node and two strings as parameters to a JsonResult in Umbraco, I encountered an issue where the node variable had no value when debugging the method. Below is the JavaScript code: function newsSub() { if(validateForm('ne ...

Choose a list in order to create a new list

If I were to choose a specific state in Nigeria, what steps should I follow to generate a drop-down menu with a list of local governments within that state? ...

The main attribute in the NPM package.json is missing or has no appropriate entry

I'm really struggling to figure out the best approach for setting up my package.json file. I have a JavaScript module that contains multiple reusable JS files, let's call it Module1. In Module1's package.json, the name attribute is set to " ...

How to emphasize a portion of an expression in AngularJS using bold formatting

I have a specific goal in mind: to emphasize part of an angular expression by making it bold. To achieve this, I am working with an object obj which needs to be converted into a string str. obj = $scope.gridOptions1.api.getFilterModel(); for (var pr ...

What are some ways to retain data while navigating between different online pages?

Can anyone provide guidance on how to maintain the contents of a shopping cart as I navigate between pages, all without losing the information? Is this achievable using solely JavaScript? ...

Ways to extract data from a table in SQL utilizing jQuery, JSON, and AngularJS without relying on a web method

I need to retrieve table data from an SQL database. When the user clicks a button, I want the selected data table from the drop-down to be displayed. Although my drop-down is functioning correctly, I am unable to retrieve the selected table. public sta ...