Understanding information in Backbone.js

I have multiple backbone models with nested sub-models. Here's how I've approached the solution:

Models.Base = Backbone.Model.extend ({
    relatedModels:  {},

    /**
     * Parses data based on the list of related models.
     *
     * @since                   Version 1
     * @param {Object} response Response
     * @return {Object}         Parsed data
     */
    parse: function (response) {
        var key,
            embeddedClass,
            embeddedData;

        for (key in this.relatedModels) {
            embeddedClass = this.relatedModels[key];
            embeddedData = response[key];
            response[key] = new embeddedClass (embeddedData, { parse: true });
        }

        return response;
    }
});

(utilizing information from this post - Nested Models in Backbone.js, how to approach)

Everything works smoothly when fetching data from the server:

Models.Individual = Models.Base.extend({
    idAttribute:    "idInd",
    urlRoot:    "data/individuals/save",

    relatedModels:  {
        details:        Collections.DetailList,
        relationships:  Collections.RelationshipList
    }
});

...However, when I try to initialize a model using plain JSON, like this:

var Ind = new Models.Individual ({
    idInd: 1,
    name: "Bob Holness",
    details: [
        { option: "I'd like an 'e' please, bob" },
        { option: "Can I have a 'p' please, bob" }
    ],
    relationships: []
});

...it doesn't seem to parse "details". It appears that the Parse function is not being executed. How can I ensure that the data is parsed in both scenarios?

Answer №1

To simplify the process, consider adding parse: true to the constructor as shown below:

var Ind = new Models.Individual ({
    idInd: 1,
    ...
}, { parse: true });

If you find yourself doing this frequently, you can modify the constructor in your base class to automatically include parse: true when creating a new model instance:

Models.Base = Backbone.Model.extend({
    constructor: function(attributes, options) {
        var opts = $.extend({}, options || {});
        if (_.isUndefined(opts.parse)) {
            opts.parse = true;
        }
        Backbone.Model.call(this, attributes, opts);
    },

    ...
});

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

Troubleshooting a Form Validation Issue with React's useState Hook

I am currently working on form validation for a project. The form includes two essential elements: a textbox for messages and a textbox for recipients. These elements are controlled by state.message (a string) and state.recipients (an array). The state var ...

What is the best way to link JSON array information to the HTML using MVC?

I'm currently working with MVC5 and I am trying to populate a div element with data using the .html(data) method. .done(function (data) { var result = $.parseJSON(data); $("#mydata").html(result); }); <div id="mydata"></div> Th ...

Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following: for (var i = 0, len = self.Scope.data.length; i < len; i++) { var data = self.Scope.data[i]; var self = this; //Executing First asynchronous function self.EcritureService.createNewDa ...

Creating a simulated callback function using Jest with a promise

I am currently testing a specific function within my component that is triggered only when the API request is successful. To provide some background, this function is called upon clicking a button: return onUpdate(params, setError, success, cancel); Once ...

What is the process for detaching and attaching click animations using the on() method?

I am encountering an issue with a recursive loop that executes a simple animation. These animations are controlled by the page load and clicking on controls .carousel_item. Click here for live sample JSFiddles for demonstration purposes Challenge: The pr ...

Tips for preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

Obtain the initial Firebase child element without a specific key

Trying to access the first child of a firebase object is my current challenge. The reference is structured as follows: var sitesToVisitRef = firebase.database().ref('sitesToVisit') The reference is confirmed functional as I am able to write to ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

Interactive image grid with adjustable description field per image upon selection

My goal is to create a grid of images with a single text field below the grid. This text field should display the description of the image that was last clicked. The grid is implemented using floating divs within a main div, as shown in the code snippet be ...

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...

What is causing this get method to return such a message?

One of my functions tabulates user-specific data using a GET method that sends a query parameter userId: <script> let thisArray = [] let = userId = $('#userId').val(); $.ajax({ method:&ap ...

What is the best way to implement validation for a textfield to prevent submission if a negative value is entered?

I am working with a text field of type number and I have successfully set a minimum value of 0 to ensure that negative values are not accepted. However, I have encountered an issue where I am unable to delete the 0 once it is entered. Is there a way to fix ...

Frequent running of jQuery scripts

In my jQuery ajax code, I created a FitnessPlanDay: // Add Day ajax $('#addDay').on("click", function() { $.ajax({ url: '@Url.Action("AddDay")', type: 'POST', ...

Decoding JSON data into Enum fields

Within my Android application, I encounter a straightforward JSON object containing basic key-value pairs. For example: {"username" : "billySmith", "gender" : 1} In addition, there is an enum with matching field names username and gender (String and int, ...

Querying MongoDB to locate books by the same author or those that are categorized in at least one similar category

Looking to discover books by the same author or with at least one matching category. This is how my Book Schema looks: const bookSchema = new Schema( { title: { type: String, required: true }, author:{ ...

Transform JSON data into a structured dataframe

I need to convert the following JSON data into a Dataframe using Python: JSON: {"Results": {"forecast": [2.1632421537363355, 16.35421956127545], "prediction_interval": ["[-114.9747272420262, 119.301211 ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Unpacking a nested array with GSON

I am encountering difficulties deserializing the JSON data available at . Despite my efforts, an error persists. Below is the code snippet I have been working on: Gson gson = new Gson(); String json = readHTTPS(new URL("https://mtgox.com/code/data/getD ...

What is the best way to change an http call in a controller to a Service/factory pattern that accepts a parameter?

Currently, I have a controller making use of http.get, http.push and http.post methods within my AngularJS app. During my learning journey with AngularJS, I've discovered that it's more efficient to place http.get calls in service files. While I ...

transform the JSON string into a two-dimensional boolean array

I'm looking for a way to transform a JSON string into a 2D array in C#. Currently, I have code that retrieves the text/json from a web browser and saves it as a string. "BoolArray": [ [ true, true, false, ... ], [ true, ...