Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.