mercredi 27 juillet 2016

Ember.js - Remove Only One instance of Object with removeObject

Explanation

I have a very simple calorie tracking app that uses the Nutritionix API to search for food items based on the user's input. The results are added to a results array, which is then displayed to the user. When a user clicks the "Add" button next to one of these items, the calories are added to a counter, and the food itself is added to a todaysFood array (using Ember's pushObject). This is then used to display which food the user has consumed today in a separate table.

When a user clicks the remove button next to one of the todaysFood items, it triggers an action, removeItem, and passes the index of the item clicked to removeItem. This index is used inside of Ember's removeObject to remove the item from the todaysFood array, and thus update the view (remove that item from the list and its calories from the counter).

Problem

When more than one of the same item are added to todaysFood, clicking remove on just one of those items removes ALL of the instances from todaysFood, and the view. This makes sense to me now, because of the docs' example:

var cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
cities.removeObject('Chicago');  // ['Berlin', 'Lima']
cities.removeObject('Lima');     // ['Berlin']
cities.removeObject('Tokyo')     // ['Berlin']

However, it also only removes the calories of ONE item, not all instances.

So, the question is: How do I remove only ONE instance of that item when remove is clicked? I.e., if two tacos are added, and I click remove on one, I only want that ONE to be removed (from the list and the calories).

Here is my removeItem action:

removeItem(index) {
        var self = this;

        // Store property paths for easy access
        let todaysPath = this.get('healthData').todaysFood;
        let caloriesPath = 'healthData.calories';

        this.set(caloriesPath, this.get(caloriesPath) - Math.round(todaysPath[index].fields.nf_calories));

        todaysPath.removeObject(todaysPath[index]);

    }

Disclaimer

I'm aware that I may not be handling this correctly at all. I'm open to any suggestions to make this better. Thanks!




Aucun commentaire:

Enregistrer un commentaire