Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing data in the DOM

I have a list of books and I want to store data against each book e.g. Price, Quantity, id, catergory id, size, weight etc.

I was looking at storing all this in the dom by extending the li elements representing each book in the list using data- attributes. This data could then be utilised directly with javascript.

However I have read that accessing data- attributes is slow in a performance sense. In addition I can have multiple instances of the same book so am a little concerened about bloat in the html.

An alternative would be to use a JS object to store data for each book.

So my question is what is the best practice for storing data in the frontend, DOM or Javscript?

Thanks in advance

like image 298
user502014 Avatar asked Jan 13 '13 21:01

user502014


2 Answers

The data- attributes are generally used more as a way to get data into your JavaScript (i.e. From your server-side template), and less a runtime place to store your data. A better place keep your active data is in a JavaScript object, especially if you will be accessing it or manipulating it frequently during the life of your script.

This is more in keeping with an MVC approach, where the data lives in your Model, but may be represented in your View. For this reason, some of the newer MVC frameworks like AngularJS provide automatic two-way binding between the two.

like image 154
keithjgrant Avatar answered Oct 03 '22 00:10

keithjgrant


The choice is really dependant on your application architecture and type of functionality in your application. If you are building a single page app I found that using a well constructed json object in conjunction with a good templating plugin gives you much more flexibility in terms of functionality.

I found that indexing your data on an id in your json and then storing that id in the "data-" element gives you a nice way of reacting to browser events (clicks etc) without having to search through JSON structure. Having a JSON structure also makes it a bit easier to do operations such as sorting lists and other global operations that you might want to do without having to rebuild your data from DOM. This method is also better when you work with MVC like frameworks or implement your own "observable" data structures.

On the other hand if you are working with mostly server side code and have only basic functionality in your page that utilizes your "data-" data (such as display book details on click or something simple like that), it is probably simpler to just use the "data-" attribute to store additional details.

like image 44
Michal Avatar answered Oct 03 '22 00:10

Michal