Created
March 7, 2012 18:11
-
-
Save barneycarroll/1994765 to your computer and use it in GitHub Desktop.
Make editing/extending jQuery.data objects slightly less verbose
This file contains 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
/* | |
$(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