我不能让backbone.localstorage.js删除的项正确

问题描述:

下面是代码的样本我的工作:我不能让backbone.localstorage.js删除的项正确

我能够创建localStorage的对象,我能保存到它。

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

但是,我无法删除localstorage条目。

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(); 
}); 

这里是应用程序的一个js小提琴:https://jsfiddle.net/brettdavis4/3sy61zaj/1/

您需要通过ID来获得从集合中现有的模型,然后destroy()它。这将从集合和localStorage中删除它。

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

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

+0

谢谢!我对你有另一个问题。我修改了应用程序以在刷新浏览器时从localstorage中检索项目。如果我尝试在刷新后从列表中删除项目,则会出现错误。你有什么建议吗? https://jsfiddle.net/brettdavis4/ynm2sse9/2/ –