Search code examples
javascriptbackbone.js

I can't get backbone.localstorage.js to save correctly


I working on an app that saves a user's food log. I'm using backbone.js.

I've got most of it working properly. The only issue I'm having is using backbone.localstorage.js. It's not creating the localstorage entry in the browser.

Here is where I'm creating my entry.

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

I've put my app in a jsfiddle: https://jsfiddle.net/brettdavis4/654fqc6w/3/


Solution

  • The reason it is not creating any entries is because you are not invoking model.save(), which is when model is sent to persistence layer for the first time. Or you can use collection.create() as well, which internally invokes model.save().

    The methods such as collection.add(), collection.remove() returns the affected model/s, you can just invoke save(), destroy() etc to pass in the necessary action to persistence layer via sync. Backbone local storage is just a proxy for Backbone ajax sync. You need to invoke the sync mechanism somehow by triggering appropriate methods.


    For example,

    replacing

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

    with

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

    will create the instance in local storage.

    Or you can do

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

    (for some reason I'm not able to upate the fiddle, it's throwing errors when I try to update/fork) but I've tested the above.