Monday, March 16, 2015

using data- attributes and jQuery-ing for them

One of the joys of writing small apps is that you can experiment with different paradigms of construction and finding DOM elements, messing with ideas for Model and DOM mapping.

I'm making a little status server pinger, using that trivial keyval store I made up (and the server proxy node stuff I found as well). One of the key requirements is that it be asynchronous; I don't want to hold up construction of the page on any given server query. In general, then, I'll have ajax queries returning en masse, and they need to put information in specific locations.

One technique would be to use arbitrary keys just for the Model/View mapping; either numeric indexes or just restrictions on key values (so they would make sense as element IDs). Or I could pass the DOM reference through the nested callbacks, so the function retrieving the data has the place on the page where it goes handy. Both seem kind of clunky... what I'd really like to do is be able to use arbitrary ids (for example, URLs which have 'illegal' DOM id characters) for elements on the page, and then find them via that id.

So jQuery is optimized for finding things by id and class, but you can also select elements by data attrbiutes. So if I had something like

<ul data-entriesForUrl="http://somesite.com"></ul>

I could find that element via 

$('*[data-entriesForUrl="http://somesite.com"]');
I'd guess that that's not efficient but should suit my purposes.

No comments:

Post a Comment