Reputation: 687
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
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:
Upvotes: 1
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);
Upvotes: 1