'this'キーワードに問題があります。以下が機能しない理由は理解できますが、修正方法がわかりません...
//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();
}
別のshowItems関数を使用しないことでこれを修正できる可能性が高いことはわかっていますが、別の方法で修正する方法を確認したいと思います。理想的には、現在のオブジェクトへの参照をサクセスハンドラーに渡したいのですが、その方法がわかりません...