Javascript tricks: a .data() method for Prototype

I was recently working on an old project that is still using Prototype as it’s JavaScript framework. We’ve been so deep in jQuery on our other projects that I needed a little mind shifting to get back into the Prototype way of doing things.

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>

and then you can use it in your javascript like so

  alert($('dom_with_data').data('my_param'));

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s