khushboo29
khushboo29

Reputation: 916

concept of this in ajax call

 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.

  1. '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?

  2. Why arn't we using 'tour' inside other functions - error, beforeSend.etc.

Please somebody help.

Upvotes: 1

Views: 29

Answers (1)

Ageonix
Ageonix

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

Related Questions