Skip to content

Instantly share code, notes, and snippets.

@milosdjakonovic
Created January 10, 2016 11:18
Show Gist options
  • Save milosdjakonovic/6c3564deec8de067acfa to your computer and use it in GitHub Desktop.
Save milosdjakonovic/6c3564deec8de067acfa to your computer and use it in GitHub Desktop.
jQuery like data function in vanilla JavaScript
/**
*
* 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