1

this.xhr is undefined, when load event occurs. How can I solve this problem?

I've tried to use bind to solve this problem but it does not work!

 ContactForm.form.addEventListener("submit", (submitEvent) => {
            ContactForm.submitHandler(submitEvent);
 }).bind(ContactForm);

(The form data send to controller successfully and the controller send data to load event.)

var ContactForm = {
xhr: new XMLHttpRequest(),
aborted: false,
form: document.querySelector("#contact-form"),
attachment: document.querySelector("#Attachment"),
progressArea: document.querySelector("#progress-area"),
addProgressBlock: function addProgressBlock(file) {
   // some codes
},
submitHandler: function (submitEvent) {
    submitEvent.preventDefault();
    
    const files = this.attachment.files;
    
    this.xhr.open("POST", "/ContactUs/ContactUsForm/");
    const formData = new FormData(this.form);

    this.xhr.addEventListener("load",
        function () {
            if ((this.xhr.status >= 200 && this.xhr.status < 300) || this.xhr.status === 304) {
              // Why this.xhr is undefined, when "load" event occurs?
            } else {
                console.log("Status: " + this.xhr.status);
            }
        });

    const block = this.addProgressBlock(files[0]);

    this.xhr.upload.addEventListener("progress",
        function (event) {
           // some codes
           
        });

    this.xhr.addEventListener("abort", function () {



        document.querySelector("#Attachment").value = null;
        //this = Object.create(ContactForm);
        return false;
    });

    this.xhr.send(formData);

},

cancelUploadHandler: function () {
    this.attachment.files = null;
    this.progressArea.innerHTML = null;
    this.aborted = false;
    this.xhr.abort();
}
};

var myContactForm = Object.create(ContactForm);

$(document).ready(function () {
if (myContactForm.attachment) {

    myContactForm.form.addEventListener("submit", function (submitEvent) {
        myContactForm.submitHandler(submitEvent);
    });
}
});
x19
  • 8,277
  • 15
  • 68
  • 126
  • This example of the problem covered by the duplicate requires fixing the `this` value of the anonymous handler `function () { if ((this.xhr.status ... // why ...`. The posted code already calls ` myContactForm.submitHandler` with the correct `this` value using _one_ method of doing so A tip: run code in strict mode to produce errors you should probably known about. – traktor Jul 13 '20 at 02:16

0 Answers0