Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using localStorage in Backbone.js

I am putting together a backbone example in which models are created edited and deleted. I am able to save new models and edits to local storage, but am having a problem getting localstorage to properly display on refresh. It seems to be loading as a single object, and therefore gives me one model regardless of how many were added.

 var Thing = Backbone.Model.extend({
     defaults: {
         title: 'blank'
     }
 });
 var ThingView = Backbone.View.extend({
     template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
     editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
     events: {
         "click #remove": "deleteItem",
         "click #edit": "editItem",
         "click #save": "saveItem",
     },
     deleteItem: function () {
         console.log('deleted');
         this.model.destroy();
         this.remove();
     },
     editItem: function () {
         console.log('editing');
         this.$el.html(this.editTemplate(this.model.toJSON()));
     },
     saveItem: function () {
         console.log('saved');
         editTitle = $('input.name').val();
         console.log(editTitle);
         this.model.save({
             title: editTitle
         });
         this.$el.html(this.template(this.model.toJSON()));
     },
     render: function () {
         var attributes = this.model.toJSON();
         this.$el.append(this.template(attributes));
         return this;
     }
 });
 var ThingsList = Backbone.Collection.extend({
     model: Thing,
     localStorage: new Store("store-name"),
 });
 var storeVar = localStorage.getItem("store-name");
 console.log(storeVar);
 var thingsList = new ThingsList;
 thingsList.reset(storeVar);
 var ThingsListView = Backbone.View.extend({
     el: $('body'),
     events: {
         'click #add': 'insertItem',
     },
     initialize: function () {
         this.render();
         this.collection.on("add", this.renderThing, this);
     },
     insertItem: function (e) {
         newTitle = $('input').val();
         newThing = new Thing({
             title: newTitle
         });
         this.collection.add(newThing);
         newThing.save();
         console.log(this.collection.length);
     },
     render: function () {
         _.each(this.collection.models, function (items) {
             this.renderThing(items);
         }, this);
     },
     renderThing: function (items) {
         var thingView = new ThingView({
             model: items
         });
         this.$el.append(thingView.render().el);
     }
 });
 var thingsListView = new ThingsListView({
     collection: thingsList
 });
like image 236
user1469779 Avatar asked Jun 20 '12 15:06

user1469779


2 Answers

You need to add the items to your collection, and then to read it in you need to call fetch. You also have a couple of extra trailing commas in your objects.

Here's a slightly modified version of your code which seems to work.

var Thing = Backbone.Model.extend({
  defaults:{
    title:'blank'
  }
 });

 var ThingView = Backbone.View.extend({
    //el: $('body'),
     template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
     editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),


    events: {
    "click #remove": "deleteItem",    
    "click #edit": "editItem",
    "click #save": "saveItem",
    },

    deleteItem: function(){
      console.log('deleted');

            this.model.destroy();
            //remove view from page
            this.remove();
    },

    editItem: function(){
     console.log('editing');
     this.$el.html(this.editTemplate(this.model.toJSON())); 
    },

    saveItem: function(){
     console.log('saved');
     editTitle = $('input.name').val();
     console.log(editTitle);
     this.model.save({title: editTitle});
     this.$el.html(this.template(this.model.toJSON()));
    },

    render: function(){
      var attributes = this.model.toJSON();
      this.$el.append(this.template(attributes));
      return this;
    }
 });

 var storeVar = localStorage.getItem("store-name");

 var ThingsList = Backbone.Collection.extend({
   model: Thing,
   localStorage: new Store("store-name")
});

 var things = [
  { title: "Macbook Air", price: 799 },
  { title: "Macbook Pro", price: 999 },
  { title: "The new iPad", price: 399 },
  { title: "Magic Mouse", price: 50 },
  { title: "Cinema Display", price: 799 }
];

console.log(things);

var thingsList = new ThingsList;

var ThingsListView = Backbone.View.extend({
   el: $('body'),

events: {
      'click #add': 'insertItem'
    },

initialize: function () {
    this.render();
    this.collection.on("add", this.renderThing, this);
    },


    insertItem: function(e){
      newTitle = $('input').val();
      newThing = new Thing({ title: newTitle });
      this.collection.add(newThing);
      newThing.save();
      //this.model.saveItem;
      console.log(this.collection.length);
    },


   render: function(){
     _.each(this.collection.models, function (items) {
            this.renderThing(items);
        }, this);
    },


  renderThing: function(items) {
    //console.log('added something');
    var thingView = new ThingView({ model: items }); 
        items.save();
    this.$el.append(thingView.render().el); 
  }

});

var thingsListView = new ThingsListView( {collection: thingsList} );
thingsList.fetch();
console.log(thingsList.toJSON());
thingsList.reset(things);

Edit: I see you are trying to read in the value stored in local storage under "store-name", the way backbone-localStorage works is that it uses the name of the store (in your case "Store-name") to store the ids of the rest of the models and then saves each model under a combination of the store name and the id, so say you had three models, you would end up with 4 entries in local storage,

  localStorage["store-name"]  //id1, id2, id3"
  localStorage["store-name-id1"] //model with id1
  localStorage["store-name-id2"] // model with id2
  localStorage["store-name-id3"] // model with id3

EDIT 2

Here's a link to a jsfiddle of your code, to start I'm leaving the line thingsList.fetch(); commented out, uncomment that line and comment out thingsList.add(things); and run it a second time and it should pull the models from local Storage (I left an alert in there).

like image 189
Jack Avatar answered Oct 23 '22 15:10

Jack


var Thing = Backbone.Model.extend({
     defaults: {
         title: 'blank'
     }
 });
 var ThingView = Backbone.View.extend({
     template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
     editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
     events: {
         "click #remove": "deleteItem",
         "click #edit": "editItem",
         "click #save": "saveItem",
     },
     deleteItem: function () {
         console.log('deleted');
         this.model.destroy();
         this.remove();
     },
     editItem: function () {
         console.log('editing');
         this.$el.html(this.editTemplate(this.model.toJSON()));
     },
     saveItem: function () {
         console.log('saved');
         editTitle = $('input.name').val();
         console.log(editTitle);
         this.model.save({
             title: editTitle
         });
         this.$el.html(this.template(this.model.toJSON()));
     },
     render: function () {
         var attributes = this.model.toJSON();
         this.$el.append(this.template(attributes));
         return this;
     }
 });
 var ThingsList = Backbone.Collection.extend({
     model: Thing,
     localStorage: new Store("store-name"),
 });
 var storeVar = localStorage["store-name-7ee7d1e3-bbb7-b3e4-1fe8-124f76c2b64d"];
 console.log(storeVar);
 var thingsList = new ThingsList;
 //thingsList.reset(storeVar);
 var ThingsListView = Backbone.View.extend({
     el: $('body'),
     events: {
         'click #add': 'insertItem',
     },
     initialize: function () {
    thingsList.fetch();
    thingsList.toJSON();
         this.render();
         this.collection.on("add", this.renderThing, this);
     },
     insertItem: function (e) {
         newTitle = $('input').val();
         newThing = new Thing({
             title: newTitle
         });
         this.collection.add(newThing);
         newThing.save();
         console.log(this.collection.length);
     },
     render: function () {
         _.each(this.collection.models, function (items) {
             this.renderThing(items);
         }, this);
     },
     renderThing: function (items) {
         var thingView = new ThingView({
             model: items
         });
         this.$el.append(thingView.render().el);
     }
 });
 var thingsListView = new ThingsListView({
     collection: thingsList
 });
like image 8
user1469779 Avatar answered Oct 23 '22 15:10

user1469779