1

In fact i need to access FileUploader.prototype.saveImage() method like the following code :

function FileUploader(object) {
    this.checkInputs(object);
    if (this.isImageSelected()) {
        this.beforeInit(object);
        this.prepareData();
        this.uploadFile().success(function (response) {
            var response = jQuery.parseJSON(response);
            if (response.status != null && response.status) {
                this.saveImage(response.data);
            } else {
                this.setError({
                    error_code: 3,
                    error_message: " error found "
                });
            }
        });
    }
}

FileUploader.prototype.saveImage = function (data) {
    ...
}

the previous call this.saveImage() return error

Uncaught TypeError: undefined is not a function

could someone help me please

oofy
  • 21
  • 1
  • 10

1 Answers1

2

If you create anonymous function this will be window object, so you need to store the value of this in variable like this:

function FileUploader(object) {
    this.checkInputs(object);
    if (this.isImageSelected()) {
        this.beforeInit(object);
        this.prepareData();
        var self = this;
        this.uploadFile().success(function (response) {
            var response = jQuery.parseJSON(response);
            if (response.status != null && response.status) {
                self.saveImage(response.data);
            } else {
                self.setError({
                    error_code: 3,
                    error_message: " error found "
                });
            }
        });
    }
}

Or you can use bind:

function FileUploader(object) {
    this.checkInputs(object);
    if (this.isImageSelected()) {
        this.beforeInit(object);
        this.prepareData();
        this.uploadFile().success(function (response) {
            var response = jQuery.parseJSON(response);
            if (response.status != null && response.status) {
                this.saveImage(response.data);
            } else {
                this.setError({
                    error_code: 3,
                    error_message: " error found "
                });
            }
        }.bind(this));
    }
}
jcubic
  • 61,973
  • 54
  • 229
  • 402