Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Forked from cowboy/jquery.ba-dataplus.js
Created May 19, 2011 02:29
Show Gist options
  • Save rwaldron/980066 to your computer and use it in GitHub Desktop.
Save rwaldron/980066 to your computer and use it in GitHub Desktop.
jQuery initData
/*!
* jQuery initData - v0.1pre - 5/18/2011
* http://benalman.com/
*
* Copyright (c) 2011 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($){
$.fn.initData = function(key, fn) {
// Get the first element.
var elem = $(this).eq(0);
// Get the element data, if it exists.
var obj = elem.data(key);
// If it doesn't exist...
if ( !obj ) {
// Initialize the data from the function's return value.
obj = fn.call(elem[0], key);
// And set the data on the element.
elem.data(key, obj);
}
// Return the data object.
return obj;
};
})(jQuery);
// Do this:
var data = $('body').initData('key', function() {
return {x: 1, y: 2};
});
// Instead of this:
var elem = $('body');
var data = elem.data('key');
if ( !data ) {
data = {x: 1, y: 2};
elem.data('key', data);
}
// Or this:
var elem = $('body');
var data;
elem.data('key', data = elem.data('key') || {x: 1, y: 2});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment