Reputation: 2148
I have two functions added to jQuery native methods and which use jquery data() method to store information to retrieve latter.
Thing is I don't want to store the attribute if it has already been stored.
So I have :
$.fn.foo = function() {
if(!$.hasData(this)) {
$.data(this, 'width', this.css('width'));
$('#test').append('foo : Added to "data"<br>');
}
}
$.fn.bar = function() {
if(!$.hasData(this)) {
$.data(this, 'width', this.css('width'));
$('#test').append('bar : Added to "data"<br>');
}
}
$('element').foo();
$('element').bar();
But it outputs "Added to data" twice, instead of once. It seems that $.data() doesn't act globally at all. How should I adapt the code so that the data behave globally ?
Here's the jsfiddle : http://jsfiddle.net/e9e9vbnn/
Upvotes: 0
Views: 56
Reputation: 388326
$.data() takes a dom element reference as its first argument, not a jQuery object. Inside the plugin method this
will refer to the called jQuery wrapper object, not a dom element reference.
$.fn.foo = function() {
//also return this to maintain chanability
return this.each(function() {
if (!$.hasData(this)) {
$.data(this, 'width', $(this).css('width'));
$('#test').append('foo : Added to "data"<br>');
}
})
}
$.fn.bar = function() {
return this.each(function() {
if (!$.hasData(this)) {
$.data(this, 'width', $(this).css('width'));
$('#test').append('bar : Added to "data"<br>');
}
})
}
$('#element').foo();
$('#element').bar();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='test'></div>
<div id='element'></div>
Upvotes: 1