I've heard over and over again that it is bad practice to "use the DOM as a database."
While I mostly agree with that sentiment, this question is more about the less black and white cases. Keeping in mind the latest revisions to jQuery's .data()
methods and the HTML5 data-attribute spec, is it really so bad to stick some data in the DOM for the sake of convenience?
For example, I recently implemented a "live" calculation feature on a table full of inputs by doing something like this:
<table>
<tr>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
</tr>
</table>
jQuery:
$('table').bind('calculate',function(){
var total = 0;
$(this).find('tr').each(function(){
total += $(this).data('value');
});
// display total
});
$('table input').bind('change keyup',function(){
$(this).closest('tr').data('value',$(this).val());
$(this).closest('table').trigger('calculate');
});
This is an over-simplified example because I could skip the calls to .data()
and go straight to the input values, but let's imagine a slightly more complex scenario where elements other than inputs are affecting the row values.
Is it wrong to use the DOM to store simple data in this kind of situation?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…