Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created May 18, 2011 20:52
Show Gist options
  • Save cowboy/979530 to your computer and use it in GitHub Desktop.
Save cowboy/979530 to your computer and use it in GitHub Desktop.
jQuery Data+: a new signature to allow easy initializing/getting of a per-element "state object"
/*!
* jQuery Data+ - v0.1pre - 6/3/2011
* http://benalman.com/
*
* Copyright (c) 2011 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($) {
// The original .data method will be available as ._data.
$.fn._data = $.fn.data;
// If `true` is passed as an additional first argument, .data works in "get or
// init state object" mode. In this case, if a state object already exists on
// the element for the specified key, a reference to it is returned. If a
// state object does not exist, it is stored first. If the value passed is a
// function, its return value is used as the state object. Note that this will
// only work on the first element in the set, any additional elements will be
// ignored. Also, this only really makes sense if the value to be set is an
// object, ok?
$.fn.data = function(init, key, value) {
var result, undef;
if ( init === true ) {
// Get the first element's state object, if it exists.
result = this._data(key);
// If that element doesn't already have a state object...
if ( result === undef ) {
// If the passed value is a function, initialize the state object from
// that function's return value, otherwise just use the value.
result = $.isFunction(value) ? value.call(this[0], key) : value;
// Store the state object.
this.eq(0)._data(key, result);
}
} else {
// Default to the "normal" behavior.
result = this._data(init, key);
}
return result;
};
})(jQuery);
// Do this:
var data = $('body').data(true, 'key', {x: 1, y: 2});
// Or even this (function only gets executed if 'key' returns no value):
var data = $('body').data(true, 'key', function(key) {
// this == DOM element
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