my AJAX funciton doesn't quite to work as I expect.
It appears that "this" inside the AJAX success callback doesn't refer to the same "this" as within the scope of the showSnapshotComment function.
I've tried using context it is still not working. My usage is probably incorrect. I am probably overthinking it.
function showSnapshotComments(snapshot) {
var self = $j(this);
alert($j(this).attr('class'));
$j.ajax({
cache: false,
context: this,
url: 'show_snapshot_comments/' + snapshot.id,
async: true,
dataType: 'script',
success: function() {
$j('#snapshots a.photo').each(function(i) {
$j(this).qtip({
content: $j(this).nextAll('.info').eq(i),
position: {
target: 'mouse',
adjust: { mouse: true },
viewport: $j(window)
},
hide: {
event: 'click mouseleave',
delay: 300
},
show: {
solo: true,
event: 'click mouseenter'
},
style: {
tip: true,
classes: "ui-tooltip-light"
}
});
});
}
});
}
Change your reference to self to be a DOM element instead of a jquery object (self = this) and in the success callback function change your this
references to self
.
To understand why you need to do this you should read up on closures and closure scope:
http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
The issue is with scoping of this variable. Try the code below instead:
var self = $j(this);
var that = this;
alert($j(this).attr('class'));
$j.ajax({
cache: false,
context: that,
.
.
.
.
this
inside the AJAX success callback does refer to the same this
as the showSnaphotComments
the answers You get are correct but the simplest answer is explaining that the real issue is the $j().each
function inside the success callback - it will change the context as it iterates over the DOM elements ... but the this
inside the AJAX success is correct try the following :
function showSnapshotComments(snapshot) {
var self = $j(this);
alert($j(this).attr('class'));
$j.ajax({
cache: false,
context: this,
url: 'show_snapshot_comments/' + snapshot.id,
async: true,
dataType: 'script',
success: function() {
var self = this; // same this as in showSnapshotComments
$j('#snapshots a.photo').each(function(i) {
$j(self).qtip({ // this changed to self
content: $j(self).nextAll('.info').eq(i), // same here
position: {
target: 'mouse',
adjust: { mouse: true },
viewport: $j(window)
},
hide: {
event: 'click mouseleave',
delay: 300
},
show: {
solo: true,
event: 'click mouseenter'
},
style: {
tip: true,
classes: "ui-tooltip-light"
}
});
});
}