Retrieving JSON data using Backbone.js fetch() and translating it into a model results in get()

My current issue involves fetching a JSON file and storing it in a model for later access. However, I am encountering difficulties when trying to access the attributes through the get() method as it keeps returning undefined. The JSON file contains an array of games which are objects with various attributes. My main goal is to save them in the model and retrieve them. Here's what I have attempted so far:

var player = Backbone.Model.extend({
   initialize: function(app, options) {
      this.app = app;
      var _this = this;

      this.fetch({
         url: "someurl",
         success: function() {
            console.log("success");
         }
      });
   }
});

var instplayer = new player();
instplayer.on('change', function(){
   console.log(model);
   console.log(model.get(games));
})

I believe that there should be an event trigger to ensure that get() is called only when the data has fully loaded. Despite my attempts, I still receive undefined. What steps do I need to take to resolve this issue?

Answer №1

Imagine you have a JSON structure for your player, as shown below:

{
    "username": "joe",
    "games": [
        {
            "title": "Pacman"
        }, {
            "title": "Super Mario"
        } 
    ]
}

If this was the data format you were dealing with, here is an example of how you could manage and render it using code:

var Game = Backbone.Model.extend({
  defaults: {
    title: ''
  }
});

var Games = Backbone.Collection.extend({
  model: Game
});

var Player = Backbone.Model.extend({
  defaults: {
    username: ''
  },
  url: 'http://www.mocky.io/v2/56261127250000a01accb34f',
  initialize: function(){
    this.games = new Games();
    this.listenTo( this, "sync", this.initGames );
    this.fetch();
  },
  initGames: function(){
    this.games.add( this.get('games') );
    this.trigger('ready', this);
  }
});

var PlayerView = Backbone.View.extend({
  template: _.template('<h1><%=username%></h1> and his games: <ol class="games"></ol>'),
  render: function(){
    this.$el.html( this.template( this.model.toJSON() ) );
    this.model.games.each( this.renderGame, this );
    return this;
  },
  renderGame: function(game, i){
    var gameView = new GameView({ model: game });
    gameView.render().$el.appendTo( this.$('.games') );
  }
});

var GameView = Backbone.View.extend({
  tagName: 'li',
  template: _.template('<strong>Game:</strong> <%=title%gt;'),
  render: function(){
    this.$el.html( this.template( this.model.toJSON() ));
    return this;
  }
});


var dude = new Player();
dude.on('ready', function(player){
  var playerView = new PlayerView({ model: player });
  playerView.render().$el.appendTo( document.body );
});
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>

Answer №2

It's important to ensure there are no typos in your code, especially when passing parameters to functions.

instplayer.on('change', function(){
  console.log(model);
  console.log(model.get(games));
})

Make sure you pass the correct parameters like this:

instplayer.on('change', function(model, options){
  console.log(model);
  console.log(model.get("games"));
})

Also, remember that 'games' should be a string and not a variable.

Additionally, consider what the json data returns and if necessary, override the parse function for accurate results.

If you're fetching an array of objects, it might be better to use a collection of players instead.

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

Using only if-else statements and else-if conditions in JavaScript, arrange four numbers in order

How can I arrange 4 numbers in ascending order using only if-else and else-if statements in JavaScript without utilizing the sort function? ...

What are efficient techniques for filtering and iterating over an array in PHP?

Is there a way for me to extract the network plans along with their prices from this specific GET API? Can someone provide assistance? I am looking to specifically extract the AIRTEL DATA PLAN [dataPlan, duration,type, status, and Price for basic_user] in ...

Troubleshooting Issues with AngularJS HTTP.get Requests

I'm currently working on a simple AngularJS application that is supposed to extract data from a .json file. While my code doesn't show any errors upon running it, it fails to retrieve the JSON values as expected. I have a feeling that I may be ov ...

"Encountering a 'python: No such file or directory' error while running `npm install` and trying to rebuild with node-gyp on a Mac Pro M

When attempting to run the npm install command, I encountered an error within my application. System information: macOS Monterey : version 12.5 Chip: Apple M1 Pro Node.js version: 14.19.3 node-gyp version: 9.1.0 Python version: 3.8.9 > <a href=" ...

sum inside the while loop

Below is the provided HTML: <form> <textarea id="input1"></textarea> <textarea id="input2"></textarea> <span></span> </form> The following JavaScript code is included: $("#input2").keyup{ var a = ...

Persistently save retrieved information and store data in MongoDB by utilizing Node.js

I am facing the challenge of continuously making an http.get request to an API that provides location data. I have tried a basic get request to test if the data is being received, and it is. However, the issue is that I need this process to run in a contin ...

Update the node server's URL address

After successfully deploying my first AngularJS application on Heroku using Node.js, I have encountered a small issue regarding the URL. Currently, the site is accessible at . But I would prefer it to be accessed at . How can I achieve this change? var ...

Transferring PHP Multidimentional Array data to Javascript

I've scoured this website for a solution, but unfortunately, nothing seems to be working. So, I've decided to reach out to you all for help. I hope you can assist me with my issue. The problem lies within a PHP file that is populating an array w ...

create a function that returns JSX in React

Having trouble with the FilterBydescription component in the Render function. I am expecting to return JSX elements, but instead I am getting undefined in UseAdvertisementsFilters. It seems like the context is getting lost somewhere, but I can't figur ...

There is an issue with the syntax in your for-loop control where a closing parenthesis is missing

When I try to navigate through the arrays from 1 to 4 in the given JSON data, Firebug shows me an error message: SyntaxError: missing ) after for-loop control [Break On This Error] for( x in LGIntake.corpCodeOptions.marketSegment.1){ StartI...aseId=0 ...

Understanding the source of an useEffect's trigger to create a conditional statement

Within my useEffect, I have two states included in the dependencies array: const [currentTab, setCurrentTab] = useState('open'); const [searchParams, setSearchParams] = useState(''); useEffect(() => { if (condition) { // logi ...

Having trouble accessing the Webservice through AJAX

Attempting to call a webservice method using an AJAX method is proving challenging. Despite the effort, accessing the Webservice method through the AJAX Call remains unsuccessful. The expected outcome is for the webservice to return a JSON string in the aj ...

The combination of NextAuth.js and Auth0 seems to be causing an issue with offline_access breaking

I am currently integrating next-auth with the Auth0 provider into an existing application. Everything is functioning properly, however, when attempting to include the offline_access scope in order to retrieve a refresh token, the application randomly crash ...

What is the return type format for this website?

Recently discovered this interesting website erail. I am curious about the format of the data it returns. It doesn't seem to be json or xml. Can anyone help me identify it? Thank you. ...

The dynamic duo of MongoDB and Prisma: forging a groundbreaking one-to-many relationship

Is it possible to establish a one-way m-to-n relationship without requiring both collections to have each other's ids? I am attempting the following: model Country { id String @id @default(auto()) @map("_id") @db.ObjectId ...

What is the method for sending a JSON array as a POST parameter in Swift?

Despite my efforts, I am having trouble getting the API I use to accept JSON as a POST parameter. var post2:NSString = "data={\"item_id\":\"19\"}" var url2:NSURL = NSURL(string: "\(BASE_URL)item/")! var postData2:NSData = post.d ...

What are the ramifications of using the 'new' keyword in JavaScript?

Currently, I am in the process of developing a plugin for jQuery, and I am encountering a JSLint error that redirects to JSLint: Problem at line 80 character 45: Do not use 'new' for side effects. (new jQuery.fasterTrim(this, options)); Despit ...

When selecting an old list, only the most recently created ID is displayed, rather than the ID of the specific list being

I've set up a dashboard where I can create lists and have them displayed on the screen, but there seems to be an issue when trying to open any list as only the last created one opens. Can anyone point out what mistake I might be making? The technologi ...

Steps to trigger an action upon selecting a radio button on an HTML and CSS website

After creating a website with HTML and CSS that allows users to select options using radio buttons, I am now seeking advice on how to implement actions based on their choices. If a user selects an option, I want a specific action to occur, but I am unsur ...

A step-by-step guide on incorporating universal CSRF tokens using JQuery AJAX

As part of my development work, I am in the process of creating jquery code that communicates with the server through ajax to input data into a database based on specific request parameters. My main concern at this point is the vulnerability to CSRF attac ...