views:

69

answers:

3

I'm a big fan of jQuery's .data() method, but I can't always use it. Often times I am rendering html templates that I pass via AJAX and I need to attach metadata to each of the elements in the template. For example:

<ul>
{% for item in itemlist %}
    <li metadata="{{ item.metadata }}">{{ item.name }}</li>
{% endfor %}
</ul>

I know attaching attributes to store data is bad practice (and it might not even work in older versions of IE). What is the best practice? Is there a good alternative to this method?

+2  A: 

If the elements in question all have ids, then have (whatever server-side language that is) inject them into a javascript array, where the ids are the keys, and the metadata the values.

Example:

<script type="text/javascript">
    var metadata;
    {% for item in itemlist %}
        metadata['{{ item.id }}'] = '{{ item.metadata }}';
    {% endfor %}
    //metadata contains a set of id => metadat pairs
</script>

<ul>
    {% for item in itemlist %}
    <li id="{{ item.id }}">{{ item.name }}</li>
    {% endfor %}
</ul>
Eric
could you add an explanatory code sample please Eric?
Richard Ev
See my updated answer
Eric
+1  A: 

I think the practice of attaching classes that serve no purpose other than to provide metadata is fine, and so do the makers of jQueryUI it seems (see: .ui-state-error, .ui-state-highlight, .ui-state-active, etc), but I don't know if that qualifies as bad practice for you.

mVChr
I wouldn't consider jQuery UI's ui-state-* classes to be metadata, since they affect the associated element's style. My question pertains specifically to data which doesn't affect style.
thebossman
The point remains that you can use classes to store data without affecting style if you never give these classes a style.
mVChr
+2  A: 

data-* attributes. See http://stackoverflow.com/questions/427262/can-i-just-make-up-attributes-on-my-html-tags/.

Ms2ger
+1 for data-attributes
Anurag
Very interesting. Will this work with IE7/8?
thebossman
element.getAttribute("data-foo") will work perfectly fine in every browser that supports DOM level 1. This will work just as well with your example metadata attribute, of course, but the point is mainly that data-* attributes are guaranteed not to clash with any future attributes. (And validity is nice too, obviously.)
Ms2ger
I see. I like this answer best. Thanks.
thebossman