Is it good practice to store arrays or objects in a div?

I noticed not too long ago that I can do this in Javascript. I can create a button div and attach an array, object or value to it.

var newDiv = document.createElement("div");
newDiv.id = dName
newDiv.value = value;

      

Later, when the div is clicked, I can then call this data like this:

function clickFunction(e){
    console.log(e.path[0].value, "clicked");
    var itemArray = e.path[0].value;
    console.log(itemArray.inputRequest.length, "dataReqs needed");
}

      

I was wondering if this is good or not. I don't know if the location of this data will always be .path [0]. Can anyone confirm if this is good practice or not? I'm working on a UI that needs a lot of automatic Divs, so I'm trying to keep things as automatic and simple as possible. No library is responding.

+3


source to share


2 answers


Everybody has an opinion, but you will find many "no" to this answer. Why?

The main template is MV *. I highly recommend reading this chapter of Basic JavaScript Design Patterns.

In the end, it depends on how much data you want to store there. If it gets tricky, move it to a model or controller. There are options for this purpose ( read more about the HTML data attribute here ).



If you are storing more than just a number or a string, I would not recommend it.

Reasons against:

  • If other people also manipulate your code, it is easier to follow design patterns so that everyone has the same understanding of your code.
  • Store data in a model or inside a controller. Benefits: You don't need to press a button to access them.
  • If you store them in a model / controller, you can share data more easily.
  • All your data will be visible in the DOM. It just gets very ugly when you go through the rendered HTML and try to find an error.
  • Data testing is very difficult.
+1


source


The HTML5 spec has attributes data-

that have been introduced specifically for this purpose.

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

So, you can rewrite your code to use them.



var newDiv = document.createElement("div");
newDiv.id = 'some name';
newDiv.dataset.value = 'some value';


function clickFunction(e){
    console.log(e.target.dataset.value);
}

document.body.appendChild( newDiv );
newDiv.addEventListener('click', clickFunction);

      

http://jsfiddle.net/5dvheb0k/

+1


source







All Articles