-
-
Save rwaldron/980066 to your computer and use it in GitHub Desktop.
jQuery initData
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
/*! | |
* 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); |
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
// 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