Transforming Backbone JSON data into a template for display

Yesterday, I asked a question that was very helpful to me.

I have rewritten most of the code by following tutorials, YouTube videos, and seeking help on Stack Overflow. However, I am unsure of what I am doing wrong when trying to push the JSON data to the underscore template.

Essentially, my goal is to extract data from a JSON array, loop through it, and display it. While I've watched tutorials using .get to achieve this, they were not dealing with a JSON array. Any assistance would be greatly appreciated.

This is how my code looks: (I've indicated the line where I think things are going wrong)

<body>
  <div class="News"></div>

  <script type="text/template" id="NewsTemplate">
    <table>                
      <% _.each(NewsCollection, function(item) { %>           
        <tr>
          <td><%= item.title %></td>
        </tr>          
      <% }); %>   
    </table>
  </script>

  <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone.js"></script>

  <script type="text/javascript">
    var NewsModel = Backbone.Model.extend({ });

    // Define backbone collection to retrieve Google News JSON array
    var NewsCollection = Backbone.Collection.extend({
      url: 'data.js'
    })

    var NewsList = Backbone.View.extend({               
      el: '.News',
      template: _.template($("#NewsTemplate").html()),             
      render: function () {
        var that = this;
        var NewsItems = new NewsCollection();
          NewsItems.fetch({

          // I suspect something might be off here

          success: function (NewsItems) {
            $(this.el).html(that.template({'collection.toJSON': NewsItems.toJSON()}));
          }
        })
      }                
    });       

    // Router for Backbone to take action upon loading homepage
    var Router = Backbone.Router.extend({            
      routes: {
        '': 'home'  
      }            
    });

    var newslist = new NewsList();           

    var router = new Router();          
    router.on('route:home' , function (){
      newslist.render();
    });

    Backbone.history.start();
  </script>
</body>

Answer №1

Check out this revision:

success: function (NewsItems) {
  $(this.el).html(that.template({ newsItems: NewsItems.toJSON()}));
}

Make sure to update your template as well:

  <script type="text/template" id="NewsTemplate">
    <table>                
      <% _.each(newsItems, function(item) { %>           
        <tr>
          <td><%= item.title %></td>
        </tr>          
      <% }); %>   
    </table>
  </script>

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

Tips for syncing HTML Canvas to track the mouse's X and Y position accurately across various screen resolutions

I'm facing an issue with my canvas game where the onclick buttons are redirecting to another menu. However, when I open the Canvas on a monitor with a different resolution, all the X & Y coordinates change and nothing works as expected. Is there a wa ...

Retrieving form output number using JQuery

Hello, I'm new to this site and have no prior experience with javascript coding. Here is what I have in my javascript file: $(document).ready(function() { $("input").click(function(event) { updateTotal(); }); }); function updateTotal() { var to ...

Tips for transforming JSON output from Facebook's graph API into a different format

Feeling a bit lost on whether I'm on the right track, I came across a snippet of code in a tutorial video on YouTube. Unfortunately, the series was left incomplete with just the content from the initial video. I've been attempting to access all ...

Retrieve only ObjectIds that are embedded in an Array using MongoDB's .find() method

I am looking to extract only the ObjectIds from a specific document that is nested within the projects Array. I am working on creating a database where each user will have their own set of projects. Thank you! db.users.find().pretty() { "_id" : Obje ...

Is it possible to edit the HTML DOM of an external URL that is opened using window.open?

Imagine a scenario where I have a page located at: www.mydomain.com When a user clicks on a button, it triggers the opening of a new window using: newWin = window.open("https://www.otherdomain.com","a","height=800,width=1000"); Now, my objective is to m ...

Redirecting from HTTP to HTTPS with node.js/Express

Are there steps I can take to modify my web application to operate on HTTPS instead of HTTP using node.js/express? I require it to run on HTTPS due to the use of geolocation, which Chrome no longer supports unless served from a secure context like HTTPS. ...

Searching for multiple values using ng-model in AngularJS is a powerful feature that allows

I've looked everywhere for a solution to my problem but I haven't found an exact match. Can anyone lend a hand? Here's the ng-repeat filter list I'm working with: <ul> <li ng-repeat="f in filterOptions"> <p>{{f ...

Choosing an item from a list using React-Redux

Currently learning React, I am facing some challenges in selecting an item from a list of recipes. My main focus right now is on deleting a recipe from the list, but before that, I need to understand how to identify and select a specific recipe. For refer ...

Having trouble accessing and establishing a connection with MongoDB

I've been working on a mini URL shortener project using JavaScript, Express, and MongoDB, but I've encountered some errors when trying to launch my local server and connect to MongoDB! Here's a snippet of my code: const express = require(&ap ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

What is the best way to trigger the Reactjs MUI DatePicker popup to display when clicking inside it for editing the date, without relying on the

As of now, DatePicker displays a calendar icon for opening the date picker popup. While I can eliminate the icon using the disableOpenPicker property, my goal is to open the popup when the user clicks on the Datepicker input field, functioning just like ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

dont forget to preserve the checkbox and radio button selections when the page is refreshed

I have developed a filter using jQuery and Laravel (PHP) to filter data based on checkbox or radio button selections. However, after refreshing the page, the checked state of the checkboxes or radio buttons is lost. I need the checked state to persist even ...

JS - Reducing in size increases request size

I'm facing an issue with compressing my request - instead of reducing the size, it seems to be increasing it: const requestData = LZString.compress(JSON.stringify({ data: bigBase64StringHere })); await axios.post("api-endpoint", requestData, ...

Error: The locator I used with the ID getUserById did not find any elements

Here is the code snippet from my HTML file: <h1>User list</h1> <button class="btn btn-primary" [routerLink]="'/register'">Register</button> <br> <br> <table class="table& ...

Exploring the application of javascript method within a Vue template

Currently, I am attempting to extract a numeric value from the end of a URL. However, I am encountering an error in doing so. It has been a while since I last worked with Vue, but I know that we can use methods/functions to achieve the desired outcome. Cou ...

The slider on my iPad and Kindle Fire in Linux mode is not functioning properly

Having an issue on my e-commerce platform, Bence Tupperware, which is built with MVC.Net. The problem seems to be related to the slider at the top of the page. After checking in Mozilla's responsive design mode, everything appears to work fine on devi ...

URL Bootstrap Table Formatter - Enhancing Your Table Design

Javascript: function LinkFormatter(value, row, index) { return "<a href='"+row.url+"'>"+value+"</a>"; } HTML: <th data-field="snum" data-sortable="true" data-formatter="LinkFormatter" >LINK</th> <th data-sortable=" ...

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

Combining two objects in node-red: A step-by-step guide

msg.payload : Object object HAMK307: object a_temperature: 23.1 a_humidity: 46 a_brightness: 3703.05 a_lights: "on" a_presence: "empty" r_temperature: 35.59 r_humidity: 30.46 r_pressure: 994.43 a_time: object ID: "HAMK-307" m ...