简体   繁体   English

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

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

I am trying to implement localStorage with my simple OOP todo list. 我正在尝试通过简单的OOP待办事项列表实现localStorage。

The fiddle is here: https://jsfiddle.net/b81t2789/ 小提琴在这里: https : //jsfiddle.net/b81t2789/

I thought I could just treat the local storage like an array and copy the logic I used with my actual array but that doesn't work. 我以为我可以将本地存储像一个数组一样对待,并复制我在实际数组中使用的逻辑,但这不起作用。

Here, right after pushing the task into the array, I added a line that stores the task in the local storage and stringifies it: 在这里,在将任务推入数组之后,我添加了一行,将任务存储在本地存储中并对其进行字符串化:

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

Then right below the function that displays the new array element I added one that retrieves the item from local storage, parses it, then creates a DOM element with the new task and appends it to another container. 然后,在显示新数组元素的函数的正下方,我添加了一个从本地存储中检索项目的内容,对其进行解析,然后使用新任务创建一个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);
}

This doesn't work at all, not sure why, and then if I were to be able to get this to work how would I continue to go about storing and updating notes like I did in the array with local Storage? 这根本行不通,不知道为什么,然后,如果我能够使它生效,我将如何继续像在本地存储阵列中那样继续存储和更新笔记? I thought this would be easy as I figured out how to make a todo with objects and arrays pretty quickly (when I thought it would be super difficult, but it's been a week now and I've made no progress!) 我以为这很容易,因为我想出了如何很快地用对象和数组做待办事项(当时我以为这很困难,但是已经过去了一周,但我没有取得任何进展!)

I guess these are the pitfalls of learning to code by yourself, any help would be much appreciated thank you! 我想这些是您自己学习编码的陷阱,非常感谢您的任何帮助!

Here is the full javascript code: 这是完整的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);
    });
  }
}

Being localStorage a key-value storage, depending on your needs, you are better off serializing (stringifying, whatever) the array and saving in a single index. 作为localStorage的键值存储,取决于您的需求,最好不要序列化(字符串化)数组并将其保存在单个索引中。

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

If you really need to split it for performance reasons, you have to index them by a arbitrary index. 如果出于性能原因确实需要对其进行拆分,则必须通过任意索引对其进行索引。 If you have reordering it gets tricky and you can either reflush the whole set of tasks every time someone adds/edits/deletes/reorder the tasks (memory-efficient, but very CPU intensive) or save the indexes in a different key so you can reconstruct the order later, like: 如果您重新排序,它将变得很棘手,您可以在有人添加/编辑/删除/重新排序任务时重新刷新整个任务集(内存效率高,但占用大量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];

The first idea is very simple to implement, but will give you problems with arbitrarily long lists, the second one is much more easy on the CPU but much harder to implement (and uses more memory). 第一个想法很容易实现,但是会给您带来任意长列表的问题,第二个想法在CPU上更容易实现,但更难实现(并使用更多内存)。 It depends on the specifics of your case. 这取决于您的情况的具体情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM