Mastering Backbone - Incorporating JSON information with backbone

I am currently in the initial stages of transitioning my application to the backbone framework.

One of the tasks involves handling data that is fetched as JSON from an ajax call.

{f1:"f1_value", f2:"f2_value", f3:"f3_value"},
{f1:"f1_value", f2:"f2_value", f3:"f3_value"},
{f1:"f1_value", f2:"f2_value", f3:"f3_value"},

This dataset always consists of 3 columns but can vary in the number of rows.

Once processed client-side into HTML, this data is used to populate a dynamic div, which can extend as needed. Each data chunk is intended to represent a single view within the framework.

<div id = "data_hold"></div>

How can I integrate this data into the framework?

    var ModelTest,
        CollectionTest,
        ViewTest;

    ModelTest = Backbone.Model.extend({
    });
    CollectionTest = Backbone.Collection.extend({
        model: ModelTest
    }
    ViewTest = Backbone.View.extend({
    });

Answer №1

Mastering Backbone Basics:

var User,
    Task,
    ProjectView;

User = Backbone.Model.extend({ });

// Set the URL for the collection. It can be passed as an option in the
// Collection's initialize function instead of being static.

Task = Backbone.Collection.extend({
    model: User,
    url: 'http://localhost/my_json_source'
});

ProjectView = Backbone.View.extend({
    // Specify the target element for rendering. It can be an existing 
    // element or dynamically generated and attached to the DOM.
    el: $('#data_hold'),

    // Call the local render method when the collection is updated.

    initialize: function(options) { 
        this.collection.bind('reset', _.bind(this.render, this));
    },

    // Clear the element and append rows of the collection as paragraphs.
    // Use '_this = this' to access the View's context within each().

    render: function() {
        var _this = this;
        this.$el.html('');
        this.collection.each(function(item) {
            _this.$el.append('<p>' + item.get('name') + '</p>');
            });
    }
});

// Initialize the collection and view, then fetch the collection to trigger 
// rendering after it's updated.

$(function() {
    taskCollection = new Task();
    projectView = new ProjectView({collection: taskCollection});
    taskCollection.fetch();
});

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

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Long taps do not activate the context menu in the mobile interface, as noted in the Google Maps API

During the development of my project, I encountered an issue with the Google Maps API not functioning correctly on mobile devices. I am utilizing GMaps.js, but even that example does not properly support right-click (long tap event). Here is a snippet of ...

Unlock the secrets of recovering deleted data from a text area in Kendo UI Angular

Currently working with Kendo UI for Angular, I need to capture deleted content and remove it from another text area within the same component. My project is using Angular-13. I'm stuck on how to accomplish this task. Any suggestions would be greatly ...

Obtaining a subset of data from firebase

I am currently working on retrieving a sub-collection from the Firestore database using Angular. In my database, I have a collection called 'Company' which contains fields for 'Name' and 'Id', as well as a sub-collection named ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...

What is the best way to sum the numbers in this code snippet?

I'm trying to iterate through an array called arr = [[1,2],4] using for loops to access the numbers. However, I've noticed that I can't seem to add the last number for some reason. Can anyone explain why this is happening? let arr = [[1, ...

When collapsing an accordion, Bootstrap radio buttons fail to properly select

I have attempted various methods to achieve the desired functionality of having the accordion content close and open accordingly when checking a radio button, while also having the button visually appear as 'checked'. For a more in-depth example, ...

building CharFields dynamically in Django

I am looking to gather input from the user using CharField. Using the value entered in CharField, I want to generate the same number of CharFields on the same page. For example, if the user enters "3" and clicks OK, it should display "3" CharFields below ...

Ways to arrange the JSON array by keys in reverse order utilizing Angular

let data = { '2021-07-20-21:10': { sends: 1, recvs: 1, notSents: 0, rejects: 0, xptSkips: 0, timeouts: 0, appErrors: 0, responseTimeAvg: 172, responseTimeMax: 172, ...

Unexpected issue encountered for identifiers beginning with a numerical digit

Is it possible to select an element from a page with an id that begins with a number? $('#3|assets_main|ast_module|start-iso-date') Upon attempting to do so, the following error occurs: Uncaught Error: Syntax error, unrecognized expression: ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

Unraveling a nested JSON structure and converting it into a List of Objects using Circe in Scala

Here is a snippet of JSON data that I am working with: { "results": { "result_1": { "text": "abc" }, "result_2": { "text": "def" ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

Sending data from an external input field to a form using AngularJS programmatically with element name

I am facing a challenge where I need to include an Input element in a Form, even though the Input is located outside of the form. While I have managed to add the input using form.$addControl(outerInput), it is not producing the desired outcome as shown in ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

Trigger the fire controller code upon the change of the textbox date in ASP.NET MVC

I am looking for a way to trigger controller code when a user clicks out of a date textbox without using HTML helpers, only plain HTML. I am new to MVC and have previously worked with web forms. The controller code that needs to be executed is as follows: ...

I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // ...

Creating a series of promises in a structured chain

How can the code structure be improved, especially regarding exception handling within a "promise chain"? $("#save").click(function(e) { e.preventDefault(); let $self = $(this); let profile = {} $self.prop("disabled" ...

The useCallback hooks persist outdated values when the list is refreshed

Why am I not getting the expected values every time the function onRefresh is called using Hooks? Example when onRefresh is called twice: Expected values: true 0 20 false true 0 20 false Received values: false 0 0 false false 20 20 false Initial st ...

The function cannot be invoked. The 'Boolean' type does not have any call signatures. An error has occurred in the computed property of Vue3

Currently, I am working on creating a computed property that checks if an item is in the array. The function I have created returns a boolean value and takes one parameter, which is the item to be checked. isSelected: function (item: MediaGalleryItemTypes) ...