Determining the Existence of a Model in Backbone/Marionette

I've built a simple backbone application, but I'm struggling with a more complex check that needs to be performed.

Below is my code. I'm creating a list of chat participants. Eventually, I'll pass this list into a JavaScript function.

   Participant = Backbone.Model.extend({});

    Participants = Backbone.Collection.extend({
        model: Participant
    });

    ParticipantView = Backbone.Marionette.ItemView.extend({
        template: "#participant-template",
        tagName: 'div',
        className: 'call-participant',

        initialize: function () {
            this.$el.prop("id", this.model.get("chatid") + "-" + this.model.get("participantName"));
        },
    });

    ParticipantsView = Backbone.Marionette.CompositeView.extend({
        template: "#participants-template",
        tagName: 'div',
        itemView: ParticipantView,

        appendHtml: function(collectionView, itemView) {
            collectionView.$el.append(itemView.el);
        }
    });

    MyApp.addInitializer(function(options)) {
        var participantsView = new ParticipantsView({
            collection: options.participantNames
        });
        MyApp.participantContainer.show(participantsView);
            var participantsModel = new Participants();
    };

    $(document).ready(function() {        
        MyApp.start({participantsModel: participantsModel});
    })

The issue I'm facing is that when participants leave or join the chat, the message is resent with a new participant list, potentially missing some participantName values.

So, my question is: How and where do I instruct backbone.marionette to compare the existing models with the new model list for a specific chatid, and remove models that are no longer in the list, while adding new ones?

I construct my ID using chatid and participantName (which is unique as it is the JID without the server part). This ID format helps me differentiate between multiple chat lists on a single page.

Thank you. Feel free to ask for more information if needed. jsFiddle: http://jsfiddle.net/966pG/175/

Warm regards,

Gary Shergill

EDIT: I'm aware of get and set methods, but I am unsure how to utilize them effectively. I've tried referring to the documentation "".

EDIT: Providing a live scenario below. I have a JavaScript function that listens for pubsub events and, upon receiving the relevant event, creates an array of participant objects:

    var participants = [];
    $(iq).find('participants').each(function() {
        var participantsNodes = this.childNodes;
        for (var i = 0; i < participantsNodes.length; i++) {
            var participantAttr = participantsNodes[i].attributes
            var participant = participantAttr[0].nodeValue;
            participants.push({"participantName": participant, "chatid": chatid});
        }
    });
    var chatid = $(iq).find('chatid').text();
    ...

                participantsModel.add(new Participants({
                    chatid : chatid,
                    participantArray : participants
                }))

Answer №1

Following the discussion in the comments

When using Backbone's Collection.set function, it automatically handles adding a new set of participants. It distinguishes between new and existing participants, triggering the necessary add and remove events accordingly.

Remember to include an array of Participants, rather than just names. You can easily achieve this by utilizing the map function.

//array of names retrieved from server
arr = getNamesFromServer()
arrOfParticipants = arr.map(function(name) {
  id = calculateChatID(name,/*any additional information needed */)
  return new Participant(name:name,chatID: id);
}

participantNames.set(arrOfParticipants)

The method of tracking participants and updating them is entirely up to you.

If the server can provide the information in the correct format (an array of JSON objects that match Participant), it is best to use Backbone's sync functions. By setting up a matching RESTful URL or customizing the url property on your model/collection, you can simply call participantNames.fetch() to handle everything efficiently.

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

Why does my Angular service throw an error stating "undefined is not a function" when passing my function as an argument?

I am currently working on implementing factory and two constructor patterns in Angular. My goal is to convert the factory into an Angular service. Below is a simplified version of the code I am working with: function processFactory () { // some code ...

Utilize a scanner to read from a file and store the data in an

In my current project, I have successfully implemented a method to read double values from a file using a scanner and store them in an array. However, I am facing a unique challenge that I need help with. I want to read a specific set of values (the first ...

Is there a javascript file storing an image?

Currently, I am in the process of creating my personal portfolio website and incorporating react-bootstrap for designing my react components. I have been attempting to add an image using the Image component provided by react-bootstrap. However, I noticed ...

javascript display error message in innerHTML if passwords do not match

Hello, I found your code to be helpful but I am facing an issue. I want to display a message using innerHTML when the passwords do not match. I have been trying to implement this feature but it is not working for me. Below is my current code. Please provid ...

Activate Bootstrap dropdown with an external button click

I am currently working with Bootstrap 5 dropdowns and I have a specific requirement. I want the button that triggers the dropdown to be located outside of its parent element (under A). Is there a way to achieve this using Jquery or JS? <div class=&quo ...

Retrieving information within the iteration

I am facing an issue with connecting to an external server named Pexels in order to retrieve photos from node.js. The problem seems to be related to JavaScript, as Pexels limits the user to download up to 40 pictures per page. https://api.pexels.com/v1/cu ...

Tips for reformatting table row data into multiple rows for mobile screens using ng-repeat in Angular

Just started using Angular JS and I have some data available: var aUsers=[{'name':'sachin','runs':20000},{'name':'dravid','runs':15000},{'name':'ganguly','runs':1800 ...

Is it possible to enhance controllers in Sails.js through extension methods?

There are times when I need to execute a certain action on every page of my web application or make a specific method available to all controllers. Previously, in object-oriented MVC frameworks, I would have my controllers extend a base controller and de ...

Add or remove an ID from the swatch gallery based on its presence or absence

I'm currently working on a handleClick function for a gradient swatch gallery. The goal is to add an id of "bg-gradient" to the clicked element, and if another swatch is clicked, remove that id from the previously clicked swatch and add it to the newl ...

What is the best way to display the shape value of a tensor?

I utilized the function print tf.shape(image) The result appears as follows Tensor("Shape:0", shape=(3,), dtype=int32, device=/device:CPU:0) I am interested in knowing the values within the shape (such as the dimensions). How can I retrieve and display ...

Using TypeScript to extend functionality from Array

I am currently working on designing a robust data model for an AngularJS application, and I am interested in having my model inherit from Array<BaseModel>. However, I have not yet discovered a foolproof way to accomplish this. In a hypothetical scen ...

Transform a Java function that utilizes bytes into Kotlin

I am having difficulty converting a Java function to Kotlin-specific. Here is the Java code: private boolean isOldOemCommissioningFormat(byte[] assetData) { if (assetData == null || assetData.length < mAssetDataDelimeterByteCount + mA ...

Should each of them be opened in a new connection if web and worker processes are separated?

In my current NodeJS web app project, there are two processes in play - a web process and a worker process. These processes communicate via AMQP. To start the application, I run two scripts: one for the web process called server.js, and another for the wor ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

JavaScript does not allow the use of variables outside of functions

As someone diving into the world of Javascript after working extensively with server-side languages like PHP, I've noticed a peculiar issue. It seems that I am unable to access variables defined outside of a function from within the function itself. T ...

Is there a way to refresh the current page in Ionic 3 when the browser is reloaded?

I have encountered a problem in my work with an Ionic 3 App. I am looking for a solution where the browser will refresh the current page instead of redirecting me to the home page. Is this achievable? I attempted to solve it using the following code: thi ...

What is the best way to create shaded areas upon clicking them?

How can I implement shading on areas when they are clicked? Contractor Form (Package One) <area id="39" name ="39" alt="" title="39" href="#" shape="poly" coords="12,204,12,120,138,117,144,72,248,72,252,124,526,125,632,81,668,157,698,149,722,2 ...

Utilize jQuery to refresh the database with the information retrieved from the ajax-request

I am attempting to update the database. This is what I am doing From my JavaScript code var data = { "jobid": $('#jobid').val(), "names": $('#names').val(), "scripttype": $('#testscripts').val() }; var msg=""; f ...

Bootstrap's pill-tab feature isn't functioning properly

Why is this tab not functioning properly? Do I need to make changes to the jQuery section? The Id and Href appear to be correct, but the tab is not working as expected. $('#v-pills-tab a').on('click', function (e) { e.pr ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...