-
-
Save Yuffster/3174627 to your computer and use it in GitHub Desktop.
| Element.implement({ | |
| getData: function() { | |
| var data = {}, attrs = this.attributes; | |
| for (var i=0; i<attrs.length; i++){ | |
| k = attrs.item(i).nodeName; | |
| if (k.match(/^data-/)) data[k.replace(/^data-/, '')] = attrs.item(i).nodeValue; | |
| } return data; | |
| }, | |
| clearData: function() { | |
| var self = this; | |
| Object.each(this.getData(), function(v,k){ | |
| self.removeProperty('data-'+k, ''); | |
| }); | |
| return this; | |
| }, | |
| setData: function(k,v) { | |
| this.setAttribute('data-'+k, v); | |
| return this; | |
| } | |
| }); |
That's useful for when you're working with single data keys. ;) If you notice, the entire thing is just a thin wrapper over get[Attribute] to begin with, so I'm totally with you there.
I wrote this because I've been attaching "arbitrary" data attributes to elements which I needed to process and clear periodically, so the main benefit of this is to return just the custom data attributes without the data- prepended so I don't have to do the key translation each time and I can work with them procedurally rather than manually.
The setData is the only borderline useless method, but I like having symmetry in APIs. :)
Wouldn't it be grand to have an element wrapper which mimics the .data attributes in the spec, using timers or property change events? :)
element.get("data-hello")...? :)