Skip to content

Instantly share code, notes, and snippets.

@mattfeury
Created August 8, 2012 21:27
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 mattfeury/3298929 to your computer and use it in GitHub Desktop.
Save mattfeury/3298929 to your computer and use it in GitHub Desktop.
Show how jQuery caches data attributes on access
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.
@manfe
Copy link

manfe commented Oct 6, 2015

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 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment