Created
August 8, 2012 21:27
-
-
Save mattfeury/3298929 to your computer and use it in GitHub Desktop.
Show how jQuery caches data attributes on access
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
function getBooyan() { | |
return $('body').data('booyan') | |
} | |
$(function() { | |
// Set a data attribute on an element. This can be done in the html as well, but is simplified in js for this example. | |
// e.g. <body data-booyan="magic">...</body> | |
$('body').attr('data-booyan', 'magic'); | |
// Retrieve as data | |
var booyan = getBooyan(); // booyan == 'magic' | |
// Reset the attribute to a new value. In our usage, this would be done by KnockoutJS | |
$('body').attr('data-booyan', 'black-magic'); | |
var newBooyan = getBooyan(); // booyan still == 'magic' | |
}) | |
// Design decisions aside, this is definitely an issue when combined with KnockoutJS | |
// which updates attributes as observables change. jQuery.data cannot be relied on in these cases. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is really pissing me off. I tought was just me reconizing this "magic". After 3 years this gist helped me. Understand the difference between data and attr 👍