0

I'm trying to create a simple JS class and then trying to create an object but in the marked row it says "Cannot read property 'show' of undefined".

function DashboardNumberItem(dashboardItemId, dataUrl) {
    this.dashBoardItem = $("#" + dashboardItemId);
    this.dataurl = dataUrl;
    this.placeholder = $("#" + dashboardItemId + " .number-placeholder");
    this.dashBoardItem.hide();
}

DashboardNumberItem.prototype.loadData = function() {
    $.ajax({
        url: this.dataurl,
        method: 'GET',
        dataType: 'json',
        success : function(data) {
            this.dashBoardItem.show(); // this.dashBoardItem is undefined?!
            this.placeholder.text(data);
        }
    });
};

var dashboardItem = new DashboardNumberItem("dashboard-item-vardhandelseimportcount", "/Controller/Action");
dashboardItem.loadData();

Why does this happen and how can I make it work?

HischT
  • 933
  • 1
  • 9
  • 26
  • Not sure how _jQuery_ does it, but `this` in an _XMLHttpRequest's_ callback usually points to the request, not the Object which created the request – Paul S. Feb 26 '15 at 14:23

1 Answers1

2

this probably isn't what you expect it to be, and will be pointing to jQuery's XMLHttpRequest Object rather than your DashboardNumberItem instance, so set up a new variable e.g. var that = this;

DashboardNumberItem.prototype.loadData = function() {
    var that = this; // set up a reference to capture it
    $.ajax({
        url: that.dataurl,
        method: 'GET',
        dataType: 'json',
        success : function(data) {
            that.dashBoardItem.show(); // which you can now use in another context
            that.placeholder.text(data);
        }
    });
};
Paul S.
  • 64,864
  • 9
  • 122
  • 138