Error encountered when trying to generate a collection from JSON using Backbone framework

jQuery(function() {

var Hotel = Backbone.Model.extend({
        defaults: {
            idHotel:"",
            hotelName:"Grand Marina",
            hotelAddress:"Lakeview Drive",
            hotelStars:"4",
            hotelRoomsCount:"180",
            hotelPicture:"img/placeholder.png",
            cityName:"Marina Del Rey"
        },
    });

var Hotels = Backbone.Collection.extend({
    model:Hotel,
    url: './hotels'
});

var HotelView = Backbone.View.extend({
    tagName:"div",
    className:"hotelContainer",
    template:$("#hotelTemplate").html(),

    render:function () {
        var tmpl = _.template(this.template); 
        this.$el.html(tmpl(this.model.toJSON())); 
        return this;
    },

    events: {
        "click .delete": "deleteBook"
    },

    deleteBook:function () {
        this.model.destroy();
        this.remove();
    }
});

var HotelsView = Backbone.View.extend({
    el:$("#hotels"),

    initialize:function(){
        this.collection = new Hotels();
        this.collection.fetch().done(function () {
            console.log(this.collection.fetch())
        })
        .fail(function() {
            console.log(this.collection.fetch())
          throw 'Something went wrong while fetching the todos';
        });;
        this.render();

        this.collection.on("add", this.renderHotel, this);
        this.collection.on("remove", this.removeHotel, this);
        this.collection.on("reset", this.render, this);
    },

    render: function() {
        var that = this;
        _.each(this.collection.models, function(item) {
            that.renderHotel(item);
        }, this);
    },

    addHotel: function(e) {
        e.preventDefault();

        var formData = {};

        $("#addHotel").find("input").each(function(i, el){
            if ($(el).val() !== "") {
                formData[el.id] = $(el).val();
            }
        });

        hotels.push(formData);

        this.collection.add(new Hotel(formData));
    },

    events:{
        "click #add":"addHotel"
    },

    renderHotel:function(item){
        var hotelView = new HotelView({
            model: item
        });
        this.$el.append(hotelView.render().el);
    }
});

var hotelsView = new HotelsView();

});

The JSON on ./hotels

[{"idHotel":"8","hotelName":"Al'arab","hotelAddress":"Al'arab street","hotelStars":"5","hotelRoomsCount":"100","hotelPicture":"hotel3.jpg","hotelCity":"6","idCity":"6","cityName":"Dubai"},{"idHotel":"3","hotelName":"Kinpinski","hotelAddress":"ul.Bistur Pqsuk N:4","hotelStars":"5","hotelRoomsCount":"130","hotelPicture":"hotel1.jpg","hotelCity":"4","idCity":"4","cityName":"Varna"},{"idHotel":"2","hotelName":"LeFleour","hotelAddress":"bul.Vitoshka N:3","hotelStars":"4","hotelRoomsCount":"23","hotelPicture":"hotel2.jpg","hotelCity":"1","idCity":"1","cityName":"Sofia"}]

End it gives error this.collection is undefined

Here is the HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <link rel="stylesheet" href="screen.css">
    </head>
    <body>
    <?php
        session_start();
        $_SESSION['currentPage'] = 'index.php';
        include_once('hotels.php');
        include_once('header.php');
    ?>
    <div id="hotels">
        <script id="hotelTemplate" type="text/template">
            <img src="img/<%= hotelPicture %>"/>
            <ul>
                <li><%= hotelName %></li>
                <li><%= hotelAddress %></li>
                <li><%= hotelStars %></li>
                <li><%= hotelRoomsCount %></li>
                <li><%= cityName %></li>
            </ul>
        </script>
    </div>
    <script src="http://localhost:8889/js/jquery.js"></script>
    <script src="http://localhost:8889/js/underscore.js"></script>
    <script src="http://localhost:8889/js/backbone.js"></script>
    <script src="http://localhost:8889/js/app.js"></script>
    </body>
    </html>

Answer №1

The value of this within the callbacks may surprise you. Try updating your code to:

initialize:function(){
    var self = this;
    this.collection = new Hotels();
    this.collection.fetch().done(function () {
        console.log(self.collection.fetch())
    })
    .fail(function() {
        console.log(self.collection.fetch())
        throw 'An issue occurred while fetching the items';
    });;
    this.render();

    this.collection.on("add", this.renderHotel, this);
    this.collection.on("remove", this.removeHotel, this);
    this.collection.on("reset", this.render, this);
},

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

What is causing the ajax code to malfunction?

I am new to ASP MVC and trying to create a login form using AJAX. I have written a JsonResult in the controller to check the username and password, but for some reason it is not working. Here is my controller code: public ActionResult login() { ...

External vendor scripts such as JavaScript and jQuery are not functioning properly after being rendered in a ReactJS environment

I am currently developing a frontend web app using ReactJS. I obtained a template from W3layout that is built with HTML5, CSS3, and custom JS files, along with various third-party/vendor plugins like nice-select, bootstrap, slik, owl-carousel, etc. Despit ...

Wrapping an array into a string in Laravel: a step-by-step guide

Is there a way to convert my return array into a string in Laravel? I would like it to look something like this: Laravel: $columnDefinitions = array(); $columnDefinition = new \stdClass(); $columnDefinition->label = "No"; $column ...

Can Browserify be used with AngularJS to bundle directive templateUrls using relative paths?

Currently, I am developing a web application using AngularJS and Browserify to bundle my JavaScript files into a single package for use on the webpage. My project structure looks something like this: app |-index.html |-index.js |-bundle.js |-components ...

Personalize your BigBlueButton experience with custom HTML 5 client modifications

Does anyone know how to remove the three-dot options menu button in the Big Blue Button HTML 5 client that's installed on Ubuntu? Our setup involves displaying the html5 client inside an iframe, so we need to handle the meeting leave and end functions ...

Centering the scrollIntoView feature on mobile devices is presenting challenges with NextJS applications

Description While navigating on mobile browsers, I'm facing a challenge with keeping an element centered as I scroll due to the browser window minimizing. I've experimented with different solutions such as utilizing the react-scroll library and ...

The map() function efficiently retrieves all object values from an array in the backend simultaneously

Using axios, I am downloading backend structure data. The data is structured as advancedProfile.technologies (an array with 5 objects) with keys {title, link, category, date, id}. Afterwards, I am rendering divs using the map function. The code line loo ...

Retrieve the name of the product from the corresponding parent element

My goal is to trigger an alert box with the product name when the "Buy now" button is clicked. I have added the necessary code in jquery to maintain the onclick event of the button. <h2 class="product-name"><a href="product1.php" title="Sample Pr ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

How to Utilize Muuri Javascript Library with Bootstrap Tabs: Resizing Required for Expansion?

Struggling for days and feeling frustrated, I'm hoping someone can help me crack this mystery. My idea is straightforward - three Bootstrap 4 tabs with drag and drop functionality inside each, all displayed in a responsive stacked masonry layout. To a ...

Switch out the image source and add attributions until the AJAX call is complete

<div id="fbAdsIconDiv" class="social_icon"> <img src="~/Content/images/fbAdsAddOn_1.png" onclick="toggleImage(this)" id="fbAdsAddOn" data-toggle="tooltip" title="click to enable" class="confirmBox f ...

What is the best way to generate a JSON object with Angular and showcase its content through HTML?

Currently, I am dealing with a JSON object that is completely unfamiliar to me. Without knowing the keys or values of this object, I was able to successfully manipulate it and extract the necessary information. Ultimately, I have generated an array (whic ...

Issue: The registration token(s) provided for the sendToDevice() function are not valid

Currently, I am working on my final project where I am attempting to send notifications using Firebase Cloud Function when onUpdate is triggered. However, I encountered an error during the process. Despite following tutorials on YouTube and various website ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...

Issue with React component not updating

Experiencing an issue in a React code related to nested components within React. Link to code The problem arises from having a parent component called "testing" with two child components, Component1 and Component2, each with Component3 as a sub-child und ...

Adjusting the background color of the list item

I'm looking for a way to change the background color of the li tag when the user focuses on the input, similar to what can be seen at the bottom of this page here. After researching similar questions, it appears that achieving this effect in pure CSS ...

Is it necessary for the error event of xmlhttprequest to include an error message?

Currently, I am in the process of developing an AJAX request within a Firefox extension. The following code snippet illustrates my approach: function GetMenu(){ var oReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); ...

Integrate guidelines into JSON stringify

I am working with a class called OrderParameterInfo: class OrderParameterInfo { Name: string; Value: string; My goal is to create a JSON string. When I use JSON.stringify(OrderParameterInfo("foo_name", "foo_value")), it generates {&quo ...

I must interact with the video within the iframe by clicking on it

I am trying to interact with an iframe video on a webpage. Here is the code snippet for the video: <div class="videoWrapper" style="" xpath="1"> <iframe width="854" height="480" src="xxxxxxx" frameborder="0" allow="autoplay; encrypted-media" all ...