Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created March 7, 2012 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/1994765 to your computer and use it in GitHub Desktop.
Save barneycarroll/1994765 to your computer and use it in GitHub Desktop.
Make editing/extending jQuery.data objects slightly less verbose
/*
$(el).data() is fine if you're using it for simple key/value pairs, but if there's any depth (objects), adding to or modifying said objects becomes a verbose pain in the ass.
This extension method uses $.extend() to add or modify any object with the given key:
$(el).data('plugin',$.extend($(el).data('plugin'),{state:1}))
...becomes:
$(el).dataExtend('plugin',{state:1})
...and you can use the same $.extend syntax to do deep copies, overload several objects, etc.
*/
$.fn.dataExtend = function(){
// Are we in a deep copy situation?
// If so the data object label will be the second argument.
var i = typeof arguments[0] === "boolean" ? 1 : 0;
// Grab the label before replacing it in the arguments.
var key = arguments[i];
// Replace the label with the actual object.
arguments[i] = this.data(arguments[i]);
// Replace data with itself extended by whatever was passed.
this.data(key,$.extend.apply(this,arguments));
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment