1

When I run this code it generates the appropriate file upload ui and adds the event listener to the upload button. However the first line in the upload function throws an error - Cannot read property 'style' of undefined - for this.missingFile. What am I doing wrong here?

function FileUploader(props) {
    var div = document.querySelector(props.element);

    var uid = generateGuid();

    var templateHtml = "<p><div id=\"dvMissingFile-" + uid + "\" class=\"missing-file\"> Please choose a file.</div><input type=\"file\" id=\"flUploadedFile-" + uid + "\" name=\"flUploadedFile-" + uid + "\"/></p><div class=\"dvProgressBar\" id=\"progress-" + uid + "\"><div></div></div>";
    div.innerHTML = templateHtml;

    this.uploadButton = document.querySelector(props.uploadButton);
    this.fileInput = document.querySelector("#flUploadedFile-" + uid);
    this.missingFile = document.querySelector("#dvMissingFile-" + uid);
    this.progress = document.querySelector("#progress-" + uid);
    this.url = props.postUrl;

    this.upload = function() {
        this.missingFile.style.display = "none";

        if (this.fileInput.files.length === 0) {
            this.missingFile.style.display = "";
        }
        else {
            var file = this.fileInput.files[0];
            var xhr = new XMLHttpRequest();
            var pbar = document.querySelector("#progress-" + uid + ">div");
            if (xhr.upload) {

                // do upload
            }
        }
    }

    this.uploadButton.addEventListener("click", this.upload);
}

Usage example

<div id="dvUploader"></div>
<button type="button" id="btnUpload" class="btn btn-primary">Upload</button>
<script>
var uploader = new FileUploader({
                    element: "#dvUploader",
                    uploadButton: "#btnUpload",
                    postUrl: "myposturl"
});
</script>
2
  • 1
    this within the function upload is not the same this as before. You can use fat arrow notation this.upload = () => {} Commented Sep 19, 2018 at 14:01
  • Or put the upload function on the prototype if you don't want to use fat arrows. Or use bind to explicitly set the this context of the function. Commented Sep 19, 2018 at 14:02

1 Answer 1

1

One small update to your code can help:

    this.upload = function() {
// ...
    }.bind(this);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.