The error occurred in underscore.js at line 1461 where it showed "Uncaught ReferenceError: users

I am currently exploring backbone.js and underscore.js and working on building a sample application.

Here is the code snippet I have been using:

<script type="text/template" id="user-list-template">
    <table class = "table striped">
            <thead>
                <tr>
                    <th>User Name</th>
                    <th>Age</th>
                    <th>Location</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <% _.each(users, function(user){%>
                        <tr>
                            <td><% user.get('sUserName') %></td>
                            <td><% user.get('iAge') %></td>
                            <td><% user.get('sLocation') %></td>
                            <td></td>
                        </tr>
                <% }) %>
            </tbody>
    </table>
</script>
var UserList = Backbone.View.extend({
    el: '.page',
    render: function() {
        var that = this;
        var users = new Users;
        users.fetch({
            success: function(users) {
                alert("Successfully called REST Service");
                var template = _.template($('#user-list-template').html(), { users: users.models });
                that.$el.html(template);
                console.log('Content has been rendered successfully.');
            }
        })

    }
});

However, I encountered an exception:

Uncaught ReferenceError: users is not defined
    at HTMLDivElement.eval (eval at m.template (underscore.js:1454), <anonymous>:6:9)
    at HTMLDivElement.c (underscore.js:1461)
    at n.access (jquery.min.js:3)
    at n.fn.init.html (jquery.min.js:3)
    at success ((index):64)
    at Object.t.success (backbone.js:1051)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at x (jquery.min.js:4)
    at XMLHttpRequest.b (jquery.min.js:4)

Answer №1

It has been highlighted that using <%= %> (or preferably <%- %> for escape) is the correct approach, but your main issue seems to lie in how you are invoking the template.

The function _.template() in underscore actually returns a reusable function that can be utilized with different data sets.

var users = new Backbone.Collection([
{sUserName: 'Alice', iAge: 35, sLocation: 'London'},
{sUserName: 'Bob', iAge: 5, sLocation: 'Buenos Aires'}
]);
var template = _.template($('#user-list-template').html());
$('#result').html(template({users: users.models}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script type="text/template" id="user-list-template">
    <table class = "table striped">
            <thead>
                <tr>
                    <th>User Name</th>
                    <th>Age</th>
                    <th>Location</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <% _.each(users, function(user){%>
                        <tr>
                            <td><%- user.get('sUserName') %></td>
                            <td><%- user.get('iAge') %></td>
                            <td><%- user.get('sLocation') %></td>
                            <td></td>
                        </tr>
                <% }) %>
            </tbody>
    </table>
</script>
<div id="result"/>

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

"Is it possible to differentiate between a variable that is BehaviorSubject and one that is not

I am dealing with a variable that can be of type Date or BehaviorSubject<Date | null>. My concern is figuring out how to determine whether the variable is a BehaviorSubject or not. Can you help me with this? ...

The information retrieved from the database query is failing to appear on my webpage

I am encountering an issue where I am unable to display product details on my webpage in a specific format after submitting an ID number through a form. The query does not show any data when submitted. My objective is to append the latest retrieved data be ...

Detecting mouseclick on an ASP.NET TextBox

I have implemented a popup box that allows users to enter a brief note limited to 50 characters. However, I am facing an issue where users can easily copy and paste text using the right mouse click. Is there a way to prevent this action? After researching ...

Setting up Express JS version 4 without using the app.configure method

Express js version 4.0 has been recently released and I have encountered an issue with my Express 3-app after updating because the app.configure() method was removed in the new version. This is how my Express 3 configuration looks like: // all environmen ...

Unable to retrieve VueJs instance variable outside of main.js file

I have a list of fruits saved in a file named fruit_list. The file contains the following information. export default { fruits: [ 'APPLE', 'BANANA', 'CHERRY', 'GRAPE', ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

Problems with Key Presses in Form Verification

Yesterday evening, our supervisor called me to report an issue with our app. He mentioned that when he tried to log in using a dummy password, the validation was successful. It seems that clicking on the mouse to authenticate the password was working corr ...

Share on your Twitter feed

Currently seeking assistance in implementing a function on my website that allows users to post their individual posts to Twitter. For example: Message: "hello world" [twitter] By clicking on the twitter button, the message will be posted along with the p ...

What is the best way to mandate multiple input fields in AngularJS?

I am currently working on creating a basic web page with a few input fields that must be filled out to proceed. Below is the code I have so far: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/l ...

What is the process for having a Google Map marker direct to a specific URL?

Check out my HTML: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Customize the dimensions of the div element that houses the map */ #map { height: 700px; /* K ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

Using Javascript's Speech Recognition to activate a button

I am new to using JavaScript Speech Recognition and decided to work with the Annyang library. My goal is to automatically trigger the "show date" button when the user says 'hello', without actually clicking the button. However, I've been fac ...

Once the hidden DIV is revealed, the Youtube video within it begins to load

I currently have a hidden DIV on my website that contains a YouTube clip. My goal is to load the video in the background once the page has fully loaded, so that it's ready to play when the user clicks the button to reveal the DIV. However, at the mo ...

Is it possible to decrement the index of an array by 1 and seamlessly loop back to the end in just one line of code?

Imagine I am manually adjusting the index of an array in JavaScript. I have functions to increase and decrease the index, with the goal of looping back to the beginning or end of the array when reaching the limits. While the increase function can be writte ...

Step-by-step guide on building an endless reviews carousel

Can someone assist me in creating an endless reviews carousel? I've been grappling with it for the past two days. Just so you know, I'm a newcomer to web development and my code may not be the cleanest. Here's the code snippet: <!DOCTYPE ...

Can a guild ID be stored in a Discord set?

Having an issue storing guild IDs in my bot. I tried using Set(), but when the bot goes offline, all IDs are removed from the set and I have to continually add them again. Is there a solution for this problem? Here is what I attempted: const collection = ...

Tips for enabling the `ignoreUndefinedProperties` feature in Node.js

I'm currently in the process of creating a REST api for my Node.js and Express application. However, I keep encountering an error stating that properties are undefined whenever I attempt to send a request. How can I go about enabling 'ignoreundef ...

Guide to sending properties to reducer in React with Redux

I've been grappling with the complexities of react-redux for hours. I'm aiming to display an <Alert /> to the user when the value of isVisible is true. However, I'm still struggling to grasp the architecture of redux. Despite my effort ...

Is it possible to eliminate a style that was applied using the .css() method?

Currently, I am using jQuery to modify the CSS and would like to know how to remove the styling that is being applied based on the input value provided: If the color is not '000000', then change the background-color of the body element to the sp ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...