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…
That’s what the
contextoption of$.ajaxis for:That will make sure the current (correct)
thisis passed along toshowItems.