I just wrote a very simple snippet to understand how jQuery data()
functions and the code is as follows:
$(function () {
carousel = function() {
this.prop1 = 1;
this.prop2 = 'two';
this.prop3 = 3;
}
var _str = $('#test'),
$str_data = _str.data();
console.log($str_data);
data = _str.data('carousel');
if (!data) _str.data('carousel' , new carousel());
console.log(data);
if (!data) {
console.log('no data');
}
});
Now, the objective of this code was to add data() to the div
element using the new
operator and then checking if that piece of data was added, however in my snippet of code in-spite of me adding data to the div
element using the below line of code:
if (!data) _str.data('carousel' , new carousel());
When I checked again to see on the next line if data is actually added:
if (!data) {
console.log('no data');
}
The test passes, which means no data was added. So what am I missing?