I am storing the following data attribute for select elements for loading the options.
<select name="DependsOn_Field" data-load='automatic' data-source='web.module().fields' data-value='name' data-display='label' data-filter='exclude_single' id='DependantField'></select>
My questions is what is the best way when need to store many data attributes for a single DOM element? Is it better to have single data attribute having the JSON data or having separate data attributes for each value needed.
I think the question boils down to are the data attributes static? Are they possibly ever going to change? If they are going to change or you may want to edit them, then JSON is definitely better. However if they are static and you are just going to read those attributes, I think the data attribute is fine, this is exactly what the data attribute is for. I know it looks cumbersome because you have a bunch of attributes but I think it's fine.
EDIT by change or edit, I mean edit them dynamically in the clients browser.
Hope this helps.
That's entirely dependant on how they are being used.
If your values are simple strings and you are accessing them from JavaScript, then it likely makes sense to keep them in data-
attributes.
If your values are complex JSON objects, then it may make more sense to store the complete JSON value in a data-
attribute, and define a helper that will read it (assuming for simplicity that jQuery is available):
function getElemData(elem) {
var $elem = $(elem);
var elemData = $elem.data("_jsonData");
if (!elemData) {
elemData = JSON.parse($elem.attr("data-json-data"));
$elem.data("_jsonData", elemData);
}
return elemData;
}
And finally, if the data are just being passed around (ex, written by the server, then read and sent directly on somewhere else), it most likely makes sense to keep the entire blob in a single data-
attribut.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With