Created
July 25, 2012 05:48
-
-
Save Yuffster/3174627 to your computer and use it in GitHub Desktop.
Data attribute API extension for MooTools.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| }); |
Wouldn't it be grand to have an element wrapper which mimics the .data attributes in the spec, using timers or property change events? :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. :)