Exploring the functionality of backbone.js collections

I'm encountering an issue with managing my collection. Initially, I populate the attendees into a collection using fetch. This action loads existing attendees from the database into the collection. There is also a button that allows users to add new attendees. However, when a user manually enters an attendee, it seems to clear out the models loaded into the collection via fetch and starts anew. Although all manually added attendees now appear in the collection, I aim for both the fetched loaded and manually added attendees to be listed.

var InviteeView = Backbone.View.extend({
tagName: "tr",
initialize: function() {
    this.collection = new InviteeJSONList();    
    _.bindAll(this, 'render','appendItem','remove','saveInvitee');
},
events: {
    "click .removeInvitee":"remove",
    "click .saveInvitee":"saveInvitee"
},
render: function() {
    var source = $("#invitee-template").html();
    var template = Handlebars.compile(source);
    var context = inviteeListJSON.attributes['json'];
    var html=template(context);

    $(this.el).html(html);

    return this;
},
appendItem: function() {
    $("#attendees").append(this.render().el);
},
remove: function() {
    $(this.el).remove();
},
...

Following the fetch() method, which populates the collection with 2 items retrieved from the REST API:

console.log(this.collection.models) outputs:
[d]
[d,d] 

However, upon manually adding an attendee through a button, the collection appears to reset:

console.log(this.collection.models) outputs:
[d] 

Answer №1

It's great to see that everything is functioning properly, as there are multiple approaches to take. Personally, I might have organized it in a different way to make use of the Backbone methods that create modes, but the main objective is to have working code. Here are some of my ideas:

  • Instead of directly instantiating the Models in the Collection parse() method, consider having parse return an array of data objects that Backbone can use to instantiate the models, and then trigger a

  • Rather than calling fetch for the Collection inside AttendeeView, place it outside the View class

  • You could either have AttendeeView be the view for a single attendee, or rename it AttendeeListView and have it display the list

For example:

AttendeeList = Backbone.Collection.extend({
 ...
   parse: function(response) {
           // create an array of objects from which the models can be parsed
           var rawItems = [];
               $.each(response['attendees'], function(key, value) {
                 rawItems.push({
                        id: data['id'],
                        user_id: data['user_id'],
                        meeting_id: data['id'],
                        status: data['status'],
                        comments: data['comments'],
                        attended: data['datetime'],
                        first_name: data['first_name'],
                        last_name: data['last_name'],
                        email: data['email'],
                        counter: this.counter,
                        user_uuid: data['user_uuid'],
                        unavailable_dates: data['unavailable_dates']
                    });
                });
              return rawItems;
           },
         ...
       }

Then you can either use the success/failure call backs:

  AttendeeList.fetch( onListFetchSuccess , onListFetchFail );

or listen for the reset event that gets triggered:

  AttendeeList.on('reset', createAttendeeListView );

(Please note that I haven't actually tested this code, it's just a general outline)

Answer №2

After some troubleshooting, I successfully resolved the issue by relocating the url parameter and parse function from the collection to the view. The result is that everything is now functioning properly.

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

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

Hide the div when it loses focus

CSS <input type="textarea" id="form1"> <div id="messageBox">This is a message box with hidden secrets</div> <button>Do Not Click</button> and JavaScript $(function(){ $("#form1").blur(function() { $("#message ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

You can activate Lightgallery just one time in VueJs

I am facing an issue where lightgallery can only be opened once. Subsequent clicks on the button are unresponsive. The lightgallery is being used as a component. Within my parent component, I have two buttons for opening image or video gallery ParentComp ...

Issue with setInterval not functioning in IE10

I am facing an issue with the following code snippet: $(function(){ function load() { $("#queuerefresh").load("1.txt"); } load(); setInterval(load,1000); }); Using: http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq ...

The operation is unable to be executed in an external document

Working on a WordPress page, I am utilizing the Google Maps API. The functions in my file are as follows: function custom_map_style() { // Enqueue Google Maps API wp_enqueue_script('maps', 'https://maps.googleapis.com/maps/api/js? ...

Using jQuery to append content with a variable as the source

Recently delving into jQuery and encountering an issue with getting my variable inside src when using append. Either it's not functional at all, or just displaying the variable name in string form in the console. Here is the code causing trouble: va ...

What is the best way to navigate through a series of images using left and right arrows in a React

I need help implementing a feature where I can slide horizontally through a collection grid of 10 movie items per row, similar to Netflix grids. Is there an easy way to achieve this with arrows on the right and left ends? <div className="collection-p ...

Adding information into a column with axios

I have built my ReactJS app using function components and I am currently trying to display user data from my APIs in a datagrid format. However, when testing my code, I encountered an error in the console stating "TypeError: destroy is not a function". I b ...

The socket.onopen() function may not be triggered when using a websocket or socket.io-client

My exploration led me to experiment with both socket.io-client for react native and websockets following the guidelines on the official React Native documentation. However, despite running the code below without any errors, I did not observe any changes in ...

Unable to find module reference "three" at 137

Returning to an older project, I realized that nothing was loading. When I checked the console log, this is what I found: Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". In my ...

"Data passed to a JavaScript callback function may result in an undefined

I've been experiencing some issues with callbacks and getting return data as undefined. function goodMorning(name, msg) { return `${name} ${msg}`; } function greet(name, msg, cb) { const myName = "Sairam"; console.log(`${cb(name)} ${cb(msg)} ...

"Learn the process of incorporating a trendline into a line chart using Highcharts by manipulating the

I am facing difficulties in creating a trend line for a line chart. I have tried some old solutions but they did not work for me. Below is my current code: { "key": "003", "title": "Detections", "ty ...

Understanding how to parse a JSON object in JavaScript is a

In my JSON object, I have the following data: rows = [{name:"testname1" , age:"25"}, {name:"testname2" , age:"26"}] My goal is to extract the names and store them in a variable like this: name = "testname1, testname2"; ...

javascript- Accessing Media Devices with Safari

After checking the provided link, I am unsure if Safari 15 supports getUserMedia. I attempted to use it to access the camera on Safari 15, and although it asked for permission, it did not display anything after granting access. The link indicates that Safa ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

Guide on accessing a div by using the class name of another div

If I have five divs where the first four share the same class, while the fifth has a different class. How can I target any of the first four divs using the class name present in the fifth div which is labeled as "otherclass" in this scenario? No IDs are ...

Encountering a "window not defined" error while implementing Leaflet in my Nuxt JS application

I'm encountering an issue while trying to generate my nuxt app, specifically on my 'Area' page. It seems like the error is related to the leaflet maps being used on this page. https://i.sstatic.net/Cj9ai.png Initially, I attempted to resol ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...