What is the proper way of separating my meta-data from the HTML? As my projects grow bigger and bigger tying up meta-data with HTML becomes more and more messy. Any good alternatives?
Meta Data: Everything the JS needs to know about an HTML element which isn’t straight-forwardly encoded in the HTML elements and their attributes. E.g. a geolocation, enabled, disabled action.
Example: Say I have a list of places I want to show up on a map whenever I click on one of them. How do I identify that exact same place in JS so I could tell the map ‘hey, move to that location’? Easiest way, that becomes messy in the end, is to tie it into the HTML, say the li id will be the geolocation. That’s easy, but it is a code smell. How do I do this properly? .data() in jQuery also becomes horrible to maintain soon afterwards.
Conclusion: that’s it, I’m going to find/write good MVC for JS.
If you want to attach metadata to DOM elements then use HTML5 data- attributes or use jQuery’s .data() method to do it programmatically.
Here’s a real world example I just used it on that really helped. I sent a request to the server to upload a file and I get a JSON response with the File Name, Content Type, Size and a GUID. On the response I want to add a list item to show the file but I want to preserve the JSON data. Here’s how I did it in the callback:
What’s great about this is now the list item HAS all my metadata attached to it.
So I could do something like this and know everything about it:
The implementations are really limitless.
ALSO, as of jQuery 1.4.3 .data() will automatically pick up the data- attributes in your HTML. So
<div data-foo="bar"></div>can be immediately accessed in code using$('div').data('foo') //bar