我正在开发一个保存用户饮食日志的应用程序。我正在使用backbone.js。
我已经让大部分工作正常了。我遇到的唯一问题是使用backbone.localstorage.js。它不会在浏览器中创建本地存储条目。
这是我创建条目的地方。
var AllFoods = Backbone.Collection.extend({
model: Food,
localStorage: new Backbone.LocalStorage("allfoods")
});
我已将我的应用程序放入 jsfiddle 中: https://jsfiddle.net/brettdavis4/654fqc6w/3/
最佳答案
它没有创建任何条目的原因是因为您没有调用model.save()
,这是模型第一次发送到持久层的时间。或者您也可以使用collection.create()
,它会在内部调用model.save()
。
诸如collection.add()
、collection.remove()
之类的方法会返回受影响的模型,您只需调用save()
、destroy()
等通过同步将必要的操作传递给持久层。 Backbone 本地存储只是 Backbone ajax 同步的代理。您需要通过触发适当的方法来以某种方式调用同步机制。
例如,
替换
this.foods.add({
id: foodid,
title: item_name,
brand: brand_name,
calories: calorieAmt,
fat: fatAmt,
sodium: sodiumAmt,
protein: proteinAmt,
carbs: carbsAmt,
sugar: sugarAmt,
html: trackedhtml
});
与
this.foods.create({
id: foodid,
title: item_name,
brand: brand_name,
calories: calorieAmt,
fat: fatAmt,
sodium: sodiumAmt,
protein: proteinAmt,
carbs: carbsAmt,
sugar: sugarAmt,
html: trackedhtml
});
将在本地存储中创建实例。
或者你也可以这样做
var model = this.foods.add({
id: foodid,
title: item_name,
brand: brand_name,
calories: calorieAmt,
fat: fatAmt,
sodium: sodiumAmt,
protein: proteinAmt,
carbs: carbsAmt,
sugar: sugarAmt,
html: trackedhtml
});
model.save();
(由于某种原因,我无法更新 fiddle ,当我尝试更新/ fork 时它会抛出错误)但我已经测试了上述内容。
关于javascript - 我无法正确保存backbone.localstorage.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470403/