I can't get backbone.localstorage.js to delete an item correctly

100 Views Asked by At

Here is a sample of the code I'm working on:

I'm able to create the localstorage object and I'm able to save to it.

var FoodJournalDay = Backbone.Collection.extend({
    model: Food,
    localStorage: new Backbone.LocalStorage("foodjournal")
});

However, I'm not able to delete the localstorage entry.

var App = Backbone.View.extend({

    el: 'body',

    events: {
        "input #searchBox" : "prepCollection",
        "click #listing li" : "track",
        "click #save": "saveClicked",
        "click #savefoodday": "savefoodClicked",        
        "click .destroy": "destroy"
    },

    initialize: function () {

        this.model = new SearchList();
        this.foods = new AllFoods();
        this.journal = new FoodJournalDay();

        this.model.on('destroy', this.remove, this);
        this.listenTo(this.journal, 'destroy', this.renderfoods);

        this.foods.fetch();

    },

    saveClicked: function() {
        this.listenTo(this.journal, 'add', this.renderfoods);        

        this.journal.create(new Food({
            id: foodid,
            title: item_name,
            brand: brand_name,
            calories: calorieAmt,
            fat: fatAmt,
            sodium: sodiumAmt,
            protein: proteinAmt,
            carbs: carbsAmt,
            sugar: sugarAmt,
            html: trackedhtml
        }));
    },

    destroy: function (e) {

        var model = new FoodJournalDay({ id: id });
        this.journal.remove();
    },



    var app = new App();
});

Here is a js fiddle of the app: https://jsfiddle.net/brettdavis4/3sy61zaj/1/

1

There are 1 best solutions below

1
Eric Guan On BEST ANSWER

You need to get the existing model from the collection by id, and then destroy() it. Which will remove it from the collection and localStorage.

this.journal.get(id).destroy();

https://jsfiddle.net/guanzo/3sy61zaj/2/