在Backbone.js中使用localStorage

时间:2012-06-20 15:53:58

标签: backbone.js local-storage

我正在整理一个骨干示例,其中编辑和删除模型。我能够将新模型和编辑保存到本地存储,但是在刷新时正确显示localstorage时遇到问题。它似乎是作为单个对象加载,因此无论添加了多少个,都会给我一个模型。

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

2 个答案:

答案 0 :(得分:8)

您需要将项目添加到集合中,然后在需要调用fetch时读取它。您的对象中还有一些额外的尾随逗号。

以下是您的代码的略微修改版本,似乎有效。

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

编辑:我看到您正在尝试读取存储在“store-name”下的本地存储中的值,backbone-localStorage的工作方式是它使用商店的名称(在您的案例“商店名称”)存储其余模型的ID,然后在商店名称和ID的组合下保存每个模型,所以说你有三个模型,你最终会在本地有4个条目存储,

  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

编辑2

这是指向jsfiddle代码的链接,开始我要离开行thingsList.fetch();注释掉,取消注释该行并注释掉thingsList.add(things);并再次运行它它应该从本地存储中提取模型(我在那里留下了警报)。

答案 1 :(得分:8)

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