Calculating a property that yields the total sum of another property found on every model

In my cart model, I have items stored with item_id, item_name, and item_price properties like this:

[
    {
        "item_id": 1,
        "item_name":"Item 1",
        "item_price": 500
    },
    {
        "item_id": 2,
        "item_name": "Item 2",
        "item_price": 230
    },
    {
        "item_id": 3,
        "item_name": "Item 3",
        "item_price": 150
    }
]

To calculate the total cost of all items in the cart, I need to sum up the item_price property. This total will be displayed and then passed to ember data or an ajax call for completing a purchase.

I am attempting to use Ember's computed functionality to achieve this, but I may not completely understand how to aggregate data using computeds. Here is what I have tried:

totalDue: Ember.computed.sum('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6cbc9c2c3ca88e6c3c7c5ce88cfd2c3cb">[email protected]</a>_price')

However, the controller is returning a total of 0. I am currently utilizing ember version 2.2.0.

Answer №1

If you want to achieve this task, follow these steps:

totalCost: Ember.computed('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b4b6bdbcb5f799bcb8bab1f7b0adbcb4">[email protected]</a>_price', function() {
  const model = this.get('model');
  if (!model) {
    return 0;
  }

  let total = 0;
  model.forEach(item => total += Ember.get(item, 'item_price'));
  return total;
})

See working example here.

Answer №2

If you want a concise solution, you can achieve the same result with this neat one-liner:

totalAmount: Ember.computed('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9e4e6edece50dc2ededebe5ecaaedc2e8">[email protected]</a>_price', function() {
  return this.get('model').mapBy('item_price').reduce((x, y) => x + y, 0);
})

View Live Demo

Answer №3

Here's an alternative way to achieve the same result:

const shoppingCart = Ember.Controller.extend({
      items: [
        {
          "item_id": 1,
          "item_name":"Item 1",
          "item_price": 500
        },
        {
          "item_id": 2,
          "item_name": "Item 2",
          "item_price": 230
        },
        {
          "item_id": 3,
          "item_name": "Item 3",
          "item_price": 150
        }
      ],

      priceList: Ember.computed.mapBy('items', 'item_price'),
      total: Ember.computed.sum('priceList')
    });

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

Embed JavaScript locally within an iframe HTML

When attempting to add HTML code within an iframe to showcase data, everything works as expected. However, the issue arises when trying to include any JavaScript within the iframe, as it doesn't seem to be recognized locally. Below is the example cod ...

IE throws an exception when attempting to use Canvas as it is not supported

One of my challenges involves working with a Canvas Element: <canvas id="canvas" width="300" height="300"> Sorry, your browser does not support the Canvas element </canvas> In my JavaScript file, I have the following code: var ct= docum ...

Tips for relocating a div panel below all other div panels when a button is clicked with JQuery and CSS

There are several panels stacked below each other. Each panel has a button that, when clicked by the user, should move the panel to the bottom of the stack. For example: If there are 10 panels aligned sequentially and the user wants to remove Panel 2 by ...

What steps can I take to incorporate Waze data into my website?

Waze, an application that provides real-time traffic information, also has a live map available at Waze livemap. This live map shows various marks indicating different elements of the traffic. I recently stumbled upon a website: Here is the link - egaraz, ...

Iterate through a listbox and append the content to a textbox using JavaScript

I am currently working on a script to read all the data from a listbox and populate a textbox with those values. I initially attempted to use a for loop for this task, but it seems to be running only once and then stopping. var listbox = $('#<%=l ...

Guide to fixing Vue app crashes caused by Web Sockets error

I'm encountering an issue with my Vue application as I am unable to load a specific page due to the app crashing. The console displays the following error, even though there is no implementation of Web Sockets in the app. Despite adding this snippet ...

Converting information from one form to another using Typescript

I am in need of transforming data received from BE into a different format so that it can be inserted into a table component. The original format looks like this: { "displayName": "Income", "baseVersionSum": null, ...

Exploring the contrast between RFC and RFCE in the realm of ReactJS

As a newcomer to Reactjs, I'm curious about the distinction between "react functional component" and "react functional component export". Can someone help explain? Below is an example of a react functional component: import React from 'react&apo ...

Is there a way to solve this problem by creating a loop for the code?

document.getElementById("output1").innerHTML = totalDistance + ", " + hours + ":" + minutes+", $" + cost; this code combines input values to create an output. I am currently facing an issue where I need to loop thi ...

The navbar toggler icon is not displaying

<header class="container"> <div class="container pt-3 col-md-5 col-sm-5 col-xs-6 text-center"> <a href="#" class="site-logo"><img src="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

Navigate through JSON data to uncover the tree structure path

In my project, I am working on creating a treeview user interface using the JSON provided below. I have included properties such as node-id and parentId to keep track of the current expanded structure. Next, I am considering adding a breadcrumb UI compone ...

The functionality of Vue's keep-alive feature seems to be malfunctioning within Quasar, as the mounted hook is consistently triggered when using

I am working on a Quasar application where I want to implement page caching using keep-alive in a specific scenario. The scenario is as follows: the user goes from the home page to Page 1, then navigates to Page 2, and finally returns to Page 1 using $rout ...

Checkbox selection and display: Check the box to reveal its value in a div, along with a close button for

While following a tutorial, I came across a scenario where multiple checkboxes are involved. Upon selecting the checkbox and clicking on the "get selected value" button, the value of the selected checkboxes is alerted. However, I would like to make a mod ...

It seems like the texture may not have been created correctly

My WebGL app for volume ray casting is nearly complete. However, I have encountered an issue with simulating a 3D texture using a 2D texture. Creating a large texture from smaller slices, the dimensions of the huge texture are approximately 4096x4096px. Th ...

Using jQuery to dynamically add or remove table rows based on user inputs

Apologies if this is too elementary. I am attempting to insert rows into a table if the current number of rows is less than what the user requires. Simultaneously, I need to remove any excess rows if the current number exceeds the user's specificati ...

JavaScript CompleteLink message

Hey there, I've come across a JavaScript code for a countdown timer but need some assistance with it. The issue I'm facing is that within the code, there's a line that displays a message to the user when the timer reaches zero. I want to kn ...

Visit the map only after the promises have been fulfilled

In my current project, I am utilizing the loadash map function for data structuring. The data retrieved consists of a series of IDs that require querying the database and integrating the results into the map before returning. However, the data is delayed i ...

The "Temporary Text" feature in an HTML form

Seeking assistance with implementing dynamic text in place of static text for the placeholder attribute, sourced from a key-value pair in a localization file. Currently developing on the Aurelia framework and would appreciate any guidance on this matter. T ...

`Troubleshooting odd behavior with date selection in AngularJS`

When I try to set the default date as the maximum date in a date input field, something strange happens. Initially, I select today's date as the value and everything works fine. However, if I clear the date by clicking on an 'x' icon, the va ...