Created
January 10, 2016 11:18
-
-
Save milosdjakonovic/6c3564deec8de067acfa to your computer and use it in GitHub Desktop.
jQuery like data function in vanilla JavaScript
This file contains 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 wrapper, necessary | |
* for attaching custom user | |
* data to element. | |
* | |
* It acts like jQuery wrapper | |
* -creates an instance of wrapper | |
* with element as zero field | |
* providing access to `data` | |
* method. | |
* | |
* Example usage: | |
* | |
* elwrap('#element').data('someKey') ===> returns undefined if niether elwrap('#element').data('someKey') was | |
* previously set or #element doesn't have data-someKey attribute (just like jQuery does) | |
* | |
* elwrap('#element').data('someKey', 'someValue') ===> sets value for given key to wrapper of #element, returning reference to wrapper object | |
* (just like jQuery) so you can use multiple set in one line: elwrap('#element').data('someKey', 'someValue').data( 'someKey2', 'someValue2' ).data('someKey3', 'someValue3') | |
* so you can acces them with: | |
* | |
* elwrap('#element').data('someKey') | |
* | |
* | |
*/ | |
window.elwrap = window.elwrap || (function(w,d){ | |
var Wrapper = function(element){ | |
this[0] = element; | |
var dataStore = {}; | |
this.data = function(key, value){ | |
if (typeof value === typeof undefined) { | |
return dataStore[key] || this[0].getAttribute('data-' + key); | |
} else { | |
dataStore[key] = value; | |
return this; | |
} | |
} | |
}, | |
created = []; | |
return function(elem){ | |
if (typeof elem === 'string') { | |
//you can safely strip next 4 lines as IE<8 usage is insignificant | |
if (!d.querySelector) { | |
throw new Error('Browsers without document.querySelector/querySelectorAll (IE<8) should have dom Element reference as argument.'); | |
return false; | |
} | |
elem = d.querySelector(elem); | |
} | |
var tmpLength = created.length; | |
for(var i = 0; i<tmpLength; i++){ | |
if (elem === created[i][0]) { | |
return created[i]; | |
} | |
} | |
var fresh = new Wrapper(elem); | |
created.push(fresh); | |
return fresh; | |
} | |
})(window,document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment