Reputation: 916
function Tour(el) {
var tour = this;
this.el = el;
this.fetchPhotos = function() {
$.ajax('/photos.html', {
data: {location: tour.el.data('location')},
context: tour,
success: function(response) {
console.log(this===tour);
this.el.find('.photos').html(response).fadeIn();
},
error: function() {
this.el.find('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
},
timeout: 3000,
beforeSend: function() {
this.el.addClass('is-fetching');
},
complete: function() {
this.el.removeClass('is-fetching');
}
});
}
this.el.on('click', 'button', this.fetchPhotos);
}
$(document).ready(function() {
var paris = new Tour($('#paris'));
var london = new Tour($('#london '));
});
console log output in success function = true
Above code snippet is from tutorial. I have 2 queries related to 'this' object.
'tour' & 'this' are same(as output suggests) but when i replace 'tour' with 'this' in data option of ajax call, it stops working. Why so?
Why arn't we using 'tour' inside other functions - error, beforeSend.etc.
Please somebody help.
Upvotes: 1
Views: 29
Reputation: 1808
It all had to do with the "context" keyword in the Ajax call. Context tells it what "this" will be when one of the Ajax callbacks, such as success, are called. In your case, you are passing 'tour' as the context, which means in your success function, 'this' is equal to 'tour'.
Upvotes: 1