What could be causing the issue when trying to sort a list by the difference between two fields?

Currently, I have a list of items with like and dislike buttons attached to each one. My goal is to organize this list based on the total score, which is calculated by subtracting the number of dislikes from the number of likes.

I am facing some challenges and questions related to this process:

  1. Why is the handlebar + sort method not functioning properly on the client side, and how can I fix it?
  2. Would a server-side solution be more efficient, considering that it may take up unnecessary disk space and be seen as premature optimization?

In my collections file, specifically in items.js, I store the item information in the following manner:

var item = _.extend(itemAttributes, {
  lovers:       [], 
  likes:        0,
  haters:       [], 
  dislikes:     0
  //popularity:      likes - dislikes I tried inserting in collection but doesnt work too 
});

To sort the items, I am using a handlebar helper along with an extension of the main list controller.

Handlebar segment:

Template.registerHelper('popularity', function(likes, dislikes) {
    var popularity = likes - dislikes;
    return popularity;


Sorting logic in router.js:

BestItemController = ItemListController.extend({
  sort: {popularity: -1},
    nextPath: function() {
    return Router.routes.BestItem.path({itemsLimit: this.itemsLimit() + this.increment})
  }
});

The handlebar calculations for popularity seem to be working fine in displaying the popularity score, however, the actual sorting does not seem to be functioning correctly. It appears that the sorting operation is based on the original item fields rather than the calculated popularity score.

I have also attempted to add an additional schema field (as mentioned in the commented line), but encountered errors stating that the 'likes' are not defined.

If anyone could offer guidance or suggest alternative methods for improving this process, it would be greatly appreciated. For example, perhaps sorting could be done within the individual template helper files instead of the main router.js files.

Thank you in advance for any assistance!

Answer №1

If you want to achieve client-side sorting, here is one approach you can take:

Assuming you are displaying your items using an {{#each item}} iteration, you can replace item with a custom helper. This helper function will take a cursor or an array as an argument and sort the items based on the current sorting settings.

Your custom helper could be implemented like this:

Template.items.helpers({
  sortedItems: function(){
    return sortMyItems(items.find()) // add .fetch() if you need an array
  }
});

Define the sortMyItems function at the beginning of your file to handle the sorting logic:

sortMyItems = function(cursor) {
    if(!cursor) {
        return [];
    }
    var sortBy = Session.get("sortBy");
    var sortAscending = Session.get("sortAscending ");
    if(typeof(sortAscending) == "undefined") sortAscending = true;
    var sorted = [];
    var raw = cursor.fetch();
    
    if(sortBy) {
        sorted= _.sortBy(raw, sortBy);

        if(!sortAscending) {
            sorted= sorted.reverse();
        }
    }

    return sorted;
}

While I use Session variables in this example, it's recommended to use reactive variables or reactive dictionaries for better encapsulation within the view.

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

Broken Mui Input - Full width with attributes for minimum and maximum values

I've created a sandbox to demonstrate an issue I came across that seems unbelievable, but it's happening. Here's the link: https://codesandbox.io/s/nifty-swanson-yxj4n2?file=/NumberField.js:1075-1097 The problem is simple - when both the ht ...

Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it. google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]}); google.setOnLoadCallback(function(){ createTable($(& ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

Tips for preloading a small placeholder image before the main content is loaded

After browsing , I noticed an interesting image loading style. The website initially shows a patterned image before revealing the actual content. This method creates visually appealing content while waiting for the entire webpage to load. Upon inspecting ...

Calculate the mean value of each array, and then determine which average is higher

After running the code snippet provided, I noticed that it outputs "first" instead of "second". Can you help me verify my logic here? I first calculate both averages and then compare them to return the greater one. Do you see any issues with this approac ...

Strange flickering/visualization issue experienced with transparent MeshPhongMaterial in Three.JS

In my scene, I have a Mesh called cylinder: const cylinder = new Mesh( new CylinderGeometry(2, 2, 1, 32), new MeshPhongMaterial({ color: color, shininess: 32, opacity: 0, transparent: true, specular: 0xffff82, }), ); I made the ...

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

How to effectively utilize string concatenation in AngularJS for the src attribute of an HTML img

I am currently utilizing the YouTube API v3 to extract videos from a playlist. Each video JSON object includes a unique videoId. My aim is to use this videoId to construct the src attribute in the img element using Angular. Here's my current setup: ...

What are the best practices for updating models using Bookshelf.js?

I'm struggling to make sense of the Bookshelf API, particularly when it comes to performing upsert operations. Let me outline my specific scenario: My model is named Radio, with a custom primary key called serial. For this example, let's assume ...

Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to ...

What is the specific collection where data is stored by the django-mongodb engine?

I recently started using the django-mongodb engine to establish a connection between Django and MongoDB. Within my application, there is a model called "bandwidth". Whenever I save data using python manage.py shell, it gets stored in a collection named " ...

In Javascript, where are declared classes stored?

When working in a browser environment like Firefox 60+, I've encountered an issue while attempting to retrieve a class from the global window object: class c{}; console.log(window.c); // undefined This is peculiar, as for any other declaration, it w ...

Tips for efficiently handling multiple collections in MongoDB when incorporating ASP.NET API Core2.1

In the informative Microsoft Tutorial on How to Develop a Web API using ASP.NET Core and MongoDB, they introduce a collection in MongoDB called "Books." When configuring the connection to this collection, certain code snippets are added to Startup.cs. pub ...

Having trouble getting the Mongoid edit form to function properly in Ruby

I'm struggling with getting the edit functionality to work in my simple application that features a hotline model using mongoid documents. The create and view functions are functioning properly, but I can't seem to get the edit function to work. ...

Having trouble transferring a PHP string to jQuery

I recently set up a script on my computer that displays a list of active interfaces: $ interfaces eth0 lo wlan0 Now, let me share my PHP code snippet with you: <?php $output=shell_exec('./interfaces'); $string = trim(preg_replace(&ap ...

What is the best way to apply an active class to the parent li element when selecting an item within it? I want to achieve this effect

$(function() { var pgurl = window.location.href.substr(window.location.href .lastIndexOf("/") + 1); $("#nav ul li a").each(function() { if ($(this).attr("href") == pgurl || $(this).attr("href") == '') $(thi ...

Load JavaScript only when the lightbox appears

Every page on my website has a button that, when clicked, opens a lightbox. Inside the lightbox is a form that requires JavaScript files, specifically Angular. These JavaScript files are exclusive to the form and not used elsewhere on the site. To improve ...

Establishing the redux provider in conjunction with react admin

Looking to implement a redux store in my project without using it in react admin, just in the rest of my application. I have included the usual redux provider code in my src/index.js file: ReactDOM.render( <Provider store={store}> <Ro ...

Implementing specific CSS styles for different routes in Angular 5: Use Bootstrap CSS exclusively for admin routes

I am looking to apply Bootstrap CSS only to routes starting with '/admin'. I have enabled lazy loading for both admin and public modules. ...