Retrieving information from the server using Backbone to generate a model and assemble a collection

I need assistance with setting up a model and collection for a URL that returns a list of players in JSON format:

http://anexampleproject/api/players

My goal is to create a model and collection for this data and then display the name of each player in the console. Can someone guide me on how to achieve this?

Here is an example of the JSON returned by the URL:

 [
       {
          "id": 1,
          "name": "Lily",
          "age": 14,
          "city": "New York"
       },
       {
         "id": 2,
         "name": "BIlly",
          "age": 14,
          "city": "New York"
      }
    ]

Answer №1

var data = [{
    "id": 1,
    "name": "Lily",
    "age": 14,
    "city": "New York"
}, {
    "id": 2,
    "name": "BIlly",
    "age": 14,
    "city": "New York"
}];

var MyModel = Backbone.Model.extend({
    defaults: {
        "id": "",
        "name": "",
        "age": 0,
        "city": ""
    }
});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

var myCollection = new MyCollection(data);

EDIT:

Using a different approach

var MyCollection = Backbone.Collection.extend({
    url: "http://anexampleproject/api/players",
    model: MyModel
});

var myCollection = new MyCollection();
myCollection.fetch({
    success: function(){

    },
    error: function(){

    }
});

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

Guide to invoking the NPM request multiple times within the mocha before hook

Can anyone advise on the correct way to call request multiple times (2 times) in mocha before hook? I am currently facing an issue where I get an error saying 'done() called too many times'. describe('...', function(){ before(functio ...

What is the process for implementing a title search filter in Vue.js?

Hey there, hoping you're having a good night! I've been trying to set up a bookstore using Vue.js with code retrieved from a Json api. However, I'm encountering some issues with the "computed" property. Here's the code snippet: new Vue ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

Warning: Unidentified JavaScript alert(notification) encountered without declaring a

Imagine this scenario - when I type the following command: open google.com I need JavaScript to detect "open google.com" and prompt me with an alert. The challenge is figuring out how to generate an alert for just "google.com" without including "open". ...

What is the correct way to send a GET request in angular?

Trying to make a GET request from Angular to Spring Java, but encountering error code 415 zone.js:3243 GET http://localhost:8080/user/friend/1 415 Below is my Spring Java code for the endpoint: @RequestMapping( value = "/friend/{idUser}", ...

The ios browser environment is unable to retrieve the value during vuejs development

When using vuejs components to create a countdown component, everything seems normal in the pc and Android environments. However, in the iOS environment, there seems to be an issue with obtaining the real count calculation as it returns NaN. <templ ...

Expanding a collection of text inputs on-the-fly (HTML/JavaScript)

Looking to streamline our data entry process, I am developing an app for in-house tasks. Our team will be required to input information about various "items" that correspond to multiple "categories." To facilitate this task efficiently, I'm explorin ...

Convert the array of strings into JSON format and send it

Assistance needed with sending JSON to the server side. Below is the desired format: "myProfile": { "languages": [ "English", "German" ] } So, myProfile is essentially a JSONObject with "languages" being an array of strings, correct? Could someone provi ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

"Tricky HTML table layout challenge: Margins, paddings, and borders causing

Working with HTML <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td> <img src="..."> </td> </tr> </tbody> </table> Applying CSS rules * { border: none; ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Gaining entry to information while an HTML form is being submitted

After a 15-year break, I am diving back into web development and currently learning Node.js and ExpressJS. I have set up a registration form on index.html and now want to transfer the entered data to response.html. However, when I hit Submit, the form is p ...

Transferring image Buffer over API for uploading to IPFS network

My attempt to upload an image to IPFS involves the following steps: I start by uploading the image from my web UI, converting it to a buffer in my Angular component. The next step is to send it via a put/post request (using HttpClient) to my NodeJS Expres ...

jQuery does not change the scroll position of elements

I'm looking to implement a feature on my website where certain points act as "magnets" and when the user is near one of these points, the window automatically scrolls to the top. I found a jQuery plugin that does something similar which you can check ...

The map is not displayed on the leaflet

I am having trouble getting the map to display properly. I have added the cdn link in my head. <link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="18747d797e747d6c5829 ...

I am having trouble comprehending this specific type definition within a properly formatted JSON Schema

Exploring the definitions of Cats and Dogs within: { "Boxes": { "type":"object", "properties": { "Cats": {"type":["integer","null"]}, "Dogs": {"type":["integer","null"]} ...

The code line "npx create-react-app myapp" is not functioning as expected

When running the command 'npx create-react-app my-app', I encountered the following error message: Error: '"node"' is not recognized as an internal or external command, operable program or batch file. Before suggesting to cre ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

How does Jasmine compare to the second parameter with the toBeCloseTo function?

Jasmine's documentation is often brief, but not always sufficient. I am curious about the second parameter of the toBeCloseTo function. The official reference only provides this example: it("The 'toBeCloseTo' matcher is for precision mat ...