Experiencing issues with organizing and displaying data using backbone.js

Experiencing some issues with sorting and displaying data using backbone.js. The collection is sorted by 'title' in the comparator function, but when rendering begins, the views of models are displayed in a different order.

    var TodoList = Backbone.Collection.extend({

    model: Todo,

    comparator: function(todo) {
        return todo.get('title');
    },

//function for sorting
    sortByDate: function () {
       this.comparator = function(todo){
           return todo.get('title');
       };
       this.sort();
    }

    });

    var TodoView = Backbone.View.extend({

    tagName:  "li",

    template: _.template($('#item-template').html()),

    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
    });

Answer №1

Implementing a comparator for your collection guarantees that the models are organized in a specific order. To display them in that sequence, you simply need to retrieve the models from the collection (usually done within your collection view) and render them.

For instance, if you do not have a collection view, you can use the following approach

todoList.each(function (todo) {
  $('#output').append(new TodoView({model: todo}).el);
});

Typically, this code would be inside your collection view. It might also be beneficial to keep a record of your views so that you can easily update or delete them. For example

var TodoCollectionView = Backbone.View.extend({

    views: {}, 

    render: function () {
        var frag = document.createDocumentFragment();
        this.collection.each(function (model) {
           var view = this.viewForModel(model);
           frag.appendChild(view.render().el);
        },this);

       this.$el.html(frag);
    },

    viewForModel: function (model) {
        var view;    
        if (this.views[model.cid]) {
           view = this.views[model.cid];
        } else {
           view = new TodoView({model: model});
           this.views[model.cid] = view;
        }
       return view;
    }
});

Check out this jsbin link for reference

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

Use Vue's DOM manipulation to properly surround iframes with divs

I'm facing a scenario where my Vue component displays HTML content retrieved from the database in the following format: <div id="post-body-text" class="post__main-text" v-html="postText" ...

Setting or passing a variable via URL in Angular 2 applications

I am working on an Angular2 application that includes a chart component. Users can adjust the chart by setting certain variables. I want to give users the option to have the chart preset with specific variables by using a URL link. For instance: localhost ...

When scrolling, apply a CSS class to a div element once it becomes visible on the

I'm in the process of developing a timeline feature for my website, and I am facing an issue where the addClass function is being applied to all sections, even those that are not currently visible on the screen during scrolling. If you would like to ...

The checkbox event listener becomes dysfunctional when the innerHTML of its container is modified

My current challenge involves creating checkboxes with a blank line inserted after each one. I also need these checkboxes to trigger a function when changed. This is my code snippet: var div = document.getElementById("test"); var cb1 = document.createEl ...

Tips for persisting form values even after refreshing the page - a guide to setting form values that stay in place

When I submit a long form, an external JavaScript validation is triggered to check the input field validity. If all fields pass validation, a jQuery modal appears prompting the user to either register or log in. If the user chooses to register and complet ...

Issue with submitting content using Asp.Net Core along with Vue.JS and Axios

Hello there! I'm a novice when it comes to Vue.JS and I'm facing an issue while trying to post an object using axios, as all the properties are being received as null values. Let me share my basic Model: public class Employees { public int ...

How can you display an item in Angular JS only if there are elements in the ng-repeat loop

In my JSON data, a series of objects contain an array called "options". Some of these objects have items in this array while others do not. An example is shown below: { "label": "ORDERS", "enabled": true, "selected": true, "options": [ { ...

Can you explain how to extract information from an API response using res.send?

Utilizing the MEAN stack in JavaScript for my single page application has been seamless. A crucial component of my architecture involves an Angular factory that communicates with my API. app.factory('authorizing', function($resource){ retur ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

What methods can be used in VueJS to restrict users from entering numeric values?

I am struggling to create a validation that prevents users from inputting numeric values into a textbox. I have tried using a native JavaScript solution, but it does not seem to be working on my end. In my textbox, I have set up this trigger v-on:keyup=" ...

The error message "req.body undefined in NEXT JS" pops

Feeling lost and confused? I'm encountering an 'undefined' issue while attempting to upload my form data to Supabase. The data is being passed as undefined to the API, but when I inspect it within the submit handler, it displays correctly b ...

What is the best way to deselect all rows from the <Table> component in Material-UI while using ReactJS?

Currently, in my ReactJS application using Material-UI's <Table/>, I have successfully implemented the select all checkbox feature. The functionality keeps track of which row has been selected by using onRowSelection={this.handleRowSelection}. H ...

Unable to employ Datastore emulator on Nodejs app

Trying to integrate the datastore emulator with my nodejs application has been a challenge. Initially, I followed the guidelines provided here. Within my node application, I set up the following: var config = { projectId : "scio1-ts-datastore" } ...

Arranging a string alphabetically according to a specific term found in a dictionary entry

Is there a simple way to arrange words in a string based on their values in a dictionary? a = 'A B' b = {'B':0, 'A':1} The desired output is: c = 'B A' I attempted the following: c = sorted(a, key=b.values()) Unfo ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...

Steps for extracting a specific portion of a value contained within an attribute

In my code, there are multiple hyperlinks with different values attached to an onclick function. Here is an example: <a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a> <a onclick="Util ...

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

What steps should I follow to obtain code coverage data in my Aurelia application with the help of karma?

After creating my Aurelia app using the Aurelia CLI (au new), I wanted to set up code coverage, preferably with karma-coverage, but was open to other options as well. First, I ran npm install karma-coverage --save-dev and then copied the test.js task over ...

Serving pages with Node JS and loading .js files on the client side

Here is a simple JS file that will be familiar to those who have worked with Socket.IO in NodeJS and Express: var express = require('express'), app = express(), server = require('http').createServer(app), io = require(&apos ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...