将对象存储到localStorage

时间:2016-10-15 21:17:06

标签: javascript html5

我的域名非常简单。我有一个Message类和一个MessagesManager类。

Message有3个属性:

  1. author
  2. message(正文)
  3. timestamp
  4. MessagesManager基本上只是一个保存消息历史,添加新消息等的接口。

    我想将消息存储在localStorage中,以便以后可以检索它们,但我不知道该怎么做。

    class MessagesManager {
        constructor() {
            this.msgs = []; //retrieve from localStorage
        }
    
        add(author, message) {
            var msg = new Message(author, message)
            this.msgs.push(msg);
        }
    
        save() {
            // save to localStorage
        }
    
        delete() {
            this.msgs = [];
        }
    }
    

    我的Message

    class Message {
        constructor(author, message) {
            this.timestamp = Date.now();
            this.author = author;
            this.message = message;
        }
    
        toString() {
            var date = new Date(this.timestamp);
    
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
    
            if (hours < 10) hours = "0" + hours;
            if (minutes < 10) minutes = "0" + minutes;
            if (seconds < 10) seconds = "0" + seconds;
    
            var time = "[" + [hours, minutes, seconds].join(":") + "]";
    
            return time + " " + this.author + ": " + this.message;
        }
    }
    

    localStorage中存储消息(作为对象,类型)的最好/最好的方法是什么,同时也能够轻松地检索它们(即在MessagesManager构造函数中)?< / p>

1 个答案:

答案 0 :(得分:0)

试试这个:

GettingData: function(key1,key2){
  console.log('Getting Data of '+key2);
  var ref = firebase.database().ref('/users/'+key1+'/products/'+key2).orderByKey().equalTo('name');
  ref.on('child_added', function(data) {
    console.log('pushing value' + data.val() + 'to ' + this.databaseresult);
    this.push('databaseresult', data.val());
    console.log('Productdata of '+ key1 +' is LOADED');
  }.bind(this));
},

 <!-- One way binding -->
 <x-element id="results" products="[[databaseresults]]"></x-element>

 <!-- Two way binding -->
 <x-element id="results" products="{{databaseresults}}"></x-element>

}

文档:http://www.w3schools.com/html/html5_webstorage.asp