Reputation: 1
This question is related to mine and explains what .data
method is in Jquery.
Apart from the relation to HTML5 data-*
element attributes (like <p class='foo_cl' data-bar='gee'>
, for example) why would I code:
$('body').data("my_lab", {some:"object"}); // §1
instead of
$('body').my_lab = {some:"object"}; // §2
(I am mostly interested in the case where the Jquery selector gives one object, like for $('body')
above)
The later (§2) seems more readable and shorter, and I guess would be more efficient, than the former (§1). Of course data
is a Jquery selector (but I could use each
to set the .my_lab
field, etc...)
And I might even consider changing the DOM element with the ugly looking
$('body')[0].my_lab = {some:"object"}; // §3 is ugly
(which is perhaps undefined behavior, see this)
Of course, there is the potential issue of colliding the field name my_lab
with some existing field in JQuery implementation; but I assume that using some common suffix (like my_
) in field names should be enough.
FWIW, I am only interested in recent Jquery (e.g. Jquery 2.1.4) on recent Firefox (e.g. 38 or 42) on Linux.
In other words, why would adding my own fields in JQuery objects be frowned upon?
Upvotes: 5
Views: 68
Reputation: 2953
By doing
$('body').my_lab = {some:"object"};
You are setting value to a specified jQuery wrapper. You would not be able to reaccess the data with another selector :
$('body').my_lab = {some:"object"};
console.log($('body').my_lab); // will log undefined
This is why using data is basically more reliable
$('body').data('my_lab', {some:"object"});
console.log($('body').data("my_lab")); // will log {some: "object"}
For the 3rd option : $("body")[0].attr = { my : "object" }
part :
The jQuery data method prevents potential memory leaks when manipulating the dom / removing elements from the page (by removing the binded data and stuff) and avoid attribute conflicts (like setting domElement existing attributes and other subtle things)
So basically, if you have jQuery in you app, you don't really have any good reason to reinvent the wheel by doing manual binding between dom element and javascript data.
Upvotes: 7