Saving objects in localStorage which has a method

耗尽温柔 提交于 2021-02-10 18:11:56

问题


The problem is that I am saving projects, which are made with project factory function. The projects also have addToDo method and I am saving this projects into myProjects array.

I am struggling with, that when my projects are saved or retrieved to/from localStorage, they loose functionality (addToDo method). As after page refresh I can't add todos to the projects anymore. So I guess that method of project factory isn't saved to localStorage. Thanks.

let newProject;
let myProjects = localStorage.getItem("projects")
  ? JSON.parse(localStorage.getItem("projects"))
  : [
    
  ];

const saveToLocalStorage = () => {
  localStorage.setItem("projects", JSON.stringify(myProjects));
};

// Project factory, which takes in title and makes toDo array, to which the toDos will be added...
const newProjectFactory = (id, title) => {
  const toDos = [];

  const add_toDo = (toDo) => {
    toDos.push(toDo);
  };

  return { id, title, toDos, add_toDo };
};

const newProjectEvent = (event) => {
  // DOM elements of form ...
  event.preventDefault();
  const newProjectTitle = document.getElementById("newProjectName").value;

  let ID;
  if (myProjects.length > 0) {
    ID = myProjects[myProjects.length - 1].id + 1;
  } else {
    ID = 0;
  }

  newProject = newProjectFactory(ID, newProjectTitle);

  myProjects.push(newProject);
  
};


回答1:


A pattern like this might be useful. You can keep them in an single object or create two functions such as newProjectFactory and newProjectFromJSON.

const Project = {
  factory: (id, title) => {
    return Project.from({ id, title });
  },
  from: (state) => {
    const { toDos = [], id, title } = state || {};

    const add_toDo = (toDo) => {
      toDos.push(toDo);
    };

    return { id, title, toDos, add_toDo };
  }
};

const project = Project.factory(1, 'title');
project.add_toDo('taco');

const json = JSON.stringify(project);
const deserialized = Project.from(JSON.parse(json));
console.log(deserialized);

The factory method is exactly what you have now, it simply creates a new project given your factory inputs. The from method is a little closer to the metal where it allows you inject specific state properties. The factory simply creates a more ergonomic api for creating projects while the from is used to marshal data.

Another thing you might want to consider is adding a toJSON method on the factory object. This will allow you to add private fields to json as well that may not be serialized while using the normal revealing pattern. A good use case is probably the toDos array. You probably don't want that public but want it in json.

const newProjectfactory = () => {
  const toDos = [];
  
  const toJSON = () => {
    return { toDos };
  };
  
  const addTodo = (todo) => {
    toDos.push(todo);
  };
  
  return {
    addTodo,
    toJSON
  };
}

const project = newProjectfactory();
console.log(JSON.stringify(project));


来源:https://stackoverflow.com/questions/64141609/saving-objects-in-localstorage-which-has-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!