0

My domain is quite simple. I have a Message class, and a MessagesManager class.

Message has 3 attributes:

  1. author
  2. message (body)
  3. timestamp

MessagesManager is basically just an interface that keeps the history of messages, adds new messages etc.

I want to store the messages in localStorage so that they can be retrieved at later points, yet I'm not sure how to do it.

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 = [];
    }
}

And my 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;
    }
}

What is the nicest/best way to store the messages (as objects, kind of) in the localStorage, while also being able to retrieve them easily (ie. in MessagesManager contructor)?

emihir0
  • 1,200
  • 3
  • 16
  • 39

1 Answers1

0

Try this:

class MessagesManager {
   constructor() {
      this.msgs = (localStorage.getItem("messages"))?JSON.parse(localStorage.getItem("messages")):[];
}

add(author, message) {
    var msg = new Message(author, message)
    this.msgs.push(msg);
}

save() {
    localStorage.setItem("messages", JSON.stringify(this.msgs));
}

delete() {
    this.msgs = [];
    localStorage.removeItem("messages");
}

}

Docs: http://www.w3schools.com/html/html5_webstorage.asp

Jacopo Brovida
  • 465
  • 4
  • 10