WouldBeNerd
WouldBeNerd

Reputation: 687

Is it a GOOD practice to store Arrays or Objects in a div?

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

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

Later on, when the div is clicked I am then able to call on this data like so:

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 whether or not this is okay. I do not know if the location to this data will always be .path[0]. Can anyone confirm whether this is a good practice or not? I am working on a UI that needs lots of automated Divs, so I am trying to keep everything as automated and simple as possible. No Library answers please.

Upvotes: 3

Views: 510

Answers (2)

ohboy21
ohboy21

Reputation: 4319

Everything is an opinion, but you will find many 'No's to this answer. Why?

The basic pattern is MV*. I highly recommend reading this chapter of Essential JavaScript Design Patterns.

In the end, it depends of how much data you want to store there. If it's getting to complex, move it to a model or controller. There are options for this purpose (read here more on HTML data-attribute).

If you store more than a simple Number or String, I wouldn't recommend it.

Reasons against it:

  • If other people also manipulate your Code, it's easier to follow design patterns so everybody has the same understanding of your code.
  • Store your data in a model or inside the controller. Advantages are you don't have to click a button to access them.
  • If you store them in a model/controller, you can share the data more easily.
  • All of your data will be visible in the DOM. It's just getting really ugly when you look through the rendered HTML and try to find a bug.
  • Testing the data is very hard this way.

Upvotes: 1

pawel
pawel

Reputation: 36965

There are data- attributes in the HTML5 specification that were introduced specifically for this purpose.

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

So you could rewrite your code to make use of 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/

Upvotes: 1

Related Questions