One function in jQuery that I’ve used heavily is the .data() method. I like that I can stick data on a DOM element with an accepted convention, as opposed to adding arbitrarily named attributes to elements. But I haven’t seen this in Prototype. So I wrote it up.
Once you’ve got this snippet in your JS code, and integrated into prototype (notice the last line where we extend Prototype with our new methods), you are off to the races. In your html, you can attach data to dom elements with
<div id="dom_with_data" data-my_param="here we go"> This element has data. </div>
It’s not yet as functional as the jQuery version. But it was all I needed at the time. There are a couple items I’d like to add, when I find some time:
- make the regex a little more forgiving. Currently the attribute data-123 won’t work. And neither will data-this-is-my-param.
- make the function return all data if called with no keys.
make the setter work. Currently this only works to fetch data which has been stuck on elements by way of the data-* attribute. It’d be nice to be able to set data on an element with the same method, like jQueryUPDATE 7/12/12 Added the setter functionality and updated the gist
For now, I’m happy to let it roll. If you use it and make improvements, let me know and I’ll merge’em in.