我创建了一些模型,所有模型都保存在本地存储集合中。我的挑战是如何使用模型属性值之一从本地存储中的集合中删除模型。下面是我的代码摘录:
var Food = Backbone.Model.extend({
defaults: {
title: '',
calories: 0,
date: '',
history: false
}
});
var Foods = Backbone.Collection.extend({
model: Food,
localStorage: new Backbone.LocalStorage('Health-Tracker')
});
my_foods = new Foods({});
var ls = new Backbone.LocalStorage('Health-Tracker');
var res = ls.findAll();
var n = res.length;
var i, id;
for (i = 0; i < n; i++) {
food = res[i];
id = food['id'];
title = food['title'];
calories = food['calories'];
date = food['date'];
history = food['history'];
//I am stuck here
if (history) {
ls.remove(food); // Not working
// I have also tried this
ls.remove(id); // not working
}
}
请注意,较大代码其他部分中的某些模型的历史记录已成功设置为true。以上只是历史记录值为true时我需要采取措施的地方。现在这是错误的代码。 感谢您的协助
答案 0 :(得分:0)
请注意,此应用程序不使用服务器来存储/检索数据。所有模型都存储在本地存储中。使用findAll()和remove()就像我上面从本地存储中删除一样,是一个非常漫长的过程。添加了以下内容以从本地存储中删除模型:
my_foods.fetch();
my_foods.models.forEach(function(food){
day = food.get('day');
new_day = get_new_day();// this function isn't included above
if (new_day > day) {
food.destroy();
}
});