Andrew Connell
Andrew Connell

Reputation: 5287

Accessing 'this' within ajax callback with prototype pattern

I'm having some issues with the 'this' keyword. I understand why the following isn't working, but can't figure out how to fix it...

//Namespace
var CPT = CPT || {};

//Constructor
CPT.Grid = function (hostElement, surlWeb) {
  this.hostElement = hostElement;
  this.surlWeb = surlWeb;
}

//Prototype
CPT.Grid.prototype = {

  init: function () {

    $.ajax({
      url: this.surlWeb,
      headers: { "accept": "application/json" },
      success: this.showItems
    });
  },

  showItems: function (data) {
    //do some work 

    // this is the error... no access to hostElement because 'this' is the AJAX call
    this.hostElement.html(items.join(''));
  }
}

function getProducts() {
  var grid = new CPT.Grid($("#displayDiv"), someUrl);
  grid.init();
}

I know I can likely fix this by not having a separate showItems function, but I'd like to see how to do it another way. Ideally I'd like to pass a reference to the current object into the success handler, but can't figure out how to do that...

Upvotes: 0

Views: 409

Answers (2)

Anoop
Anoop

Reputation: 23208

You are passing function reference. which will not have same context.

...

var self = this;
$.ajax({
      url: this.surlWeb,
      headers: { "accept": "application/json" },
      success: function(){self.showItems.apply(self, arguments)
    });
  },

Or

You can bind a context to your method

this.showItems = this.showItems.bind(this); // will not work IE < 9
 $.ajax({
          url: this.surlWeb,
          headers: { "accept": "application/json" },
          success: this.showItems
        });
      },

Upvotes: 1

pimvdb
pimvdb

Reputation: 154818

That's what the context option of $.ajax is for:

$.ajax({
  // ...
  context: this,
  success: this.showItems
});

That will make sure the current (correct) this is passed along to showItems.

Upvotes: 5

Related Questions