I would like to ask for more an opinion than a question: What would the community recommend to do when you must do a webpage with lots of data, for example, a products listing, that should have some functionality like buy (adds to cart), sorting, etc. if you have to manipulate the data of the current product - price, title, image, link and other attributes? How you do it in your projects?
For example we have a page with dozens of products, each of them has attributes: price, title, description, image(URL), link(URL). How would you store the data to use it on some user interaction? Personally, I've done it by just inserting each of the attribute in tags, something like:
<div class="product" data-product_id="123">
<div class="pr_title">Title</div>
<div class="pr_body">Body</div>
<div class="pr_img"><img src="http://www.www.www/img.png"></div>
<div class="pr_link"><a href="http://www.stackoverflow.com/">Buy!</a></div>
</div>
This way I have my html structure for presentation and I worked with data in jQuery by something like:
var url = $('.product').find('.pr_link').find('a').attr('href');
But when the project got big and there were 10-15 more attributes added to each element, getting data from current product got pretty complicated and the code became mostly unreadable.
I thought of using same structure, but to keep data in some object like:
var products = {
1: {
title: "abc",
description: "lorem ipsum",
price: 25.19,
img: "http://www.www.www/img.png",
link: "http://www.stackoverflow.com"
}
}
and keep markup as simple as possible, only using elements and styles needed for design with css:
<div class="product" data-product_id="123">
<div class="title">Title</div>
<div>Body</div>
<img src="http://www.www.www/img.png">
<a href="http://www.stackoverflow.com/">Buy!</a>
</div>
so onClick I would need to retrieve the id of the product and query it in our object "products":
var url = products[id].title;
While this is the most convenient way to work with it requires a new object.
Another idea was to keep all data in data- attributes of the parent div element like:
<div class="product" data-product_id="123" data-title="abc" data-body="Body">
but for much as I know jQuery doesn't work with data attributes well (natively).
So what are your suggestions? Maybe you have some even better ideas to share.
P.S. I tried to find some information on the subject, but most likely failed to find the way to formulate it well so I found nothing about it. If there are links or even similar questions on stack exchange sites, please feel free to post them. Thank you in advance!
.attr()or.data()(the latter can be less helpful since it does data conversion, so, e.g., "123" would be returned as a number not a string).