普通的OOP Javascript:将localStorage视为数组不起作用

Plain OOP Javascript: Treating localStorage as an Array doesn't work?

本文关键字:localStorage 数组 不起作用 OOP Javascript      更新时间:2023-09-26

我正在尝试使用简单的OOP待办事项列表实现localStorage。

小提琴在这里:https://jsfiddle.net/b81t2789/

我以为我可以像对待一个数组一样对待本地存储,并复制我用于实际阵列的逻辑,但这不起作用。

在这里,在将任务推送到数组之后,我添加了一行将任务存储在本地存储中并将其字符串化:

// function that adds new task to the array
function pushArray(){
  var newtask = new Task(toDo.value, "No note yet");
  taskItems.push(newtask);  
  var storedTask = localStorage.setItem(newtask, JSON.stringify(newtask));
  displayStorage(result2, storedTask);
  displayArray(result, newtask.Name);
  appendNote(result, newtask);
}

然后在显示新数组元素的函数正下方,我添加了一个从本地存储中检索项目,解析它,然后使用新任务创建一个 DOM 元素并将其附加到另一个容器。

//function that displays array elements
function displayArray(parent,obj){
  var task = make("div","class","taskitem",obj);
  parent.appendChild(task);
  fadeIn(task);
}
//function that displays storage elements
function displayStorage(parent,obj){
  var retrieveObject = localStorage.getItem(obj);
  var parseTask = JSON.parse(retrieveObject);
  var newDiv = make("div", "class", "newdiv", parseTask);
  parent.appendChild(newDiv);
  fadeIn(newDiv);
}

这根本不起作用,不知道为什么,然后如果我能够让它工作,我将如何继续像我在使用本地存储的数组中所做的那样存储和更新笔记?我认为这很容易,因为我很快就想出了如何对对象和数组进行待办事项(当时我认为这会非常困难,但现在已经一周了,我没有取得任何进展!

我想这些是自己学习编码的陷阱,任何帮助将不胜感激,谢谢!

以下是完整的JavaScript代码:

//getElementById shortcut
function grab(id) { 
  return document.getElementById(id); 
}
// add eventlistener shortcut
var when = function() {
  return function(obj, event, func) {
    obj.addEventListener(event, func, false);
  }; 
}();
//Custom function to create DOM elements and set their contents
function make(el,type,name,content){
  var theElement = document.createElement(el);
  theElement.setAttribute(type, name);
  theElement.innerHTML = content;
  return theElement;
}
//compute style shortcut
function setStyle(theElement){
  return window.getComputedStyle(theElement);
}
//fade in shortcut.
function fadeIn(theElement){
  var compute = setStyle(theElement).opacity;
  theElement.style.opacity = 1;
}
/*****************************************************/
var toDo = grab("todo");
var result = grab("demo");
var demolist = grab("demolist");
var button = grab("btn");
// submit input on enter which fires function that pushes task into the array.
when(toDo, "keypress", function(event){
  if (event.key == "Enter" || event.keyCode == 13) {
    pushArray();
    toDo.value = "";
  }
});
// "SHOW ARRAY" FUNCTION to verify that the array is being updated (I like this better than using the console);
when(button, "click", function(event){
  demolist.innerHTML = "";
   for(i=0; i< taskItems.length; i++){
     demolist.innerHTML += taskItems[i].Name + " " + taskItems[i].Note + "<br>";
   }
});

function showNotes(theNote){
  var defaultNote = "No note yet";
  if(theNote){
  }
}
var taskItems = [];
/*********************************************************/
//create Task object
function Task(name, note){
  this.Name = name;
  this.Note = note;
  this.completed = false;
}
// function that adds new task to the array
function pushArray(){
  var newtask = new Task(toDo.value, "No note yet");
  taskItems.push(newtask);  
  displayArray(result, newtask.Name);
  appendNote(result, newtask);
}
//function that displays array elements
function displayArray(parent,obj){
  var task = make("div","class","taskitem",obj);
  parent.appendChild(task);
  fadeIn(task);
}
//function that displays notes
function appendNote(theElement,obj){ 
  var newClassItem = make("input","class","tasknote");
  theElement.appendChild(newClassItem);
  when(newClassItem, "keypress", submitNote.bind(null, obj, newClassItem));
}
//function for submitting notes
function submitNote(task,noteInput){
  if (event.key == "Enter" || event.keyCode == 13) {
    task.Note = noteInput.value;
    var newNote = make("div", "class", "hasNote", task.Note);
    noteInput.parentNode.replaceChild(newNote, noteInput);
    fadeIn(newNote);
    when(newNote,"dblclick", function(){
      newNote.parentNode.replaceChild(noteInput, newNote);
    });
  }
}

由于 localStorage 是一种键值存储,根据您的需要,您最好序列化(字符串化,无论如何)数组并保存在单个索引中。

var tasks = [
  'post the question on SO',
  'describe it carefully',
  'get a nice reply',
  'implement the suggested solution'
];

如果出于性能原因确实需要拆分它,则必须按任意索引对它们进行索引。如果你有重新排序,它会变得棘手,你可以在每次有人添加/编辑/删除/重新排序任务时重新刷新整组任务(内存高效,但非常占用 CPU 资源),或者将索引保存在不同的键中,以便以后可以重建顺序,例如:

var tasks = {
  'task1': 'implement the suggested solution',
  'task2': 'describe it carefully',
  'task4': 'get a nice reply',
  'task9': 'post the question on SO'
};
var tasksOrder = [9, 2, 4, 1];

第一个想法很容易实现,但会给你带来任意长列表的问题,第二个想法在 CPU 上更容易实现,但更难实现(并且使用更多内存)。这取决于您案件的具体情况。